-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext_test.go
96 lines (84 loc) · 2.41 KB
/
context_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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package transaction
import (
"context"
"database/sql"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
type mockConn struct {
id string
}
func (m *mockConn) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
return nil, nil
}
func (m *mockConn) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {
return nil, nil
}
func (m *mockConn) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
return nil, nil
}
func (m *mockConn) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
return nil
}
func newMockConn(id string) Conn {
return &mockConn{id: id}
}
func TestGetTransactionFromContext(t *testing.T) {
// Iterate over the test cases directly in the for loop
for name, tt := range map[string]struct {
ctx context.Context
want Conn
}{
"get existing transaction": {
ctx: context.WithValue(context.Background(), transactionKey{}, newMockConn("txn1")),
want: newMockConn("txn1"),
},
"no transaction in context": {
ctx: context.Background(),
want: nil,
},
"wrong type in context": {
ctx: context.WithValue(context.Background(), transactionKey{}, "invalid type"),
want: nil,
},
} {
t.Run(name, func(t *testing.T) {
got := getTransactionFromContext(tt.ctx)
if diff := cmp.Diff(got, tt.want, cmpopts.IgnoreUnexported(mockConn{})); diff != "" {
t.Errorf("\n(-got +want)\n%s", diff)
}
})
}
}
func TestSetTransactionToContext(t *testing.T) {
for name, tt := range map[string]struct {
initialCtx context.Context
setTxn Conn
want Conn
}{
"set new transaction in context": {
initialCtx: context.Background(),
setTxn: newMockConn("txn2"),
want: newMockConn("txn2"),
},
"transaction already in context, should not overwrite": {
initialCtx: context.WithValue(context.Background(), transactionKey{}, newMockConn("txn3")),
setTxn: newMockConn("txn4"),
want: newMockConn("txn3"),
},
"set nil transaction": {
initialCtx: context.Background(),
setTxn: nil,
want: nil,
},
} {
t.Run(name, func(t *testing.T) {
ctx := setTransactionToContext(tt.initialCtx, tt.setTxn)
got := getTransactionFromContext(ctx)
if diff := cmp.Diff(got, tt.want, cmpopts.IgnoreUnexported(mockConn{})); diff != "" {
t.Errorf("\n(-got +want)\n%s", diff)
}
})
}
}