Skip to content

Commit

Permalink
Use testDB mock
Browse files Browse the repository at this point in the history
  • Loading branch information
qbart committed Oct 30, 2021
1 parent a4887be commit 9755cd9
Show file tree
Hide file tree
Showing 13 changed files with 99 additions and 82 deletions.
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,7 @@ github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3
github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
Expand Down
3 changes: 1 addition & 2 deletions krabdb/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"database/sql"

"github.com/jmoiron/sqlx"
"github.com/ohkrab/krab/krabenv"
)

type ExecerContext interface {
Expand All @@ -22,7 +21,7 @@ type DB struct {
}

func Connect(connectionString string) (*DB, error) {
db, err := sqlx.Connect("pgx", krabenv.DatabaseURL())
db, err := sqlx.Connect("pgx", connectionString)
if err != nil {
return nil, err
}
Expand Down
4 changes: 1 addition & 3 deletions spec/action_migrate_down_arguments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package spec

import (
"testing"

"github.com/ohkrab/krab/krabdb"
)

func TestActionMigrateDownArugments(t *testing.T) {
withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_animals" {
version = "v1"
Expand Down
4 changes: 1 addition & 3 deletions spec/action_migrate_down_hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package spec

import (
"testing"

"github.com/ohkrab/krab/krabdb"
)

func TestActionMigrateDownHooks(t *testing.T) {
withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_animals" {
version = "v1"
Expand Down
7 changes: 3 additions & 4 deletions spec/action_migrate_down_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ package spec
import (
"testing"

"github.com/ohkrab/krab/krabdb"
"github.com/stretchr/testify/assert"
)

func TestActionMigrateDown(t *testing.T) {
assert := assert.New(t)

withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_animals" {
version = "v1"
Expand Down Expand Up @@ -65,7 +64,7 @@ Done
func TestActionMigrateDownOnError(t *testing.T) {
assert := assert.New(t)

withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_animals" {
version = "v1"
Expand Down Expand Up @@ -118,7 +117,7 @@ Done
func TestActionMigrateDownWhenSchemaDoesNotExist(t *testing.T) {
assert := assert.New(t)

withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_animals" {
version = "v1"
Expand Down
4 changes: 1 addition & 3 deletions spec/action_migrate_down_transaction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package spec

import (
"testing"

"github.com/ohkrab/krab/krabdb"
)

func TestActionMigrateDownTransactions(t *testing.T) {
withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_animals" {
version = "v1"
Expand Down
4 changes: 1 addition & 3 deletions spec/action_migrate_up_arguments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package spec

import (
"testing"

"github.com/ohkrab/krab/krabdb"
)

func TestActionMigrateUpArguments(t *testing.T) {
withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_animals" {
version = "v1"
Expand Down
4 changes: 1 addition & 3 deletions spec/action_migrate_up_dsl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package spec

import (
"testing"

"github.com/ohkrab/krab/krabdb"
)

func TestActionMigrateUpDsl(t *testing.T) {
withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_categories" {
version = "v1"
Expand Down
4 changes: 1 addition & 3 deletions spec/action_migrate_up_hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package spec

import (
"testing"

"github.com/ohkrab/krab/krabdb"
)

func TestActionMigrateUpHooks(t *testing.T) {
withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_animals" {
version = "v1"
Expand Down
5 changes: 2 additions & 3 deletions spec/action_migrate_up_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import (
"testing"

"github.com/ohkrab/krab/krab"
"github.com/ohkrab/krab/krabdb"
)

func TestActionMigrateUp(t *testing.T) {
withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "do_nothing" {
version = "v1"
Expand All @@ -34,7 +33,7 @@ Done
}

func TestActionMigrateUpWithError(t *testing.T) {
withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
krab.NewSchemaMigrationTable("public").Init(context.TODO(), db)

c := mockCli(mockConfig(`
Expand Down
4 changes: 1 addition & 3 deletions spec/action_migrate_up_transaction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package spec

import (
"testing"

"github.com/ohkrab/krab/krabdb"
)

func TestActionMigrateUpTransactions(t *testing.T) {
withPg(t, func(db *krabdb.DB) {
withPg(t, func(db *testDB) {
c := mockCli(mockConfig(`
migration "create_animals" {
version = "v1"
Expand Down
56 changes: 4 additions & 52 deletions spec/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@ import (

_ "github.com/jackc/pgx/v4"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/jmoiron/sqlx"
"github.com/ohkrab/krab/cli"
"github.com/ohkrab/krab/krab"
"github.com/ohkrab/krab/krabcli"
"github.com/ohkrab/krab/krabdb"
"github.com/ohkrab/krab/krabenv"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -76,7 +74,7 @@ func (m *cliMock) AssertUiErrorOutputContains(t *testing.T, output string) bool
)
}

func (m *cliMock) AssertSchemaMigrationTableMissing(t *testing.T, db *krabdb.DB, schema string) bool {
func (m *cliMock) AssertSchemaMigrationTableMissing(t *testing.T, db krabdb.QueryerContext, schema string) bool {
_, err := krab.NewSchemaMigrationTable(schema).SelectAll(context.TODO(), db)
if assert.Error(t, err) {
return assert.Contains(
Expand All @@ -89,7 +87,7 @@ func (m *cliMock) AssertSchemaMigrationTableMissing(t *testing.T, db *krabdb.DB,
return false
}

func (m *cliMock) AssertSchemaMigrationTable(t *testing.T, db *krabdb.DB, schema string, expectedVersions ...string) bool {
func (m *cliMock) AssertSchemaMigrationTable(t *testing.T, db krabdb.QueryerContext, schema string, expectedVersions ...string) bool {
versions, err := krab.NewSchemaMigrationTable(schema).SelectAll(context.TODO(), db)
if assert.NoError(t, err) {
if assert.Equal(t, len(versions), len(expectedVersions), "Scheme versions count mismatch") {
Expand All @@ -108,7 +106,7 @@ func (m *cliMock) AssertSchemaMigrationTable(t *testing.T, db *krabdb.DB, schema
return false
}

func (m *cliMock) Query(t *testing.T, db *krabdb.DB, query string) ([]string, []map[string]interface{}) {
func (m *cliMock) Query(t *testing.T, db krabdb.QueryerContext, query string) ([]string, []map[string]interface{}) {
rows, err := db.QueryContext(context.TODO(), query)
assert.NoError(t, err, fmt.Sprint("Query ", query, " must execute successfully"))
defer rows.Close()
Expand All @@ -119,7 +117,7 @@ func (m *cliMock) Query(t *testing.T, db *krabdb.DB, query string) ([]string, []
return cols, vals
}

func (m *cliMock) Insert(t *testing.T, db *krabdb.DB, table string, cols string, vals string) bool {
func (m *cliMock) Insert(t *testing.T, db krabdb.ExecerContext, table string, cols string, vals string) bool {
_, err := db.ExecContext(
context.TODO(),
fmt.Sprintf(
Expand Down Expand Up @@ -170,49 +168,3 @@ func mockParser(pathContentPair ...string) *krab.Parser {
p.FS = afero.Afero{Fs: memfs}
return p
}

func withPg(t *testing.T, f func(db *krabdb.DB)) {
db, err := krabdb.Connect(krabenv.DatabaseURL())
if err != nil {
t.Fatal(err)
}
defer db.Close()

defer cleanDb(db)
f(db)
}

func cleanDb(db *krabdb.DB) {
_, err := db.ExecContext(context.TODO(), `
DO
$$
DECLARE
r RECORD;
BEGIN
FOR r IN
(
SELECT table_schema, table_name
FROM information_schema.tables
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
)
LOOP
EXECUTE 'DROP TABLE ' || quote_ident(r.table_schema) || '.' || quote_ident(r.table_name) || ' CASCADE';
END LOOP;
END
$$`)

if err != nil {
panic(err)
}
}

func sqlxRowsMapScan(rows *sqlx.Rows) []map[string]interface{} {
res := []map[string]interface{}{}
for rows.Next() {
row := map[string]interface{}{}
rows.MapScan(row)
res = append(res, row)
}

return res
}
81 changes: 81 additions & 0 deletions spec/testdb_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package spec

import (
"context"
"database/sql"
"io"
"os"
"strings"
"testing"

_ "github.com/jackc/pgx/v4"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/jmoiron/sqlx"
"github.com/ohkrab/krab/krabdb"
)

type testDB struct {
db *sqlx.DB
recorder io.StringWriter
}

func (d *testDB) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
d.recorder.WriteString(query)
return d.db.SelectContext(ctx, dest, query, args...)
}

func (d *testDB) QueryContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) {
d.recorder.WriteString(query)
return d.db.QueryxContext(ctx, query, args...)
}

func (d *testDB) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
d.recorder.WriteString(query)
return d.db.ExecContext(ctx, query, args...)
}

func withPg(t *testing.T, f func(db *testDB)) {
db, err := sqlx.Connect("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
t.Fatal(err)
}
defer db.Close()

defer cleanDb(db)
f(&testDB{db: db, recorder: &strings.Builder{}})
}

func cleanDb(db krabdb.ExecerContext) {
_, err := db.ExecContext(context.TODO(), `
DO
$$
DECLARE
r RECORD;
BEGIN
FOR r IN
(
SELECT table_schema, table_name
FROM information_schema.tables
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
)
LOOP
EXECUTE 'DROP TABLE ' || quote_ident(r.table_schema) || '.' || quote_ident(r.table_name) || ' CASCADE';
END LOOP;
END
$$`)

if err != nil {
panic(err)
}
}

func sqlxRowsMapScan(rows *sqlx.Rows) []map[string]interface{} {
res := []map[string]interface{}{}
for rows.Next() {
row := map[string]interface{}{}
rows.MapScan(row)
res = append(res, row)
}

return res
}

0 comments on commit 9755cd9

Please sign in to comment.