3
0

Prepate compose repository test framework

This commit is contained in:
Denis Arh 2019-05-14 11:34:16 +02:00
parent a80e45e4a1
commit 88d759ad19
2 changed files with 77 additions and 4 deletions

View File

@ -0,0 +1,56 @@
// +build integration
package repository
import (
"os"
"testing"
"time"
"github.com/namsral/flag"
"github.com/titpetric/factory"
"go.uber.org/zap/zapcore"
"github.com/crusttech/crust/internal/logger"
)
func TestMain(m *testing.M) {
logger.Init(zapcore.DebugLevel)
dsn := ""
flag.StringVar(&dsn, "compose-db-dsn", "", "")
flag.Parse()
factory.Database.Add("compose", dsn)
os.Exit(m.Run())
}
// zapProfiler logs query statistics to zap.logger
type (
testLogProfiler struct {
logger testProfilerLogger
}
testProfilerLogger interface {
Logf(format string, args ...interface{})
}
)
func newTestLogProfiler(logger testProfilerLogger) *testLogProfiler {
return &testLogProfiler{
logger: logger,
}
}
// Post prints the query statistics to stdout
func (p testLogProfiler) Post(c *factory.DatabaseProfilerContext) {
p.logger.Logf(
"%s\nArgs: %v\nDuration: %fs",
c.Query,
c.Args,
time.Since(c.Time).Seconds(),
)
}
// Flush stdout (no-op for this profiler)
func (testLogProfiler) Flush() {}

View File

@ -6,6 +6,9 @@ import (
"context"
"testing"
"github.com/titpetric/factory"
"github.com/crusttech/crust/compose/types"
"github.com/crusttech/crust/internal/test"
)
@ -14,16 +17,30 @@ func TestRepository(t *testing.T) {
repo.With(context.Background(), nil)
}
func tx(t *testing.T, f func() error) {
var err error
db := DB(context.Background())
func tx(t *testing.T, f func(context.Context, *factory.DB, *types.Namespace) error) {
var (
err error
ctx = context.Background()
db = DB(ctx)
ns *types.Namespace
)
err = db.Begin()
test.Assert(t, err == nil, "Could not begin transaction: %+v", err)
err = f()
ns, err = Namespace(ctx, db).Create(&types.Namespace{})
test.Assert(t, err == nil, "Test transaction setup (namespace creation) resulted in an error: %+v", err)
// Setup test log profiler and route all db logs to test log facility
// We do this right after transaction is started and setup is done, no need for extra queries there...
db.Profiler = newTestLogProfiler(t)
err = f(ctx, db, ns)
test.Assert(t, err == nil, "Test transaction resulted in an error: %+v", err)
// Remove profiler to omit final rollback statement in the logs
db.Profiler = nil
err = db.Rollback()
test.Assert(t, err == nil, "Could not rollback transaction: %+v", err)
}