forked from google/go-cloud
/
drivertest.go
2615 lines (2444 loc) · 69.8 KB
/
drivertest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Go Cloud Development Kit Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package drivertest provides a conformance test for implementations of
// driver.
package drivertest // import "gocloud.dev/blob/drivertest"
import (
"bytes"
"context"
"crypto/md5"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"gocloud.dev/blob"
"gocloud.dev/blob/driver"
"gocloud.dev/gcerrors"
"gocloud.dev/internal/escape"
)
// Harness descibes the functionality test harnesses must provide to run
// conformance tests.
type Harness interface {
// MakeDriver creates a driver.Bucket to test.
// Multiple calls to MakeDriver during a test run must refer to the
// same storage bucket; i.e., a blob created using one driver.Bucket must
// be readable by a subsequent driver.Bucket.
MakeDriver(ctx context.Context) (driver.Bucket, error)
// MakeDriverForNonexistentBucket creates a driver.Bucket for a nonexistent
// bucket. If that concept doesn't make sense for a driver, return (nil, nil).
MakeDriverForNonexistentBucket(ctx context.Context) (driver.Bucket, error)
// HTTPClient should return an unauthorized *http.Client, or nil.
// Required if the service supports SignedURL.
HTTPClient() *http.Client
// Close closes resources used by the harness.
Close()
}
// HarnessMaker describes functions that construct a harness for running tests.
// It is called exactly once per test; Harness.Close() will be called when the test is complete.
type HarnessMaker func(ctx context.Context, t *testing.T) (Harness, error)
// AsTest represents a test of As functionality.
// The conformance test:
// 1. Calls BucketCheck.
// 2. Creates a blob in a directory, using BeforeWrite as a WriterOption.
// 3. Fetches the blob's attributes and calls AttributeCheck.
// 4. Creates a Reader for the blob using BeforeReader as a ReaderOption,
//
// and calls ReaderCheck with the resulting Reader.
//
// 5. Calls List using BeforeList as a ListOption, with Delimiter set so
//
// that only the directory is returned, and calls ListObjectCheck
// on the single directory list entry returned.
//
// 6. Calls List using BeforeList as a ListOption, and calls ListObjectCheck
//
// on the single blob entry returned.
//
// 7. Tries to read a non-existent blob, and calls ErrorCheck with the error.
// 8. Makes a copy of the blob, using BeforeCopy as a CopyOption.
// 9. Calls SignedURL using BeforeSign as a SignedURLOption for each supported
//
// signing method (i.e. GET, PUT and DELETE).
//
// For example, an AsTest might set a driver-specific field to a custom
// value in BeforeWrite, and then verify the custom value was returned in
// AttributesCheck and/or ReaderCheck.
type AsTest interface {
// Name should return a descriptive name for the test.
Name() string
// BucketCheck will be called to allow verification of Bucket.As.
BucketCheck(b *blob.Bucket) error
// ErrorCheck will be called to allow verification of Bucket.ErrorAs.
ErrorCheck(b *blob.Bucket, err error) error
// BeforeRead will be passed directly to ReaderOptions as part of reading
// a test blob.
BeforeRead(as func(interface{}) bool) error
// BeforeWrite will be passed directly to WriterOptions as part of creating
// a test blob.
BeforeWrite(as func(interface{}) bool) error
// BeforeCopy will be passed directly to CopyOptions as part of copying
// the test blob.
BeforeCopy(as func(interface{}) bool) error
// BeforeList will be passed directly to ListOptions as part of listing the
// test blob.
BeforeList(as func(interface{}) bool) error
// BeforeSign will be passed directly to SignedURLOptions as part of
// generating a signed URL to the test blob.
BeforeSign(as func(interface{}) bool) error
// AttributesCheck will be called after fetching the test blob's attributes.
// It should call attrs.As and verify the results.
AttributesCheck(attrs *blob.Attributes) error
// ReaderCheck will be called after creating a blob.Reader.
// It should call r.As and verify the results.
ReaderCheck(r *blob.Reader) error
// ListObjectCheck will be called after calling List with the test object's
// name as the Prefix. It should call o.As and verify the results.
ListObjectCheck(o *blob.ListObject) error
}
type verifyAsFailsOnNil struct{}
func (verifyAsFailsOnNil) Name() string {
return "verify As returns false when passed nil"
}
func (verifyAsFailsOnNil) BucketCheck(b *blob.Bucket) error {
if b.As(nil) {
return errors.New("want Bucket.As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) ErrorCheck(b *blob.Bucket, err error) (ret error) {
defer func() {
if recover() == nil {
ret = errors.New("want ErrorAs to panic when passed nil")
}
}()
b.ErrorAs(err, nil)
return nil
}
func (verifyAsFailsOnNil) BeforeRead(as func(interface{}) bool) error {
if as(nil) {
return errors.New("want BeforeReader's As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) BeforeWrite(as func(interface{}) bool) error {
if as(nil) {
return errors.New("want BeforeWrite's As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) BeforeCopy(as func(interface{}) bool) error {
if as(nil) {
return errors.New("want BeforeCopy's As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) BeforeList(as func(interface{}) bool) error {
if as(nil) {
return errors.New("want BeforeList's As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) BeforeSign(as func(interface{}) bool) error {
if as(nil) {
return errors.New("want BeforeSign's As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) AttributesCheck(attrs *blob.Attributes) error {
if attrs.As(nil) {
return errors.New("want Attributes.As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) ReaderCheck(r *blob.Reader) error {
if r.As(nil) {
return errors.New("want Reader.As to return false when passed nil")
}
return nil
}
func (verifyAsFailsOnNil) ListObjectCheck(o *blob.ListObject) error {
if o.As(nil) {
return errors.New("want ListObject.As to return false when passed nil")
}
return nil
}
// RunConformanceTests runs conformance tests for driver implementations of blob.
func RunConformanceTests(t *testing.T, newHarness HarnessMaker, asTests []AsTest) {
t.Run("TestNonexistentBucket", func(t *testing.T) {
testNonexistentBucket(t, newHarness)
})
t.Run("TestList", func(t *testing.T) {
testList(t, newHarness)
})
t.Run("TestListWeirdKeys", func(t *testing.T) {
testListWeirdKeys(t, newHarness)
})
t.Run("TestListDelimiters", func(t *testing.T) {
testListDelimiters(t, newHarness)
})
t.Run("TestDirsWithCharactersBeforeDelimiter", func(t *testing.T) {
testDirsWithCharactersBeforeDelimiter(t, newHarness)
})
t.Run("TestRead", func(t *testing.T) {
testRead(t, newHarness)
})
t.Run("TestAttributes", func(t *testing.T) {
testAttributes(t, newHarness)
})
t.Run("TestWrite", func(t *testing.T) {
testWrite(t, newHarness)
})
t.Run("TestCanceledWrite", func(t *testing.T) {
testCanceledWrite(t, newHarness)
})
t.Run("TestConcurrentWriteAndRead", func(t *testing.T) {
testConcurrentWriteAndRead(t, newHarness)
})
t.Run("TestMetadata", func(t *testing.T) {
testMetadata(t, newHarness)
})
t.Run("TestMD5", func(t *testing.T) {
testMD5(t, newHarness)
})
t.Run("TestCopy", func(t *testing.T) {
testCopy(t, newHarness)
})
t.Run("TestDelete", func(t *testing.T) {
testDelete(t, newHarness)
})
t.Run("TestKeys", func(t *testing.T) {
testKeys(t, newHarness)
})
t.Run("TestSignedURL", func(t *testing.T) {
testSignedURL(t, newHarness)
})
asTests = append(asTests, verifyAsFailsOnNil{})
t.Run("TestAs", func(t *testing.T) {
for _, st := range asTests {
if st.Name() == "" {
t.Fatalf("AsTest.Name is required")
}
t.Run(st.Name(), func(t *testing.T) {
testAs(t, newHarness, st)
})
}
})
}
// RunBenchmarks runs benchmarks for driver implementations of blob.
func RunBenchmarks(b *testing.B, bkt *blob.Bucket) {
b.Run("BenchmarkRead", func(b *testing.B) {
benchmarkRead(b, bkt)
})
b.Run("BenchmarkWriteReadDelete", func(b *testing.B) {
benchmarkWriteReadDelete(b, bkt)
})
}
// testNonexistentBucket tests the functionality of IsAccessible.
func testNonexistentBucket(t *testing.T, newHarness HarnessMaker) {
ctx := context.Background()
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
defer h.Close()
// Get a driver instance pointing to a nonexistent bucket.
{
drv, err := h.MakeDriverForNonexistentBucket(ctx)
if err != nil {
t.Fatal(err)
}
if drv == nil {
// No such thing as a "nonexistent bucket" for this driver.
t.Skip()
}
b := blob.NewBucket(drv)
defer b.Close()
exists, err := b.IsAccessible(ctx)
if err != nil {
t.Fatal(err)
}
if exists {
t.Error("got IsAccessible true for nonexistent bucket, want false")
}
}
// Verify that IsAccessible returns true for a real bucket.
{
drv, err := h.MakeDriver(ctx)
if err != nil {
t.Fatal(err)
}
b := blob.NewBucket(drv)
defer b.Close()
exists, err := b.IsAccessible(ctx)
if err != nil {
t.Fatal(err)
}
if !exists {
t.Error("got IsAccessible false for real bucket, want true")
}
}
}
// testList tests the functionality of List.
func testList(t *testing.T, newHarness HarnessMaker) {
const keyPrefix = "blob-for-list"
content := []byte("hello")
keyForIndex := func(i int) string { return fmt.Sprintf("%s-%d", keyPrefix, i) }
gotIndices := func(t *testing.T, objs []*driver.ListObject) []int {
var got []int
for _, obj := range objs {
if !strings.HasPrefix(obj.Key, keyPrefix) {
t.Errorf("got name %q, expected it to have prefix %q", obj.Key, keyPrefix)
continue
}
i, err := strconv.Atoi(obj.Key[len(keyPrefix)+1:])
if err != nil {
t.Error(err)
continue
}
got = append(got, i)
}
return got
}
tests := []struct {
name string
pageSize int
prefix string
wantPages [][]int
want []int
}{
{
name: "no objects",
prefix: "no-objects-with-this-prefix",
wantPages: [][]int{nil},
},
{
name: "exactly 1 object due to prefix",
prefix: keyForIndex(1),
wantPages: [][]int{{1}},
want: []int{1},
},
{
name: "no pagination",
prefix: keyPrefix,
wantPages: [][]int{{0, 1, 2}},
want: []int{0, 1, 2},
},
{
name: "by 1",
prefix: keyPrefix,
pageSize: 1,
wantPages: [][]int{{0}, {1}, {2}},
want: []int{0, 1, 2},
},
{
name: "by 2",
prefix: keyPrefix,
pageSize: 2,
wantPages: [][]int{{0, 1}, {2}},
want: []int{0, 1, 2},
},
{
name: "by 3",
prefix: keyPrefix,
pageSize: 3,
wantPages: [][]int{{0, 1, 2}},
want: []int{0, 1, 2},
},
}
ctx := context.Background()
// Creates blobs for sub-tests below.
// We only create the blobs once, for efficiency and because there's
// no guarantee that after we create them they will be immediately returned
// from List. The very first time the test is run against a Bucket, it may be
// flaky due to this race.
init := func(t *testing.T) (driver.Bucket, func()) {
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
drv, err := h.MakeDriver(ctx)
if err != nil {
t.Fatal(err)
}
// See if the blobs are already there.
b := blob.NewBucket(drv)
iter := b.List(&blob.ListOptions{Prefix: keyPrefix})
found := iterToSetOfKeys(ctx, t, iter)
for i := 0; i < 3; i++ {
key := keyForIndex(i)
if !found[key] {
if err := b.WriteAll(ctx, key, content, nil); err != nil {
b.Close()
t.Fatal(err)
}
}
}
return drv, func() { b.Close(); h.Close() }
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
drv, done := init(t)
defer done()
var gotPages [][]int
var got []int
var nextPageToken []byte
for {
page, err := drv.ListPaged(ctx, &driver.ListOptions{
PageSize: tc.pageSize,
Prefix: tc.prefix,
PageToken: nextPageToken,
})
if err != nil {
t.Fatal(err)
}
gotThisPage := gotIndices(t, page.Objects)
got = append(got, gotThisPage...)
gotPages = append(gotPages, gotThisPage)
if len(page.NextPageToken) == 0 {
break
}
nextPageToken = page.NextPageToken
}
if diff := cmp.Diff(gotPages, tc.wantPages); diff != "" {
t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", gotPages, tc.wantPages, diff)
}
if diff := cmp.Diff(got, tc.want); diff != "" {
t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", got, tc.want, diff)
}
})
}
// Verify pagination works when inserting in a retrieved page.
t.Run("PaginationConsistencyAfterInsert", func(t *testing.T) {
drv, done := init(t)
defer done()
// Fetch a page of 2 results: 0, 1.
page, err := drv.ListPaged(ctx, &driver.ListOptions{
PageSize: 2,
Prefix: keyPrefix,
})
if err != nil {
t.Fatal(err)
}
got := gotIndices(t, page.Objects)
want := []int{0, 1}
if diff := cmp.Diff(got, want); diff != "" {
t.Fatalf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
}
// Insert a key "0a" in the middle of the page we already retrieved.
b := blob.NewBucket(drv)
defer b.Close()
key := page.Objects[0].Key + "a"
if err := b.WriteAll(ctx, key, content, nil); err != nil {
t.Fatal(err)
}
defer func() {
_ = b.Delete(ctx, key)
}()
// Fetch the next page. It should not include 0, 0a, or 1, and it should
// include 2.
page, err = drv.ListPaged(ctx, &driver.ListOptions{
Prefix: keyPrefix,
PageToken: page.NextPageToken,
})
if err != nil {
t.Fatal(err)
}
got = gotIndices(t, page.Objects)
want = []int{2}
if diff := cmp.Diff(got, want); diff != "" {
t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
}
})
// Verify pagination works when deleting in a retrieved page.
t.Run("PaginationConsistencyAfterDelete", func(t *testing.T) {
drv, done := init(t)
defer done()
// Fetch a page of 2 results: 0, 1.
page, err := drv.ListPaged(ctx, &driver.ListOptions{
PageSize: 2,
Prefix: keyPrefix,
})
if err != nil {
t.Fatal(err)
}
got := gotIndices(t, page.Objects)
want := []int{0, 1}
if diff := cmp.Diff(got, want); diff != "" {
t.Fatalf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
}
// Delete key "1".
b := blob.NewBucket(drv)
defer b.Close()
key := page.Objects[1].Key
if err := b.Delete(ctx, key); err != nil {
t.Fatal(err)
}
defer func() {
_ = b.WriteAll(ctx, key, content, nil)
}()
// Fetch the next page. It should not include 0 or 1, and it should
// include 2.
page, err = drv.ListPaged(ctx, &driver.ListOptions{
Prefix: keyPrefix,
PageToken: page.NextPageToken,
})
if err != nil {
t.Fatal(err)
}
got = gotIndices(t, page.Objects)
want = []int{2}
if diff := cmp.Diff(got, want); diff != "" {
t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
}
})
}
// testListWeirdKeys tests the functionality of List on weird keys.
func testListWeirdKeys(t *testing.T, newHarness HarnessMaker) {
const keyPrefix = "list-weirdkeys-"
content := []byte("hello")
ctx := context.Background()
// We're going to create a blob for each of the weird key strings, and
// then verify we can see them with List.
want := map[string]bool{}
for _, k := range escape.WeirdStrings {
want[keyPrefix+k] = true
}
// Creates blobs for sub-tests below.
// We only create the blobs once, for efficiency and because there's
// no guarantee that after we create them they will be immediately returned
// from List. The very first time the test is run against a Bucket, it may be
// flaky due to this race.
init := func(t *testing.T) (*blob.Bucket, func()) {
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
drv, err := h.MakeDriver(ctx)
if err != nil {
t.Fatal(err)
}
// See if the blobs are already there.
b := blob.NewBucket(drv)
iter := b.List(&blob.ListOptions{Prefix: keyPrefix})
found := iterToSetOfKeys(ctx, t, iter)
for _, k := range escape.WeirdStrings {
key := keyPrefix + k
if !found[key] {
if err := b.WriteAll(ctx, key, content, nil); err != nil {
b.Close()
t.Fatal(err)
}
}
}
return b, func() { b.Close(); h.Close() }
}
b, done := init(t)
defer done()
iter := b.List(&blob.ListOptions{Prefix: keyPrefix})
got := iterToSetOfKeys(ctx, t, iter)
if diff := cmp.Diff(got, want); diff != "" {
t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
}
}
// listResult is a recursive view of the hierarchy. It's used to verify List
// using Delimiter.
type listResult struct {
Key string
IsDir bool
// If IsDir is true and recursion is enabled, the recursive listing of the directory.
Sub []listResult
}
// doList lists b using prefix and delim.
// If recurse is true, it recurses into directories filling in listResult.Sub.
func doList(ctx context.Context, b *blob.Bucket, prefix, delim string, recurse bool) ([]listResult, error) {
iter := b.List(&blob.ListOptions{
Prefix: prefix,
Delimiter: delim,
})
var retval []listResult
for {
obj, err := iter.Next(ctx)
if err == io.EOF {
if obj != nil {
return nil, errors.New("obj is not nil on EOF")
}
break
}
if err != nil {
return nil, err
}
var sub []listResult
if obj.IsDir && recurse {
sub, err = doList(ctx, b, obj.Key, delim, true)
if err != nil {
return nil, err
}
}
retval = append(retval, listResult{
Key: obj.Key,
IsDir: obj.IsDir,
Sub: sub,
})
}
return retval, nil
}
// testListDelimiters tests the functionality of List using Delimiters.
func testListDelimiters(t *testing.T, newHarness HarnessMaker) {
const keyPrefix = "blob-for-delimiters-"
content := []byte("hello")
// The set of files to use for these tests. The strings in each entry will
// be joined using delim, so the result is a directory structure like this
// (using / as delimiter):
// dir1/a.txt
// dir1/b.txt
// dir1/subdir/c.txt
// dir1/subdir/d.txt
// dir2/e.txt
// f.txt
keys := [][]string{
{"dir1", "a.txt"},
{"dir1", "b.txt"},
{"dir1", "subdir", "c.txt"},
{"dir1", "subdir", "d.txt"},
{"dir2", "e.txt"},
{"f.txt"},
}
// Test with several different delimiters.
tests := []struct {
name, delim string
// Expected result of doList with an empty delimiter.
// All keys should be listed at the top level, with no directories.
wantFlat []listResult
// Expected result of doList with delimiter and recurse = true.
// All keys should be listed, with keys in directories in the Sub field
// of their directory.
wantRecursive []listResult
// Expected result of repeatedly calling driver.ListPaged with delimiter
// and page size = 1.
wantPaged []listResult
// expected result of doList with delimiter and recurse = false
// after dir2/e.txt is deleted
// dir1/ and f.txt should be listed; dir2/ should no longer be present
// because there are no keys in it.
wantAfterDel []listResult
}{
{
name: "fwdslash",
delim: "/",
wantFlat: []listResult{
{Key: keyPrefix + "/dir1/a.txt"},
{Key: keyPrefix + "/dir1/b.txt"},
{Key: keyPrefix + "/dir1/subdir/c.txt"},
{Key: keyPrefix + "/dir1/subdir/d.txt"},
{Key: keyPrefix + "/dir2/e.txt"},
{Key: keyPrefix + "/f.txt"},
},
wantRecursive: []listResult{
{
Key: keyPrefix + "/dir1/",
IsDir: true,
Sub: []listResult{
{Key: keyPrefix + "/dir1/a.txt"},
{Key: keyPrefix + "/dir1/b.txt"},
{
Key: keyPrefix + "/dir1/subdir/",
IsDir: true,
Sub: []listResult{
{Key: keyPrefix + "/dir1/subdir/c.txt"},
{Key: keyPrefix + "/dir1/subdir/d.txt"},
},
},
},
},
{
Key: keyPrefix + "/dir2/",
IsDir: true,
Sub: []listResult{
{Key: keyPrefix + "/dir2/e.txt"},
},
},
{Key: keyPrefix + "/f.txt"},
},
wantPaged: []listResult{
{
Key: keyPrefix + "/dir1/",
IsDir: true,
},
{
Key: keyPrefix + "/dir2/",
IsDir: true,
},
{Key: keyPrefix + "/f.txt"},
},
wantAfterDel: []listResult{
{
Key: keyPrefix + "/dir1/",
IsDir: true,
},
{Key: keyPrefix + "/f.txt"},
},
},
{
name: "backslash",
delim: "\\",
wantFlat: []listResult{
{Key: keyPrefix + "\\dir1\\a.txt"},
{Key: keyPrefix + "\\dir1\\b.txt"},
{Key: keyPrefix + "\\dir1\\subdir\\c.txt"},
{Key: keyPrefix + "\\dir1\\subdir\\d.txt"},
{Key: keyPrefix + "\\dir2\\e.txt"},
{Key: keyPrefix + "\\f.txt"},
},
wantRecursive: []listResult{
{
Key: keyPrefix + "\\dir1\\",
IsDir: true,
Sub: []listResult{
{Key: keyPrefix + "\\dir1\\a.txt"},
{Key: keyPrefix + "\\dir1\\b.txt"},
{
Key: keyPrefix + "\\dir1\\subdir\\",
IsDir: true,
Sub: []listResult{
{Key: keyPrefix + "\\dir1\\subdir\\c.txt"},
{Key: keyPrefix + "\\dir1\\subdir\\d.txt"},
},
},
},
},
{
Key: keyPrefix + "\\dir2\\",
IsDir: true,
Sub: []listResult{
{Key: keyPrefix + "\\dir2\\e.txt"},
},
},
{Key: keyPrefix + "\\f.txt"},
},
wantPaged: []listResult{
{
Key: keyPrefix + "\\dir1\\",
IsDir: true,
},
{
Key: keyPrefix + "\\dir2\\",
IsDir: true,
},
{Key: keyPrefix + "\\f.txt"},
},
wantAfterDel: []listResult{
{
Key: keyPrefix + "\\dir1\\",
IsDir: true,
},
{Key: keyPrefix + "\\f.txt"},
},
},
{
name: "abc",
delim: "abc",
wantFlat: []listResult{
{Key: keyPrefix + "abcdir1abca.txt"},
{Key: keyPrefix + "abcdir1abcb.txt"},
{Key: keyPrefix + "abcdir1abcsubdirabcc.txt"},
{Key: keyPrefix + "abcdir1abcsubdirabcd.txt"},
{Key: keyPrefix + "abcdir2abce.txt"},
{Key: keyPrefix + "abcf.txt"},
},
wantRecursive: []listResult{
{
Key: keyPrefix + "abcdir1abc",
IsDir: true,
Sub: []listResult{
{Key: keyPrefix + "abcdir1abca.txt"},
{Key: keyPrefix + "abcdir1abcb.txt"},
{
Key: keyPrefix + "abcdir1abcsubdirabc",
IsDir: true,
Sub: []listResult{
{Key: keyPrefix + "abcdir1abcsubdirabcc.txt"},
{Key: keyPrefix + "abcdir1abcsubdirabcd.txt"},
},
},
},
},
{
Key: keyPrefix + "abcdir2abc",
IsDir: true,
Sub: []listResult{
{Key: keyPrefix + "abcdir2abce.txt"},
},
},
{Key: keyPrefix + "abcf.txt"},
},
wantPaged: []listResult{
{
Key: keyPrefix + "abcdir1abc",
IsDir: true,
},
{
Key: keyPrefix + "abcdir2abc",
IsDir: true,
},
{Key: keyPrefix + "abcf.txt"},
},
wantAfterDel: []listResult{
{
Key: keyPrefix + "abcdir1abc",
IsDir: true,
},
{Key: keyPrefix + "abcf.txt"},
},
},
}
ctx := context.Background()
// Creates blobs for sub-tests below.
// We only create the blobs once, for efficiency and because there's
// no guarantee that after we create them they will be immediately returned
// from List. The very first time the test is run against a Bucket, it may be
// flaky due to this race.
init := func(t *testing.T, delim string) (driver.Bucket, *blob.Bucket, func()) {
h, err := newHarness(ctx, t)
if err != nil {
t.Fatal(err)
}
drv, err := h.MakeDriver(ctx)
if err != nil {
t.Fatal(err)
}
b := blob.NewBucket(drv)
// See if the blobs are already there.
prefix := keyPrefix + delim
iter := b.List(&blob.ListOptions{Prefix: prefix})
found := iterToSetOfKeys(ctx, t, iter)
for _, keyParts := range keys {
key := prefix + strings.Join(keyParts, delim)
if !found[key] {
if err := b.WriteAll(ctx, key, content, nil); err != nil {
b.Close()
t.Fatal(err)
}
}
}
return drv, b, func() { b.Close(); h.Close() }
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
drv, b, done := init(t, tc.delim)
defer done()
// Fetch without using delimiter.
got, err := doList(ctx, b, keyPrefix+tc.delim, "", true)
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(got, tc.wantFlat); diff != "" {
t.Errorf("with no delimiter, got\n%v\nwant\n%v\ndiff\n%s", got, tc.wantFlat, diff)
}
// Fetch using delimiter, recursively.
got, err = doList(ctx, b, keyPrefix+tc.delim, tc.delim, true)
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(got, tc.wantRecursive); diff != "" {
t.Errorf("with delimiter, got\n%v\nwant\n%v\ndiff\n%s", got, tc.wantRecursive, diff)
}
// Test pagination via driver.ListPaged.
var nextPageToken []byte
got = nil
for {
page, err := drv.ListPaged(ctx, &driver.ListOptions{
Prefix: keyPrefix + tc.delim,
Delimiter: tc.delim,
PageSize: 1,
PageToken: nextPageToken,
})
if err != nil {
t.Fatal(err)
}
if len(page.Objects) > 1 {
t.Errorf("got %d objects on a page, want 0 or 1", len(page.Objects))
}
for _, obj := range page.Objects {
got = append(got, listResult{
Key: obj.Key,
IsDir: obj.IsDir,
})
}
if len(page.NextPageToken) == 0 {
break
}
nextPageToken = page.NextPageToken
}
if diff := cmp.Diff(got, tc.wantPaged); diff != "" {
t.Errorf("paged got\n%v\nwant\n%v\ndiff\n%s", got, tc.wantPaged, diff)
}
// Delete dir2/e.txt and verify that dir2/ is no longer returned.
key := strings.Join(append([]string{keyPrefix}, "dir2", "e.txt"), tc.delim)
if err := b.Delete(ctx, key); err != nil {
t.Fatal(err)
}
// Attempt to restore dir2/e.txt at the end of the test for the next run.
defer func() {
_ = b.WriteAll(ctx, key, content, nil)
}()
got, err = doList(ctx, b, keyPrefix+tc.delim, tc.delim, false)
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(got, tc.wantAfterDel); diff != "" {
t.Errorf("after delete, got\n%v\nwant\n%v\ndiff\n%s", got, tc.wantAfterDel, diff)
}
})
}
}
// testDirsWithCharactersBeforeDelimiter tests a case where there's
// a directory on a pagination boundary that ends with a character that's
// less than the delimiter.
// See https://github.com/google/go-cloud/issues/3089.
func testDirsWithCharactersBeforeDelimiter(t *testing.T, newHarness HarnessMaker) {
const keyPrefix = "blob-for-dirs-with-chars-before-delimiter/"
content := []byte("hello")
// The set of files to use for these tests.
keys := []string{
"testFile1",
"t/t/t",
"t-/t.",
"dir1/testFile1dir1",
"dir2/testFile1dir2",
"d",
}
// Note that "t-/" is before "t/". The delimiter is included in the
// alphabetical ordering.
want := []string{"d", "dir1/", "dir2/", "t-/", "t/", "testFile1"}
// Create blobs.
// We only create the blobs once, for efficiency and because there's
// no guarantee that after we create them they will be immediately returned