-
Notifications
You must be signed in to change notification settings - Fork 813
/
Copy pathdrivertest.go
2338 lines (2130 loc) · 62.7 KB
/
drivertest.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The Go Cloud Development Kit Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package drivertest provides a conformance test for implementations of
// driver.
package drivertest // import "gocloud.dev/docstore/drivertest"
import (
"context"
"errors"
"fmt"
"io"
"math"
"reflect"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/google/uuid"
"gocloud.dev/docstore"
"gocloud.dev/docstore/driver"
"gocloud.dev/gcerrors"
"google.golang.org/protobuf/proto"
tspb "google.golang.org/protobuf/types/known/timestamppb"
)
// ByteArray is an array of 2 bytes.
type ByteArray [2]byte
// CollectionKind describes the kind of testing collection to create.
type CollectionKind int
const (
// SingleKey is collection with a single primary key field of type string named
// drivertest.KeyField.
SingleKey CollectionKind = iota
// TwoKey is a collection that will consist entirely of HighScore structs (see below),
// whose two primary key fields are "Game" and "Player", both strings. Use
// drivertest.HighScoreKey as the key function.
TwoKey
// AltRev is a collection that behaves like a SingleKey collection, except
// that the revision field should be drivertest.AlternateRevisionField.
AltRev
// NoRev is a collection whose documents will not have a revision field.
NoRev
)
// Harness descibes the functionality test harnesses must provide to run
// conformance tests.
type Harness interface {
// MakeCollection makes a driver.Collection for testing.
MakeCollection(context.Context, CollectionKind) (driver.Collection, error)
// BeforeDoTypes should return a list of values whose types are valid for the as
// function given to BeforeDo. For example, if the driver converts Get actions
// to *GetRequests and write actions to *WriteRequests, then BeforeDoTypes should
// return []interface{}{&GetRequest{}, &WriteRequest{}}.
// TODO(jba): consider splitting these by action kind.
BeforeDoTypes() []interface{}
// BeforeQueryTypes should return a list of values whose types are valid for the as
// function given to BeforeQuery.
BeforeQueryTypes() []interface{}
// RevisionsEqual reports whether two revisions are equal.
RevisionsEqual(rev1, rev2 interface{}) bool
// Close closes resources used by the harness.
Close()
}
// HarnessMaker describes functions that construct a harness for running tests.
// It is called exactly once per test; Harness.Close() will be called when the test is complete.
type HarnessMaker func(ctx context.Context, t *testing.T) (Harness, error)
// UnsupportedType is an enum for types not supported by native codecs. We chose
// to describe this negatively (types that aren't supported rather than types
// that are) to make the more inclusive cases easier to write. A driver can
// return nil for CodecTester.UnsupportedTypes, then add values from this enum
// one by one until all tests pass.
type UnsupportedType int
// These are known unsupported types by one or more driver. Each of them
// corresponses to an unsupported type specific test which if the driver
// actually supports.
const (
// Native codec doesn't support any unsigned integer type
Uint UnsupportedType = iota
// Native codec doesn't support arrays
Arrays
// Native codec doesn't support full time precision
NanosecondTimes
// Native codec doesn't support [][]byte
BinarySet
)
// CodecTester describes functions that encode and decode values using both the
// docstore codec for a driver, and that driver's own "native" codec.
type CodecTester interface {
UnsupportedTypes() []UnsupportedType
NativeEncode(interface{}) (interface{}, error)
NativeDecode(value, dest interface{}) error
DocstoreEncode(interface{}) (interface{}, error)
DocstoreDecode(value, dest interface{}) error
}
// AsTest represents a test of As functionality.
type AsTest interface {
// Name should return a descriptive name for the test.
Name() string
// CollectionCheck will be called to allow verification of Collection.As.
CollectionCheck(coll *docstore.Collection) error
// QueryCheck will be called after calling Query. It should call it.As and
// verify the results.
QueryCheck(it *docstore.DocumentIterator) error
// ErrorCheck is called to allow verification of Collection.ErrorAs.
ErrorCheck(c *docstore.Collection, err error) error
}
type verifyAsFailsOnNil struct{}
func (verifyAsFailsOnNil) Name() string {
return "verify As returns false when passed nil"
}
func (verifyAsFailsOnNil) CollectionCheck(coll *docstore.Collection) error {
if coll.As(nil) {
return errors.New("want Collection.As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) QueryCheck(it *docstore.DocumentIterator) error {
if it.As(nil) {
return errors.New("want DocumentIterator.As to return false when passed nil")
}
return nil
}
func (v verifyAsFailsOnNil) ErrorCheck(c *docstore.Collection, err error) (ret error) {
defer func() {
if recover() == nil {
ret = errors.New("want ErrorAs to panic when passed nil")
}
}()
c.ErrorAs(err, nil)
return nil
}
// RunConformanceTests runs conformance tests for driver implementations of docstore.
func RunConformanceTests(t *testing.T, newHarness HarnessMaker, ct CodecTester, asTests []AsTest) {
t.Helper()
t.Run("TypeDrivenCodec", func(t *testing.T) { testTypeDrivenDecode(t, ct) })
t.Run("BlindCodec", func(t *testing.T) { testBlindDecode(t, ct) })
t.Run("Create", func(t *testing.T) { withRevCollections(t, newHarness, testCreate) })
t.Run("Put", func(t *testing.T) { withRevCollections(t, newHarness, testPut) })
t.Run("Replace", func(t *testing.T) { withRevCollections(t, newHarness, testReplace) })
t.Run("Get", func(t *testing.T) { withRevCollections(t, newHarness, testGet) })
t.Run("Delete", func(t *testing.T) { withRevCollections(t, newHarness, testDelete) })
t.Run("Update", func(t *testing.T) { withRevCollections(t, newHarness, testUpdate) })
t.Run("Data", func(t *testing.T) { withCollection(t, newHarness, SingleKey, testData) })
t.Run("Proto", func(t *testing.T) { withCollection(t, newHarness, SingleKey, testProto) })
t.Run("MultipleActions", func(t *testing.T) { withRevCollections(t, newHarness, testMultipleActions) })
t.Run("GetQueryKeyField", func(t *testing.T) { withRevCollections(t, newHarness, testGetQueryKeyField) })
t.Run("SerializeRevision", func(t *testing.T) { withCollection(t, newHarness, SingleKey, testSerializeRevision) })
t.Run("ActionsOnStructNoRev", func(t *testing.T) {
withCollection(t, newHarness, NoRev, testActionsOnStructNoRev)
})
t.Run("ActionsWithCompositeID", func(t *testing.T) { withCollection(t, newHarness, TwoKey, testActionsWithCompositeID) })
t.Run("GetQuery", func(t *testing.T) { withCollection(t, newHarness, TwoKey, testGetQuery) })
t.Run("ExampleInDoc", func(t *testing.T) { withCollection(t, newHarness, NoRev, testExampleInDoc) })
t.Run("BeforeDo", func(t *testing.T) { testBeforeDo(t, newHarness) })
t.Run("BeforeQuery", func(t *testing.T) { testBeforeQuery(t, newHarness) })
asTests = append(asTests, verifyAsFailsOnNil{})
t.Run("As", func(t *testing.T) {
for _, st := range asTests {
if st.Name() == "" {
t.Fatalf("AsTest.Name is required")
}
t.Run(st.Name(), func(t *testing.T) {
withCollection(t, newHarness, TwoKey, func(t *testing.T, _ Harness, coll *docstore.Collection) {
t.Helper()
testAs(t, coll, st)
})
})
}
})
}
// withCollection calls f with a fresh harness and an empty collection of the given kind.
func withCollection(t *testing.T, newHarness HarnessMaker, kind CollectionKind, f func(*testing.T, Harness, *docstore.Collection)) {
t.Helper()
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
withColl(t, h, kind, f)
}
// withRevCollections calls f twice: once with the SingleKey collection, using documents and code that expect
// the standard revision field; and once with the AltRev collection, that uses an alternative revisionf field
// name.
func withRevCollections(t *testing.T, newHarness HarnessMaker, f func(*testing.T, *docstore.Collection, string)) {
t.Helper()
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
t.Run("StdRev", func(t *testing.T) {
withColl(t, h, SingleKey, func(t *testing.T, _ Harness, coll *docstore.Collection) {
t.Helper()
f(t, coll, docstore.DefaultRevisionField)
})
})
t.Run("AltRev", func(t *testing.T) {
withColl(t, h, AltRev, func(t *testing.T, _ Harness, coll *docstore.Collection) {
t.Helper()
f(t, coll, AlternateRevisionField)
})
})
}
// withColl calls f with h and an empty collection of the given kind. It takes care of closing
// the collection after f returns.
func withColl(t *testing.T, h Harness, kind CollectionKind, f func(*testing.T, Harness, *docstore.Collection)) {
t.Helper()
ctx := context.Background()
dc, err := h.MakeCollection(ctx, kind)
if err != nil {
t.Fatal(err)
}
coll := docstore.NewCollection(dc)
defer coll.Close()
ClearCollection(t, coll)
f(t, h, coll)
}
// KeyField is the primary key field for the main test collection.
const KeyField = "name"
// AlternateRevisionField is used for testing the option to provide a different
// name for the revision field.
const AlternateRevisionField = "Etag"
type docmap = map[string]interface{}
func newDoc(doc interface{}) interface{} {
switch v := doc.(type) {
case docmap:
return docmap{KeyField: v[KeyField]}
case *docstruct:
return &docstruct{Name: v.Name}
}
return nil
}
func key(doc interface{}) interface{} {
switch d := doc.(type) {
case docmap:
return d[KeyField]
case *docstruct:
return d.Name
}
return nil
}
func setKey(doc, key interface{}) {
switch d := doc.(type) {
case docmap:
d[KeyField] = key
case *docstruct:
d.Name = key
}
}
func revision(doc interface{}, revField string) interface{} {
switch d := doc.(type) {
case docmap:
return d[revField]
case *docstruct:
if revField == docstore.DefaultRevisionField {
return d.DocstoreRevision
}
return d.Etag
}
return nil
}
func setRevision(doc, rev interface{}, revField string) {
switch d := doc.(type) {
case docmap:
d[revField] = rev
case *docstruct:
if revField == docstore.DefaultRevisionField {
d.DocstoreRevision = rev
} else {
d.Etag = rev
}
}
}
type docstruct struct {
Name interface{} `docstore:"name"`
DocstoreRevision interface{}
Etag interface{}
I int
U uint
F float64
St string
B bool
M map[string]interface{}
}
func nonexistentDoc() docmap { return docmap{KeyField: "doesNotExist"} }
func testCreate(t *testing.T, coll *docstore.Collection, revField string) {
t.Helper()
ctx := context.Background()
for _, tc := range []struct {
name string
doc interface{}
wantErr gcerrors.ErrorCode
}{
{
name: "named map",
doc: docmap{KeyField: "testCreateMap", "b": true, revField: nil},
},
{
name: "existing",
doc: docmap{KeyField: "testCreateMap", revField: nil},
wantErr: gcerrors.AlreadyExists,
},
{
name: "unnamed map",
doc: docmap{"b": true, revField: nil},
},
{
name: "named struct",
doc: &docstruct{Name: "testCreateStruct", B: true},
},
{
name: "unnamed struct",
doc: &docstruct{B: true},
},
{
name: "empty named struct",
doc: &docstruct{Name: "", B: true},
},
{
name: "with non-nil revision",
doc: docmap{KeyField: "testCreate2", revField: 0},
wantErr: gcerrors.InvalidArgument,
},
} {
t.Run(tc.name, func(t *testing.T) {
if tc.wantErr == gcerrors.OK {
checkNoRevisionField(t, tc.doc, revField)
if err := coll.Create(ctx, tc.doc); err != nil {
t.Fatalf("Create: %v", err)
}
checkHasRevisionField(t, tc.doc, revField)
got := newDoc(tc.doc)
if err := coll.Get(ctx, got); err != nil {
t.Fatalf("Get: %v", err)
}
if diff := cmpDiff(got, tc.doc); diff != "" {
t.Fatal(diff)
}
} else {
err := coll.Create(ctx, tc.doc)
checkCode(t, err, tc.wantErr)
}
})
}
}
func testPut(t *testing.T, coll *docstore.Collection, revField string) {
t.Helper()
ctx := context.Background()
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
var maprev, strmap interface{}
for _, tc := range []struct {
name string
doc interface{}
rev bool
}{
{
name: "create map",
doc: docmap{KeyField: "testPutMap", "b": true, revField: nil},
},
{
name: "create struct",
doc: &docstruct{Name: "testPutStruct", B: true},
},
{
name: "replace map",
doc: docmap{KeyField: "testPutMap", "b": false, revField: nil},
rev: true,
},
{
name: "replace struct",
doc: &docstruct{Name: "testPutStruct", B: false},
rev: true,
},
} {
t.Run(tc.name, func(t *testing.T) {
checkNoRevisionField(t, tc.doc, revField)
must(coll.Put(ctx, tc.doc))
checkHasRevisionField(t, tc.doc, revField)
got := newDoc(tc.doc)
must(coll.Get(ctx, got))
if diff := cmpDiff(got, tc.doc); diff != "" {
t.Fatalf(diff)
}
if tc.rev {
switch v := tc.doc.(type) {
case docmap:
maprev = v[revField]
case *docstruct:
if revField == docstore.DefaultRevisionField {
strmap = v.DocstoreRevision
} else {
strmap = v.Etag
}
}
}
})
}
// Putting a doc with a revision field is the same as replace, meaning
// it will fail if the document doesn't exist.
for _, tc := range []struct {
name string
doc interface{}
}{
{
name: "replace map wrong key",
doc: docmap{KeyField: "testPutMap2", revField: maprev},
},
{
name: "replace struct wrong key",
doc: &docstruct{Name: "testPutStruct2", DocstoreRevision: strmap, Etag: strmap},
},
} {
t.Run(tc.name, func(t *testing.T) {
err := coll.Put(ctx, tc.doc)
if c := gcerrors.Code(err); c != gcerrors.NotFound && c != gcerrors.FailedPrecondition {
t.Errorf("got %v, want NotFound or FailedPrecondition", err)
}
})
}
t.Run("revision", func(t *testing.T) {
testRevisionField(t, coll, revField, func(doc interface{}) error {
return coll.Put(ctx, doc)
})
})
err := coll.Put(ctx, &docstruct{Name: ""})
checkCode(t, err, gcerrors.InvalidArgument)
}
func testReplace(t *testing.T, coll *docstore.Collection, revField string) {
t.Helper()
ctx := context.Background()
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
for _, tc := range []struct {
name string
doc1, doc2 interface{}
}{
{
name: "replace map",
doc1: docmap{KeyField: "testReplaceMap", "s": "a", revField: nil},
doc2: docmap{KeyField: "testReplaceMap", "s": "b", revField: nil},
},
{
name: "replace struct",
doc1: &docstruct{Name: "testReplaceStruct", St: "a"},
doc2: &docstruct{Name: "testReplaceStruct", St: "b"},
},
} {
t.Run(tc.name, func(t *testing.T) {
must(coll.Put(ctx, tc.doc1))
checkNoRevisionField(t, tc.doc2, revField)
must(coll.Replace(ctx, tc.doc2))
checkHasRevisionField(t, tc.doc2, revField)
got := newDoc(tc.doc2)
must(coll.Get(ctx, got))
if diff := cmpDiff(got, tc.doc2); diff != "" {
t.Fatalf(diff)
}
})
}
// Can't replace a nonexistent doc.
checkCode(t, coll.Replace(ctx, nonexistentDoc()), gcerrors.NotFound)
t.Run("revision", func(t *testing.T) {
testRevisionField(t, coll, revField, func(doc interface{}) error {
return coll.Replace(ctx, doc)
})
})
}
// Check that doc does not have a revision field (or has a nil one).
func checkNoRevisionField(t *testing.T, doc interface{}, revField string) {
t.Helper()
ddoc, err := driver.NewDocument(doc)
if err != nil {
t.Fatal(err)
}
if rev, _ := ddoc.GetField(revField); rev != nil {
t.Fatal("doc has revision field")
}
}
// Check that doc has a non-nil revision field.
func checkHasRevisionField(t *testing.T, doc interface{}, revField string) {
t.Helper()
ddoc, err := driver.NewDocument(doc)
if err != nil {
t.Fatal(err)
}
if rev, err := ddoc.GetField(revField); err != nil || rev == nil {
t.Fatalf("doc missing revision field (error = %v)", err)
}
}
func testGet(t *testing.T, coll *docstore.Collection, revField string) {
t.Helper()
ctx := context.Background()
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
for _, tc := range []struct {
name string
doc interface{}
fps []docstore.FieldPath
want interface{}
}{
// If Get is called with no field paths, the full document is populated.
{
name: "get map",
doc: docmap{
KeyField: "testGetMap",
"s": "a string",
"i": int64(95),
"f": 32.3,
"m": map[string]interface{}{"a": "one", "b": "two"},
revField: nil,
},
},
{
name: "get struct",
doc: &docstruct{
Name: "testGetStruct",
St: "a string",
I: 95,
F: 32.3,
M: map[string]interface{}{"a": "one", "b": "two"},
},
},
// If Get is called with field paths, the resulting document has only those fields.
{
name: "get map with field path",
doc: docmap{
KeyField: "testGetMapFP",
"s": "a string",
"i": int64(95),
"f": 32.3,
"m": map[string]interface{}{"a": "one", "b": "two"},
revField: nil,
},
fps: []docstore.FieldPath{"f", "m.b", docstore.FieldPath(revField)},
want: docmap{
KeyField: "testGetMapFP",
"f": 32.3,
"m": map[string]interface{}{"b": "two"},
},
},
{
name: "get struct with field path",
doc: &docstruct{
Name: "testGetStructFP",
St: "a string",
I: 95,
F: 32.3,
M: map[string]interface{}{"a": "one", "b": "two"},
},
fps: []docstore.FieldPath{"St", "M.a", docstore.FieldPath(revField)},
want: &docstruct{
Name: "testGetStructFP",
St: "a string",
M: map[string]interface{}{"a": "one"},
},
},
{
name: "get struct wrong case",
doc: &docstruct{
Name: "testGetStructWC",
St: "a string",
I: 95,
F: 32.3,
M: map[string]interface{}{"a": "one", "b": "two"},
},
fps: []docstore.FieldPath{"st", "m.a"},
want: &docstruct{
Name: "testGetStructWC",
},
},
} {
t.Run(tc.name, func(t *testing.T) {
must(coll.Put(ctx, tc.doc))
got := newDoc(tc.doc)
must(coll.Get(ctx, got, tc.fps...))
if tc.want == nil {
tc.want = tc.doc
}
setRevision(tc.want, revision(got, revField), revField)
if diff := cmpDiff(got, tc.want); diff != "" {
t.Error("Get with field paths:\n", diff)
}
})
}
err := coll.Get(ctx, nonexistentDoc())
checkCode(t, err, gcerrors.NotFound)
err = coll.Get(ctx, &docstruct{Name: ""})
checkCode(t, err, gcerrors.InvalidArgument)
}
func testDelete(t *testing.T, coll *docstore.Collection, revField string) {
t.Helper()
ctx := context.Background()
var rev interface{}
for _, tc := range []struct {
name string
doc interface{}
wantErr gcerrors.ErrorCode
}{
{
name: "delete map",
doc: docmap{KeyField: "testDeleteMap", revField: nil},
},
{
name: "delete map wrong rev",
doc: docmap{KeyField: "testDeleteMap", "b": true, revField: nil},
wantErr: gcerrors.FailedPrecondition,
},
{
name: "delete struct",
doc: &docstruct{Name: "testDeleteStruct"},
},
{
name: "delete struct wrong rev",
doc: &docstruct{Name: "testDeleteStruct", B: true},
wantErr: gcerrors.FailedPrecondition,
},
} {
t.Run(tc.name, func(t *testing.T) {
if err := coll.Put(ctx, tc.doc); err != nil {
t.Fatal(err)
}
if tc.wantErr == gcerrors.OK {
rev = revision(tc.doc, revField)
if err := coll.Delete(ctx, tc.doc); err != nil {
t.Fatal(err)
}
// The document should no longer exist.
if err := coll.Get(ctx, tc.doc); err == nil {
t.Error("want error, got nil")
}
} else {
setRevision(tc.doc, rev, revField)
checkCode(t, coll.Delete(ctx, tc.doc), gcerrors.FailedPrecondition)
}
})
}
// Delete doesn't fail if the doc doesn't exist.
if err := coll.Delete(ctx, nonexistentDoc()); err != nil {
t.Errorf("delete nonexistent doc: want nil, got %v", err)
}
err := coll.Delete(ctx, &docstruct{Name: ""})
checkCode(t, err, gcerrors.InvalidArgument)
}
func testUpdate(t *testing.T, coll *docstore.Collection, revField string) {
t.Helper()
ctx := context.Background()
for _, tc := range []struct {
name string
doc interface{}
mods docstore.Mods
want interface{}
}{
{
name: "update map",
doc: docmap{KeyField: "testUpdateMap", "a": "A", "b": "B", "n": 3.5, "i": 1, revField: nil},
mods: docstore.Mods{
"a": "X",
"b": nil,
"c": "C",
"n": docstore.Increment(-1),
"i": nil,
"m": 3,
},
want: docmap{KeyField: "testUpdateMap", "a": "X", "c": "C", "n": 2.5, "m": int64(3)},
},
{
name: "update map overwrite only",
doc: docmap{KeyField: "testUpdateMapWrt", "a": "A", revField: nil},
mods: docstore.Mods{
"a": "X",
"b": nil,
"m": 3,
},
want: docmap{KeyField: "testUpdateMapWrt", "a": "X", "m": int64(3)},
},
{
name: "update map increment only",
doc: docmap{KeyField: "testUpdateMapInc", "a": "A", "n": 3.5, "i": 1, revField: nil},
mods: docstore.Mods{
"n": docstore.Increment(-1),
"i": docstore.Increment(2.5),
"m": docstore.Increment(3),
},
want: docmap{KeyField: "testUpdateMapInc", "a": "A", "n": 2.5, "i": 3.5, "m": int64(3)},
},
{
name: "update struct",
doc: &docstruct{Name: "testUpdateStruct", St: "st", I: 1, F: 3.5},
mods: docstore.Mods{
"St": "str",
"I": nil,
"U": 4,
"F": docstore.Increment(-3),
},
want: &docstruct{Name: "testUpdateStruct", St: "str", U: 4, F: 0.5},
},
{
name: "update struct overwrite only",
doc: &docstruct{Name: "testUpdateStructWrt", St: "st", I: 1},
mods: docstore.Mods{
"St": "str",
"I": nil,
"U": 4,
},
want: &docstruct{Name: "testUpdateStructWrt", St: "str", U: 4},
},
{
name: "update struct increment only",
doc: &docstruct{Name: "testUpdateStructInc", St: "st", I: 1, F: 3.5},
mods: docstore.Mods{
"U": docstore.Increment(4),
"F": docstore.Increment(-3),
},
want: &docstruct{Name: "testUpdateStructInc", St: "st", U: 4, I: 1, F: 0.5},
},
} {
t.Run(tc.name, func(t *testing.T) {
if err := coll.Put(ctx, tc.doc); err != nil {
t.Fatal(err)
}
setRevision(tc.doc, nil, revField)
got := newDoc(tc.doc)
checkNoRevisionField(t, tc.doc, revField)
errs := coll.Actions().Update(tc.doc, tc.mods).Get(got).Do(ctx)
if errs != nil {
t.Fatal(errs)
}
checkHasRevisionField(t, tc.doc, revField)
setRevision(tc.want, revision(got, revField), revField)
if diff := cmp.Diff(got, tc.want, cmpopts.IgnoreUnexported(tspb.Timestamp{})); diff != "" {
t.Error(diff)
}
})
}
// Can't update a nonexistent doc.
if err := coll.Update(ctx, nonexistentDoc(), docstore.Mods{"x": "y"}); err == nil {
t.Error("nonexistent document: got nil, want error")
}
// Bad increment value.
err := coll.Update(ctx, docmap{KeyField: "update invalid"}, docstore.Mods{"x": docstore.Increment("3")})
checkCode(t, err, gcerrors.InvalidArgument)
t.Run("revision", func(t *testing.T) {
testRevisionField(t, coll, revField, func(doc interface{}) error {
return coll.Update(ctx, doc, docstore.Mods{"s": "c"})
})
})
}
// Test that:
// - Writing a document with a revision field succeeds if the document hasn't changed.
// - Writing a document with a revision field fails if the document has changed.
func testRevisionField(t *testing.T, coll *docstore.Collection, revField string, write func(interface{}) error) {
t.Helper()
ctx := context.Background()
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
for _, tc := range []struct {
name string
doc interface{}
}{
{
name: "map revision",
doc: docmap{KeyField: "testRevisionMap", "s": "a", revField: nil},
},
{
name: "struct revision",
doc: &docstruct{Name: "testRevisionStruct", St: "a"},
},
} {
t.Run(tc.name, func(t *testing.T) {
must(coll.Put(ctx, tc.doc))
got := newDoc(tc.doc)
must(coll.Get(ctx, got))
rev := revision(got, revField)
if rev == nil {
t.Fatal("missing revision field")
}
// A write should succeed, because the document hasn't changed since it was gotten.
if err := write(tc.doc); err != nil {
t.Fatalf("write with revision field got %v, want nil", err)
}
// This write should fail: got's revision field hasn't changed, but the stored document has.
err := write(got)
if c := gcerrors.Code(err); c != gcerrors.FailedPrecondition && c != gcerrors.NotFound {
t.Errorf("write with old revision field: got %v, wanted FailedPrecondition or NotFound", err)
}
})
}
}
// Verify that the driver can serialize and deserialize revisions.
func testSerializeRevision(t *testing.T, h Harness, coll *docstore.Collection) {
t.Helper()
ctx := context.Background()
doc := docmap{KeyField: "testSerializeRevision", "x": 1, docstore.DefaultRevisionField: nil}
if err := coll.Create(ctx, doc); err != nil {
t.Fatal(err)
}
want := doc[docstore.DefaultRevisionField]
if want == nil {
t.Fatal("nil revision")
}
s, err := coll.RevisionToString(want)
if err != nil {
t.Fatal(err)
}
got, err := coll.StringToRevision(s)
if err != nil {
t.Fatal(err)
}
if !h.RevisionsEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
}
// Test all Go integer types are supported, and they all come back as int64.
func testData(t *testing.T, _ Harness, coll *docstore.Collection) {
t.Helper()
ctx := context.Background()
for _, test := range []struct {
in, want interface{}
}{
{int(-1), int64(-1)},
{int8(-8), int64(-8)},
{int16(-16), int64(-16)},
{int32(-32), int64(-32)},
{int64(-64), int64(-64)},
{uint(1), int64(1)},
{uint8(8), int64(8)},
{uint16(16), int64(16)},
{uint32(32), int64(32)},
{uint64(64), int64(64)},
{float32(3.5), float64(3.5)},
{[]byte{0, 1, 2}, []byte{0, 1, 2}},
} {
doc := docmap{KeyField: "testData", "val": test.in}
got := docmap{KeyField: doc[KeyField]}
if errs := coll.Actions().Put(doc).Get(got).Do(ctx); errs != nil {
t.Fatal(errs)
}
want := docmap{
"val": test.want,
KeyField: doc[KeyField],
}
if len(got) != len(want) {
t.Errorf("%v: got %v, want %v", test.in, got, want)
} else if g := got["val"]; !cmp.Equal(g, test.want) {
t.Errorf("%v: got %v (%T), want %v (%T)", test.in, g, g, test.want, test.want)
}
}
// TODO: strings: valid vs. invalid unicode
}
var (
// A time with non-zero milliseconds, but zero nanoseconds.
milliTime = time.Date(2019, time.March, 27, 0, 0, 0, 5*1e6, time.UTC)
// A time with non-zero nanoseconds.
nanoTime = time.Date(2019, time.March, 27, 0, 0, 0, 5*1e6+7, time.UTC)
)
// Test that encoding from a struct and then decoding into the same struct works properly.
// The decoding is "type-driven" because the decoder knows the expected type of the value
// it is decoding--it is the type of a struct field.
func testTypeDrivenDecode(t *testing.T, ct CodecTester) {
t.Helper()
if ct == nil {
t.Skip("no CodecTester")
}
check := func(in, dec interface{}, encode func(interface{}) (interface{}, error), decode func(interface{}, interface{}) error) {
t.Helper()
enc, err := encode(in)
if err != nil {
t.Fatalf("%+v", err)
}
if err := decode(enc, dec); err != nil {
t.Fatalf("%+v", err)
}
if diff := cmp.Diff(in, dec); diff != "" {
t.Error(diff)
}
}
s := "bar"
dsrt := &docstoreRoundTrip{
N: nil,