Skip to content

Commit

Permalink
Added testtx
Browse files Browse the repository at this point in the history
  • Loading branch information
aneshas committed Mar 17, 2024
1 parent 5697c10 commit 50dc32e
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,5 +138,9 @@ This way, your infrastructural concerns stay in the infrastructure layer where t

*Please note that this is only one way of using the abstraction*

## Testing
You can use `testtx.New()` as a convenient test helper. It creates a test transactor which only calls f without
setting any sort of transaction in the `ctx` and preserves any errors raised by f in `.Err` field.

## Next up
- [ ] Add a way to configure transaction isolation levels for individual drivers eg. `pgxtx.NewDBFromPool(pool, ...opts)`
- Add isolation level configuration for individual drivers eg. through `pgxtx.NewDBFromPool(pool, ...opts)`
17 changes: 17 additions & 0 deletions testtx/testtx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package testtx

import "context"

func New() *TX {
return &TX{}
}

type TX struct {
Err error
}

func (t *TX) WithTransaction(ctx context.Context, f func(ctx context.Context) error) error {
t.Err = f(ctx)

return t.Err
}
52 changes: 52 additions & 0 deletions testtx/testtx_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package testtx_test

import (
"context"
"fmt"
"github.com/aneshas/tx/v2"
"github.com/aneshas/tx/v2/testtx"
"github.com/stretchr/testify/assert"
"testing"
)

type svc struct {
tx.Transactor

DidSomething bool
}

func (s *svc) doSomething(ctx context.Context, err error) error {
return s.WithTransaction(ctx, func(ctx context.Context) error {
s.DidSomething = true

return err
})
}

func TestShould_Delegate_Call(t *testing.T) {
transactor := testtx.New()

s := &svc{
Transactor: transactor,
}

err := s.doSomething(context.TODO(), nil)

assert.NoError(t, err)
assert.True(t, s.DidSomething)
}

func TestShould_Save_Err(t *testing.T) {
transactor := testtx.New()

s := &svc{
Transactor: transactor,
}

wantErr := fmt.Errorf("something bad ocurred")

err := s.doSomething(context.TODO(), wantErr)

assert.ErrorIs(t, err, wantErr)
assert.ErrorIs(t, transactor.Err, wantErr)
}

0 comments on commit 50dc32e

Please sign in to comment.