1
0
Fork 0
gobelt/dbc/sqldb_test.go

101 lines
2.0 KiB
Go
Raw Normal View History

2018-07-07 12:11:23 +00:00
package dbc
2018-06-23 21:46:35 +00:00
import (
"context"
"flag"
"os"
"testing"
_ "github.com/go-sql-driver/mysql" // MySQL driver
"github.com/localhots/gobelt/log"
2018-06-23 21:46:35 +00:00
)
type record struct {
ID uint `db:"id"`
Name string `db:"name"`
}
2018-07-07 12:11:23 +00:00
var conn Conn
2018-06-23 21:46:35 +00:00
func TestMain(m *testing.M) {
ctx := context.Background()
2018-06-23 21:46:35 +00:00
dsn := flag.String("dsn", "", "Database source name")
flag.Parse()
if *dsn == "" {
log.Warn(ctx, "Database source name is not provided, some tests would be skipped")
} else {
connect(ctx, *dsn)
seed(ctx)
2018-06-23 21:46:35 +00:00
}
log.Info(ctx, "Starting test suite")
exitCode := m.Run()
if exitCode == 0 {
log.Info(ctx, "Test suite completed successfully")
} else {
log.Error(ctx, "Test suite failed")
}
if conn != nil {
if err := conn.Close(); err != nil {
log.Errorf(ctx, "Failed to close connection: %v\n", err)
}
}
os.Exit(exitCode)
}
func connect(ctx context.Context, dsn string) {
log.Info(ctx, "Establishing connection to the test database")
2018-06-23 21:46:35 +00:00
var err error
conn, err = Connect(ctx, MySQL, dsn)
2018-06-23 21:46:35 +00:00
if err != nil {
log.Fatalf(ctx, "Failed to connect: %v\n", err)
2018-06-23 21:46:35 +00:00
}
}
2018-06-23 21:46:35 +00:00
func seed(ctx context.Context) {
log.Info(ctx, "Seeding database")
mustExecMain(conn.Exec(ctx, `DROP TABLE IF EXISTS sqldb_test`))
2018-07-07 12:11:23 +00:00
mustExecMain(conn.Exec(ctx, `
2018-06-23 21:46:35 +00:00
CREATE TABLE sqldb_test (
id int(11) UNSIGNED NOT NULL,
name VARCHAR(10) DEFAULT '',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=ascii
`))
2018-07-07 12:11:23 +00:00
mustExecMain(conn.Exec(ctx, `
2018-06-23 21:46:35 +00:00
INSERT INTO sqldb_test (id, name)
VALUES
(1, "Alice"),
(2, "Bob")
`))
}
2018-07-07 12:11:23 +00:00
func mustExec(t *testing.T, r ExecResult) ExecResult {
2018-06-23 21:46:35 +00:00
t.Helper()
if r.Error() != nil {
2018-07-07 12:11:23 +00:00
t.Fatalf("Exec failed: %v", r.Error())
2018-06-23 21:46:35 +00:00
}
return r
}
2018-07-07 12:11:23 +00:00
func mustExecMain(r ExecResult) ExecResult {
2018-06-23 21:46:35 +00:00
if r.Error() != nil {
log.Fatalf(context.Background(), "Query failed: %v\n", r.Error())
2018-06-23 21:46:35 +00:00
}
return r
}
2018-07-07 12:11:23 +00:00
func mustQuery(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("Query failed: %v", err)
}
}
func requireConn(t *testing.T) {
t.Helper()
if conn == nil {
t.Skip("Connection required")
}
}