Debian Codegraph @

docstore/drivertest/drivertest.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package drivertest provides a conformance test for implementations of
16 // driver.
17 package drivertest // import "gocloud.dev/docstore/drivertest"
18
19 import (
20 "context"
21 "errors"
22 "fmt"
23 "io"
24 "maps"
25 "math"
26 "reflect"
27 "strings"
28 "testing"
29 "time"
30
31 "github.com/google/go-cmp/cmp"
32 "github.com/google/go-cmp/cmp/cmpopts"
33 "github.com/google/uuid"
34 "gocloud.dev/docstore"
35 "gocloud.dev/docstore/driver"
36 "gocloud.dev/gcerrors"
37 "google.golang.org/protobuf/proto"
38 tspb "google.golang.org/protobuf/types/known/timestamppb"
39 )
40
41 // ByteArray is an array of 2 bytes.
42 type ByteArray [2]byte
43
44 // CollectionKind describes the kind of testing collection to create.
45 type CollectionKind int
46
47 const (
48 // SingleKey is collection with a single primary key field of type string named
49 // drivertest.KeyField.
50 SingleKey CollectionKind = iota
51
52 // TwoKey is a collection that will consist entirely of HighScore structs (see below),
53 // whose two primary key fields are "Game" and "Player", both strings. Use
54 // drivertest.HighScoreKey as the key function.
55 TwoKey
56
57 // AltRev is a collection that behaves like a SingleKey collection, except
58 // that the revision field should be drivertest.AlternateRevisionField.
59 AltRev
60
61 // NoRev is a collection whose documents will not have a revision field.
62 NoRev
63 )
64
65 // Harness descibes the functionality test harnesses must provide to run
66 // conformance tests.
67 type Harness interface {
68 // MakeCollection makes a driver.Collection for testing.
69 MakeCollection(context.Context, CollectionKind) (driver.Collection, error)
70
71 // BeforeDoTypes should return a list of values whose types are valid for the as
72 // function given to BeforeDo. For example, if the driver converts Get actions
73 // to *GetRequests and write actions to *WriteRequests, then BeforeDoTypes should
74 // return []interface{}{&GetRequest{}, &WriteRequest{}}.
75 // TODO(jba): consider splitting these by action kind.
76 BeforeDoTypes() []any
77
78 // BeforeQueryTypes should return a list of values whose types are valid for the as
79 // function given to BeforeQuery.
80 BeforeQueryTypes() []any
81
82 // RevisionsEqual reports whether two revisions are equal.
83 RevisionsEqual(rev1, rev2 any) bool
84
85 // SupportsAtomicWrites should report if a collection supports atomic writes
86 SupportsAtomicWrites() bool
87
88 // Close closes resources used by the harness.
89 Close()
90 }
91
92 // HarnessMaker describes functions that construct a harness for running tests.
93 // It is called exactly once per test; Harness.Close() will be called when the test is complete.
94 type HarnessMaker func(ctx context.Context, t *testing.T) (Harness, error)
95
96 // UnsupportedType is an enum for types not supported by native codecs. We chose
97 // to describe this negatively (types that aren't supported rather than types
98 // that are) to make the more inclusive cases easier to write. A driver can
99 // return nil for CodecTester.UnsupportedTypes, then add values from this enum
100 // one by one until all tests pass.
101 type UnsupportedType int
102
103 // These are known unsupported types by one or more driver. Each of them
104 // corresponses to an unsupported type specific test which if the driver
105 // actually supports.
106 const (
107 // Native codec doesn't support any unsigned integer type
108 Uint UnsupportedType = iota
109 // Native codec doesn't support arrays
110 Arrays
111 // Native codec doesn't support full time precision
112 NanosecondTimes
113 // Native codec doesn't support [][]byte
114 BinarySet
115 )
116
117 // CodecTester describes functions that encode and decode values using both the
118 // docstore codec for a driver, and that driver's own "native" codec.
119 type CodecTester interface {
120 UnsupportedTypes() []UnsupportedType
121 NativeEncode(any) (any, error)
122 NativeDecode(value, dest any) error
123 DocstoreEncode(any) (any, error)
124 DocstoreDecode(value, dest any) error
125 }
126
127 // AsTest represents a test of As functionality.
128 type AsTest interface {
129 // Name should return a descriptive name for the test.
130 Name() string
131 // CollectionCheck will be called to allow verification of Collection.As.
132 CollectionCheck(coll *docstore.Collection) error
133 // QueryCheck will be called after calling Query. It should call it.As and
134 // verify the results.
135 QueryCheck(it *docstore.DocumentIterator) error
136 // ErrorCheck is called to allow verification of Collection.ErrorAs.
137 ErrorCheck(c *docstore.Collection, err error) error
138 }
139
140 type verifyAsFailsOnNil struct{}
141
142 func (verifyAsFailsOnNil) Name() string {
143 return "verify As returns false when passed nil"
144 }
145
146 func (verifyAsFailsOnNil) CollectionCheck(coll *docstore.Collection) error {
147 if coll.As(nil) {
148 return errors.New("want Collection.As to return false when passed nil")
149 }
150 return nil
151 }
152
153 func (verifyAsFailsOnNil) QueryCheck(it *docstore.DocumentIterator) error {
154 if it.As(nil) {
155 return errors.New("want DocumentIterator.As to return false when passed nil")
156 }
157 return nil
158 }
159
160 func (v verifyAsFailsOnNil) ErrorCheck(c *docstore.Collection, err error) (ret error) {
161 defer func() {
162 if recover() == nil {
163 ret = errors.New("want ErrorAs to panic when passed nil")
164 }
165 }()
166 c.ErrorAs(err, nil)
167 return nil
168 }
169
170 // RunConformanceTests runs conformance tests for driver implementations of docstore.
171 func RunConformanceTests(t *testing.T, newHarness HarnessMaker, ct CodecTester, asTests []AsTest) {
172 t.Helper()
173
174 t.Run("TypeDrivenCodec", func(t *testing.T) { testTypeDrivenDecode(t, ct) })
175 t.Run("BlindCodec", func(t *testing.T) { testBlindDecode(t, ct) })
176
177 t.Run("Create", func(t *testing.T) { withRevCollections(t, newHarness, testCreate) })
178 t.Run("AtomicWrites", func(t *testing.T) { withRevCollections(t, newHarness, testAtomicWrites) })
179 t.Run("AtomicWritesFail", func(t *testing.T) { withRevCollections(t, newHarness, testAtomicWritesFail) })
180 t.Run("Put", func(t *testing.T) { withRevCollections(t, newHarness, testPut) })
181 t.Run("Replace", func(t *testing.T) { withRevCollections(t, newHarness, testReplace) })
182 t.Run("Get", func(t *testing.T) { withRevCollections(t, newHarness, testGet) })
183 t.Run("Delete", func(t *testing.T) { withRevCollections(t, newHarness, testDelete) })
184 t.Run("Update", func(t *testing.T) { withRevCollections(t, newHarness, testUpdate) })
185 t.Run("Data", func(t *testing.T) { withCollection(t, newHarness, SingleKey, testData) })
186 t.Run("Proto", func(t *testing.T) { withCollection(t, newHarness, SingleKey, testProto) })
187 t.Run("MultipleActions", func(t *testing.T) { withRevCollections(t, newHarness, testMultipleActions) })
188 t.Run("GetQueryKeyField", func(t *testing.T) { withRevCollections(t, newHarness, testGetQueryKeyField) })
189 t.Run("SerializeRevision", func(t *testing.T) { withCollection(t, newHarness, SingleKey, testSerializeRevision) })
190 t.Run("ActionsOnStructNoRev", func(t *testing.T) {
191 withCollection(t, newHarness, NoRev, testActionsOnStructNoRev)
192 })
193 t.Run("ActionsWithCompositeID", func(t *testing.T) { withCollection(t, newHarness, TwoKey, testActionsWithCompositeID) })
194 t.Run("GetQuery", func(t *testing.T) { withCollection(t, newHarness, TwoKey, testGetQuery) })
195
196 t.Run("ExampleInDoc", func(t *testing.T) { withCollection(t, newHarness, NoRev, testExampleInDoc) })
197
198 t.Run("BeforeDo", func(t *testing.T) { testBeforeDo(t, newHarness) })
199 t.Run("BeforeQuery", func(t *testing.T) { testBeforeQuery(t, newHarness) })
200
201 asTests = append(asTests, verifyAsFailsOnNil{})
202 t.Run("As", func(t *testing.T) {
203 for _, st := range asTests {
204 if st.Name() == "" {
205 t.Fatalf("AsTest.Name is required")
206 }
207 t.Run(st.Name(), func(t *testing.T) {
208 withCollection(t, newHarness, TwoKey, func(t *testing.T, _ Harness, coll *docstore.Collection) {
209 t.Helper()
210
211 testAs(t, coll, st)
212 })
213 })
214 }
215 })
216 }
217
218 // withCollection calls f with a fresh harness and an empty collection of the given kind.
219 func withCollection(t *testing.T, newHarness HarnessMaker, kind CollectionKind, f func(*testing.T, Harness, *docstore.Collection)) {
220 t.Helper()
221
222 ctx := context.Background()
223 h, err := newHarness(ctx, t)
224 if err != nil {
225 t.Fatal(err)
226 }
227 defer h.Close()
228
229 withColl(t, h, kind, f)
230 }
231
232 // withRevCollections calls f twice: once with the SingleKey collection, using documents and code that expect
233 // the standard revision field; and once with the AltRev collection, that uses an alternative revisionf field
234 // name.
235 func withRevCollections(t *testing.T, newHarness HarnessMaker, f func(*testing.T, *docstore.Collection, string)) {
236 t.Helper()
237
238 ctx := context.Background()
239 h, err := newHarness(ctx, t)
240 if err != nil {
241 t.Fatal(err)
242 }
243 defer h.Close()
244 if strings.Contains(t.Name(), "AtomicWrites") && !h.SupportsAtomicWrites() {
245 t.Skip()
246 }
247
248 t.Run("StdRev", func(t *testing.T) {
249 withColl(t, h, SingleKey, func(t *testing.T, _ Harness, coll *docstore.Collection) {
250 t.Helper()
251
252 f(t, coll, docstore.DefaultRevisionField)
253 })
254 })
255 t.Run("AltRev", func(t *testing.T) {
256 withColl(t, h, AltRev, func(t *testing.T, _ Harness, coll *docstore.Collection) {
257 t.Helper()
258
259 f(t, coll, AlternateRevisionField)
260 })
261 })
262 }
263
264 // withColl calls f with h and an empty collection of the given kind. It takes care of closing
265 // the collection after f returns.
266 func withColl(t *testing.T, h Harness, kind CollectionKind, f func(*testing.T, Harness, *docstore.Collection)) {
267 t.Helper()
268
269 ctx := context.Background()
270 dc, err := h.MakeCollection(ctx, kind)
271 if err != nil {
272 t.Fatal(err)
273 }
274 coll := docstore.NewCollection(dc)
275 defer coll.Close()
276 ClearCollection(t, coll)
277 f(t, h, coll)
278 }
279
280 // KeyField is the primary key field for the main test collection.
281 const KeyField = "name"
282
283 // AlternateRevisionField is used for testing the option to provide a different
284 // name for the revision field.
285 const AlternateRevisionField = "Etag"
286
287 type docmap = map[string]any
288
289 func newDoc(doc any) any {
290 switch v := doc.(type) {
291 case docmap:
292 return docmap{KeyField: v[KeyField]}
293 case *docstruct:
294 return &docstruct{Name: v.Name}
295 }
296 return nil
297 }
298
299 func key(doc any) any {
300 switch d := doc.(type) {
301 case docmap:
302 return d[KeyField]
303 case *docstruct:
304 return d.Name
305 }
306 return nil
307 }
308
309 func setKey(doc, key any) {
310 switch d := doc.(type) {
311 case docmap:
312 d[KeyField] = key
313 case *docstruct:
314 d.Name = key
315 }
316 }
317
318 func revision(doc any, revField string) any {
319 switch d := doc.(type) {
320 case docmap:
321 return d[revField]
322 case *docstruct:
323 if revField == docstore.DefaultRevisionField {
324 return d.DocstoreRevision
325 }
326 return d.Etag
327 }
328 return nil
329 }
330
331 func setRevision(doc, rev any, revField string) {
332 switch d := doc.(type) {
333 case docmap:
334 d[revField] = rev
335 case *docstruct:
336 if revField == docstore.DefaultRevisionField {
337 d.DocstoreRevision = rev
338 } else {
339 d.Etag = rev
340 }
341 }
342 }
343
344 type docstruct struct {
345 Name any `docstore:"name"`
346 DocstoreRevision any
347 Etag any
348
349 I int
350 U uint
351 F float64
352 St string
353 B bool
354 M map[string]any
355 }
356
357 func nonexistentDoc() docmap { return docmap{KeyField: "doesNotExist"} }
358
359 func testCreate(t *testing.T, coll *docstore.Collection, revField string) {
360 t.Helper()
361
362 ctx := context.Background()
363 for _, tc := range []struct {
364 name string
365 doc any
366 wantErr gcerrors.ErrorCode
367 }{
368 {
369 name: "named map",
370 doc: docmap{KeyField: "testCreateMap", "b": true, revField: nil},
371 },
372 {
373 name: "existing",
374 doc: docmap{KeyField: "testCreateMap", revField: nil},
375 wantErr: gcerrors.AlreadyExists,
376 },
377 {
378 name: "unnamed map",
379 doc: docmap{"b": true, revField: nil},
380 },
381 {
382 name: "named struct",
383 doc: &docstruct{Name: "testCreateStruct", B: true},
384 },
385 {
386 name: "unnamed struct",
387 doc: &docstruct{B: true},
388 },
389 {
390 name: "empty named struct",
391 doc: &docstruct{Name: "", B: true},
392 },
393 {
394 name: "with non-nil revision",
395 doc: docmap{KeyField: "testCreate2", revField: 0},
396 wantErr: gcerrors.InvalidArgument,
397 },
398 } {
399 t.Run(tc.name, func(t *testing.T) {
400 if tc.wantErr == gcerrors.OK {
401 checkNoRevisionField(t, tc.doc, revField)
402 if err := coll.Create(ctx, tc.doc); err != nil {
403 t.Fatalf("Create: %v", err)
404 }
405 checkHasRevisionField(t, tc.doc, revField)
406
407 got := newDoc(tc.doc)
408 if err := coll.Get(ctx, got); err != nil {
409 t.Fatalf("Get: %v", err)
410 }
411 if diff := cmpDiff(got, tc.doc); diff != "" {
412 t.Fatal(diff)
413 }
414 } else {
415 err := coll.Create(ctx, tc.doc)
416 checkCode(t, err, tc.wantErr)
417 }
418 })
419 }
420 }
421
422 func testPut(t *testing.T, coll *docstore.Collection, revField string) {
423 t.Helper()
424
425 ctx := context.Background()
426 must := func(err error) {
427 t.Helper()
428 if err != nil {
429 t.Fatal(err)
430 }
431 }
432 var maprev, strmap any
433
434 for _, tc := range []struct {
435 name string
436 doc any
437 rev bool
438 }{
439 {
440 name: "create map",
441 doc: docmap{KeyField: "testPutMap", "b": true, revField: nil},
442 },
443 {
444 name: "create struct",
445 doc: &docstruct{Name: "testPutStruct", B: true},
446 },
447 {
448 name: "replace map",
449 doc: docmap{KeyField: "testPutMap", "b": false, revField: nil},
450 rev: true,
451 },
452 {
453 name: "replace struct",
454 doc: &docstruct{Name: "testPutStruct", B: false},
455 rev: true,
456 },
457 } {
458 t.Run(tc.name, func(t *testing.T) {
459 checkNoRevisionField(t, tc.doc, revField)
460 must(coll.Put(ctx, tc.doc))
461 checkHasRevisionField(t, tc.doc, revField)
462 got := newDoc(tc.doc)
463 must(coll.Get(ctx, got))
464 if diff := cmpDiff(got, tc.doc); diff != "" {
465 t.Fatal(diff)
466 }
467 if tc.rev {
468 switch v := tc.doc.(type) {
469 case docmap:
470 maprev = v[revField]
471 case *docstruct:
472 if revField == docstore.DefaultRevisionField {
473 strmap = v.DocstoreRevision
474 } else {
475 strmap = v.Etag
476 }
477 }
478 }
479 })
480 }
481
482 // Putting a doc with a revision field is the same as replace, meaning
483 // it will fail if the document doesn't exist.
484 for _, tc := range []struct {
485 name string
486 doc any
487 }{
488 {
489 name: "replace map wrong key",
490 doc: docmap{KeyField: "testPutMap2", revField: maprev},
491 },
492 {
493 name: "replace struct wrong key",
494 doc: &docstruct{Name: "testPutStruct2", DocstoreRevision: strmap, Etag: strmap},
495 },
496 } {
497 t.Run(tc.name, func(t *testing.T) {
498 err := coll.Put(ctx, tc.doc)
499 if c := gcerrors.Code(err); c != gcerrors.NotFound && c != gcerrors.FailedPrecondition {
500 t.Errorf("got %v, want NotFound or FailedPrecondition", err)
501 }
502 })
503 }
504
505 t.Run("revision", func(t *testing.T) {
506 testRevisionField(t, coll, revField, func(doc any) error {
507 return coll.Put(ctx, doc)
508 })
509 })
510
511 err := coll.Put(ctx, &docstruct{Name: ""})
512 checkCode(t, err, gcerrors.InvalidArgument)
513 }
514
515 func testReplace(t *testing.T, coll *docstore.Collection, revField string) {
516 t.Helper()
517
518 ctx := context.Background()
519 must := func(err error) {
520 t.Helper()
521 if err != nil {
522 t.Fatal(err)
523 }
524 }
525
526 for _, tc := range []struct {
527 name string
528 doc1, doc2 any
529 }{
530 {
531 name: "replace map",
532 doc1: docmap{KeyField: "testReplaceMap", "s": "a", revField: nil},
533 doc2: docmap{KeyField: "testReplaceMap", "s": "b", revField: nil},
534 },
535 {
536 name: "replace struct",
537 doc1: &docstruct{Name: "testReplaceStruct", St: "a"},
538 doc2: &docstruct{Name: "testReplaceStruct", St: "b"},
539 },
540 } {
541 t.Run(tc.name, func(t *testing.T) {
542 must(coll.Put(ctx, tc.doc1))
543 checkNoRevisionField(t, tc.doc2, revField)
544 must(coll.Replace(ctx, tc.doc2))
545 checkHasRevisionField(t, tc.doc2, revField)
546 got := newDoc(tc.doc2)
547 must(coll.Get(ctx, got))
548 if diff := cmpDiff(got, tc.doc2); diff != "" {
549 t.Fatal(diff)
550 }
551 })
552 }
553
554 // Can't replace a nonexistent doc.
555 checkCode(t, coll.Replace(ctx, nonexistentDoc()), gcerrors.NotFound)
556
557 t.Run("revision", func(t *testing.T) {
558 testRevisionField(t, coll, revField, func(doc any) error {
559 return coll.Replace(ctx, doc)
560 })
561 })
562 }
563
564 // Check that doc does not have a revision field (or has a nil one).
565 func checkNoRevisionField(t *testing.T, doc any, revField string) {
566 t.Helper()
567 ddoc, err := driver.NewDocument(doc)
568 if err != nil {
569 t.Fatal(err)
570 }
571 if rev, _ := ddoc.GetField(revField); rev != nil {
572 t.Fatal("doc has revision field")
573 }
574 }
575
576 // Check that doc has a non-nil revision field.
577 func checkHasRevisionField(t *testing.T, doc any, revField string) {
578 t.Helper()
579
580 ddoc, err := driver.NewDocument(doc)
581 if err != nil {
582 t.Fatal(err)
583 }
584 if rev, err := ddoc.GetField(revField); err != nil || rev == nil {
585 t.Fatalf("doc missing revision field (error = %v)", err)
586 }
587 }
588
589 func testGet(t *testing.T, coll *docstore.Collection, revField string) {
590 t.Helper()
591
592 ctx := context.Background()
593 must := func(err error) {
594 t.Helper()
595 if err != nil {
596 t.Fatal(err)
597 }
598 }
599
600 for _, tc := range []struct {
601 name string
602 doc any
603 fps []docstore.FieldPath
604 want any
605 }{
606 // If Get is called with no field paths, the full document is populated.
607 {
608 name: "get map",
609 doc: docmap{
610 KeyField: "testGetMap",
611 "s": "a string",
612 "i": int64(95),
613 "f": 32.3,
614 "m": map[string]any{"a": "one", "b": "two"},
615 revField: nil,
616 },
617 },
618 {
619 name: "get struct",
620 doc: &docstruct{
621 Name: "testGetStruct",
622 St: "a string",
623 I: 95,
624 F: 32.3,
625 M: map[string]any{"a": "one", "b": "two"},
626 },
627 },
628 // If Get is called with field paths, the resulting document has only those fields.
629 {
630 name: "get map with field path",
631 doc: docmap{
632 KeyField: "testGetMapFP",
633 "s": "a string",
634 "i": int64(95),
635 "f": 32.3,
636 "m": map[string]any{"a": "one", "b": "two"},
637 revField: nil,
638 },
639 fps: []docstore.FieldPath{"f", "m.b", docstore.FieldPath(revField)},
640 want: docmap{
641 KeyField: "testGetMapFP",
642 "f": 32.3,
643 "m": map[string]any{"b": "two"},
644 },
645 },
646 {
647 name: "get struct with field path",
648 doc: &docstruct{
649 Name: "testGetStructFP",
650 St: "a string",
651 I: 95,
652 F: 32.3,
653 M: map[string]any{"a": "one", "b": "two"},
654 },
655 fps: []docstore.FieldPath{"St", "M.a", docstore.FieldPath(revField)},
656 want: &docstruct{
657 Name: "testGetStructFP",
658 St: "a string",
659 M: map[string]any{"a": "one"},
660 },
661 },
662 {
663 name: "get struct wrong case",
664 doc: &docstruct{
665 Name: "testGetStructWC",
666 St: "a string",
667 I: 95,
668 F: 32.3,
669 M: map[string]any{"a": "one", "b": "two"},
670 },
671 fps: []docstore.FieldPath{"st", "m.a"},
672 want: &docstruct{
673 Name: "testGetStructWC",
674 },
675 },
676 } {
677 t.Run(tc.name, func(t *testing.T) {
678 must(coll.Put(ctx, tc.doc))
679 got := newDoc(tc.doc)
680 must(coll.Get(ctx, got, tc.fps...))
681 if tc.want == nil {
682 tc.want = tc.doc
683 }
684 setRevision(tc.want, revision(got, revField), revField)
685 if diff := cmpDiff(got, tc.want); diff != "" {
686 t.Error("Get with field paths:\n", diff)
687 }
688 })
689 }
690
691 err := coll.Get(ctx, nonexistentDoc())
692 checkCode(t, err, gcerrors.NotFound)
693
694 err = coll.Get(ctx, &docstruct{Name: ""})
695 checkCode(t, err, gcerrors.InvalidArgument)
696 }
697
698 func testDelete(t *testing.T, coll *docstore.Collection, revField string) {
699 t.Helper()
700
701 ctx := context.Background()
702 var rev any
703
704 for _, tc := range []struct {
705 name string
706 doc any
707 wantErr gcerrors.ErrorCode
708 }{
709 {
710 name: "delete map",
711 doc: docmap{KeyField: "testDeleteMap", revField: nil},
712 },
713 {
714 name: "delete map wrong rev",
715 doc: docmap{KeyField: "testDeleteMap", "b": true, revField: nil},
716 wantErr: gcerrors.FailedPrecondition,
717 },
718 {
719 name: "delete struct",
720 doc: &docstruct{Name: "testDeleteStruct"},
721 },
722 {
723 name: "delete struct wrong rev",
724 doc: &docstruct{Name: "testDeleteStruct", B: true},
725 wantErr: gcerrors.FailedPrecondition,
726 },
727 } {
728 t.Run(tc.name, func(t *testing.T) {
729 if err := coll.Put(ctx, tc.doc); err != nil {
730 t.Fatal(err)
731 }
732 if tc.wantErr == gcerrors.OK {
733 rev = revision(tc.doc, revField)
734 if err := coll.Delete(ctx, tc.doc); err != nil {
735 t.Fatal(err)
736 }
737 // The document should no longer exist.
738 if err := coll.Get(ctx, tc.doc); err == nil {
739 t.Error("want error, got nil")
740 }
741 } else {
742 setRevision(tc.doc, rev, revField)
743 checkCode(t, coll.Delete(ctx, tc.doc), gcerrors.FailedPrecondition)
744 }
745 })
746 }
747 // Delete doesn't fail if the doc doesn't exist.
748 if err := coll.Delete(ctx, nonexistentDoc()); err != nil {
749 t.Errorf("delete nonexistent doc: want nil, got %v", err)
750 }
751
752 err := coll.Delete(ctx, &docstruct{Name: ""})
753 checkCode(t, err, gcerrors.InvalidArgument)
754 }
755
756 func testUpdate(t *testing.T, coll *docstore.Collection, revField string) {
757 t.Helper()
758
759 ctx := context.Background()
760 for _, tc := range []struct {
761 name string
762 doc any
763 mods docstore.Mods
764 want any
765 }{
766 {
767 name: "update map",
768 doc: docmap{KeyField: "testUpdateMap", "a": "A", "b": "B", "n": 3.5, "i": 1, revField: nil},
769 mods: docstore.Mods{
770 "a": "X",
771 "b": nil,
772 "c": "C",
773 "n": docstore.Increment(-1),
774 "i": nil,
775 "m": 3,
776 },
777 want: docmap{KeyField: "testUpdateMap", "a": "X", "c": "C", "n": 2.5, "m": int64(3)},
778 },
779 {
780 name: "update map overwrite only",
781 doc: docmap{KeyField: "testUpdateMapWrt", "a": "A", revField: nil},
782 mods: docstore.Mods{
783 "a": "X",
784 "b": nil,
785 "m": 3,
786 },
787 want: docmap{KeyField: "testUpdateMapWrt", "a": "X", "m": int64(3)},
788 },
789 {
790 name: "update map increment only",
791 doc: docmap{KeyField: "testUpdateMapInc", "a": "A", "n": 3.5, "i": 1, revField: nil},
792 mods: docstore.Mods{
793 "n": docstore.Increment(-1),
794 "i": docstore.Increment(2.5),
795 "m": docstore.Increment(3),
796 },
797 want: docmap{KeyField: "testUpdateMapInc", "a": "A", "n": 2.5, "i": 3.5, "m": int64(3)},
798 },
799 {
800 name: "update struct",
801 doc: &docstruct{Name: "testUpdateStruct", St: "st", I: 1, F: 3.5},
802 mods: docstore.Mods{
803 "St": "str",
804 "I": nil,
805 "U": 4,
806 "F": docstore.Increment(-3),
807 },
808 want: &docstruct{Name: "testUpdateStruct", St: "str", U: 4, F: 0.5},
809 },
810 {
811 name: "update struct overwrite only",
812 doc: &docstruct{Name: "testUpdateStructWrt", St: "st", I: 1},
813 mods: docstore.Mods{
814 "St": "str",
815 "I": nil,
816 "U": 4,
817 },
818 want: &docstruct{Name: "testUpdateStructWrt", St: "str", U: 4},
819 },
820 {
821 name: "update struct increment only",
822 doc: &docstruct{Name: "testUpdateStructInc", St: "st", I: 1, F: 3.5},
823 mods: docstore.Mods{
824 "U": docstore.Increment(4),
825 "F": docstore.Increment(-3),
826 },
827 want: &docstruct{Name: "testUpdateStructInc", St: "st", U: 4, I: 1, F: 0.5},
828 },
829 } {
830 t.Run(tc.name, func(t *testing.T) {
831 if err := coll.Put(ctx, tc.doc); err != nil {
832 t.Fatal(err)
833 }
834 setRevision(tc.doc, nil, revField)
835 got := newDoc(tc.doc)
836 checkNoRevisionField(t, tc.doc, revField)
837 errs := coll.Actions().Update(tc.doc, tc.mods).Get(got).Do(ctx)
838 if errs != nil {
839 t.Fatal(errs)
840 }
841 checkHasRevisionField(t, tc.doc, revField)
842 setRevision(tc.want, revision(got, revField), revField)
843 if diff := cmp.Diff(got, tc.want, cmpopts.IgnoreUnexported(tspb.Timestamp{})); diff != "" {
844 t.Error(diff)
845 }
846 })
847 }
848
849 // Can't update a nonexistent doc.
850 if err := coll.Update(ctx, nonexistentDoc(), docstore.Mods{"x": "y"}); err == nil {
851 t.Error("nonexistent document: got nil, want error")
852 }
853
854 // Bad increment value.
855 err := coll.Update(ctx, docmap{KeyField: "update invalid"}, docstore.Mods{"x": docstore.Increment("3")})
856 checkCode(t, err, gcerrors.InvalidArgument)
857
858 t.Run("revision", func(t *testing.T) {
859 testRevisionField(t, coll, revField, func(doc any) error {
860 return coll.Update(ctx, doc, docstore.Mods{"s": "c"})
861 })
862 })
863 }
864
865 // Test that:
866 // - Writing a document with a revision field succeeds if the document hasn't changed.
867 // - Writing a document with a revision field fails if the document has changed.
868 func testRevisionField(t *testing.T, coll *docstore.Collection, revField string, write func(any) error) {
869 t.Helper()
870
871 ctx := context.Background()
872 must := func(err error) {
873 t.Helper()
874 if err != nil {
875 t.Fatal(err)
876 }
877 }
878 for _, tc := range []struct {
879 name string
880 doc any
881 }{
882 {
883 name: "map revision",
884 doc: docmap{KeyField: "testRevisionMap", "s": "a", revField: nil},
885 },
886 {
887 name: "struct revision",
888 doc: &docstruct{Name: "testRevisionStruct", St: "a"},
889 },
890 } {
891 t.Run(tc.name, func(t *testing.T) {
892 must(coll.Put(ctx, tc.doc))
893 got := newDoc(tc.doc)
894 must(coll.Get(ctx, got))
895 rev := revision(got, revField)
896 if rev == nil {
897 t.Fatal("missing revision field")
898 }
899 // A write should succeed, because the document hasn't changed since it was gotten.
900 if err := write(tc.doc); err != nil {
901 t.Fatalf("write with revision field got %v, want nil", err)
902 }
903 // This write should fail: got's revision field hasn't changed, but the stored document has.
904 err := write(got)
905 if c := gcerrors.Code(err); c != gcerrors.FailedPrecondition && c != gcerrors.NotFound {
906 t.Errorf("write with old revision field: got %v, wanted FailedPrecondition or NotFound", err)
907 }
908 })
909 }
910 }
911
912 // Verify that the driver can serialize and deserialize revisions.
913 func testSerializeRevision(t *testing.T, h Harness, coll *docstore.Collection) {
914 t.Helper()
915
916 ctx := context.Background()
917 doc := docmap{KeyField: "testSerializeRevision", "x": 1, docstore.DefaultRevisionField: nil}
918 if err := coll.Create(ctx, doc); err != nil {
919 t.Fatal(err)
920 }
921 want := doc[docstore.DefaultRevisionField]
922 if want == nil {
923 t.Fatal("nil revision")
924 }
925 s, err := coll.RevisionToString(want)
926 if err != nil {
927 t.Fatal(err)
928 }
929 got, err := coll.StringToRevision(s)
930 if err != nil {
931 t.Fatal(err)
932 }
933 if !h.RevisionsEqual(got, want) {
934 t.Fatalf("got %v, want %v", got, want)
935 }
936 }
937
938 // Test all Go integer types are supported, and they all come back as int64.
939 func testData(t *testing.T, _ Harness, coll *docstore.Collection) {
940 t.Helper()
941
942 ctx := context.Background()
943 for _, test := range []struct {
944 in, want any
945 }{
946 {int(-1), int64(-1)},
947 {int8(-8), int64(-8)},
948 {int16(-16), int64(-16)},
949 {int32(-32), int64(-32)},
950 {int64(-64), int64(-64)},
951 {uint(1), int64(1)},
952 {uint8(8), int64(8)},
953 {uint16(16), int64(16)},
954 {uint32(32), int64(32)},
955 {uint64(64), int64(64)},
956 {float32(3.5), float64(3.5)},
957 {[]byte{0, 1, 2}, []byte{0, 1, 2}},
958 } {
959 doc := docmap{KeyField: "testData", "val": test.in}
960 got := docmap{KeyField: doc[KeyField]}
961 if errs := coll.Actions().Put(doc).Get(got).Do(ctx); errs != nil {
962 t.Fatal(errs)
963 }
964 want := docmap{
965 "val": test.want,
966 KeyField: doc[KeyField],
967 }
968 if len(got) != len(want) {
969 t.Errorf("%v: got %v, want %v", test.in, got, want)
970 } else if g := got["val"]; !cmp.Equal(g, test.want) {
971 t.Errorf("%v: got %v (%T), want %v (%T)", test.in, g, g, test.want, test.want)
972 }
973 }
974
975 // TODO: strings: valid vs. invalid unicode
976 }
977
978 var (
979 // A time with non-zero milliseconds, but zero nanoseconds.
980 milliTime = time.Date(2019, time.March, 27, 0, 0, 0, 5*1e6, time.UTC)
981 // A time with non-zero nanoseconds.
982 nanoTime = time.Date(2019, time.March, 27, 0, 0, 0, 5*1e6+7, time.UTC)
983 )
984
985 // Test that encoding from a struct and then decoding into the same struct works properly.
986 // The decoding is "type-driven" because the decoder knows the expected type of the value
987 // it is decoding--it is the type of a struct field.
988 func testTypeDrivenDecode(t *testing.T, ct CodecTester) {
989 t.Helper()
990
991 if ct == nil {
992 t.Skip("no CodecTester")
993 }
994 check := func(in, dec any, encode func(any) (any, error), decode func(any, any) error) {
995 t.Helper()
996 enc, err := encode(in)
997 if err != nil {
998 t.Fatalf("%+v", err)
999 }
1000 if err := decode(enc, dec); err != nil {
1001 t.Fatalf("%+v", err)
1002 }
1003 if diff := cmp.Diff(in, dec); diff != "" {
1004 t.Error(diff)
1005 }
1006 }
1007
1008 s := "bar"
1009 dsrt := &docstoreRoundTrip{
1010 N: nil,
1011 I: 1,
1012 U: 2,
1013 F: 2.5,
1014 St: "foo",
1015 B: true,
1016 L: []int{3, 4, 5},
1017 A: [2]int{6, 7},
1018 A2: [2]int8{1, 2},
1019 At: ByteArray{1, 2},
1020 Uu: uuid.NameSpaceDNS,
1021 M: map[string]bool{"a": true, "b": false},
1022 By: []byte{6, 7, 8},
1023 P: &s,
1024 T: milliTime,
1025 }
1026
1027 check(dsrt, &docstoreRoundTrip{}, ct.DocstoreEncode, ct.DocstoreDecode)
1028
1029 // Test native-to-docstore and docstore-to-native round trips with a smaller set
1030 // of types.
1031 nm := &nativeMinimal{
1032 N: nil,
1033 I: 1,
1034 F: 2.5,
1035 St: "foo",
1036 B: true,
1037 L: []int{3, 4, 5},
1038 A: [2]int{6, 7},
1039 A2: [2]int8{6, 7},
1040 At: ByteArray{1, 2},
1041 M: map[string]bool{"a": true, "b": false},
1042 By: []byte{6, 7, 8},
1043 P: &s,
1044 T: milliTime,
1045 LF: []float64{18.8, -19.9, 20},
1046 LS: []string{"foo", "bar"},
1047 }
1048 check(nm, &nativeMinimal{}, ct.DocstoreEncode, ct.NativeDecode)
1049 check(nm, &nativeMinimal{}, ct.NativeEncode, ct.DocstoreDecode)
1050
1051 // Test various other types, unless they are unsupported.
1052 unsupported := map[UnsupportedType]bool{}
1053 for _, u := range ct.UnsupportedTypes() {
1054 unsupported[u] = true
1055 }
1056
1057 // Unsigned integers.
1058 if !unsupported[Uint] {
1059 type Uint struct {
1060 U uint
1061 }
1062 u := &Uint{10}
1063 check(u, &Uint{}, ct.DocstoreEncode, ct.NativeDecode)
1064 check(u, &Uint{}, ct.NativeEncode, ct.DocstoreDecode)
1065 }
1066
1067 // Arrays.
1068 if !unsupported[Arrays] {
1069 type Arrays struct {
1070 A [2]int
1071 }
1072 a := &Arrays{[2]int{13, 14}}
1073 check(a, &Arrays{}, ct.DocstoreEncode, ct.NativeDecode)
1074 check(a, &Arrays{}, ct.NativeEncode, ct.DocstoreDecode)
1075 }
1076 // Nanosecond-precision time.
1077 type NT struct {
1078 T time.Time
1079 }
1080
1081 nt := &NT{nanoTime}
1082 if unsupported[NanosecondTimes] {
1083 // Expect rounding to the nearest millisecond.
1084 check := func(encode func(any) (any, error), decode func(any, any) error) {
1085 enc, err := encode(nt)
1086 if err != nil {
1087 t.Fatalf("%+v", err)
1088 }
1089 var got NT
1090 if err := decode(enc, &got); err != nil {
1091 t.Fatalf("%+v", err)
1092 }
1093 want := nt.T.Round(time.Millisecond)
1094 if !got.T.Equal(want) {
1095 t.Errorf("got %v, want %v", got.T, want)
1096 }
1097 }
1098 check(ct.DocstoreEncode, ct.NativeDecode)
1099 check(ct.NativeEncode, ct.DocstoreDecode)
1100 } else {
1101 // Expect perfect round-tripping of nanosecond times.
1102 check(nt, &NT{}, ct.DocstoreEncode, ct.NativeDecode)
1103 check(nt, &NT{}, ct.NativeEncode, ct.DocstoreDecode)
1104 }
1105
1106 // Binary sets.
1107 if !unsupported[BinarySet] {
1108 type BinarySet struct {
1109 B [][]byte
1110 }
1111 b := &BinarySet{[][]byte{{15}, {16}, {17}}}
1112 check(b, &BinarySet{}, ct.DocstoreEncode, ct.NativeDecode)
1113 check(b, &BinarySet{}, ct.NativeEncode, ct.DocstoreDecode)
1114 }
1115 }
1116
1117 // Test decoding into an interface{}, where the decoder doesn't know the type of the
1118 // result and must return some Go type that accurately represents the value.
1119 // This is implemented by the AsInterface method of driver.Decoder.
1120 // Since it's fine for different drivers to return different types in this case,
1121 // each test case compares against a list of possible values.
1122 func testBlindDecode(t *testing.T, ct CodecTester) {
1123 t.Helper()
1124
1125 if ct == nil {
1126 t.Skip("no CodecTester")
1127 }
1128 t.Run("DocstoreEncode", func(t *testing.T) { testBlindDecode1(t, ct.DocstoreEncode, ct.DocstoreDecode) })
1129 t.Run("NativeEncode", func(t *testing.T) { testBlindDecode1(t, ct.NativeEncode, ct.DocstoreDecode) })
1130 }
1131
1132 func testBlindDecode1(t *testing.T, encode func(any) (any, error), decode func(_, _ any) error) {
1133 t.Helper()
1134
1135 // Encode and decode expect a document, so use this struct to hold the values.
1136 type S struct{ X any }
1137
1138 for _, test := range []struct {
1139 in any // the value to be encoded
1140 want any // one possibility
1141 want2 any // a second possibility
1142 }{
1143 {in: nil, want: nil},
1144 {in: true, want: true},
1145 {in: "foo", want: "foo"},
1146 {in: 'c', want: 'c', want2: int64('c')},
1147 {in: int(3), want: int32(3), want2: int64(3)},
1148 {in: int8(3), want: int32(3), want2: int64(3)},
1149 {in: int(-3), want: int32(-3), want2: int64(-3)},
1150 {in: int64(math.MaxInt32 + 1), want: int64(math.MaxInt32 + 1)},
1151 {in: float32(1.5), want: float64(1.5)},
1152 {in: float64(1.5), want: float64(1.5)},
1153 {in: []byte{1, 2}, want: []byte{1, 2}},
1154 {
1155 in: []int{1, 2},
1156 want: []any{int32(1), int32(2)},
1157 want2: []any{int64(1), int64(2)},
1158 },
1159 {in: []float32{1.5, 2.5}, want: []any{float64(1.5), float64(2.5)}},
1160 {in: []float64{1.5, 2.5}, want: []any{float64(1.5), float64(2.5)}},
1161 {in: milliTime, want: milliTime, want2: "2019-03-27T00:00:00.005Z"},
1162 {
1163 in: []time.Time{milliTime},
1164 want: []any{milliTime},
1165 want2: []any{"2019-03-27T00:00:00.005Z"},
1166 },
1167 {
1168 in: map[string]int{"a": 1},
1169 want: map[string]any{"a": int64(1)},
1170 want2: map[string]any{"a": int32(1)},
1171 },
1172 {in: map[string][]byte{"a": {1, 2}}, want: map[string]any{"a": []byte{1, 2}}},
1173 } {
1174 enc, err := encode(&S{test.in})
1175 if err != nil {
1176 t.Fatalf("encoding %T: %v", test.in, err)
1177 }
1178 var got S
1179 if err := decode(enc, &got); err != nil {
1180 t.Fatalf("decoding %T: %v", test.in, err)
1181 }
1182 matched := false
1183 wants := []any{test.want}
1184 if test.want2 != nil {
1185 wants = append(wants, test.want2)
1186 }
1187 for _, w := range wants {
1188 if cmp.Equal(got.X, w) {
1189 matched = true
1190 break
1191 }
1192 }
1193 if !matched {
1194 t.Errorf("%T: got %#v (%T), not equal to %#v or %#v", test.in, got.X, got.X, test.want, test.want2)
1195 }
1196 }
1197 }
1198
1199 // A round trip with the docstore codec should work for all docstore-supported types,
1200 // regardless of native driver support.
1201 type docstoreRoundTrip struct {
1202 N *int
1203 I int
1204 U uint
1205 F float64
1206 St string
1207 B bool
1208 By []byte
1209 L []int
1210 A [2]int
1211 A2 [2]int8
1212 At ByteArray
1213 Uu uuid.UUID
1214 M map[string]bool
1215 P *string
1216 T time.Time
1217 }
1218
1219 // TODO(jba): add more fields: structs; embedding.
1220
1221 // All native codecs should support these types. If one doesn't, remove it from this
1222 // struct and make a new single-field struct for it.
1223 type nativeMinimal struct {
1224 N *int
1225 I int
1226 F float64
1227 St string
1228 B bool
1229 By []byte
1230 L []int
1231 A [2]int
1232 A2 [2]int8
1233 At ByteArray
1234 M map[string]bool
1235 P *string
1236 T time.Time
1237 LF []float64
1238 LS []string
1239 }
1240
1241 // testProto tests encoding/decoding of a document with protocol buffer
1242 // and pointer-to-protocol-buffer fields.
1243 func testProto(t *testing.T, _ Harness, coll *docstore.Collection) {
1244 t.Helper()
1245
1246 ctx := context.Background()
1247 type protoStruct struct {
1248 Name string `docstore:"name"`
1249 Proto tspb.Timestamp
1250 PtrToProto *tspb.Timestamp
1251 DocstoreRevision any
1252 }
1253 doc := &protoStruct{
1254 Name: "testing",
1255 Proto: tspb.Timestamp{Seconds: 42},
1256 PtrToProto: &tspb.Timestamp{Seconds: 43},
1257 }
1258
1259 err := coll.Create(ctx, doc)
1260 if err != nil {
1261 t.Fatal(err)
1262 }
1263 got := &protoStruct{}
1264 err = coll.Query().Get(ctx).Next(ctx, got)
1265 if err != nil {
1266 t.Fatal(err)
1267 }
1268 if diff := cmp.Diff(got, doc, cmpopts.IgnoreUnexported(tspb.Timestamp{})); diff != "" {
1269 t.Error(diff)
1270 }
1271 }
1272
1273 // The following is the schema for the collection where the ID is composed from
1274 // multiple fields instead of one. It can be used for query testing.
1275 // It is loosely borrowed from the DynamoDB documentation.
1276 // It is rich enough to require indexes for some drivers.
1277
1278 // A HighScore records one user's high score in a particular game.
1279 // The primary key fields are Game and Player.
1280 type HighScore struct {
1281 Game string
1282 Player string
1283 Score int
1284 Time time.Time
1285 WithGlitch bool
1286 DocstoreRevision any
1287 }
1288
1289 func newHighScore() any { return &HighScore{} }
1290
1291 // HighScoreKey constructs a single primary key from a HighScore struct or a map
1292 // with the same fields by concatenating the Game and Player fields.
1293 func HighScoreKey(doc docstore.Document) any {
1294 switch d := doc.(type) {
1295 case *HighScore:
1296 return d.key()
1297 case map[string]any:
1298 return barConcat(d["Game"], d["Player"])
1299 default:
1300 panic("bad arg")
1301 }
1302 }
1303
1304 func (h *HighScore) key() string {
1305 if h.Game == "" || h.Player == "" {
1306 return ""
1307 }
1308 return barConcat(h.Game, h.Player)
1309 }
1310
1311 func barConcat(a, b any) string { return fmt.Sprintf("%v|%v", a, b) }
1312
1313 func highScoreLess(h1, h2 *HighScore) bool { return h1.key() < h2.key() }
1314
1315 func (h *HighScore) String() string {
1316 return fmt.Sprintf("%s=%d@%s", h.key(), h.Score, h.Time.Format("01/02"))
1317 }
1318
1319 func date(month, day int) time.Time {
1320 return time.Date(2019, time.Month(month), day, 0, 0, 0, 0, time.UTC)
1321 }
1322
1323 const (
1324 game1 = "Praise All Monsters"
1325 game2 = "Zombie DMV"
1326 game3 = "Days Gone"
1327 )
1328
1329 var highScores = []*HighScore{
1330 {game1, "pat", 49, date(3, 13), false, nil},
1331 {game1, "mel", 60, date(4, 10), false, nil},
1332 {game1, "andy", 81, date(2, 1), false, nil},
1333 {game1, "fran", 33, date(3, 19), false, nil},
1334 {game2, "pat", 120, date(4, 1), true, nil},
1335 {game2, "billie", 111, date(4, 10), false, nil},
1336 {game2, "mel", 190, date(4, 18), true, nil},
1337 {game2, "fran", 33, date(3, 20), false, nil},
1338 }
1339
1340 func addHighScores(t *testing.T, coll *docstore.Collection) {
1341 t.Helper()
1342
1343 alist := coll.Actions()
1344 for _, doc := range highScores {
1345 d := *doc
1346 alist.Put(&d)
1347 }
1348 if err := alist.Do(context.Background()); err != nil {
1349 t.Fatalf("%+v", err)
1350 }
1351 }
1352
1353 func testGetQueryKeyField(t *testing.T, coll *docstore.Collection, revField string) {
1354 t.Helper()
1355
1356 // Query the key field of a collection that has one.
1357 // (The collection used for testGetQuery uses a key function rather than a key field.)
1358 ctx := context.Background()
1359 docs := []docmap{
1360 {KeyField: "qkf1", "a": "one", revField: nil},
1361 {KeyField: "qkf2", "a": "two", revField: nil},
1362 {KeyField: "qkf3", "a": "three", revField: nil},
1363 }
1364 al := coll.Actions()
1365 for _, d := range docs {
1366 al.Put(d)
1367 }
1368 if err := al.Do(ctx); err != nil {
1369 t.Fatal(err)
1370 }
1371 iter := coll.Query().Where(KeyField, "<", "qkf3").Get(ctx)
1372 defer iter.Stop()
1373 got := mustCollect(ctx, t, iter)
1374 want := docs[:2]
1375 diff := cmpDiff(got, want, cmpopts.SortSlices(sortByKeyField))
1376 if diff != "" {
1377 t.Error(diff)
1378 }
1379
1380 // Test that queries with selected fields always return the key.
1381 iter = coll.Query().Get(ctx, "a", docstore.FieldPath(revField))
1382 defer iter.Stop()
1383 got = mustCollect(ctx, t, iter)
1384 for _, d := range docs {
1385 checkHasRevisionField(t, d, revField)
1386 }
1387 diff = cmpDiff(got, docs, cmpopts.SortSlices(sortByKeyField))
1388 if diff != "" {
1389 t.Error(diff)
1390 }
1391 }
1392
1393 func sortByKeyField(d1, d2 docmap) bool { return d1[KeyField].(string) < d2[KeyField].(string) }
1394
1395 // TODO(shantuo): consider add this test to all action tests, like the AltRev
1396 // ones.
1397 func testActionsWithCompositeID(t *testing.T, _ Harness, coll *docstore.Collection) {
1398 t.Helper()
1399
1400 ctx := context.Background()
1401 // Create cannot generate an ID for the document when using IDFunc.
1402 checkCode(t, coll.Create(ctx, &HighScore{}), gcerrors.InvalidArgument)
1403 checkCode(t, coll.Get(ctx, &HighScore{}), gcerrors.InvalidArgument)
1404
1405 // Put
1406 addHighScores(t, coll)
1407 // Get
1408 gots := make([]*HighScore, len(highScores))
1409 actions := coll.Actions()
1410 for i, doc := range highScores {
1411 gots[i] = &HighScore{Game: doc.Game, Player: doc.Player}
1412 actions.Get(gots[i])
1413 }
1414 if err := actions.Do(ctx); err != nil {
1415 t.Fatal(err)
1416 }
1417 for i, got := range gots {
1418 if got.DocstoreRevision == nil {
1419 t.Errorf("%v missing DocstoreRevision", got)
1420 } else {
1421 got.DocstoreRevision = nil
1422 }
1423 if diff := cmp.Diff(got, highScores[i]); diff != "" {
1424 t.Error(diff)
1425 }
1426 }
1427 }
1428
1429 func testGetQuery(t *testing.T, _ Harness, coll *docstore.Collection) {
1430 t.Helper()
1431
1432 ctx := context.Background()
1433 addHighScores(t, coll)
1434
1435 // Query filters should have the same behavior when doing string and number
1436 // comparison.
1437 tests := []struct {
1438 name string
1439 q *docstore.Query
1440 fields []docstore.FieldPath // fields to get
1441 want func(*HighScore) bool // filters highScores
1442 before func(x, y *HighScore) bool // if present, checks result order
1443 }{
1444 {
1445 name: "All",
1446 q: coll.Query(),
1447 want: func(*HighScore) bool { return true },
1448 },
1449 {
1450 name: "Game",
1451 q: coll.Query().Where("Game", "=", game2),
1452 want: func(h *HighScore) bool { return h.Game == game2 },
1453 },
1454 {
1455 name: "Score",
1456 q: coll.Query().Where("Score", ">", 100),
1457 want: func(h *HighScore) bool { return h.Score > 100 },
1458 },
1459 {
1460 name: "Player",
1461 q: coll.Query().Where("Player", "=", "billie"),
1462 want: func(h *HighScore) bool { return h.Player == "billie" },
1463 },
1464 {
1465 name: "GamePlayer",
1466 q: coll.Query().Where("Player", "=", "andy").Where("Game", "=", game1),
1467 want: func(h *HighScore) bool { return h.Player == "andy" && h.Game == game1 },
1468 },
1469 {
1470 name: "PlayerScore",
1471 q: coll.Query().Where("Player", "=", "pat").Where("Score", "<", 100),
1472 want: func(h *HighScore) bool { return h.Player == "pat" && h.Score < 100 },
1473 },
1474 {
1475 name: "GameScore",
1476 q: coll.Query().Where("Game", "=", game1).Where("Score", ">=", 50),
1477 want: func(h *HighScore) bool { return h.Game == game1 && h.Score >= 50 },
1478 },
1479 {
1480 name: "PlayerTime",
1481 q: coll.Query().Where("Player", "=", "mel").Where("Time", ">", date(4, 1)),
1482 want: func(h *HighScore) bool { return h.Player == "mel" && h.Time.After(date(4, 1)) },
1483 },
1484 {
1485 name: "ScoreTime",
1486 q: coll.Query().Where("Score", ">=", 50).Where("Time", ">", date(4, 1)),
1487 want: func(h *HighScore) bool { return h.Score >= 50 && h.Time.After(date(4, 1)) },
1488 },
1489 {
1490 name: "PlayerIn",
1491 q: coll.Query().Where("Player", "in", []string{"pat", "billie"}),
1492 want: func(h *HighScore) bool { return h.Player == "pat" || h.Player == "billie" },
1493 },
1494 {
1495 name: "PlayerNotIn",
1496 q: coll.Query().Where("Player", "not-in", []string{"pat", "billie"}),
1497 want: func(h *HighScore) bool { return h.Player != "pat" && h.Player != "billie" },
1498 },
1499 {
1500 name: "WithGlitch",
1501 q: coll.Query().Where("WithGlitch", "=", true),
1502 want: func(h *HighScore) bool { return h.WithGlitch },
1503 },
1504 {
1505 name: "WithGlitchIn",
1506 q: coll.Query().Where("WithGlitch", "in", []bool{true}),
1507 want: func(h *HighScore) bool { return h.WithGlitch },
1508 },
1509 {
1510 name: "WithGlitchNotIn",
1511 q: coll.Query().Where("WithGlitch", "not-in", []bool{true}),
1512 want: func(h *HighScore) bool { return !h.WithGlitch },
1513 },
1514 {
1515 name: "AllByPlayerAsc",
1516 q: coll.Query().OrderBy("Player", docstore.Ascending),
1517 want: func(h *HighScore) bool { return true },
1518 before: func(h1, h2 *HighScore) bool { return h1.Player < h2.Player },
1519 },
1520 {
1521 name: "AllByPlayerDesc",
1522 q: coll.Query().OrderBy("Player", docstore.Descending),
1523 want: func(h *HighScore) bool { return true },
1524 before: func(h1, h2 *HighScore) bool { return h1.Player > h2.Player },
1525 },
1526 {
1527 name: "GameByPlayerAsc",
1528 // We need a filter on Player, and it can't be the empty string (DynamoDB limitation).
1529 // So pick any string that sorts less than all valid player names.
1530 q: coll.Query().Where("Game", "=", game1).Where("Player", ">", ".").
1531 OrderBy("Player", docstore.Ascending),
1532 want: func(h *HighScore) bool { return h.Game == game1 },
1533 before: func(h1, h2 *HighScore) bool { return h1.Player < h2.Player },
1534 },
1535 {
1536 // Same as above, but descending.
1537 name: "GameByPlayerDesc",
1538 q: coll.Query().Where("Game", "=", game1).Where("Player", ">", ".").
1539 OrderBy("Player", docstore.Descending),
1540 want: func(h *HighScore) bool { return h.Game == game1 },
1541 before: func(h1, h2 *HighScore) bool { return h1.Player > h2.Player },
1542 },
1543 // TODO(jba): add more OrderBy tests.
1544 {
1545 name: "AllWithKeyFields",
1546 q: coll.Query(),
1547 fields: []docstore.FieldPath{"Game", "Player", docstore.FieldPath(docstore.DefaultRevisionField)},
1548 want: func(h *HighScore) bool {
1549 h.Score = 0
1550 h.Time = time.Time{}
1551 h.WithGlitch = false
1552 return true
1553 },
1554 },
1555 {
1556 name: "AllWithScore",
1557 q: coll.Query(),
1558 fields: []docstore.FieldPath{"Game", "Player", "Score", "WithGlitch", docstore.FieldPath(docstore.DefaultRevisionField)},
1559 want: func(h *HighScore) bool {
1560 h.Time = time.Time{}
1561 return true
1562 },
1563 },
1564 }
1565 for _, tc := range tests {
1566 t.Run(tc.name, func(t *testing.T) {
1567 got, err := collectHighScores(ctx, tc.q.Get(ctx, tc.fields...))
1568 if err != nil {
1569 t.Fatal(err)
1570 }
1571 for _, g := range got {
1572 if g.DocstoreRevision == nil {
1573 t.Errorf("%v missing DocstoreRevision", g)
1574 } else {
1575 g.DocstoreRevision = nil
1576 }
1577 }
1578 want := filterHighScores(highScores, tc.want)
1579 _, err = tc.q.Plan()
1580 if err != nil {
1581 t.Fatal(err)
1582 }
1583 diff := cmp.Diff(got, want, cmpopts.SortSlices(highScoreLess))
1584 if diff != "" {
1585 t.Fatal(diff)
1586 }
1587 if tc.before != nil {
1588 // Verify that the results are sorted according to tc.less.
1589 for i := 1; i < len(got); i++ {
1590 if tc.before(got[i], got[i-1]) {
1591 t.Errorf("%s at %d sorts before previous %s", got[i], i, got[i-1])
1592 }
1593 }
1594 }
1595 // We can't assume anything about the query plan. Just verify that Plan returns
1596 // successfully.
1597 if _, err := tc.q.Plan(KeyField); err != nil {
1598 t.Fatal(err)
1599 }
1600 })
1601 }
1602 t.Run("OffsetAndLimitCounts", func(t *testing.T) {
1603 nDocs := len(highScores) // 8
1604 tests := []struct {
1605 name string
1606 offset int
1607 limit int
1608 expected int
1609 }{
1610 {
1611 name: "LimitOnly",
1612 offset: 0,
1613 limit: 2,
1614 expected: 2,
1615 },
1616 {
1617 name: "OffsetOnly",
1618 offset: 2,
1619 limit: nDocs,
1620 expected: nDocs - 2,
1621 },
1622 {
1623 name: "OffsetAndLimit",
1624 offset: 2,
1625 limit: 2,
1626 expected: 2,
1627 },
1628 {
1629 name: "OffsetEqualToFirstPage",
1630 offset: nDocs,
1631 limit: 2,
1632 expected: 0,
1633 },
1634 {
1635 name: "OffsetLessThanFirstPage",
1636 offset: nDocs - 1,
1637 limit: 2,
1638 expected: 1,
1639 },
1640 {
1641 name: "OffsetGreaterThanFirstPage",
1642 offset: nDocs + 1,
1643 limit: 2,
1644 expected: 0,
1645 },
1646 {
1647 name: "OffsetIsZero",
1648 offset: 0,
1649 limit: 2,
1650 expected: 2,
1651 },
1652 {
1653 name: "OffsetAndLimitGreaterThanPageSize",
1654 offset: nDocs + 1,
1655 limit: nDocs + 1,
1656 expected: 0,
1657 },
1658 {
1659 name: "OffsetLessThanPageSizeAndLimitGreaterThanPageSize",
1660 offset: nDocs - 1,
1661 limit: nDocs + 1,
1662 expected: 1,
1663 },
1664 // Scenarios covered elsewhere:
1665 // - /go-cloud/docstore/query_test.go#TestInvalidQuery:
1666 // - NegativeLimit
1667 // - ZeroLimit
1668 // - TwoLimits
1669 // - NegativeOffset
1670 // - TwoOffsets
1671 // - ZeroOffsetAndLimit
1672 // - NegativeOffsetAndLimit
1673 // - ZeroOffsetAndNegativeLimit
1674 }
1675 for _, tt := range tests {
1676 t.Run(tt.name, func(t *testing.T) {
1677 offsetLimitQ := coll.Query().Offset(tt.offset).Limit(tt.limit)
1678 got := mustCollectHighScores(ctx, t, offsetLimitQ.Get(ctx))
1679
1680 if len(got) != tt.expected {
1681 t.Errorf("got %v, wanted %v documents", len(got), tt.expected)
1682 }
1683 })
1684 }
1685 })
1686 t.Run("EOF", func(t *testing.T) {
1687 // To address this issue https://github.com/google/go-cloud/issues/3405#issue-2193025645
1688 q := coll.Query()
1689 it := q.Get(context.Background())
1690 defer it.Stop()
1691 h := &HighScore{}
1692 for {
1693 err := it.Next(context.Background(), h)
1694 if err == io.EOF {
1695 break
1696 }
1697 if err != nil {
1698 t.Errorf("unexpected error: %v", err)
1699 return
1700 }
1701 }
1702 // Call Next again to trigger io.EOF
1703 err := it.Next(context.Background(), h)
1704 if err != io.EOF {
1705 t.Errorf("expected io.EOF, got %v", err)
1706 }
1707 })
1708 }
1709
1710 func filterHighScores(hs []*HighScore, f func(*HighScore) bool) []*HighScore {
1711 var res []*HighScore
1712 for _, h := range hs {
1713 c := *h // Copy in case f modifies its argument.
1714 if f(&c) {
1715 res = append(res, &c)
1716 }
1717 }
1718 return res
1719 }
1720
1721 // ClearCollection delete all documents from this collection after test.
1722 func ClearCollection(fataler interface {
1723 Helper()
1724 Fatalf(string, ...any)
1725 }, coll *docstore.Collection,
1726 ) {
1727 fataler.Helper()
1728
1729 ctx := context.Background()
1730 iter := coll.Query().Get(ctx)
1731 dels := coll.Actions()
1732 for {
1733 doc := map[string]any{}
1734 err := iter.Next(ctx, doc)
1735 if err == io.EOF {
1736 break
1737 }
1738 if err != nil {
1739 fataler.Fatalf("%+v", err)
1740 }
1741 dels.Delete(doc)
1742 }
1743 if err := dels.Do(ctx); err != nil {
1744 fataler.Fatalf("%+v", err)
1745 }
1746 }
1747
1748 func forEach(ctx context.Context, iter *docstore.DocumentIterator, create func() any, handle func(any) error) error {
1749 for {
1750 doc := create()
1751 err := iter.Next(ctx, doc)
1752 if err == io.EOF {
1753 break
1754 }
1755 if err != nil {
1756 return err
1757 }
1758 if err := handle(doc); err != nil {
1759 return err
1760 }
1761 }
1762 return nil
1763 }
1764
1765 func mustCollect(ctx context.Context, t *testing.T, iter *docstore.DocumentIterator) []docmap {
1766 t.Helper()
1767
1768 var ms []docmap
1769 newDocmap := func() any { return docmap{} }
1770 collect := func(m any) error { ms = append(ms, m.(docmap)); return nil }
1771 if err := forEach(ctx, iter, newDocmap, collect); err != nil {
1772 t.Fatal(err)
1773 }
1774 return ms
1775 }
1776
1777 func mustCollectHighScores(ctx context.Context, t *testing.T, iter *docstore.DocumentIterator) []*HighScore {
1778 t.Helper()
1779
1780 hs, err := collectHighScores(ctx, iter)
1781 if err != nil {
1782 t.Fatal(err)
1783 }
1784 return hs
1785 }
1786
1787 func collectHighScores(ctx context.Context, iter *docstore.DocumentIterator) ([]*HighScore, error) {
1788 var hs []*HighScore
1789 collect := func(h any) error { hs = append(hs, h.(*HighScore)); return nil }
1790 if err := forEach(ctx, iter, newHighScore, collect); err != nil {
1791 return nil, err
1792 }
1793 return hs, nil
1794 }
1795
1796 func testMultipleActions(t *testing.T, coll *docstore.Collection, revField string) {
1797 t.Helper()
1798
1799 ctx := context.Background()
1800
1801 must := func(err error) {
1802 t.Helper()
1803 if err != nil {
1804 t.Fatal(err)
1805 }
1806 }
1807
1808 var docs []docmap
1809 for i := range 9 {
1810 docs = append(docs, docmap{
1811 KeyField: fmt.Sprintf("testUnorderedActions%d", i),
1812 "s": fmt.Sprint(i),
1813 revField: nil,
1814 })
1815 }
1816
1817 compare := func(gots, wants []docmap) {
1818 t.Helper()
1819 for i := range gots {
1820 got := gots[i]
1821 want := clone(wants[i])
1822 want[revField] = got[revField]
1823 if !cmp.Equal(got, want, cmpopts.IgnoreUnexported(tspb.Timestamp{})) {
1824 t.Errorf("index #%d:\ngot %v\nwant %v", i, got, want)
1825 }
1826 }
1827 }
1828
1829 // Put the first three docs.
1830 actions := coll.Actions()
1831 for i := range 6 {
1832 actions.Create(docs[i])
1833 }
1834 must(actions.Do(ctx))
1835
1836 // Replace the first three and put six more.
1837 actions = coll.Actions()
1838 for i := range 3 {
1839 docs[i]["s"] = fmt.Sprintf("%d'", i)
1840 actions.Replace(docs[i])
1841 }
1842 for i := 3; i < 9; i++ {
1843 actions.Put(docs[i])
1844 }
1845 must(actions.Do(ctx))
1846
1847 // Delete the first three, get the second three, and put three more.
1848 gdocs := []docmap{
1849 {KeyField: docs[3][KeyField]},
1850 {KeyField: docs[4][KeyField]},
1851 {KeyField: docs[5][KeyField]},
1852 }
1853 actions = coll.Actions()
1854 actions.Update(docs[6], docstore.Mods{"s": "6'", "n": docstore.Increment(1)})
1855 actions.Get(gdocs[0])
1856 actions.Delete(docs[0])
1857 actions.Delete(docs[1])
1858 actions.Update(docs[7], docstore.Mods{"s": "7'"})
1859 actions.Get(gdocs[1])
1860 actions.Delete(docs[2])
1861 actions.Get(gdocs[2])
1862 actions.Update(docs[8], docstore.Mods{"n": docstore.Increment(-1)})
1863 must(actions.Do(ctx))
1864 compare(gdocs, docs[3:6])
1865
1866 // At this point, the existing documents are 3 - 9.
1867
1868 // Get the first four, try to create one that already exists, delete a
1869 // nonexistent doc, and put one. Only the Get of #3, the Delete and the Put
1870 // should succeed.
1871 actions = coll.Actions()
1872 for _, doc := range []docmap{
1873 {KeyField: docs[0][KeyField]},
1874 {KeyField: docs[1][KeyField]},
1875 {KeyField: docs[2][KeyField]},
1876 {KeyField: docs[3][KeyField]},
1877 } {
1878 actions.Get(doc)
1879 }
1880 docs[4][revField] = nil
1881 actions.Create(docs[4]) // create existing doc
1882 actions.Put(docs[5])
1883 // TODO(jba): Understand why the following line is necessary for dynamo but not the others.
1884 docs[0][revField] = nil
1885 actions.Delete(docs[0]) // delete nonexistent doc
1886 err := actions.Do(ctx)
1887 if err == nil {
1888 t.Fatal("want error, got nil")
1889 }
1890 alerr, ok := err.(docstore.ActionListError)
1891 if !ok {
1892 t.Fatalf("got %v (%T), want ActionListError", alerr, alerr)
1893 }
1894 for _, e := range alerr {
1895 switch i := e.Index; i {
1896 case 3, 5, 6:
1897 t.Errorf("index %d: got %v, want nil", i, e.Err)
1898
1899 case 4, -1: // -1 for mongodb issue, see https://jira.mongodb.org/browse/GODRIVER-1028
1900 if ec := gcerrors.Code(e.Err); ec != gcerrors.AlreadyExists &&
1901 ec != gcerrors.FailedPrecondition { // TODO(shantuo): distinguish this case for dyanmo
1902 t.Errorf("index 4: create an existing document: got %v, want error", e.Err)
1903 }
1904
1905 default:
1906 if gcerrors.Code(e.Err) != gcerrors.NotFound {
1907 t.Errorf("index %d: got %v, want NotFound", i, e.Err)
1908 }
1909 }
1910 }
1911 }
1912
1913 func testAtomicWrites(t *testing.T, coll *docstore.Collection, revField string) {
1914 t.Helper()
1915
1916 ctx := context.Background()
1917
1918 must := func(err error) {
1919 t.Helper()
1920 if err != nil {
1921 t.Fatal(err)
1922 }
1923 }
1924
1925 var docs []docmap
1926 for i := range 9 {
1927 docs = append(docs, docmap{
1928 KeyField: fmt.Sprintf("testAtomicWrites%d", i),
1929 "s": fmt.Sprint(i),
1930 revField: nil,
1931 })
1932 }
1933
1934 compare := func(gots, wants []docmap) {
1935 t.Helper()
1936 for i := range gots {
1937 got := gots[i]
1938 want := clone(wants[i])
1939 want[revField] = got[revField]
1940 if !cmp.Equal(got, want, cmpopts.IgnoreUnexported(tspb.Timestamp{})) {
1941 t.Errorf("index #%d:\ngot %v\nwant %v", i, got, want)
1942 }
1943 }
1944 }
1945
1946 // Put the nine docs.
1947 actions := coll.Actions()
1948 for i := range 9 {
1949 actions.Create(docs[i])
1950 }
1951 must(actions.Do(ctx))
1952
1953 // Delete the first three, get the second three, and update last three in transaction.
1954 gdocs := []docmap{
1955 {KeyField: docs[3][KeyField]},
1956 {KeyField: docs[4][KeyField]},
1957 {KeyField: docs[5][KeyField]},
1958 }
1959 actions = coll.Actions()
1960 actions.Get(gdocs[0])
1961 actions.Delete(docs[0])
1962 actions.Delete(docs[1])
1963 actions.Get(gdocs[1])
1964 actions.Delete(docs[2])
1965 actions.Get(gdocs[2])
1966 actions.AtomicWrites()
1967 actions.Update(docs[6], docstore.Mods{"s": "66"})
1968 actions.Update(docs[7], docstore.Mods{"s": "77"})
1969 actions.Update(docs[8], docstore.Mods{"s": "88"})
1970
1971 must(actions.Do(ctx))
1972 compare(gdocs, docs[3:6])
1973
1974 // Get the docs updated as part of atomic writes and verify that the values were updated successfully.
1975 actions = coll.Actions()
1976
1977 doc := docmap{KeyField: docs[6][KeyField]}
1978 _ = coll.Get(ctx, doc)
1979 if diff := cmpDiff("66", doc["s"]); diff != "" {
1980 t.Fatal(diff)
1981 }
1982
1983 doc = docmap{KeyField: docs[7][KeyField]}
1984 _ = coll.Get(ctx, doc)
1985 if diff := cmpDiff("77", doc["s"]); diff != "" {
1986 t.Fatal(diff)
1987 }
1988
1989 doc = docmap{KeyField: docs[8][KeyField]}
1990 _ = coll.Get(ctx, doc)
1991 if diff := cmpDiff("88", doc["s"]); diff != "" {
1992 t.Fatal(diff)
1993 }
1994 }
1995
1996 func testAtomicWritesFail(t *testing.T, coll *docstore.Collection, revField string) {
1997 t.Helper()
1998
1999 ctx := context.Background()
2000
2001 must := func(err error) {
2002 t.Helper()
2003 if err != nil {
2004 t.Fatal(err)
2005 }
2006 }
2007
2008 var docs []docmap
2009 for i := range 9 {
2010 docs = append(docs, docmap{
2011 KeyField: fmt.Sprintf("testAtomicWrites%d", i),
2012 "s": fmt.Sprint(i),
2013 revField: nil,
2014 })
2015 }
2016
2017 compare := func(gots, wants []docmap) {
2018 t.Helper()
2019 for i := range gots {
2020 got := gots[i]
2021 want := clone(wants[i])
2022 want[revField] = got[revField]
2023 if !cmp.Equal(got, want, cmpopts.IgnoreUnexported(tspb.Timestamp{})) {
2024 t.Errorf("index #%d:\ngot %v\nwant %v", i, got, want)
2025 }
2026 }
2027 }
2028
2029 // Put the first eight docs.
2030 actions := coll.Actions()
2031 for i := range 8 {
2032 actions.Create(docs[i])
2033 }
2034 must(actions.Do(ctx))
2035
2036 // Delete the first three, get the second three, and update last three in transaction.
2037 gdocs := []docmap{
2038 {KeyField: docs[3][KeyField]},
2039 {KeyField: docs[4][KeyField]},
2040 {KeyField: docs[5][KeyField]},
2041 }
2042 actions = coll.Actions()
2043 actions.Get(gdocs[0])
2044 actions.Delete(docs[0])
2045 actions.Delete(docs[1])
2046 actions.Get(gdocs[1])
2047 actions.Delete(docs[2])
2048 actions.Get(gdocs[2])
2049 actions.AtomicWrites()
2050 actions.Update(docs[6], docstore.Mods{"s": "66"})
2051 actions.Update(docs[7], docstore.Mods{"s": "77"})
2052 // this document doesn't exist so it will fail the transaction
2053 actions.Update(docs[8], docstore.Mods{"s": "88"})
2054
2055 err := actions.Do(ctx)
2056 if err == nil {
2057 t.Fatal("want transaction to fail")
2058 }
2059 compare(gdocs, docs[3:6])
2060
2061 // validate that the values still remains the original
2062 doc := docmap{KeyField: docs[6][KeyField]}
2063 _ = coll.Get(ctx, doc)
2064 if diff := cmpDiff("6", doc["s"]); diff != "" {
2065 t.Fatal(diff)
2066 }
2067
2068 doc = docmap{KeyField: docs[7][KeyField]}
2069 _ = coll.Get(ctx, doc)
2070 if diff := cmpDiff("7", doc["s"]); diff != "" {
2071 t.Fatal(diff)
2072 }
2073 }
2074
2075 func testActionsOnStructNoRev(t *testing.T, _ Harness, coll *docstore.Collection) {
2076 t.Helper()
2077
2078 type item struct {
2079 Name string `docstore:"name"`
2080 I int
2081 }
2082 doc1 := item{Name: "createandreplace"}
2083 doc2 := item{Name: "putandupdate"}
2084 ctx := context.Background()
2085
2086 got1 := item{Name: doc1.Name}
2087 got2 := map[string]any{"name": doc2.Name}
2088 if err := coll.Actions().
2089 Create(&doc1).Put(&doc2).
2090 Get(&got1).Get(got2).
2091 Do(ctx); err != nil {
2092 t.Fatal(err)
2093 }
2094 checkNoRevisionField(t, got2, docstore.DefaultRevisionField)
2095
2096 got3 := map[string]any{"name": doc1.Name}
2097 got4 := item{Name: doc2.Name}
2098 if err := coll.Actions().
2099 Replace(&doc1).Update(&item{Name: doc2.Name}, docstore.Mods{"I": 1}).
2100 Get(got3, "I").Get(&got4, "I").
2101 Do(ctx); err != nil {
2102 t.Fatal(err)
2103 }
2104 checkNoRevisionField(t, got3, docstore.DefaultRevisionField)
2105 }
2106
2107 func testExampleInDoc(t *testing.T, _ Harness, coll *docstore.Collection) {
2108 t.Helper()
2109
2110 type Name struct {
2111 First, Last string
2112 }
2113 type Book struct {
2114 Title string `docstore:"name"`
2115 Author Name `docstore:"author"`
2116 PublicationYears []int `docstore:"pub_years,omitempty"`
2117 NumPublications int `docstore:"-"`
2118 }
2119
2120 must := func(err error) {
2121 t.Helper()
2122 if err != nil {
2123 t.Fatal(err)
2124 }
2125 }
2126 checkFieldEqual := func(got, want any, field string) {
2127 t.Helper()
2128 fvg, err := MustDocument(got).GetField(field)
2129 must(err)
2130 fvw, err := MustDocument(want).GetField(field)
2131 must(err)
2132 if !cmp.Equal(fvg, fvw) {
2133 t.Errorf("%s: got %v want %v", field, fvg, fvw)
2134 }
2135 }
2136
2137 doc1 := &Book{
2138 Title: "The Master and Margarita",
2139 Author: Name{
2140 First: "Mikhail",
2141 Last: "Bulgakov",
2142 },
2143 PublicationYears: []int{1967, 1973},
2144 NumPublications: 2,
2145 }
2146
2147 doc2 := map[string]any{
2148 KeyField: "The Heart of a Dog",
2149 "author": map[string]any{
2150 "First": "Mikhail",
2151 "Last": "Bulgakov",
2152 },
2153 "pub_years": []int{1968, 1987},
2154 }
2155
2156 ctx := context.Background()
2157 must(coll.Actions().Create(doc1).Put(doc2).Do(ctx))
2158 got1 := &Book{Title: doc1.Title}
2159 got2 := &Book{Title: doc2[KeyField].(string)}
2160 must(coll.Actions().Get(got1).Get(got2).Do(ctx))
2161
2162 if got1.NumPublications != 0 {
2163 t.Errorf("docstore:\"-\" tagged field isn't ignored")
2164 }
2165 checkFieldEqual(got1, doc1, "author")
2166 checkFieldEqual(got2, doc2, "pub_years")
2167
2168 gots := mustCollect(ctx, t, coll.Query().Where("author.Last", "=", "Bulgakov").Get(ctx))
2169 if len(gots) != 2 {
2170 t.Errorf("got %v want all two results", gots)
2171 }
2172 must(coll.Actions().Delete(doc1).Delete(doc2).Do(ctx))
2173 }
2174
2175 // Verify that BeforeDo is invoked, and its as function behaves as expected.
2176 func testBeforeDo(t *testing.T, newHarness HarnessMaker) {
2177 t.Helper()
2178
2179 ctx := context.Background()
2180 withCollection(t, newHarness, SingleKey, func(t *testing.T, h Harness, coll *docstore.Collection) {
2181 t.Helper()
2182
2183 var called bool
2184 beforeDo := func(asFunc func(any) bool) error {
2185 called = true
2186 if asFunc(nil) {
2187 return errors.New("asFunc returned true when called with nil, want false")
2188 }
2189 // At least one of the expected types must return true. Special case: if
2190 // there are no types, then the as function never returns true, so skip the
2191 // check.
2192 if len(h.BeforeDoTypes()) > 0 {
2193 found := false
2194 for _, b := range h.BeforeDoTypes() {
2195 v := reflect.New(reflect.TypeOf(b)).Interface()
2196 if asFunc(v) {
2197 found = true
2198 break
2199 }
2200 }
2201 if !found {
2202 return errors.New("none of the BeforeDoTypes works with the as function")
2203 }
2204 }
2205 return nil
2206 }
2207
2208 check := func(f func(*docstore.ActionList)) {
2209 t.Helper()
2210 // First, verify that if a BeforeDo function returns an error, so does ActionList.Do.
2211 // We depend on that for the rest of the test.
2212 al := coll.Actions().BeforeDo(func(func(any) bool) error { return errors.New("") })
2213 f(al)
2214 if err := al.Do(ctx); err == nil {
2215 t.Error("beforeDo returning error: got nil from Do, want error")
2216 return
2217 }
2218 called = false
2219 al = coll.Actions().BeforeDo(beforeDo)
2220 f(al)
2221 if err := al.Do(ctx); err != nil {
2222 t.Error(err)
2223 return
2224 }
2225 if !called {
2226 t.Error("BeforeDo function never called")
2227 }
2228 }
2229
2230 doc := docmap{KeyField: "testBeforeDo"}
2231 check(func(l *docstore.ActionList) { l.Create(doc) })
2232 check(func(l *docstore.ActionList) { l.Replace(doc) })
2233 check(func(l *docstore.ActionList) { l.Put(doc) })
2234 check(func(l *docstore.ActionList) { l.Update(doc, docstore.Mods{"a": 1}) })
2235 check(func(l *docstore.ActionList) { l.Get(doc) })
2236 check(func(l *docstore.ActionList) { l.Delete(doc) })
2237 })
2238 }
2239
2240 // Verify that BeforeQuery is invoked, and its as function behaves as expected.
2241 func testBeforeQuery(t *testing.T, newHarness HarnessMaker) {
2242 t.Helper()
2243
2244 ctx := context.Background()
2245 withCollection(t, newHarness, SingleKey, func(t *testing.T, h Harness, coll *docstore.Collection) {
2246 t.Helper()
2247
2248 var called bool
2249 beforeQuery := func(asFunc func(any) bool) error {
2250 called = true
2251 if asFunc(nil) {
2252 return errors.New("asFunc returned true when called with nil, want false")
2253 }
2254 // At least one of the expected types must return true. Special case: if
2255 // there are no types, then the as function never returns true, so skip the
2256 // check.
2257 if len(h.BeforeQueryTypes()) > 0 {
2258 found := false
2259 for _, b := range h.BeforeQueryTypes() {
2260 v := reflect.New(reflect.TypeOf(b)).Interface()
2261 if asFunc(v) {
2262 found = true
2263 break
2264 }
2265 }
2266 if !found {
2267 return errors.New("none of the BeforeQueryTypes works with the as function")
2268 }
2269 }
2270 return nil
2271 }
2272
2273 iter := coll.Query().BeforeQuery(beforeQuery).Get(ctx)
2274 if err := iter.Next(ctx, docmap{}); err != io.EOF {
2275 t.Fatalf("got %v, wanted io.EOF", err)
2276 }
2277 if !called {
2278 t.Error("BeforeQuery function never called for Get")
2279 }
2280 })
2281 }
2282
2283 func testAs(t *testing.T, coll *docstore.Collection, st AsTest) {
2284 t.Helper()
2285
2286 // Verify Collection.As
2287 if err := st.CollectionCheck(coll); err != nil {
2288 t.Error(err)
2289 }
2290
2291 ctx := context.Background()
2292
2293 // Query
2294 qs := []*docstore.Query{
2295 coll.Query().Where("Game", "=", game3),
2296 // Note: don't use filter on Player, the test table has Player as the
2297 // partition key of a Global Secondary Index, which doesn't support
2298 // ConsistentRead mode, which is what the As test does in its BeforeQuery
2299 // function.
2300 coll.Query().Where("Score", ">", 50),
2301 }
2302 for _, q := range qs {
2303 iter := q.Get(ctx)
2304 if err := st.QueryCheck(iter); err != nil {
2305 t.Error(err)
2306 }
2307 }
2308
2309 // ErrorCheck
2310 doc := &HighScore{game3, "steph", 24, date(4, 25), false, nil}
2311 if err := coll.Create(ctx, doc); err != nil {
2312 t.Fatal(err)
2313 }
2314 doc.DocstoreRevision = nil
2315 if err := coll.Create(ctx, doc); err == nil {
2316 t.Fatal("got nil error from creating an existing item, want an error")
2317 } else {
2318 if alerr, ok := err.(docstore.ActionListError); ok {
2319 for _, aerr := range alerr {
2320 if checkerr := st.ErrorCheck(coll, aerr.Err); checkerr != nil {
2321 t.Error(checkerr)
2322 }
2323 }
2324 } else if checkerr := st.ErrorCheck(coll, err); checkerr != nil {
2325 t.Error(checkerr)
2326 }
2327 }
2328 }
2329
2330 func clone(m docmap) docmap {
2331 r := docmap{}
2332 maps.Copy(r, m)
2333 return r
2334 }
2335
2336 func cmpDiff(a, b any, opts ...cmp.Option) string {
2337 // Firestore revisions can be protos.
2338 return cmp.Diff(a, b, append([]cmp.Option{cmp.Comparer(proto.Equal)}, opts...)...)
2339 }
2340
2341 func checkCode(t *testing.T, err error, code gcerrors.ErrorCode) {
2342 t.Helper()
2343 if gcerrors.Code(err) != code {
2344 t.Errorf("got %v, want %s", err, code)
2345 }
2346 }