-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtx_test.go
61 lines (50 loc) · 1.52 KB
/
tx_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package azamat
import (
"fmt"
"testing"
"github.com/jmoiron/sqlx"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Not sure if this test is actually useful or how to better test this...
// The function CommitTransaction follows a pattern that seems to be pretty common
// for gophers:
// - https://entgo.io/docs/transactions#best-practices
// - https://pseudomuto.com/2018/01/clean-sql-transactions-in-golang/
// - https://stackoverflow.com/questions/16184238/database-sql-tx-detecting-commit-or-rollback
func TestCommitTransaction(t *testing.T) {
db, _ := sqlx.Open("sqlite3", ":memory:")
type Todo struct {
ID int
Title string
}
db.MustExec(`CREATE TABLE todos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL
)`)
// When transaction has an error...
err := CommitTransaction(db, func(tx *sqlx.Tx) error {
return fmt.Errorf("999 syntax error")
})
require.Error(t, err)
// Make sure we can still query table
// When transaction panics...
assert.Panics(t, func() {
err = CommitTransaction(db, func(tx *sqlx.Tx) error {
panic("999 syntax error")
})
})
require.Error(t, err)
// Make sure we can still query table
// Simple transaction...
err = CommitTransaction(db, func(tx *sqlx.Tx) error {
_, err = tx.Exec("INSERT INTO todos (title) VALUES ('very nice')")
require.NoError(t, err)
return err
})
require.NoError(t, err)
// Make sure entry was actually inserted
var rows []Todo
db.Select(&rows, "SELECT * FROM todos")
require.Len(t, rows, 1)
}