Debian Codegraph @

docstore/awsdynamodb/v2/dynamo_test.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 awsdynamodb
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "io"
22 "testing"
23
24 "github.com/aws/aws-sdk-go-v2/aws"
25 "github.com/aws/aws-sdk-go-v2/config"
26 dyn "github.com/aws/aws-sdk-go-v2/service/dynamodb"
27 "github.com/aws/smithy-go"
28 "gocloud.dev/docstore"
29 "gocloud.dev/docstore/driver"
30 "gocloud.dev/docstore/drivertest"
31 "gocloud.dev/gcerrors"
32 "gocloud.dev/internal/testing/setup"
33 )
34
35 // To create the tables and indexes needed for these tests, run create_tables.sh in
36 // this directory.
37 //
38 // The docstore-test-2 table is set up to work with queries on the drivertest.HighScore
39 // struct like so:
40 // table: "Game" partition key, "Player" sort key
41 // local index: "Game" partition key, "Score" sort key
42 // global index: "Player" partition key, "Time" sort key
43 // The conformance test queries should exercise all of these.
44 //
45 // The docstore-test-3 table is used for running benchmarks only. To eliminate
46 // the effect of dynamo auto-scaling, run:
47 // aws dynamodb update-table --table-name docstore-test-3 \
48 // --provisioned-throughput ReadCapacityUnits=1000,WriteCapacityUnits=1000
49 // Don't forget to change it back when done benchmarking.
50
51 const (
52 region = "us-east-2"
53 collectionName1 = "docstore-test-1"
54 collectionName2 = "docstore-test-2"
55 collectionName3 = "docstore-test-3" // for benchmark
56 )
57
58 type harness struct {
59 sess aws.Config
60 closer func()
61 }
62
63 func (h *harness) SupportsAtomicWrites() bool {
64 return true
65 }
66
67 func newHarness(ctx context.Context, t *testing.T) (drivertest.Harness, error) {
68 t.Helper()
69
70 // Many POST requests for DynamoDB are JSON maps, and they come in randomized
71 // key order, so strict matching doesn't work. We disable it and count on ordering
72 // and header matching.
73 scrubBody := true
74 sess, _, done, state := setup.NewAWSv2Config(ctx, t, region, scrubBody)
75 drivertest.MakeUniqueStringDeterministicForTesting(state)
76 return &harness{sess: sess, closer: done}, nil
77 }
78
79 func (*harness) BeforeDoTypes() []any {
80 return []any{
81 &dyn.BatchGetItemInput{}, &dyn.TransactWriteItemsInput{},
82 &dyn.PutItemInput{}, &dyn.DeleteItemInput{}, &dyn.UpdateItemInput{},
83 }
84 }
85
86 func (*harness) BeforeQueryTypes() []any {
87 return []any{&dyn.QueryInput{}, &dyn.ScanInput{}}
88 }
89
90 func (*harness) RevisionsEqual(rev1, rev2 any) bool {
91 return rev1 == rev2
92 }
93
94 func (h *harness) Close() {
95 h.closer()
96 }
97
98 func (h *harness) MakeCollection(_ context.Context, kind drivertest.CollectionKind) (driver.Collection, error) {
99 switch kind {
100 case drivertest.SingleKey, drivertest.NoRev:
101 return newCollection(dyn.NewFromConfig(h.sess), collectionName1, drivertest.KeyField, "", &Options{
102 AllowScans: true,
103 ConsistentRead: true,
104 })
105 case drivertest.TwoKey:
106 // For query test we don't use strong consistency mode since some tests are
107 // running on global secondary index and it doesn't support ConsistentRead.
108 return newCollection(dyn.NewFromConfig(h.sess), collectionName2, "Game", "Player", &Options{
109 AllowScans: true,
110 RunQueryFallback: InMemorySortFallback(func() any { return new(drivertest.HighScore) }),
111 })
112 case drivertest.AltRev:
113 return newCollection(dyn.NewFromConfig(h.sess), collectionName1, drivertest.KeyField, "",
114 &Options{
115 AllowScans: true,
116 RevisionField: drivertest.AlternateRevisionField,
117 ConsistentRead: true,
118 })
119 default:
120 panic("bad kind")
121 }
122 }
123
124 func collectHighScores(ctx context.Context, iter driver.DocumentIterator) ([]*drivertest.HighScore, error) {
125 var hs []*drivertest.HighScore
126 for {
127 var h drivertest.HighScore
128 doc := drivertest.MustDocument(&h)
129 err := iter.Next(ctx, doc)
130 if err == io.EOF {
131 break
132 }
133 if err != nil {
134 return nil, err
135 }
136 hs = append(hs, &h)
137 }
138 return hs, nil
139 }
140
141 type highScoreSliceIterator struct {
142 hs []*drivertest.HighScore
143 next int
144 }
145
146 func (it *highScoreSliceIterator) Next(ctx context.Context, doc driver.Document) error {
147 if it.next >= len(it.hs) {
148 return io.EOF
149 }
150 dest, ok := doc.Origin.(*drivertest.HighScore)
151 if !ok {
152 return fmt.Errorf("doc is %T, not HighScore", doc.Origin)
153 }
154 *dest = *it.hs[it.next]
155 it.next++
156 return nil
157 }
158
159 func (*highScoreSliceIterator) Stop() {}
160 func (*highScoreSliceIterator) As(any) bool { return false }
161
162 type verifyAs struct{}
163
164 func (verifyAs) Name() string {
165 return "verify As"
166 }
167
168 func (verifyAs) CollectionCheck(coll *docstore.Collection) error {
169 var db *dyn.Client
170 if !coll.As(&db) {
171 return errors.New("Collection.As failed")
172 }
173 return nil
174 }
175
176 func (verifyAs) QueryCheck(it *docstore.DocumentIterator) error {
177 var so *dyn.ScanOutput
178 var qo *dyn.QueryOutput
179 if !it.As(&so) && !it.As(&qo) {
180 return errors.New("DocumentIterator.As failed")
181 }
182 return nil
183 }
184
185 func (v verifyAs) ErrorCheck(k *docstore.Collection, err error) error {
186 var e smithy.OperationError
187 if !k.ErrorAs(err, &e) {
188 return errors.New("Collection.ErrorAs failed")
189 }
190 return nil
191 }
192
193 func TestConformance(t *testing.T) {
194 // Note: when running -record repeatedly in a short time period, change the argument
195 // in the call below to generate unique transaction tokens.
196 drivertest.MakeUniqueStringDeterministicForTesting(1)
197 drivertest.RunConformanceTests(t, newHarness, &codecTester{}, []drivertest.AsTest{verifyAs{}})
198 }
199
200 func BenchmarkConformance(b *testing.B) {
201 cfg, err := config.LoadDefaultConfig(context.Background(), config.WithRegion(region))
202 if err != nil {
203 b.Fatal("Error loading AWS config for benchmark: ", err)
204 }
205 coll, err := newCollection(dyn.NewFromConfig(cfg), collectionName3, drivertest.KeyField, "", &Options{AllowScans: true})
206 if err != nil {
207 b.Fatal(err)
208 }
209 drivertest.RunBenchmarks(b, docstore.NewCollection(coll))
210 }
211
212 // awsdynamodb-specific tests.
213
214 func TestQueryErrors(t *testing.T) {
215 // Verify that bad queries return the right errors.
216 ctx := context.Background()
217 h, err := newHarness(ctx, t)
218 if err != nil {
219 t.Fatal(err)
220 }
221 defer h.Close()
222 dc, err := h.MakeCollection(ctx, drivertest.TwoKey)
223 if err != nil {
224 t.Fatal(err)
225 }
226 coll := docstore.NewCollection(dc)
227 defer coll.Close()
228
229 // Here we are comparing a key field with the wrong type. DynamoDB cares about this
230 // because even though it's a document store and hence schemaless, the key fields
231 // do have a schema (that is, they have known, fixed types).
232 iter := coll.Query().Where("Game", "=", 1).Get(ctx)
233 defer iter.Stop()
234 err = iter.Next(ctx, &h)
235 if c := gcerrors.Code(err); c != gcerrors.InvalidArgument {
236 t.Errorf("got %v (code %s, type %T), want InvalidArgument", err, c, err)
237 }
238 }