-
Notifications
You must be signed in to change notification settings - Fork 1
/
repo_test.go
99 lines (86 loc) · 2.32 KB
/
repo_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
97
98
99
package xmongo_test
import (
"context"
"fmt"
"sync"
"testing"
"time"
"github.com/caiyunapp/xmongo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Record struct {
OID primitive.ObjectID `bson:"_id"`
Msg string `bson:"msg"`
}
var repo *xmongo.Repo[Record]
const (
databaseName = "foo"
collectionName = "bar"
)
func init() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
panic(err)
}
repo, _ = xmongo.NewRepo[Record](client.Database(databaseName).Collection(collectionName))
}
var (
insertOnce = &sync.Once{}
insertManyOnce = &sync.Once{}
)
func TestRepoInsertOne(t *testing.T) {
insertOnce.Do(func() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err := repo.InsertOne(ctx, Record{OID: primitive.NewObjectID(), Msg: "insert_one"})
if err != nil {
t.Fatal(err)
}
})
}
func TestRepoInsertMany(t *testing.T) {
insertManyOnce.Do(func() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err := repo.InsertMany(ctx, []Record{
{OID: primitive.NewObjectID(), Msg: "insert_many_1"},
{OID: primitive.NewObjectID(), Msg: "insert_many_2"},
{OID: primitive.NewObjectID(), Msg: "insert_many_3"},
})
if err != nil {
t.Fatal(err)
}
})
}
func TestRepoFindOne(t *testing.T) {
TestRepoInsertOne(t)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err := repo.FindOne(ctx, &bson.M{})
if err != nil {
t.Fatal(err)
}
}
func TestRepoFind(t *testing.T) {
TestRepoInsertMany(t)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
c := int64(3)
_, err := repo.Find(ctx, &bson.M{}, &options.FindOptions{Limit: &c})
if err != nil {
t.Fatal(err)
}
}
func ExampleRepo() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
fmt.Println(repo.FindOne(ctx, bson.M{}))
fmt.Println(repo.Find(ctx, bson.M{}))
insertRes, err := repo.InsertOne(ctx, Record{OID: primitive.NewObjectID(), Msg: "insert_one"})
fmt.Println(insertRes, err)
}