forked from googleapis/google-cloud-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry_conformance_test.go
836 lines (787 loc) · 26 KB
/
retry_conformance_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
// Copyright 2019 Google LLC
//
// 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
//
// http://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 storage
import (
"bytes"
"context"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"testing"
"cloud.google.com/go/internal/uid"
storage_v1_tests "cloud.google.com/go/storage/internal/test/conformance"
"github.com/googleapis/gax-go/v2/callctx"
"google.golang.org/api/iterator"
)
const (
projectID = "my-project-id"
serviceAccountEmail = "my-sevice-account@my-project-id.iam.gserviceaccount.com"
MiB = 1 << 10 << 10
)
var (
// Resource vars for retry tests
bucketIDs = uid.NewSpace("bucket", nil)
objectIDs = uid.NewSpace("object", nil)
notificationIDs = uid.NewSpace("notification", nil)
size9MiB = 9 * MiB
randomBytesToWrite = []byte("abcdef")
// A 3 MiB object is large enough to span several messages and trigger a
// resumable upload in the Go library (with chunksize set to 2MiB). We use
// this in tests that require a larger object that can be less than 9MiB.
randomBytes3MiB = generateRandomBytes(3 * MiB)
// A 9 MiB object is required for "storage.resumable.upload"-specific tests,
// because there is a test that test errors after the first 8MiB.
randomBytes9MiB = generateRandomBytes(size9MiB)
)
type retryFunc func(ctx context.Context, c *Client, fs *resources, preconditions bool) error
// Methods to retry. This is a map whose keys are a string describing a standard
// API call (e.g. storage.objects.get) and values are a list of functions which
// wrap library methods that implement these calls. There may be multiple values
// because multiple library methods may use the same call (e.g. get could be a
// read or just a metadata get).
//
// There may be missing methods with respect to the json API as not all methods
// are used in the client library. The following are not used:
// storage.bucket_acl.get
// storage.bucket_acl.insert
// storage.bucket_acl.patch
// storage.buckets.update
// storage.default_object_acl.get
// storage.default_object_acl.insert
// storage.default_object_acl.patch
// storage.notifications.get
// storage.object_acl.get
// storage.object_acl.insert
// storage.object_acl.patch
// storage.objects.copy
// storage.objects.update
var methods = map[string][]retryFunc{
// Idempotent operations
"storage.bucket_acl.list": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.Bucket(fs.bucket.Name).ACL().List(ctx)
return err
},
},
"storage.buckets.delete": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
// Delete files from bucket before deleting bucket
it := c.Bucket(fs.bucket.Name).Objects(ctx, nil)
for {
attrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return err
}
if err := c.Bucket(fs.bucket.Name).Object(attrs.Name).Delete(ctx); err != nil {
return err
}
}
return c.Bucket(fs.bucket.Name).Delete(ctx)
},
},
"storage.buckets.get": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.Bucket(fs.bucket.Name).Attrs(ctx)
return err
},
},
"storage.buckets.getIamPolicy": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.Bucket(fs.bucket.Name).IAM().Policy(ctx)
return err
},
},
"storage.buckets.insert": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
b := bucketIDs.New()
return c.Bucket(b).Create(ctx, projectID, nil)
},
},
"storage.buckets.list": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
it := c.Buckets(ctx, projectID)
for {
_, err := it.Next()
if err == iterator.Done {
return nil
}
if err != nil {
return err
}
}
},
},
"storage.buckets.lockRetentionPolicy": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
// buckets.lockRetentionPolicy is always idempotent, but is a special case because IfMetagenerationMatch is always required
return c.Bucket(fs.bucket.Name).If(BucketConditions{MetagenerationMatch: fs.bucket.MetaGeneration}).LockRetentionPolicy(ctx)
},
},
"storage.buckets.testIamPermissions": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.Bucket(fs.bucket.Name).IAM().TestPermissions(ctx, nil)
return err
},
},
"storage.default_object_acl.list": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.Bucket(fs.bucket.Name).DefaultObjectACL().List(ctx)
return err
},
},
"storage.hmacKey.delete": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
// key must be inactive to delete:
c.HMACKeyHandle(projectID, fs.hmacKey.AccessID).Update(ctx, HMACKeyAttrsToUpdate{State: "INACTIVE"})
return c.HMACKeyHandle(projectID, fs.hmacKey.AccessID).Delete(ctx)
},
},
"storage.hmacKey.get": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.HMACKeyHandle(projectID, fs.hmacKey.AccessID).Get(ctx)
return err
},
},
"storage.hmacKey.list": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
it := c.ListHMACKeys(ctx, projectID)
for {
_, err := it.Next()
if err == iterator.Done {
return nil
}
if err != nil {
return err
}
}
},
},
"storage.notifications.delete": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
return c.Bucket(fs.bucket.Name).DeleteNotification(ctx, fs.notification.ID)
},
},
"storage.notifications.list": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.Bucket(fs.bucket.Name).Notifications(ctx)
return err
},
},
"storage.object_acl.list": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.Bucket(fs.bucket.Name).Object(fs.object.Name).ACL().List(ctx)
return err
},
},
"storage.objects.get": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.Bucket(fs.bucket.Name).Object(fs.object.Name).Attrs(ctx)
return err
},
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
r, err := c.Bucket(fs.bucket.Name).Object(fs.object.Name).NewReader(ctx)
if err != nil {
return err
}
wr, err := r.WriteTo(io.Discard)
if got, want := wr, len(randomBytesToWrite); got != int64(want) {
return fmt.Errorf("body length mismatch\ngot:\n%v\n\nwant:\n%v", got, want)
}
return err
},
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
r, err := c.Bucket(fs.bucket.Name).Object(fs.object.Name).NewReader(ctx)
if err != nil {
return err
}
// Use ReadAll because it calls Read implicitly, not WriteTo.
b, err := io.ReadAll(r)
if got, want := len(b), len(randomBytesToWrite); got != want {
return fmt.Errorf("body length mismatch\ngot:\n%v\n\nwant:\n%v", got, want)
}
return err
},
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
// Test JSON reads.
client, ok := c.tc.(*httpStorageClient)
if ok {
client.config.readAPIWasSet = true
client.config.useJSONforReads = true
defer func() {
client.config.readAPIWasSet = false
client.config.useJSONforReads = false
}()
}
r, err := c.Bucket(fs.bucket.Name).Object(fs.object.Name).NewReader(ctx)
if err != nil {
return err
}
wr, err := io.Copy(io.Discard, r)
if got, want := wr, len(randomBytesToWrite); got != int64(want) {
return fmt.Errorf("body length mismatch\ngot:\n%v\n\nwant:\n%v", got, want)
}
return err
},
},
"storage.objects.download": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
// Before running the test method, populate a large test object.
objName := objectIDs.New()
if err := uploadTestObject(fs.bucket.Name, objName, randomBytes3MiB); err != nil {
return fmt.Errorf("failed to create large object pre test, err: %v", err)
}
// Download the large test object for the S8 download method group.
r, err := c.Bucket(fs.bucket.Name).Object(objName).NewReader(ctx)
if err != nil {
return err
}
defer r.Close()
data, err := io.ReadAll(r)
if err != nil {
return fmt.Errorf("failed to ReadAll, err: %v", err)
}
if got, want := len(data), 3*MiB; got != want {
return fmt.Errorf("body length mismatch\ngot:\n%v\n\nwant:\n%v", got, want)
}
if got, want := data, randomBytes3MiB; !bytes.Equal(got, want) {
return fmt.Errorf("body mismatch\ngot:\n%v\n\nwant:\n%v", got, want)
}
return nil
},
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
// Test download via Reader.WriteTo.
// Before running the test method, populate a large test object of 9 MiB.
objName := objectIDs.New()
if err := uploadTestObject(fs.bucket.Name, objName, randomBytes3MiB); err != nil {
return fmt.Errorf("failed to create 9 MiB large object pre test, err: %v", err)
}
// Download the large test object for the S8 download method group.
r, err := c.Bucket(fs.bucket.Name).Object(objName).NewReader(ctx)
if err != nil {
return err
}
defer r.Close()
var data bytes.Buffer
_, err = r.WriteTo(&data)
if err != nil {
return fmt.Errorf("failed to ReadAll, err: %v", err)
}
if got, want := data.Len(), 3*MiB; got != want {
return fmt.Errorf("body length mismatch\ngot:\n%v\n\nwant:\n%v", got, want)
}
if got, want := data.Bytes(), randomBytes3MiB; !bytes.Equal(got, want) {
return fmt.Errorf("body mismatch\ngot:\n%v\n\nwant:\n%v", got, want)
}
return nil
},
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
// Test JSON reads.
// Before running the test method, populate a large test object.
objName := objectIDs.New()
if err := uploadTestObject(fs.bucket.Name, objName, randomBytes3MiB); err != nil {
return fmt.Errorf("failed to create large object pre test, err: %v", err)
}
client, ok := c.tc.(*httpStorageClient)
if ok {
client.config.readAPIWasSet = true
client.config.useJSONforReads = true
defer func() {
client.config.readAPIWasSet = false
client.config.useJSONforReads = false
}()
}
// Download the large test object for the S8 download method group.
r, err := c.Bucket(fs.bucket.Name).Object(objName).NewReader(ctx)
if err != nil {
return err
}
defer r.Close()
data, err := io.ReadAll(r)
if err != nil {
return fmt.Errorf("failed to ReadAll, err: %v", err)
}
if got, want := len(data), 3*MiB; got != want {
return fmt.Errorf("body length mismatch\ngot:\n%v\n\nwant:\n%v", got, want)
}
if got, want := data, randomBytes3MiB; !bytes.Equal(got, want) {
return fmt.Errorf("body mismatch\ngot:\n%v\n\nwant:\n%v", got, want)
}
return nil
},
},
"storage.objects.list": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
it := c.Bucket(fs.bucket.Name).Objects(ctx, nil)
for {
_, err := it.Next()
if err == iterator.Done {
return nil
}
if err != nil {
return err
}
}
},
},
"storage.serviceaccount.get": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.ServiceAccount(ctx, projectID)
return err
},
},
// Conditionally idempotent operations
"storage.buckets.patch": {
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
uattrs := BucketAttrsToUpdate{StorageClass: "ARCHIVE"}
bkt := c.Bucket(fs.bucket.Name)
if preconditions {
bkt = c.Bucket(fs.bucket.Name).If(BucketConditions{MetagenerationMatch: fs.bucket.MetaGeneration})
}
_, err := bkt.Update(ctx, uattrs)
return err
},
},
"storage.buckets.setIamPolicy": {
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
bkt := c.Bucket(fs.bucket.Name)
policy, err := bkt.IAM().Policy(ctx)
if err != nil {
return err
}
if !preconditions {
policy.InternalProto.Etag = nil
}
return bkt.IAM().SetPolicy(ctx, policy)
},
},
"storage.hmacKey.update": {
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
key := c.HMACKeyHandle(projectID, fs.hmacKey.AccessID)
uattrs := HMACKeyAttrsToUpdate{State: "INACTIVE"}
if preconditions {
uattrs.Etag = fs.hmacKey.Etag
}
_, err := key.Update(ctx, uattrs)
return err
},
},
"storage.objects.compose": {
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
dstName := "new-object"
src := c.Bucket(fs.bucket.Name).Object(fs.object.Name)
dst := c.Bucket(fs.bucket.Name).Object(dstName)
if preconditions {
dst = c.Bucket(fs.bucket.Name).Object(dstName).If(Conditions{DoesNotExist: true})
}
_, err := dst.ComposerFrom(src).Run(ctx)
return err
},
},
"storage.objects.delete": {
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
obj := c.Bucket(fs.bucket.Name).Object(fs.object.Name)
if preconditions {
obj = c.Bucket(fs.bucket.Name).Object(fs.object.Name).If(Conditions{GenerationMatch: fs.object.Generation})
}
return obj.Delete(ctx)
},
},
"storage.objects.insert": {
// Single-shot upload that is sent in a single message.
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
obj := c.Bucket(fs.bucket.Name).Object("new-object.txt")
if preconditions {
obj = obj.If(Conditions{DoesNotExist: true})
}
objW := obj.NewWriter(ctx)
if _, err := io.Copy(objW, strings.NewReader("object body")); err != nil {
return fmt.Errorf("io.Copy: %v", err)
}
if err := objW.Close(); err != nil {
return fmt.Errorf("Writer.Close: %v", err)
}
return nil
},
// Single-shot upload that spans several GRPC message sends (we send
// storagepb.ServiceConstants_MAX_WRITE_CHUNK_BYTES=2MiB per msg).
// This is needed to cover all error code paths.
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
obj := c.Bucket(fs.bucket.Name).Object("new-object.txt")
if preconditions {
obj = obj.If(Conditions{DoesNotExist: true})
}
objW := obj.NewWriter(ctx)
if _, err := objW.Write(randomBytes3MiB); err != nil {
return fmt.Errorf("io.Copy: %v", err)
}
if err := objW.Close(); err != nil {
return fmt.Errorf("Writer.Close: %v", err)
}
return nil
},
// Resumable upload.
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
obj := c.Bucket(fs.bucket.Name).Object("new-object.txt")
if preconditions {
obj = obj.If(Conditions{DoesNotExist: true})
}
objW := obj.NewWriter(ctx)
objW.ChunkSize = 2 * MiB
if _, err := objW.Write(randomBytes3MiB); err != nil {
return fmt.Errorf("io.Copy: %v", err)
}
if err := objW.Close(); err != nil {
return fmt.Errorf("Writer.Close: %v", err)
}
return nil
},
},
"storage.resumable.upload": {
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
obj := c.Bucket(fs.bucket.Name).Object(objectIDs.New())
if preconditions {
obj = obj.If(Conditions{DoesNotExist: true})
}
w := obj.NewWriter(ctx)
// Set Writer.ChunkSize to 2 MiB to perform resumable uploads.
w.ChunkSize = 2097152
if _, err := w.Write(randomBytes9MiB); err != nil {
return fmt.Errorf("writing object: %v", err)
}
if err := w.Close(); err != nil {
return fmt.Errorf("closing object: %v", err)
}
return nil
},
},
"storage.objects.patch": {
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
uattrs := ObjectAttrsToUpdate{Metadata: map[string]string{"foo": "bar"}}
obj := c.Bucket(fs.bucket.Name).Object(fs.object.Name)
if preconditions {
obj = obj.If(Conditions{MetagenerationMatch: fs.object.Metageneration})
}
_, err := obj.Update(ctx, uattrs)
return err
},
},
"storage.objects.rewrite": {
func(ctx context.Context, c *Client, fs *resources, preconditions bool) error {
dstName := "new-object"
src := c.Bucket(fs.bucket.Name).Object(fs.object.Name)
dst := c.Bucket(fs.bucket.Name).Object(dstName)
if preconditions {
dst = c.Bucket(fs.bucket.Name).Object(dstName).If(Conditions{DoesNotExist: true})
}
_, err := dst.CopierFrom(src).Run(ctx)
return err
},
},
// Non-idempotent operations
"storage.bucket_acl.delete": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
return c.Bucket(fs.bucket.Name).ACL().Delete(ctx, AllUsers)
},
},
"storage.bucket_acl.update": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
return c.Bucket(fs.bucket.Name).ACL().Set(ctx, AllAuthenticatedUsers, RoleOwner)
},
},
"storage.default_object_acl.delete": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
return c.Bucket(fs.bucket.Name).DefaultObjectACL().Delete(ctx, AllAuthenticatedUsers)
},
},
"storage.default_object_acl.update": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
return c.Bucket(fs.bucket.Name).DefaultObjectACL().Set(ctx, AllAuthenticatedUsers, RoleOwner)
},
},
"storage.hmacKey.create": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
_, err := c.CreateHMACKey(ctx, projectID, serviceAccountEmail)
return err
},
},
"storage.notifications.insert": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
notification := Notification{
TopicID: "my-topic",
TopicProjectID: projectID,
PayloadFormat: "json",
}
_, err := c.Bucket(fs.bucket.Name).AddNotification(ctx, ¬ification)
return err
},
},
"storage.object_acl.delete": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
return c.Bucket(fs.bucket.Name).Object(fs.object.Name).ACL().Delete(ctx, AllAuthenticatedUsers)
},
},
"storage.object_acl.update": {
func(ctx context.Context, c *Client, fs *resources, _ bool) error {
return c.Bucket(fs.bucket.Name).Object(fs.object.Name).ACL().Set(ctx, AllAuthenticatedUsers, RoleOwner)
},
},
}
func TestRetryConformance(t *testing.T) {
host := os.Getenv("STORAGE_EMULATOR_HOST")
if host == "" {
t.Skip("This test must use the testbench emulator; set STORAGE_EMULATOR_HOST to run.")
}
endpoint, err := url.Parse(host)
if err != nil {
t.Fatalf("error parsing emulator host (make sure it includes the scheme such as http://host): %v", err)
}
ctx := context.Background()
// Create non-wrapped client to use for setup steps.
client, err := NewClient(ctx)
if err != nil {
t.Fatalf("storage.NewClient: %v", err)
}
_, _, testFiles := parseFiles(t)
for _, testFile := range testFiles {
for _, retryTest := range testFile.RetryTests {
for _, instructions := range retryTest.Cases {
for _, method := range retryTest.Methods {
methodName := method.Name
if method.Group != "" {
methodName = method.Group
}
if len(methods[methodName]) == 0 {
t.Logf("No tests for operation %v", methodName)
}
for i, fn := range methods[methodName] {
transports := []string{"http", "grpc"}
for _, transport := range transports {
testName := fmt.Sprintf("%v-%v-%v-%v-%v", transport, retryTest.Id, instructions.Instructions, methodName, i)
t.Run(testName, func(t *testing.T) {
// Create the retry subtest
subtest := &emulatorTest{T: t, name: testName, host: endpoint}
subtest.create(map[string][]string{
method.Name: instructions.Instructions,
}, transport)
// Create necessary test resources in the emulator
subtest.populateResources(ctx, client, method.Resources)
// Test
// Set retry test id through headers per test call
ctx := context.Background()
ctx = callctx.SetHeaders(ctx, "x-retry-test-id", subtest.id)
err = fn(ctx, subtest.transportClient, &subtest.resources, retryTest.PreconditionProvided)
if retryTest.ExpectSuccess && err != nil {
t.Errorf("want success, got %v", err)
}
if !retryTest.ExpectSuccess && err == nil {
t.Errorf("want failure, got success")
}
// Verify that all instructions were used up during the test
// (indicates that the client sent the correct requests).
subtest.check()
// Close out test in emulator.
subtest.delete()
})
}
}
}
}
}
}
}
type emulatorTest struct {
*testing.T
name string
id string // ID to pass as a header in the test execution
resources resources
host *url.URL // set the path when using; path is not guaranteed between calls
transportClient *Client
}
// Holds the resources for a particular test case. Only the necessary fields will
// be populated; others will be nil.
type resources struct {
bucket *BucketAttrs
object *ObjectAttrs
notification *Notification
hmacKey *HMACKey
}
// Creates given test resources with the provided client
func (et *emulatorTest) populateResources(ctx context.Context, c *Client, resources []storage_v1_tests.Resource) {
for _, resource := range resources {
switch resource {
case storage_v1_tests.Resource_BUCKET:
bkt := c.Bucket(bucketIDs.New())
if err := bkt.Create(ctx, projectID, &BucketAttrs{}); err != nil {
et.Fatalf("creating bucket: %v", err)
}
attrs, err := bkt.Attrs(ctx)
if err != nil {
et.Fatalf("getting bucket attrs: %v", err)
}
et.resources.bucket = attrs
case storage_v1_tests.Resource_OBJECT:
// Assumes bucket has been populated first.
obj := c.Bucket(et.resources.bucket.Name).Object(objectIDs.New())
w := obj.NewWriter(ctx)
if _, err := w.Write(randomBytesToWrite); err != nil {
et.Fatalf("writing object: %v", err)
}
if err := w.Close(); err != nil {
et.Fatalf("closing object: %v", err)
}
attrs, err := obj.Attrs(ctx)
if err != nil {
et.Fatalf("getting object attrs: %v", err)
}
et.resources.object = attrs
case storage_v1_tests.Resource_NOTIFICATION:
// Assumes bucket has been populated first.
n, err := c.Bucket(et.resources.bucket.Name).AddNotification(ctx, &Notification{
TopicProjectID: projectID,
TopicID: notificationIDs.New(),
PayloadFormat: JSONPayload,
})
if err != nil {
et.Fatalf("adding notification: %v", err)
}
et.resources.notification = n
case storage_v1_tests.Resource_HMAC_KEY:
key, err := c.CreateHMACKey(ctx, projectID, serviceAccountEmail)
if err != nil {
et.Fatalf("creating HMAC key: %v", err)
}
et.resources.hmacKey = key
}
}
}
// Generates size random bytes.
func generateRandomBytes(n int) []byte {
b := make([]byte, n)
_, _ = rand.Read(b)
return b
}
// Upload test object with given bytes.
func uploadTestObject(bucketName, objName string, n []byte) error {
// Create non-wrapped client to create test object.
ctx := context.Background()
c, err := NewClient(ctx)
if err != nil {
return fmt.Errorf("storage.NewClient: %v", err)
}
obj := c.Bucket(bucketName).Object(objName)
w := obj.NewWriter(ctx)
if _, err := w.Write(n); err != nil {
return fmt.Errorf("writing test object: %v", err)
}
if err := w.Close(); err != nil {
return fmt.Errorf("closing object: %v", err)
}
return nil
}
// Creates a retry test resource in the emulator
func (et *emulatorTest) create(instructions map[string][]string, transport string) {
c := http.DefaultClient
data := struct {
Instructions map[string][]string `json:"instructions"`
Transport string `json:"transport"`
}{
Instructions: instructions,
Transport: transport,
}
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(data); err != nil {
et.Fatalf("encoding request: %v", err)
}
et.host.Path = "retry_test"
resp, err := c.Post(et.host.String(), "application/json", buf)
if resp.StatusCode == 501 {
et.T.Skip("This retry test case is not yet supported in the testbench.")
}
if err != nil || resp.StatusCode != 200 {
et.Fatalf("creating retry test: err: %v, resp: %+v", err, resp)
}
defer func() {
closeErr := resp.Body.Close()
if err == nil {
err = closeErr
}
}()
testRes := struct {
TestID string `json:"id"`
}{}
if err := json.NewDecoder(resp.Body).Decode(&testRes); err != nil {
et.Fatalf("decoding test ID: %v", err)
}
et.id = testRes.TestID
et.host.Path = ""
// Create transportClient for http or grpc
ctx := context.Background()
transportClient, err := NewClient(ctx)
if err != nil {
et.Fatalf("HTTP transportClient: %v", err)
}
if transport == "grpc" {
transportClient, err = NewGRPCClient(ctx)
if err != nil {
et.Fatalf("GRPC transportClient: %v", err)
}
}
et.transportClient = transportClient
}
// Verifies that all instructions for a given retry testID have been used up
func (et *emulatorTest) check() {
et.host.Path = strings.Join([]string{"retry_test", et.id}, "/")
c := http.DefaultClient
resp, err := c.Get(et.host.String())
if err != nil || resp.StatusCode != 200 {
et.Errorf("getting retry test: err: %v, resp: %+v", err, resp)
}
defer func() {
closeErr := resp.Body.Close()
if err == nil {
err = closeErr
}
}()
testRes := struct {
Instructions map[string][]string
Completed bool
}{}
if err := json.NewDecoder(resp.Body).Decode(&testRes); err != nil {
et.Errorf("decoding response: %v", err)
}
if !testRes.Completed {
et.Errorf("test not completed; unused instructions: %+v", testRes.Instructions)
}
}
// Deletes a retry test resource
func (et *emulatorTest) delete() {
et.host.Path = strings.Join([]string{"retry_test", et.id}, "/")
c := http.DefaultClient
req, err := http.NewRequest("DELETE", et.host.String(), nil)
if err != nil {
et.Errorf("creating request: %v", err)
}
resp, err := c.Do(req)
if err != nil || resp.StatusCode != 200 {
et.Errorf("deleting test: err: %v, resp: %+v", err, resp)
}
}