generated from sv-tools/go-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsession_test.go
79 lines (67 loc) · 1.88 KB
/
session_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
package mongoifc_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"github.com/sv-tools/mongoifc"
)
func TestSession_WithTransaction(t *testing.T) {
t.Parallel()
cl := connect(t)
sess, err := cl.StartSession()
require.NoError(t, err)
t.Cleanup(func() {
sess.EndSession(context.Background())
})
name := fmt.Sprintf("test_%d", time.Now().Unix())
res, err := sess.WithTransaction(context.Background(), func(sc mongoifc.SessionContext) (interface{}, error) {
return cl.
Database(name).
Collection("test-with").
InsertOne(sc, bson.M{"foo": "bar"})
})
require.NoError(t, err)
require.NotNil(t, res.(*mongo.InsertOneResult).InsertedID)
n, err := cl.
Database(name).
Collection("test-with").
CountDocuments(context.Background(), bson.M{"foo": "bar"})
require.NoError(t, err)
require.Equal(t, int64(1), n)
}
func TestSession_StartAndAbortTransaction(t *testing.T) {
t.Parallel()
cl := connect(t)
name := fmt.Sprintf("test_%d", time.Now().Unix())
err := cl.UseSession(context.Background(), func(sc mongoifc.SessionContext) error {
err := sc.StartTransaction()
require.NoError(t, err)
res, err := cl.
Database(name).
Collection("test-start-abort").
InsertOne(sc, bson.M{"foo": "bar"})
require.NoError(t, err)
require.NotNil(t, res.InsertedID)
return sc.AbortTransaction(sc)
})
require.NoError(t, err)
n, err := cl.
Database(name).
Collection("test-start-abort").
CountDocuments(context.Background(), bson.M{"foo": "bar"})
require.NoError(t, err)
require.Zero(t, n)
}
func TestWrapSession_UnWrapSession(t *testing.T) {
t.Parallel()
cl := connect(t)
mcl := mongoifc.UnWrapClient(cl)
orig, err := mcl.StartSession()
require.NoError(t, err)
wrapped := mongoifc.WrapSession(orig)
require.Equal(t, orig, mongoifc.UnWrapSession(wrapped))
}