Skip to content

Commit

Permalink
Refactor TestFactory
Browse files Browse the repository at this point in the history
- Reduce complexity of New func
- Remove closures, use regular methods
- Extract code into MockDB func
  • Loading branch information
diyan committed Feb 13, 2017
1 parent d3af6a1 commit 00e1223
Showing 1 changed file with 40 additions and 31 deletions.
71 changes: 40 additions & 31 deletions testutil/factory/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,48 +13,57 @@ import (
)

type TestFactory struct {
t *testing.T
tx *dbr.Tx
Reset func()
SaveOrganization func(org models.Organization)
SaveProject func(project models.Project)
SaveTags func(tags ...*models.TagKey)
t *testing.T
tx *dbr.Tx
ctx echo.Context
}

func New(t *testing.T, server *echo.Echo) TestFactory {
noError := require.New(t).NoError
ctx := server.NewContext(nil, nil)
// TODO remove hack
ctx.Set("conf.Config", MakeAppConfig())
tx, err := db.GetTx(ctx)
tx, err := db.New(MakeAppConfig())
noError(err)
MockDB(server, tx)
ctx := server.NewContext(nil, nil)
db.ToE(ctx, tx)
tf := TestFactory{
t: t,
tx: tx,
}
tf.Reset = func() {
err := tf.tx.Rollback()
noError(err)
t: t,
tx: tx,
ctx: ctx,
}
return tf
}

func (tf TestFactory) noError(err error, msgAndArgs ...interface{}) {
require.New(tf.t).NoError(err, msgAndArgs)
}

func (tf TestFactory) Reset() {
err := tf.tx.Rollback()
tf.noError(err)
}

func (tf TestFactory) SaveOrganization(org models.Organization) {
orgStore := store.NewOrganizationStore(tf.ctx)
tf.noError(orgStore.SaveOrganization(org))
}

func (tf TestFactory) SaveProject(project models.Project) {
projectStore := store.NewProjectStore(tf.ctx)
tf.noError(projectStore.SaveProject(project))
}

func (tf TestFactory) SaveTags(tags ...*models.TagKey) {
projectStore := store.NewProjectStore(tf.ctx)
tf.noError(projectStore.SaveTags(tags...))
}

// TODO Tricky implementation. Mock *dbr.Tx in the test Echo instance
// MockDB adds early middleware that mock DB transaction to the test Echo instance
// TODO consider move this to the db or db_test package
func MockDB(server *echo.Echo, tx *dbr.Tx) {
server.Pre(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Set("dbr.Tx", tx)
db.ToE(c, tx)
return next(c)
}
})

orgStore := store.NewOrganizationStore(ctx)
projectStore := store.NewProjectStore(ctx)
tf.SaveOrganization = func(org models.Organization) {
noError(orgStore.SaveOrganization(org))
}
tf.SaveProject = func(project models.Project) {
noError(projectStore.SaveProject(project))
}
tf.SaveTags = func(tags ...*models.TagKey) {
noError(projectStore.SaveTags(tags...))
}
return tf
}

0 comments on commit 00e1223

Please sign in to comment.