/
firestore_test.go
79 lines (66 loc) · 1.68 KB
/
firestore_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 firestore
import (
"cloud.google.com/go/firestore"
"context"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"testing"
)
type Person struct {
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
}
type emulatorCreds struct {
}
func (ec emulatorCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{"authorization": "Bearer owner"}, nil
}
func (ec emulatorCreds) RequireTransportSecurity() bool {
return false
}
func TestFirestore(t *testing.T) {
ctx := context.Background()
container, err := setupFirestore(ctx)
if err != nil {
t.Fatal(err)
}
// Clean up the container after the test is complete
t.Cleanup(func() {
if err := container.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
})
conn, err := grpc.Dial(container.URI, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithPerRPCCredentials(emulatorCreds{}))
if err != nil {
t.Fatal(err)
}
options := []option.ClientOption{option.WithGRPCConn(conn)}
client, err := firestore.NewClient(ctx, "test-project", options...)
if err != nil {
t.Fatal(err)
}
defer client.Close()
users := client.Collection("users")
docRef := users.Doc("alovelace")
data := Person{
Firstname: "Ada",
Lastname: "Lovelace",
}
_, err = docRef.Create(ctx, data)
if err != nil {
t.Fatal(err)
}
// perform assertions
docsnap, err := docRef.Get(ctx)
if err != nil {
t.Fatal(err)
}
var saved Person
if err := docsnap.DataTo(&saved); err != nil {
t.Fatal(err)
}
if saved != data {
t.Fatalf("Expected value %s. Got %s.", data, saved)
}
}