-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsession_test.go
More file actions
80 lines (68 loc) · 1.88 KB
/
session_test.go
File metadata and controls
80 lines (68 loc) · 1.88 KB
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
package mongoifc_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"github.com/sv-tools/mongoifc/v2"
)
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.WithoutCancel(t.Context()))
})
name := fmt.Sprintf("test_%d", time.Now().Unix())
res, err := sess.WithTransaction(t.Context(), func(ctx context.Context) (any, error) {
return cl.
Database(name).
Collection("test-with").
InsertOne(ctx, bson.M{"foo": "bar"})
})
require.NoError(t, err)
require.NotNil(t, res.(*mongo.InsertOneResult).InsertedID)
n, err := cl.
Database(name).
Collection("test-with").
CountDocuments(t.Context(), 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(t.Context(), func(ctx context.Context) error {
sc := mongo.SessionFromContext(ctx)
err := sc.StartTransaction()
require.NoError(t, err)
res, err := cl.
Database(name).
Collection("test-start-abort").
InsertOne(ctx, bson.M{"foo": "bar"})
require.NoError(t, err)
require.NotNil(t, res.InsertedID)
return sc.AbortTransaction(ctx)
})
require.NoError(t, err)
n, err := cl.
Database(name).
Collection("test-start-abort").
CountDocuments(t.Context(), 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))
}