Debian Codegraph @

blob/drivertest/drivertest.go

raw
1 // Copyright 2018 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/blob/drivertest"
18
19 import (
20 "bytes"
21 "context"
22 "crypto/md5"
23 "errors"
24 "fmt"
25 "io"
26 "log"
27 "net/http"
28 "net/url"
29 "reflect"
30 "regexp"
31 "strconv"
32 "strings"
33 "sync"
34 "sync/atomic"
35 "testing"
36 "testing/iotest"
37 "time"
38
39 "github.com/google/go-cmp/cmp"
40 "github.com/google/go-cmp/cmp/cmpopts"
41 "gocloud.dev/blob"
42 "gocloud.dev/blob/driver"
43 "gocloud.dev/gcerrors"
44 "gocloud.dev/internal/escape"
45 )
46
47 // Harness descibes the functionality test harnesses must provide to run
48 // conformance tests.
49 type Harness interface {
50 // MakeDriver creates a driver.Bucket to test.
51 // Multiple calls to MakeDriver during a test run must refer to the
52 // same storage bucket; i.e., a blob created using one driver.Bucket must
53 // be readable by a subsequent driver.Bucket.
54 MakeDriver(ctx context.Context) (driver.Bucket, error)
55 // MakeDriverForNonexistentBucket creates a driver.Bucket for a nonexistent
56 // bucket. If that concept doesn't make sense for a driver, return (nil, nil).
57 MakeDriverForNonexistentBucket(ctx context.Context) (driver.Bucket, error)
58 // HTTPClient should return an unauthorized *http.Client, or nil.
59 // Required if the service supports SignedURL.
60 HTTPClient() *http.Client
61 // Close closes resources used by the harness.
62 Close()
63 }
64
65 // HarnessMaker describes functions that construct a harness for running tests.
66 // It is called exactly once per test; Harness.Close() will be called when the test is complete.
67 type HarnessMaker func(ctx context.Context, t *testing.T) (Harness, error)
68
69 // AsTest represents a test of As functionality.
70 // The conformance test:
71 // 1. Calls BucketCheck.
72 // 2. Creates a blob in a directory, using BeforeWrite as a WriterOption.
73 // 3. Fetches the blob's attributes and calls AttributeCheck.
74 // 4. Creates a Reader for the blob using BeforeReader as a ReaderOption,
75 //
76 // and calls ReaderCheck with the resulting Reader.
77 //
78 // 5. Calls List using BeforeList as a ListOption, with Delimiter set so
79 //
80 // that only the directory is returned, and calls ListObjectCheck
81 // on the single directory list entry returned.
82 //
83 // 6. Calls List using BeforeList as a ListOption, and calls ListObjectCheck
84 //
85 // on the single blob entry returned.
86 //
87 // 7. Tries to read a non-existent blob, and calls ErrorCheck with the error.
88 // 8. Makes a copy of the blob, using BeforeCopy as a CopyOption.
89 // 9. Calls SignedURL using BeforeSign as a SignedURLOption for each supported
90 //
91 // signing method (i.e. GET, PUT and DELETE).
92 //
93 // For example, an AsTest might set a driver-specific field to a custom
94 // value in BeforeWrite, and then verify the custom value was returned in
95 // AttributesCheck and/or ReaderCheck.
96 type AsTest interface {
97 // Name should return a descriptive name for the test.
98 Name() string
99 // BucketCheck will be called to allow verification of Bucket.As.
100 BucketCheck(b *blob.Bucket) error
101 // ErrorCheck will be called to allow verification of Bucket.ErrorAs.
102 ErrorCheck(b *blob.Bucket, err error) error
103 // BeforeRead will be passed directly to ReaderOptions as part of reading
104 // a test blob.
105 BeforeRead(as func(any) bool) error
106 // BeforeWrite will be passed directly to WriterOptions as part of creating
107 // a test blob.
108 BeforeWrite(as func(any) bool) error
109 // BeforeCopy will be passed directly to CopyOptions as part of copying
110 // the test blob.
111 BeforeCopy(as func(any) bool) error
112 // BeforeList will be passed directly to ListOptions as part of listing the
113 // test blob.
114 BeforeList(as func(any) bool) error
115 // BeforeSign will be passed directly to SignedURLOptions as part of
116 // generating a signed URL to the test blob.
117 BeforeSign(as func(any) bool) error
118 // AttributesCheck will be called after fetching the test blob's attributes.
119 // It should call attrs.As and verify the results.
120 AttributesCheck(attrs *blob.Attributes) error
121 // ReaderCheck will be called after creating a blob.Reader.
122 // It should call r.As and verify the results.
123 ReaderCheck(r *blob.Reader) error
124 // ListObjectCheck will be called after calling List with the test object's
125 // name as the Prefix. It should call o.As and verify the results.
126 ListObjectCheck(o *blob.ListObject) error
127 }
128
129 type verifyAsFailsOnNil struct{}
130
131 func (verifyAsFailsOnNil) Name() string {
132 return "verify As returns false when passed nil"
133 }
134
135 func (verifyAsFailsOnNil) BucketCheck(b *blob.Bucket) error {
136 if b.As(nil) {
137 return errors.New("want Bucket.As to return false when passed nil")
138 }
139 return nil
140 }
141
142 func (verifyAsFailsOnNil) ErrorCheck(b *blob.Bucket, err error) (ret error) {
143 defer func() {
144 if recover() == nil {
145 ret = errors.New("want ErrorAs to panic when passed nil")
146 }
147 }()
148 b.ErrorAs(err, nil)
149 return nil
150 }
151
152 func (verifyAsFailsOnNil) BeforeRead(as func(any) bool) error {
153 if as(nil) {
154 return errors.New("want BeforeReader's As to return false when passed nil")
155 }
156 return nil
157 }
158
159 func (verifyAsFailsOnNil) BeforeWrite(as func(any) bool) error {
160 if as(nil) {
161 return errors.New("want BeforeWrite's As to return false when passed nil")
162 }
163 return nil
164 }
165
166 func (verifyAsFailsOnNil) BeforeCopy(as func(any) bool) error {
167 if as(nil) {
168 return errors.New("want BeforeCopy's As to return false when passed nil")
169 }
170 return nil
171 }
172
173 func (verifyAsFailsOnNil) BeforeList(as func(any) bool) error {
174 if as(nil) {
175 return errors.New("want BeforeList's As to return false when passed nil")
176 }
177 return nil
178 }
179
180 func (verifyAsFailsOnNil) BeforeSign(as func(any) bool) error {
181 if as(nil) {
182 return errors.New("want BeforeSign's As to return false when passed nil")
183 }
184 return nil
185 }
186
187 func (verifyAsFailsOnNil) AttributesCheck(attrs *blob.Attributes) error {
188 if attrs.As(nil) {
189 return errors.New("want Attributes.As to return false when passed nil")
190 }
191 return nil
192 }
193
194 func (verifyAsFailsOnNil) ReaderCheck(r *blob.Reader) error {
195 if r.As(nil) {
196 return errors.New("want Reader.As to return false when passed nil")
197 }
198 return nil
199 }
200
201 func (verifyAsFailsOnNil) ListObjectCheck(o *blob.ListObject) error {
202 if o.As(nil) {
203 return errors.New("want ListObject.As to return false when passed nil")
204 }
205 return nil
206 }
207
208 // RunConformanceTests runs conformance tests for driver implementations of blob.
209 func RunConformanceTests(t *testing.T, newHarness HarnessMaker, asTests []AsTest) {
210 t.Helper()
211
212 t.Run("TestNonexistentBucket", func(t *testing.T) {
213 testNonexistentBucket(t, newHarness)
214 })
215 t.Run("TestList", func(t *testing.T) {
216 testList(t, newHarness)
217 })
218 t.Run("TestListWeirdKeys", func(t *testing.T) {
219 testListWeirdKeys(t, newHarness)
220 })
221 t.Run("TestListDelimiters", func(t *testing.T) {
222 testListDelimiters(t, newHarness)
223 })
224 t.Run("TestDirsWithCharactersBeforeDelimiter", func(t *testing.T) {
225 testDirsWithCharactersBeforeDelimiter(t, newHarness)
226 })
227 t.Run("TestRead", func(t *testing.T) {
228 testRead(t, newHarness)
229 })
230 t.Run("TestAttributes", func(t *testing.T) {
231 testAttributes(t, newHarness)
232 })
233 t.Run("TestWrite", func(t *testing.T) {
234 testWrite(t, newHarness)
235 })
236 t.Run("TestCanceledWrite", func(t *testing.T) {
237 testCanceledWrite(t, newHarness)
238 })
239 t.Run("TestConcurrentWriteAndRead", func(t *testing.T) {
240 testConcurrentWriteAndRead(t, newHarness)
241 })
242 t.Run("TestUploadDownload", func(t *testing.T) {
243 testUploadDownload(t, newHarness)
244 })
245 t.Run("TestMetadata", func(t *testing.T) {
246 testMetadata(t, newHarness)
247 })
248 t.Run("TestMD5", func(t *testing.T) {
249 testMD5(t, newHarness)
250 })
251 t.Run("TestCopy", func(t *testing.T) {
252 testCopy(t, newHarness)
253 })
254 t.Run("TestDelete", func(t *testing.T) {
255 testDelete(t, newHarness)
256 })
257 t.Run("TestKeys", func(t *testing.T) {
258 testKeys(t, newHarness)
259 })
260 t.Run("TestSignedURL", func(t *testing.T) {
261 testSignedURL(t, newHarness)
262 })
263 t.Run("TestIfNotExist", func(t *testing.T) {
264 testIfNotExist(t, newHarness)
265 })
266 asTests = append(asTests, verifyAsFailsOnNil{})
267 t.Run("TestAs", func(t *testing.T) {
268 for _, st := range asTests {
269 if st.Name() == "" {
270 t.Fatalf("AsTest.Name is required")
271 }
272 t.Run(st.Name(), func(t *testing.T) {
273 testAs(t, newHarness, st)
274 })
275 }
276 })
277 }
278
279 // RunBenchmarks runs benchmarks for driver implementations of blob.
280 func RunBenchmarks(b *testing.B, bkt *blob.Bucket) {
281 b.Helper()
282
283 b.Run("BenchmarkRead", func(b *testing.B) {
284 benchmarkRead(b, bkt)
285 })
286 b.Run("BenchmarkWriteReadDelete", func(b *testing.B) {
287 benchmarkWriteReadDelete(b, bkt)
288 })
289 }
290
291 // testNonexistentBucket tests the functionality of IsAccessible.
292 func testNonexistentBucket(t *testing.T, newHarness HarnessMaker) {
293 t.Helper()
294
295 ctx := context.Background()
296 h, err := newHarness(ctx, t)
297 if err != nil {
298 t.Fatal(err)
299 }
300 defer h.Close()
301
302 // Get a driver instance pointing to a nonexistent bucket.
303 {
304 drv, err := h.MakeDriverForNonexistentBucket(ctx)
305 if err != nil {
306 t.Fatal(err)
307 }
308 if drv == nil {
309 // No such thing as a "nonexistent bucket" for this driver.
310 t.Skip()
311 }
312 b := blob.NewBucket(drv)
313 defer b.Close()
314 exists, err := b.IsAccessible(ctx)
315 if err != nil {
316 t.Fatal(err)
317 }
318 if exists {
319 t.Error("got IsAccessible true for nonexistent bucket, want false")
320 }
321 }
322
323 // Verify that IsAccessible returns true for a real bucket.
324 {
325 drv, err := h.MakeDriver(ctx)
326 if err != nil {
327 t.Fatal(err)
328 }
329 b := blob.NewBucket(drv)
330 defer b.Close()
331 exists, err := b.IsAccessible(ctx)
332 if err != nil {
333 t.Fatal(err)
334 }
335 if !exists {
336 t.Error("got IsAccessible false for real bucket, want true")
337 }
338 }
339 }
340
341 // testList tests the functionality of List.
342 func testList(t *testing.T, newHarness HarnessMaker) {
343 t.Helper()
344
345 const keyPrefix = "blob-for-list"
346 content := []byte("hello")
347
348 keyForIndex := func(i int) string { return fmt.Sprintf("%s-%d", keyPrefix, i) }
349 gotIndices := func(t *testing.T, objs []*driver.ListObject) []int {
350 t.Helper()
351
352 var got []int
353 for _, obj := range objs {
354 if !strings.HasPrefix(obj.Key, keyPrefix) {
355 t.Errorf("got name %q, expected it to have prefix %q", obj.Key, keyPrefix)
356 continue
357 }
358 i, err := strconv.Atoi(obj.Key[len(keyPrefix)+1:])
359 if err != nil {
360 t.Error(err)
361 continue
362 }
363 got = append(got, i)
364 }
365 return got
366 }
367
368 tests := []struct {
369 name string
370 pageSize int
371 prefix string
372 wantPages [][]int
373 want []int
374 }{
375 {
376 name: "no objects",
377 prefix: "no-objects-with-this-prefix",
378 wantPages: [][]int{nil},
379 },
380 {
381 name: "exactly 1 object due to prefix",
382 prefix: keyForIndex(1),
383 wantPages: [][]int{{1}},
384 want: []int{1},
385 },
386 {
387 name: "no pagination",
388 prefix: keyPrefix,
389 wantPages: [][]int{{0, 1, 2}},
390 want: []int{0, 1, 2},
391 },
392 {
393 name: "by 1",
394 prefix: keyPrefix,
395 pageSize: 1,
396 wantPages: [][]int{{0}, {1}, {2}},
397 want: []int{0, 1, 2},
398 },
399 {
400 name: "by 2",
401 prefix: keyPrefix,
402 pageSize: 2,
403 wantPages: [][]int{{0, 1}, {2}},
404 want: []int{0, 1, 2},
405 },
406 {
407 name: "by 3",
408 prefix: keyPrefix,
409 pageSize: 3,
410 wantPages: [][]int{{0, 1, 2}},
411 want: []int{0, 1, 2},
412 },
413 }
414
415 ctx := context.Background()
416
417 // Creates blobs for sub-tests below.
418 // We only create the blobs once, for efficiency and because there's
419 // no guarantee that after we create them they will be immediately returned
420 // from List. The very first time the test is run against a Bucket, it may be
421 // flaky due to this race.
422 init := func(t *testing.T) (driver.Bucket, func()) {
423 t.Helper()
424
425 h, err := newHarness(ctx, t)
426 if err != nil {
427 t.Fatal(err)
428 }
429 drv, err := h.MakeDriver(ctx)
430 if err != nil {
431 t.Fatal(err)
432 }
433 // See if the blobs are already there.
434 b := blob.NewBucket(drv)
435 iter := b.List(&blob.ListOptions{Prefix: keyPrefix})
436 found := iterToSetOfKeys(ctx, t, iter)
437 for i := range 3 {
438 key := keyForIndex(i)
439 if !found[key] {
440 if err := b.WriteAll(ctx, key, content, nil); err != nil {
441 b.Close()
442 t.Fatal(err)
443 }
444 }
445 }
446 return drv, func() { b.Close(); h.Close() }
447 }
448
449 for _, tc := range tests {
450 t.Run(tc.name, func(t *testing.T) {
451 drv, done := init(t)
452 defer done()
453
454 var gotPages [][]int
455 var got []int
456 var nextPageToken []byte
457 for {
458 page, err := drv.ListPaged(ctx, &driver.ListOptions{
459 PageSize: tc.pageSize,
460 Prefix: tc.prefix,
461 PageToken: nextPageToken,
462 })
463 if err != nil {
464 t.Fatal(err)
465 }
466 gotThisPage := gotIndices(t, page.Objects)
467 got = append(got, gotThisPage...)
468 gotPages = append(gotPages, gotThisPage)
469 if len(page.NextPageToken) == 0 {
470 break
471 }
472 nextPageToken = page.NextPageToken
473 }
474 if diff := cmp.Diff(gotPages, tc.wantPages); diff != "" {
475 t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", gotPages, tc.wantPages, diff)
476 }
477 if diff := cmp.Diff(got, tc.want); diff != "" {
478 t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", got, tc.want, diff)
479 }
480 })
481 }
482
483 // Verify pagination works when inserting in a retrieved page.
484 t.Run("PaginationConsistencyAfterInsert", func(t *testing.T) {
485 drv, done := init(t)
486 defer done()
487
488 // Fetch a page of 2 results: 0, 1.
489 page, err := drv.ListPaged(ctx, &driver.ListOptions{
490 PageSize: 2,
491 Prefix: keyPrefix,
492 })
493 if err != nil {
494 t.Fatal(err)
495 }
496 got := gotIndices(t, page.Objects)
497 want := []int{0, 1}
498 if diff := cmp.Diff(got, want); diff != "" {
499 t.Fatalf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
500 }
501
502 // Insert a key "0a" in the middle of the page we already retrieved.
503 b := blob.NewBucket(drv)
504 defer b.Close()
505 key := page.Objects[0].Key + "a"
506 if err := b.WriteAll(ctx, key, content, nil); err != nil {
507 t.Fatal(err)
508 }
509 defer func() {
510 _ = b.Delete(ctx, key)
511 }()
512
513 // Fetch the next page. It should not include 0, 0a, or 1, and it should
514 // include 2.
515 page, err = drv.ListPaged(ctx, &driver.ListOptions{
516 Prefix: keyPrefix,
517 PageToken: page.NextPageToken,
518 })
519 if err != nil {
520 t.Fatal(err)
521 }
522 got = gotIndices(t, page.Objects)
523 want = []int{2}
524 if diff := cmp.Diff(got, want); diff != "" {
525 t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
526 }
527 })
528
529 // Verify pagination works when deleting in a retrieved page.
530 t.Run("PaginationConsistencyAfterDelete", func(t *testing.T) {
531 drv, done := init(t)
532 defer done()
533
534 // Fetch a page of 2 results: 0, 1.
535 page, err := drv.ListPaged(ctx, &driver.ListOptions{
536 PageSize: 2,
537 Prefix: keyPrefix,
538 })
539 if err != nil {
540 t.Fatal(err)
541 }
542 got := gotIndices(t, page.Objects)
543 want := []int{0, 1}
544 if diff := cmp.Diff(got, want); diff != "" {
545 t.Fatalf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
546 }
547
548 // Delete key "1".
549 b := blob.NewBucket(drv)
550 defer b.Close()
551 key := page.Objects[1].Key
552 if err := b.Delete(ctx, key); err != nil {
553 t.Fatal(err)
554 }
555 defer func() {
556 _ = b.WriteAll(ctx, key, content, nil)
557 }()
558
559 // Fetch the next page. It should not include 0 or 1, and it should
560 // include 2.
561 page, err = drv.ListPaged(ctx, &driver.ListOptions{
562 Prefix: keyPrefix,
563 PageToken: page.NextPageToken,
564 })
565 if err != nil {
566 t.Fatal(err)
567 }
568 got = gotIndices(t, page.Objects)
569 want = []int{2}
570 if diff := cmp.Diff(got, want); diff != "" {
571 t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
572 }
573 })
574 }
575
576 // testListWeirdKeys tests the functionality of List on weird keys.
577 func testListWeirdKeys(t *testing.T, newHarness HarnessMaker) {
578 t.Helper()
579
580 const keyPrefix = "list-weirdkeys-"
581 content := []byte("hello")
582 ctx := context.Background()
583
584 // We're going to create a blob for each of the weird key strings, and
585 // then verify we can see them with List.
586 want := map[string]bool{}
587 for _, k := range escape.WeirdStrings {
588 want[keyPrefix+k] = true
589 }
590
591 // Creates blobs for sub-tests below.
592 // We only create the blobs once, for efficiency and because there's
593 // no guarantee that after we create them they will be immediately returned
594 // from List. The very first time the test is run against a Bucket, it may be
595 // flaky due to this race.
596 init := func(t *testing.T) (*blob.Bucket, func()) {
597 t.Helper()
598
599 h, err := newHarness(ctx, t)
600 if err != nil {
601 t.Fatal(err)
602 }
603 drv, err := h.MakeDriver(ctx)
604 if err != nil {
605 t.Fatal(err)
606 }
607 // See if the blobs are already there.
608 b := blob.NewBucket(drv)
609 iter := b.List(&blob.ListOptions{Prefix: keyPrefix})
610 found := iterToSetOfKeys(ctx, t, iter)
611 for _, k := range escape.WeirdStrings {
612 key := keyPrefix + k
613 if !found[key] {
614 if err := b.WriteAll(ctx, key, content, nil); err != nil {
615 b.Close()
616 t.Fatal(err)
617 }
618 }
619 }
620 return b, func() { b.Close(); h.Close() }
621 }
622
623 b, done := init(t)
624 defer done()
625
626 iter := b.List(&blob.ListOptions{Prefix: keyPrefix})
627 got := iterToSetOfKeys(ctx, t, iter)
628
629 if diff := cmp.Diff(got, want); diff != "" {
630 t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", got, want, diff)
631 }
632 }
633
634 // listResult is a recursive view of the hierarchy. It's used to verify List
635 // using Delimiter.
636 type listResult struct {
637 Key string
638 IsDir bool
639 // If IsDir is true and recursion is enabled, the recursive listing of the directory.
640 Sub []listResult
641 }
642
643 // doList lists b using prefix and delim.
644 // If recurse is true, it recurses into directories filling in listResult.Sub.
645 func doList(ctx context.Context, b *blob.Bucket, prefix, delim string, recurse bool) ([]listResult, error) {
646 iter := b.List(&blob.ListOptions{
647 Prefix: prefix,
648 Delimiter: delim,
649 })
650 var retval []listResult
651 for {
652 obj, err := iter.Next(ctx)
653 if err == io.EOF {
654 if obj != nil {
655 return nil, errors.New("obj is not nil on EOF")
656 }
657 break
658 }
659 if err != nil {
660 return nil, err
661 }
662 var sub []listResult
663 if obj.IsDir && recurse {
664 sub, err = doList(ctx, b, obj.Key, delim, true)
665 if err != nil {
666 return nil, err
667 }
668 }
669 retval = append(retval, listResult{
670 Key: obj.Key,
671 IsDir: obj.IsDir,
672 Sub: sub,
673 })
674 }
675 return retval, nil
676 }
677
678 // testListDelimiters tests the functionality of List using Delimiters.
679 func testListDelimiters(t *testing.T, newHarness HarnessMaker) {
680 t.Helper()
681
682 const keyPrefix = "blob-for-delimiters-"
683 content := []byte("hello")
684
685 // The set of files to use for these tests. The strings in each entry will
686 // be joined using delim, so the result is a directory structure like this
687 // (using / as delimiter):
688 // dir1/a.txt
689 // dir1/b.txt
690 // dir1/subdir/c.txt
691 // dir1/subdir/d.txt
692 // dir2/e.txt
693 // f.txt
694 keys := [][]string{
695 {"dir1", "a.txt"},
696 {"dir1", "b.txt"},
697 {"dir1", "subdir", "c.txt"},
698 {"dir1", "subdir", "d.txt"},
699 {"dir2", "e.txt"},
700 {"f.txt"},
701 }
702
703 // Test with several different delimiters.
704 tests := []struct {
705 name, delim string
706 // Expected result of doList with an empty delimiter.
707 // All keys should be listed at the top level, with no directories.
708 wantFlat []listResult
709 // Expected result of doList with delimiter and recurse = true.
710 // All keys should be listed, with keys in directories in the Sub field
711 // of their directory.
712 wantRecursive []listResult
713 // Expected result of repeatedly calling driver.ListPaged with delimiter
714 // and page size = 1.
715 wantPaged []listResult
716 // expected result of doList with delimiter and recurse = false
717 // after dir2/e.txt is deleted
718 // dir1/ and f.txt should be listed; dir2/ should no longer be present
719 // because there are no keys in it.
720 wantAfterDel []listResult
721 }{
722 {
723 name: "fwdslash",
724 delim: "/",
725 wantFlat: []listResult{
726 {Key: keyPrefix + "/dir1/a.txt"},
727 {Key: keyPrefix + "/dir1/b.txt"},
728 {Key: keyPrefix + "/dir1/subdir/c.txt"},
729 {Key: keyPrefix + "/dir1/subdir/d.txt"},
730 {Key: keyPrefix + "/dir2/e.txt"},
731 {Key: keyPrefix + "/f.txt"},
732 },
733 wantRecursive: []listResult{
734 {
735 Key: keyPrefix + "/dir1/",
736 IsDir: true,
737 Sub: []listResult{
738 {Key: keyPrefix + "/dir1/a.txt"},
739 {Key: keyPrefix + "/dir1/b.txt"},
740 {
741 Key: keyPrefix + "/dir1/subdir/",
742 IsDir: true,
743 Sub: []listResult{
744 {Key: keyPrefix + "/dir1/subdir/c.txt"},
745 {Key: keyPrefix + "/dir1/subdir/d.txt"},
746 },
747 },
748 },
749 },
750 {
751 Key: keyPrefix + "/dir2/",
752 IsDir: true,
753 Sub: []listResult{
754 {Key: keyPrefix + "/dir2/e.txt"},
755 },
756 },
757 {Key: keyPrefix + "/f.txt"},
758 },
759 wantPaged: []listResult{
760 {
761 Key: keyPrefix + "/dir1/",
762 IsDir: true,
763 },
764 {
765 Key: keyPrefix + "/dir2/",
766 IsDir: true,
767 },
768 {Key: keyPrefix + "/f.txt"},
769 },
770 wantAfterDel: []listResult{
771 {
772 Key: keyPrefix + "/dir1/",
773 IsDir: true,
774 },
775 {Key: keyPrefix + "/f.txt"},
776 },
777 },
778 {
779 name: "backslash",
780 delim: "\\",
781 wantFlat: []listResult{
782 {Key: keyPrefix + "\\dir1\\a.txt"},
783 {Key: keyPrefix + "\\dir1\\b.txt"},
784 {Key: keyPrefix + "\\dir1\\subdir\\c.txt"},
785 {Key: keyPrefix + "\\dir1\\subdir\\d.txt"},
786 {Key: keyPrefix + "\\dir2\\e.txt"},
787 {Key: keyPrefix + "\\f.txt"},
788 },
789 wantRecursive: []listResult{
790 {
791 Key: keyPrefix + "\\dir1\\",
792 IsDir: true,
793 Sub: []listResult{
794 {Key: keyPrefix + "\\dir1\\a.txt"},
795 {Key: keyPrefix + "\\dir1\\b.txt"},
796 {
797 Key: keyPrefix + "\\dir1\\subdir\\",
798 IsDir: true,
799 Sub: []listResult{
800 {Key: keyPrefix + "\\dir1\\subdir\\c.txt"},
801 {Key: keyPrefix + "\\dir1\\subdir\\d.txt"},
802 },
803 },
804 },
805 },
806 {
807 Key: keyPrefix + "\\dir2\\",
808 IsDir: true,
809 Sub: []listResult{
810 {Key: keyPrefix + "\\dir2\\e.txt"},
811 },
812 },
813 {Key: keyPrefix + "\\f.txt"},
814 },
815 wantPaged: []listResult{
816 {
817 Key: keyPrefix + "\\dir1\\",
818 IsDir: true,
819 },
820 {
821 Key: keyPrefix + "\\dir2\\",
822 IsDir: true,
823 },
824 {Key: keyPrefix + "\\f.txt"},
825 },
826 wantAfterDel: []listResult{
827 {
828 Key: keyPrefix + "\\dir1\\",
829 IsDir: true,
830 },
831 {Key: keyPrefix + "\\f.txt"},
832 },
833 },
834 {
835 name: "abc",
836 delim: "abc",
837 wantFlat: []listResult{
838 {Key: keyPrefix + "abcdir1abca.txt"},
839 {Key: keyPrefix + "abcdir1abcb.txt"},
840 {Key: keyPrefix + "abcdir1abcsubdirabcc.txt"},
841 {Key: keyPrefix + "abcdir1abcsubdirabcd.txt"},
842 {Key: keyPrefix + "abcdir2abce.txt"},
843 {Key: keyPrefix + "abcf.txt"},
844 },
845 wantRecursive: []listResult{
846 {
847 Key: keyPrefix + "abcdir1abc",
848 IsDir: true,
849 Sub: []listResult{
850 {Key: keyPrefix + "abcdir1abca.txt"},
851 {Key: keyPrefix + "abcdir1abcb.txt"},
852 {
853 Key: keyPrefix + "abcdir1abcsubdirabc",
854 IsDir: true,
855 Sub: []listResult{
856 {Key: keyPrefix + "abcdir1abcsubdirabcc.txt"},
857 {Key: keyPrefix + "abcdir1abcsubdirabcd.txt"},
858 },
859 },
860 },
861 },
862 {
863 Key: keyPrefix + "abcdir2abc",
864 IsDir: true,
865 Sub: []listResult{
866 {Key: keyPrefix + "abcdir2abce.txt"},
867 },
868 },
869 {Key: keyPrefix + "abcf.txt"},
870 },
871 wantPaged: []listResult{
872 {
873 Key: keyPrefix + "abcdir1abc",
874 IsDir: true,
875 },
876 {
877 Key: keyPrefix + "abcdir2abc",
878 IsDir: true,
879 },
880 {Key: keyPrefix + "abcf.txt"},
881 },
882 wantAfterDel: []listResult{
883 {
884 Key: keyPrefix + "abcdir1abc",
885 IsDir: true,
886 },
887 {Key: keyPrefix + "abcf.txt"},
888 },
889 },
890 }
891
892 ctx := context.Background()
893
894 // Creates blobs for sub-tests below.
895 // We only create the blobs once, for efficiency and because there's
896 // no guarantee that after we create them they will be immediately returned
897 // from List. The very first time the test is run against a Bucket, it may be
898 // flaky due to this race.
899 init := func(t *testing.T, delim string) (driver.Bucket, *blob.Bucket, func()) {
900 t.Helper()
901
902 h, err := newHarness(ctx, t)
903 if err != nil {
904 t.Fatal(err)
905 }
906 drv, err := h.MakeDriver(ctx)
907 if err != nil {
908 t.Fatal(err)
909 }
910 b := blob.NewBucket(drv)
911
912 // See if the blobs are already there.
913 prefix := keyPrefix + delim
914 iter := b.List(&blob.ListOptions{Prefix: prefix})
915 found := iterToSetOfKeys(ctx, t, iter)
916 for _, keyParts := range keys {
917 key := prefix + strings.Join(keyParts, delim)
918 if !found[key] {
919 if err := b.WriteAll(ctx, key, content, nil); err != nil {
920 b.Close()
921 t.Fatal(err)
922 }
923 }
924 }
925 return drv, b, func() { b.Close(); h.Close() }
926 }
927
928 for _, tc := range tests {
929 t.Run(tc.name, func(t *testing.T) {
930 drv, b, done := init(t, tc.delim)
931 defer done()
932
933 // Fetch without using delimiter.
934 got, err := doList(ctx, b, keyPrefix+tc.delim, "", true)
935 if err != nil {
936 t.Fatal(err)
937 }
938 if diff := cmp.Diff(got, tc.wantFlat); diff != "" {
939 t.Errorf("with no delimiter, got\n%v\nwant\n%v\ndiff\n%s", got, tc.wantFlat, diff)
940 }
941
942 // Fetch using delimiter, recursively.
943 got, err = doList(ctx, b, keyPrefix+tc.delim, tc.delim, true)
944 if err != nil {
945 t.Fatal(err)
946 }
947 if diff := cmp.Diff(got, tc.wantRecursive); diff != "" {
948 t.Errorf("with delimiter, got\n%v\nwant\n%v\ndiff\n%s", got, tc.wantRecursive, diff)
949 }
950
951 // Test pagination via driver.ListPaged.
952 var nextPageToken []byte
953 got = nil
954 for {
955 page, err := drv.ListPaged(ctx, &driver.ListOptions{
956 Prefix: keyPrefix + tc.delim,
957 Delimiter: tc.delim,
958 PageSize: 1,
959 PageToken: nextPageToken,
960 })
961 if err != nil {
962 t.Fatal(err)
963 }
964 if len(page.Objects) > 1 {
965 t.Errorf("got %d objects on a page, want 0 or 1", len(page.Objects))
966 }
967 for _, obj := range page.Objects {
968 got = append(got, listResult{
969 Key: obj.Key,
970 IsDir: obj.IsDir,
971 })
972 }
973 if len(page.NextPageToken) == 0 {
974 break
975 }
976 nextPageToken = page.NextPageToken
977 }
978 if diff := cmp.Diff(got, tc.wantPaged); diff != "" {
979 t.Errorf("paged got\n%v\nwant\n%v\ndiff\n%s", got, tc.wantPaged, diff)
980 }
981
982 // Delete dir2/e.txt and verify that dir2/ is no longer returned.
983 key := strings.Join(append([]string{keyPrefix}, "dir2", "e.txt"), tc.delim)
984 if err := b.Delete(ctx, key); err != nil {
985 t.Fatal(err)
986 }
987 // Attempt to restore dir2/e.txt at the end of the test for the next run.
988 defer func() {
989 _ = b.WriteAll(ctx, key, content, nil)
990 }()
991
992 got, err = doList(ctx, b, keyPrefix+tc.delim, tc.delim, false)
993 if err != nil {
994 t.Fatal(err)
995 }
996 if diff := cmp.Diff(got, tc.wantAfterDel); diff != "" {
997 t.Errorf("after delete, got\n%v\nwant\n%v\ndiff\n%s", got, tc.wantAfterDel, diff)
998 }
999 })
1000 }
1001 }
1002
1003 // testDirsWithCharactersBeforeDelimiter tests a case where there's
1004 // a directory on a pagination boundary that ends with a character that's
1005 // less than the delimiter.
1006 // See https://github.com/google/go-cloud/issues/3089.
1007 func testDirsWithCharactersBeforeDelimiter(t *testing.T, newHarness HarnessMaker) {
1008 t.Helper()
1009
1010 const keyPrefix = "blob-for-dirs-with-chars-before-delimiter/"
1011 content := []byte("hello")
1012
1013 // The set of files to use for these tests.
1014 keys := []string{
1015 "testFile1",
1016 "t/t/t",
1017 "t-/t.",
1018 "dir1/testFile1dir1",
1019 "dir2/testFile1dir2",
1020 "d",
1021 }
1022
1023 // Note that "t-/" is before "t/". The delimiter is included in the
1024 // alphabetical ordering.
1025 want := []string{"d", "dir1/", "dir2/", "t-/", "t/", "testFile1"}
1026
1027 // Create blobs.
1028 // We only create the blobs once, for efficiency and because there's
1029 // no guarantee that after we create them they will be immediately returned
1030 // from List. The very first time the test is run against a Bucket, it may be
1031 // flaky due to this race.
1032 ctx := context.Background()
1033 h, err := newHarness(ctx, t)
1034 if err != nil {
1035 t.Fatal(err)
1036 }
1037 drv, err := h.MakeDriver(ctx)
1038 if err != nil {
1039 t.Fatal(err)
1040 }
1041 b := blob.NewBucket(drv)
1042
1043 // See if the blobs are already there.
1044 iter := b.List(&blob.ListOptions{Prefix: keyPrefix})
1045 found := iterToSetOfKeys(ctx, t, iter)
1046 for _, key := range keys {
1047 key = keyPrefix + key
1048 if !found[key] {
1049 if err := b.WriteAll(ctx, key, content, nil); err != nil {
1050 b.Close()
1051 t.Fatal(err)
1052 }
1053 }
1054 }
1055 defer b.Close()
1056 defer h.Close()
1057
1058 opts := &blob.ListOptions{
1059 Prefix: keyPrefix,
1060 Delimiter: "/",
1061 }
1062 // All page sizes should return the same end result.
1063 for pageSize := 10; pageSize != 0; pageSize-- {
1064 var got []string
1065 objs, token, err := b.ListPage(ctx, blob.FirstPageToken, pageSize, opts)
1066 for {
1067 if err != nil {
1068 t.Fatal(err)
1069 }
1070 for _, o := range objs {
1071 key := strings.TrimPrefix(o.Key, keyPrefix)
1072 got = append(got, key)
1073 }
1074 if token == nil {
1075 break
1076 }
1077 objs, token, err = b.ListPage(ctx, token, pageSize, opts)
1078 }
1079 if !reflect.DeepEqual(want, got) {
1080 t.Fatalf("For page size %d, got \n%v\nwant\n%v", pageSize, got, want)
1081 }
1082 }
1083 }
1084
1085 func iterToSetOfKeys(ctx context.Context, t *testing.T, iter *blob.ListIterator) map[string]bool {
1086 t.Helper()
1087
1088 retval := map[string]bool{}
1089 for {
1090 if item, err := iter.Next(ctx); err == io.EOF {
1091 break
1092 } else if err != nil {
1093 t.Fatal(err)
1094 } else {
1095 retval[item.Key] = true
1096 }
1097 }
1098 return retval
1099 }
1100
1101 // testRead tests the functionality of NewReader, NewRangeReader, and Reader.
1102 func testRead(t *testing.T, newHarness HarnessMaker) {
1103 t.Helper()
1104
1105 const key = "blob-for-reading"
1106 content := []byte("abcdefghijklmnopqurstuvwxyz")
1107 contentSize := int64(len(content))
1108
1109 tests := []struct {
1110 name string
1111 key string
1112 offset, length int64
1113 want []byte
1114 wantReadSize int64
1115 wantErr bool
1116 // set to true to skip creation of the object for
1117 // tests where we expect an error without any actual
1118 // read.
1119 skipCreate bool
1120 }{
1121 {
1122 name: "read of nonexistent key fails",
1123 key: "key-does-not-exist",
1124 length: -1,
1125 wantErr: true,
1126 },
1127 {
1128 name: "negative offset fails",
1129 key: key,
1130 offset: -1,
1131 wantErr: true,
1132 skipCreate: true,
1133 },
1134 {
1135 name: "length 0 read",
1136 key: key,
1137 want: []byte{},
1138 },
1139 {
1140 name: "read from positive offset to end",
1141 key: key,
1142 offset: 10,
1143 length: -1,
1144 want: content[10:],
1145 wantReadSize: contentSize - 10,
1146 },
1147 {
1148 name: "read a part in middle",
1149 key: key,
1150 offset: 10,
1151 length: 5,
1152 want: content[10:15],
1153 wantReadSize: 5,
1154 },
1155 {
1156 name: "read in full",
1157 key: key,
1158 length: -1,
1159 want: content,
1160 wantReadSize: contentSize,
1161 },
1162 {
1163 name: "read in full with negative length not -1",
1164 key: key,
1165 length: -42,
1166 want: content,
1167 wantReadSize: contentSize,
1168 },
1169 }
1170
1171 ctx := context.Background()
1172
1173 // Creates a blob for sub-tests below.
1174 init := func(t *testing.T, skipCreate bool) (*blob.Bucket, func()) {
1175 t.Helper()
1176
1177 h, err := newHarness(ctx, t)
1178 if err != nil {
1179 t.Fatal(err)
1180 }
1181
1182 drv, err := h.MakeDriver(ctx)
1183 if err != nil {
1184 t.Fatal(err)
1185 }
1186 b := blob.NewBucket(drv)
1187 if skipCreate {
1188 return b, func() { b.Close(); h.Close() }
1189 }
1190 if err := b.WriteAll(ctx, key, content, nil); err != nil {
1191 b.Close()
1192 t.Fatal(err)
1193 }
1194 return b, func() {
1195 _ = b.Delete(ctx, key)
1196 b.Close()
1197 h.Close()
1198 }
1199 }
1200
1201 for _, tc := range tests {
1202 t.Run(tc.name, func(t *testing.T) {
1203 b, done := init(t, tc.skipCreate)
1204 defer done()
1205
1206 r, err := b.NewRangeReader(ctx, tc.key, tc.offset, tc.length, nil)
1207 if (err != nil) != tc.wantErr {
1208 t.Errorf("got err %v want error %v", err, tc.wantErr)
1209 }
1210 if err != nil {
1211 return
1212 }
1213 defer r.Close()
1214 // Make the buffer bigger than needed to make sure we actually only read
1215 // the expected number of bytes.
1216 got := make([]byte, tc.wantReadSize+10)
1217 n, err := r.Read(got)
1218 // EOF error is optional, see https://golang.org/pkg/io/#Reader.
1219 if err != nil && err != io.EOF {
1220 t.Errorf("unexpected error during read: %v", err)
1221 }
1222 if int64(n) != tc.wantReadSize {
1223 t.Errorf("got read length %d want %d", n, tc.wantReadSize)
1224 }
1225 if !cmp.Equal(got[:tc.wantReadSize], tc.want) {
1226 t.Errorf("got %q want %q", string(got), string(tc.want))
1227 }
1228 if r.Size() != contentSize {
1229 t.Errorf("got size %d want %d", r.Size(), contentSize)
1230 }
1231 if r.ModTime().IsZero() {
1232 t.Errorf("got zero mod time, want non-zero")
1233 }
1234 // For tests that successfully read, recreate the io.Reader and
1235 // test it with iotest.TestReader.
1236 r, err = b.NewRangeReader(ctx, tc.key, tc.offset, tc.length, nil)
1237 if err != nil {
1238 t.Errorf("failed to recreate Reader: %v", err)
1239 return
1240 }
1241 defer r.Close()
1242 if err = iotest.TestReader(r, tc.want); err != nil {
1243 t.Errorf("iotest.TestReader failed: %v", err)
1244 return
1245 }
1246 })
1247 }
1248 }
1249
1250 // testAttributes tests Attributes.
1251 func testAttributes(t *testing.T, newHarness HarnessMaker) {
1252 t.Helper()
1253
1254 const (
1255 dirKey = "someDir"
1256 key = dirKey + "/blob-for-attributes"
1257 contentType = "text/plain"
1258 cacheControl = "no-cache"
1259 contentDisposition = "inline"
1260 contentEncoding = "identity"
1261 contentLanguage = "en"
1262 )
1263 content := []byte("Hello World!")
1264
1265 ctx := context.Background()
1266
1267 // Creates a blob for sub-tests below.
1268 init := func(t *testing.T) (*blob.Bucket, func()) {
1269 t.Helper()
1270
1271 h, err := newHarness(ctx, t)
1272 if err != nil {
1273 t.Fatal(err)
1274 }
1275 drv, err := h.MakeDriver(ctx)
1276 if err != nil {
1277 t.Fatal(err)
1278 }
1279 b := blob.NewBucket(drv)
1280 opts := &blob.WriterOptions{
1281 ContentType: contentType,
1282 CacheControl: cacheControl,
1283 ContentDisposition: contentDisposition,
1284 ContentEncoding: contentEncoding,
1285 ContentLanguage: contentLanguage,
1286 }
1287 if err := b.WriteAll(ctx, key, content, opts); err != nil {
1288 b.Close()
1289 t.Fatal(err)
1290 }
1291 return b, func() {
1292 _ = b.Delete(ctx, key)
1293 b.Close()
1294 h.Close()
1295 }
1296 }
1297
1298 b, done := init(t)
1299 defer done()
1300
1301 for _, badKey := range []string{
1302 "not-found",
1303 dirKey,
1304 dirKey + "/",
1305 } {
1306 _, err := b.Attributes(ctx, badKey)
1307 if err == nil {
1308 t.Errorf("got nil want error")
1309 } else if gcerrors.Code(err) != gcerrors.NotFound {
1310 t.Errorf("got %v want NotFound error", err)
1311 } else if !strings.Contains(err.Error(), badKey) {
1312 t.Errorf("got %v want error to include missing key", err)
1313 }
1314 }
1315
1316 a, err := b.Attributes(ctx, key)
1317 if err != nil {
1318 t.Fatalf("failed Attributes: %v", err)
1319 }
1320 // Also make a Reader so we can verify the subset of attributes
1321 // that it exposes.
1322 r, err := b.NewReader(ctx, key, nil)
1323 if err != nil {
1324 t.Fatalf("failed Attributes: %v", err)
1325 }
1326 if a.CacheControl != cacheControl {
1327 t.Errorf("got CacheControl %q want %q", a.CacheControl, cacheControl)
1328 }
1329 if a.ContentDisposition != contentDisposition {
1330 t.Errorf("got ContentDisposition %q want %q", a.ContentDisposition, contentDisposition)
1331 }
1332 if a.ContentEncoding != contentEncoding {
1333 t.Errorf("got ContentEncoding %q want %q", a.ContentEncoding, contentEncoding)
1334 }
1335 if a.ContentLanguage != contentLanguage {
1336 t.Errorf("got ContentLanguage %q want %q", a.ContentLanguage, contentLanguage)
1337 }
1338 if a.ContentType != contentType {
1339 t.Errorf("got ContentType %q want %q", a.ContentType, contentType)
1340 }
1341 if r.ContentType() != contentType {
1342 t.Errorf("got Reader.ContentType() %q want %q", r.ContentType(), contentType)
1343 }
1344 if !a.CreateTime.IsZero() {
1345 if a.CreateTime.After(a.ModTime) {
1346 t.Errorf("CreateTime %v is after ModTime %v", a.CreateTime, a.ModTime)
1347 }
1348 }
1349 if a.ModTime.IsZero() {
1350 t.Errorf("ModTime not set")
1351 }
1352 if a.Size != int64(len(content)) {
1353 t.Errorf("got Size %d want %d", a.Size, len(content))
1354 }
1355 if r.Size() != int64(len(content)) {
1356 t.Errorf("got Reader.Size() %d want %d", r.Size(), len(content))
1357 }
1358 if a.ETag == "" {
1359 t.Error("ETag not set")
1360 }
1361 // Some basic syntax checks on ETag based on https://en.wikipedia.org/wiki/HTTP_ETag.
1362 // It should be of the form "xxxx" or W/"xxxx".
1363 if !strings.HasPrefix(a.ETag, "W/\"") && !strings.HasPrefix(a.ETag, "\"") {
1364 t.Errorf("ETag should start with W/\" or \" (got %s)", a.ETag)
1365 }
1366 if !strings.HasSuffix(a.ETag, "\"") {
1367 t.Errorf("ETag should end with \" (got %s)", a.ETag)
1368 }
1369 r.Close()
1370
1371 // Modify and re-fetch attributes.
1372 if err := b.WriteAll(ctx, key, content, nil); err != nil {
1373 t.Fatal(err)
1374 }
1375
1376 a2, err := b.Attributes(ctx, key)
1377 if err != nil {
1378 t.Errorf("failed Attributes#2: %v", err)
1379 }
1380 if a2.ModTime.Before(a.ModTime) {
1381 t.Errorf("ModTime %v is before %v", a2.ModTime, a.ModTime)
1382 }
1383 }
1384
1385 // loadTestData loads test data, inlined using go-bindata.
1386 func loadTestData(tb testing.TB, name string) []byte {
1387 tb.Helper()
1388
1389 data, err := Asset(name)
1390 if err != nil {
1391 tb.Fatal(err)
1392 }
1393 return data
1394 }
1395
1396 // testWrite tests the functionality of NewWriter and Writer.
1397 func testWrite(t *testing.T, newHarness HarnessMaker) {
1398 t.Helper()
1399
1400 const key = "blob-for-reading"
1401 const existingContent = "existing content"
1402 smallText := loadTestData(t, "test-small.txt")
1403 mediumHTML := loadTestData(t, "test-medium.html")
1404 largeJpg := loadTestData(t, "test-large.jpg")
1405 helloWorld := []byte("hello world")
1406 helloWorldMD5 := md5.Sum(helloWorld)
1407
1408 tests := []struct {
1409 name string
1410 key string
1411 exists bool
1412 content []byte
1413 contentType string
1414 disableContentTypeDetection bool
1415 contentMD5 []byte
1416 firstChunk int
1417 wantContentType *regexp.Regexp
1418 wantErr bool
1419 wantReadErr bool // if wantErr is true, and Read after err should fail with something other than NotExists
1420 }{
1421 {
1422 name: "write to empty key fails",
1423 wantErr: true,
1424 wantReadErr: true, // read from empty key fails, but not always with NotExists
1425 },
1426 {
1427 name: "no write then close results in empty blob",
1428 key: key,
1429 },
1430 {
1431 name: "no write then close results in empty blob, blob existed",
1432 key: key,
1433 },
1434 {
1435 name: "invalid ContentType fails",
1436 key: key,
1437 contentType: "application/octet/stream",
1438 wantErr: true,
1439 },
1440 {
1441 name: "ContentType is discovered if not provided",
1442 key: key,
1443 content: mediumHTML,
1444 wantContentType: regexp.MustCompile("text/html"),
1445 },
1446 {
1447 name: "ContentType is left empty if not provided and DisableContentTypeDetection is true",
1448 key: key,
1449 content: mediumHTML,
1450 disableContentTypeDetection: true,
1451 // Sadly we can't really verify this; even though we write the ContentType
1452 // empty, different providers return different values when we read it,
1453 // from "application/octet-stream" to their own sniffing.
1454 // wantContentType: regexp.MustCompile("^$"),
1455 },
1456 {
1457 name: "write with explicit ContentType overrides discovery",
1458 key: key,
1459 content: mediumHTML,
1460 contentType: "application/json",
1461 wantContentType: regexp.MustCompile("application/json"),
1462 },
1463 {
1464 name: "Content md5 match",
1465 key: key,
1466 content: helloWorld,
1467 contentMD5: helloWorldMD5[:],
1468 },
1469 {
1470 name: "Content md5 did not match",
1471 key: key,
1472 content: []byte("not hello world"),
1473 contentMD5: helloWorldMD5[:],
1474 wantErr: true,
1475 },
1476 {
1477 name: "Content md5 did not match, blob existed",
1478 exists: true,
1479 key: key,
1480 content: []byte("not hello world"),
1481 contentMD5: helloWorldMD5[:],
1482 wantErr: true,
1483 },
1484 {
1485 name: "a small text file gets a ContentType",
1486 key: key,
1487 content: smallText,
1488 wantContentType: regexp.MustCompile("text/plain.*"),
1489 },
1490 {
1491 name: "a large jpg file gets a ContentType",
1492 key: key,
1493 content: largeJpg,
1494 wantContentType: regexp.MustCompile("image/jpeg"),
1495 },
1496 {
1497 name: "a large jpg file written in two chunks gets a ContentType",
1498 key: key,
1499 firstChunk: 10,
1500 content: largeJpg,
1501 wantContentType: regexp.MustCompile("image/jpeg"),
1502 },
1503 // TODO(issue #304): Fails for GCS.
1504 /*
1505 {
1506 name: "ContentType is parsed and reformatted",
1507 key: key,
1508 content: []byte("foo"),
1509 contentType: `FORM-DATA;name="foo"`,
1510 wantContentType: `form-data; name=foo`,
1511 },
1512 */
1513 }
1514
1515 ctx := context.Background()
1516 for _, tc := range tests {
1517 t.Run(tc.name, func(t *testing.T) {
1518 h, err := newHarness(ctx, t)
1519 if err != nil {
1520 t.Fatal(err)
1521 }
1522 defer h.Close()
1523 drv, err := h.MakeDriver(ctx)
1524 if err != nil {
1525 t.Fatal(err)
1526 }
1527 b := blob.NewBucket(drv)
1528 defer b.Close()
1529
1530 // If the test wants the blob to already exist, write it.
1531 if tc.exists {
1532 if err := b.WriteAll(ctx, key, []byte(existingContent), nil); err != nil {
1533 t.Fatal(err)
1534 }
1535 defer func() {
1536 _ = b.Delete(ctx, key)
1537 }()
1538 }
1539
1540 // Write the content.
1541 opts := &blob.WriterOptions{
1542 ContentType: tc.contentType,
1543 DisableContentTypeDetection: tc.disableContentTypeDetection,
1544 ContentMD5: tc.contentMD5[:],
1545 }
1546 w, err := b.NewWriter(ctx, tc.key, opts)
1547 if err == nil {
1548 if len(tc.content) > 0 {
1549 if tc.firstChunk == 0 {
1550 // Write the whole thing.
1551 _, err = w.Write(tc.content)
1552 } else {
1553 // Write it in 2 chunks.
1554 _, err = w.Write(tc.content[:tc.firstChunk])
1555 if err == nil {
1556 _, err = w.Write(tc.content[tc.firstChunk:])
1557 }
1558 }
1559 }
1560 if err == nil {
1561 err = w.Close()
1562 }
1563 }
1564 if (err != nil) != tc.wantErr {
1565 t.Errorf("NewWriter or Close got err %v want error %v", err, tc.wantErr)
1566 }
1567 if err != nil {
1568 // The write failed; verify that it had no effect.
1569 buf, err := b.ReadAll(ctx, tc.key)
1570 if tc.exists {
1571 // Verify the previous content is still there.
1572 if !bytes.Equal(buf, []byte(existingContent)) {
1573 t.Errorf("Write failed as expected, but content doesn't match expected previous content; got \n%s\n want \n%s", string(buf), existingContent)
1574 }
1575 } else {
1576 // Verify that the read fails with NotFound.
1577 if err == nil {
1578 t.Error("Write failed as expected, but Read after that didn't return an error")
1579 } else if !tc.wantReadErr && gcerrors.Code(err) != gcerrors.NotFound {
1580 t.Errorf("Write failed as expected, but Read after that didn't return the right error; got %v want NotFound", err)
1581 } else if !strings.Contains(err.Error(), tc.key) {
1582 t.Errorf("got %v want error to include missing key", err)
1583 }
1584 }
1585 return
1586 }
1587 defer func() { _ = b.Delete(ctx, tc.key) }()
1588
1589 // Read it back.
1590 buf, err := b.ReadAll(ctx, tc.key)
1591 if err != nil {
1592 t.Fatal(err)
1593 }
1594 if !bytes.Equal(buf, tc.content) {
1595 if len(buf) < 100 && len(tc.content) < 100 {
1596 t.Errorf("read didn't match write; got \n%s\n want \n%s", string(buf), string(tc.content))
1597 } else {
1598 t.Error("read didn't match write, content too large to display")
1599 }
1600 }
1601
1602 // Verify the ContentType.
1603 if tc.wantContentType != nil {
1604 attrs, err := b.Attributes(ctx, tc.key)
1605 if err != nil {
1606 t.Fatal(err)
1607 }
1608 if !tc.wantContentType.MatchString(attrs.ContentType) {
1609 t.Errorf("got ContentType %q, want one matching %v", attrs.ContentType, tc.wantContentType)
1610 }
1611 }
1612 })
1613 }
1614 }
1615
1616 // testCanceledWrite tests the functionality of canceling an in-progress write.
1617 func testCanceledWrite(t *testing.T, newHarness HarnessMaker) {
1618 t.Helper()
1619
1620 const key = "blob-for-canceled-write"
1621 content := []byte("hello world")
1622 cancelContent := []byte("going to cancel")
1623
1624 tests := []struct {
1625 description string
1626 contentType string
1627 exists bool
1628 }{
1629 {
1630 // The write will be buffered in the portable type as part of
1631 // ContentType detection, so the first call to the Driver will be Close.
1632 description: "EmptyContentType",
1633 },
1634 {
1635 // The write will be sent to the Driver, which may do its own
1636 // internal buffering.
1637 description: "NonEmptyContentType",
1638 contentType: "text/plain",
1639 },
1640 {
1641 description: "BlobExists",
1642 exists: true,
1643 },
1644 // TODO(issue #482): Find a way to test that a chunked upload that's interrupted
1645 // after some chunks are uploaded cancels correctly.
1646 }
1647
1648 ctx := context.Background()
1649 for _, test := range tests {
1650 t.Run(test.description, func(t *testing.T) {
1651 cancelCtx, cancel := context.WithCancel(ctx)
1652 h, err := newHarness(ctx, t)
1653 if err != nil {
1654 t.Fatal(err)
1655 }
1656 defer h.Close()
1657 drv, err := h.MakeDriver(ctx)
1658 if err != nil {
1659 t.Fatal(err)
1660 }
1661 b := blob.NewBucket(drv)
1662 defer b.Close()
1663
1664 opts := &blob.WriterOptions{
1665 ContentType: test.contentType,
1666 }
1667 // If the test wants the blob to already exist, write it.
1668 if test.exists {
1669 if err := b.WriteAll(ctx, key, content, opts); err != nil {
1670 t.Fatal(err)
1671 }
1672 defer func() {
1673 _ = b.Delete(ctx, key)
1674 }()
1675 }
1676
1677 // Create a writer with the context that we're going
1678 // to cancel.
1679 w, err := b.NewWriter(cancelCtx, key, opts)
1680 if err != nil {
1681 t.Fatal(err)
1682 }
1683 // Write the content.
1684 if _, err := w.Write(cancelContent); err != nil {
1685 t.Fatal(err)
1686 }
1687
1688 // Verify that the previous content (if any) is still readable,
1689 // because the write hasn't been Closed yet.
1690 got, err := b.ReadAll(ctx, key)
1691 if test.exists {
1692 // The previous content should still be there.
1693 if !cmp.Equal(got, content) {
1694 t.Errorf("during unclosed write, got %q want %q", string(got), string(content))
1695 }
1696 } else {
1697 // The read should fail; the write hasn't been Closed so the
1698 // blob shouldn't exist.
1699 if err == nil {
1700 t.Error("wanted read to return an error when write is not yet Closed")
1701 }
1702 }
1703
1704 // Cancel the context to abort the write.
1705 cancel()
1706 // Close should return some kind of canceled context error.
1707 // We can't verify the kind of error cleanly, so we just verify there's
1708 // an error.
1709 if err := w.Close(); err == nil {
1710 t.Errorf("got Close error %v want canceled ctx error", err)
1711 }
1712
1713 // Verify the write was truly aborted.
1714 got, err = b.ReadAll(ctx, key)
1715 if test.exists {
1716 // The previous content should still be there.
1717 if !cmp.Equal(got, content) {
1718 t.Errorf("after canceled write, got %q want %q", string(got), string(content))
1719 }
1720 } else {
1721 // The read should fail; the write was aborted so the
1722 // blob shouldn't exist.
1723 if err == nil {
1724 t.Error("wanted read to return an error when write was canceled")
1725 }
1726 }
1727 })
1728 }
1729 }
1730
1731 // testMetadata tests writing and reading the key/value metadata for a blob.
1732 func testMetadata(t *testing.T, newHarness HarnessMaker) {
1733 t.Helper()
1734
1735 const key = "blob-for-metadata"
1736 hello := []byte("hello")
1737
1738 weirdMetadata := map[string]string{}
1739 for _, k := range escape.WeirdStrings {
1740 weirdMetadata[k] = k
1741 }
1742
1743 tests := []struct {
1744 name string
1745 metadata map[string]string
1746 content []byte
1747 contentType string
1748 want map[string]string
1749 wantErr bool
1750 }{
1751 {
1752 name: "empty",
1753 content: hello,
1754 metadata: map[string]string{},
1755 want: nil,
1756 },
1757 {
1758 name: "empty key fails",
1759 content: hello,
1760 metadata: map[string]string{"": "empty key value"},
1761 wantErr: true,
1762 },
1763 {
1764 name: "duplicate case-insensitive key fails",
1765 content: hello,
1766 metadata: map[string]string{"abc": "foo", "aBc": "bar"},
1767 wantErr: true,
1768 },
1769 {
1770 name: "valid metadata",
1771 content: hello,
1772 metadata: map[string]string{
1773 "key_a": "value-a",
1774 "kEy_B": "value-b",
1775 "key_c": "vAlUe-c",
1776 },
1777 want: map[string]string{
1778 "key_a": "value-a",
1779 "key_b": "value-b",
1780 "key_c": "vAlUe-c",
1781 },
1782 },
1783 {
1784 name: "valid metadata with empty body",
1785 content: nil,
1786 metadata: map[string]string{"foo": "bar"},
1787 want: map[string]string{"foo": "bar"},
1788 },
1789 {
1790 name: "valid metadata with content type",
1791 content: hello,
1792 contentType: "text/plain",
1793 metadata: map[string]string{"foo": "bar"},
1794 want: map[string]string{"foo": "bar"},
1795 },
1796 {
1797 name: "weird metadata keys",
1798 content: hello,
1799 metadata: weirdMetadata,
1800 want: weirdMetadata,
1801 },
1802 {
1803 name: "non-utf8 metadata key",
1804 content: hello,
1805 metadata: map[string]string{escape.NonUTF8String: "bar"},
1806 wantErr: true,
1807 },
1808 {
1809 name: "non-utf8 metadata value",
1810 content: hello,
1811 metadata: map[string]string{"foo": escape.NonUTF8String},
1812 wantErr: true,
1813 },
1814 }
1815
1816 ctx := context.Background()
1817 for _, tc := range tests {
1818 t.Run(tc.name, func(t *testing.T) {
1819 h, err := newHarness(ctx, t)
1820 if err != nil {
1821 t.Fatal(err)
1822 }
1823 defer h.Close()
1824
1825 drv, err := h.MakeDriver(ctx)
1826 if err != nil {
1827 t.Fatal(err)
1828 }
1829 b := blob.NewBucket(drv)
1830 defer b.Close()
1831 opts := &blob.WriterOptions{
1832 Metadata: tc.metadata,
1833 ContentType: tc.contentType,
1834 }
1835 err = b.WriteAll(ctx, key, hello, opts)
1836 if (err != nil) != tc.wantErr {
1837 t.Errorf("got error %v want error %v", err, tc.wantErr)
1838 }
1839 if err != nil {
1840 return
1841 }
1842 defer func() {
1843 _ = b.Delete(ctx, key)
1844 }()
1845 a, err := b.Attributes(ctx, key)
1846 if err != nil {
1847 t.Fatal(err)
1848 }
1849 if diff := cmp.Diff(a.Metadata, tc.want); diff != "" {
1850 t.Errorf("got\n%v\nwant\n%v\ndiff\n%s", a.Metadata, tc.want, diff)
1851 }
1852 })
1853 }
1854 }
1855
1856 // testMD5 tests reading MD5 hashes via List and Attributes.
1857 func testMD5(t *testing.T, newHarness HarnessMaker) {
1858 t.Helper()
1859
1860 ctx := context.Background()
1861
1862 // Define two blobs with different content; we'll write them and then verify
1863 // their returned MD5 hashes.
1864 const aKey, bKey = "blob-for-md5-aaa", "blob-for-md5-bbb"
1865 aContent, bContent := []byte("hello"), []byte("goodbye")
1866 aMD5 := md5.Sum(aContent)
1867 bMD5 := md5.Sum(bContent)
1868
1869 h, err := newHarness(ctx, t)
1870 if err != nil {
1871 t.Fatal(err)
1872 }
1873 defer h.Close()
1874 drv, err := h.MakeDriver(ctx)
1875 if err != nil {
1876 t.Fatal(err)
1877 }
1878 b := blob.NewBucket(drv)
1879 defer b.Close()
1880
1881 // Write the two blobs.
1882 if err := b.WriteAll(ctx, aKey, aContent, nil); err != nil {
1883 t.Fatal(err)
1884 }
1885 defer func() { _ = b.Delete(ctx, aKey) }()
1886 if err := b.WriteAll(ctx, bKey, bContent, nil); err != nil {
1887 t.Fatal(err)
1888 }
1889 defer func() { _ = b.Delete(ctx, bKey) }()
1890
1891 // Check the MD5 we get through Attributes. Note that it's always legal to
1892 // return a nil MD5.
1893 aAttr, err := b.Attributes(ctx, aKey)
1894 if err != nil {
1895 t.Fatal(err)
1896 }
1897 if aAttr.MD5 != nil && !bytes.Equal(aAttr.MD5, aMD5[:]) {
1898 t.Errorf("got MD5\n%x\nwant\n%x", aAttr.MD5, aMD5)
1899 }
1900
1901 bAttr, err := b.Attributes(ctx, bKey)
1902 if err != nil {
1903 t.Fatal(err)
1904 }
1905 if bAttr.MD5 != nil && !bytes.Equal(bAttr.MD5, bMD5[:]) {
1906 t.Errorf("got MD5\n%x\nwant\n%x", bAttr.MD5, bMD5)
1907 }
1908
1909 // Check the MD5 we get through List. Note that it's always legal to
1910 // return a nil MD5.
1911 iter := b.List(&blob.ListOptions{Prefix: "blob-for-md5-"})
1912 obj, err := iter.Next(ctx)
1913 if err != nil {
1914 t.Fatal(err)
1915 }
1916 if obj.Key != aKey {
1917 t.Errorf("got name %q want %q", obj.Key, aKey)
1918 }
1919 if obj.MD5 != nil && !bytes.Equal(obj.MD5, aMD5[:]) {
1920 t.Errorf("got MD5\n%x\nwant\n%x", obj.MD5, aMD5)
1921 }
1922 obj, err = iter.Next(ctx)
1923 if err != nil {
1924 t.Fatal(err)
1925 }
1926 if obj.Key != bKey {
1927 t.Errorf("got name %q want %q", obj.Key, bKey)
1928 }
1929 if obj.MD5 != nil && !bytes.Equal(obj.MD5, bMD5[:]) {
1930 t.Errorf("got MD5\n%x\nwant\n%x", obj.MD5, bMD5)
1931 }
1932 }
1933
1934 // testCopy tests the functionality of Copy.
1935 func testCopy(t *testing.T, newHarness HarnessMaker) {
1936 t.Helper()
1937
1938 const (
1939 srcKey = "blob-for-copying-src"
1940 dstKey = "blob-for-copying-dest"
1941 dstKeyExists = "blob-for-copying-dest-exists"
1942 contentType = "text/plain"
1943 cacheControl = "no-cache"
1944 contentDisposition = "inline"
1945 contentEncoding = "identity"
1946 contentLanguage = "en"
1947 )
1948 contents := []byte("Hello World")
1949
1950 ctx := context.Background()
1951 t.Run("NonExistentSourceFails", func(t *testing.T) {
1952 h, err := newHarness(ctx, t)
1953 if err != nil {
1954 t.Fatal(err)
1955 }
1956 defer h.Close()
1957 drv, err := h.MakeDriver(ctx)
1958 if err != nil {
1959 t.Fatal(err)
1960 }
1961 b := blob.NewBucket(drv)
1962 defer b.Close()
1963
1964 err = b.Copy(ctx, dstKey, "does-not-exist", nil)
1965 if err == nil {
1966 t.Errorf("got nil want error")
1967 } else if gcerrors.Code(err) != gcerrors.NotFound {
1968 t.Errorf("got %v want NotFound error", err)
1969 } else if !strings.Contains(err.Error(), "does-not-exist") {
1970 t.Errorf("got %v want error to include missing key", err)
1971 }
1972 })
1973
1974 t.Run("Works", func(t *testing.T) {
1975 h, err := newHarness(ctx, t)
1976 if err != nil {
1977 t.Fatal(err)
1978 }
1979 defer h.Close()
1980 drv, err := h.MakeDriver(ctx)
1981 if err != nil {
1982 t.Fatal(err)
1983 }
1984 b := blob.NewBucket(drv)
1985 defer b.Close()
1986
1987 // Create the source blob.
1988 wopts := &blob.WriterOptions{
1989 ContentType: contentType,
1990 CacheControl: cacheControl,
1991 ContentDisposition: contentDisposition,
1992 ContentEncoding: contentEncoding,
1993 ContentLanguage: contentLanguage,
1994 Metadata: map[string]string{"foo": "bar"},
1995 }
1996 if err := b.WriteAll(ctx, srcKey, contents, wopts); err != nil {
1997 t.Fatal(err)
1998 }
1999
2000 // Grab its attributes to compare to the copy's attributes later.
2001 wantAttr, err := b.Attributes(ctx, srcKey)
2002 if err != nil {
2003 t.Fatal(err)
2004 }
2005
2006 // Clear uncomparable fields.
2007 clearUncomparableFields := func(a *blob.Attributes) {
2008 a.CreateTime = time.Time{}
2009 a.ModTime = time.Time{}
2010 a.ETag = ""
2011 }
2012 clearUncomparableFields(wantAttr)
2013
2014 // Create another blob that we're going to overwrite.
2015 if err := b.WriteAll(ctx, dstKeyExists, []byte("clobber me"), nil); err != nil {
2016 t.Fatal(err)
2017 }
2018
2019 // Copy the source to the destination.
2020 if err := b.Copy(ctx, dstKey, srcKey, nil); err != nil {
2021 t.Errorf("got unexpected error copying blob: %v", err)
2022 }
2023 // Read the copy.
2024 got, err := b.ReadAll(ctx, dstKey)
2025 if err != nil {
2026 t.Fatal(err)
2027 }
2028 if !cmp.Equal(got, contents) {
2029 t.Errorf("got %q want %q", string(got), string(contents))
2030 }
2031 // Verify attributes of the copy.
2032 gotAttr, err := b.Attributes(ctx, dstKey)
2033 if err != nil {
2034 t.Fatal(err)
2035 }
2036 clearUncomparableFields(gotAttr)
2037 if diff := cmp.Diff(gotAttr, wantAttr, cmpopts.IgnoreUnexported(blob.Attributes{})); diff != "" {
2038 t.Errorf("got %v want %v diff %s", gotAttr, wantAttr, diff)
2039 }
2040
2041 // Copy the source to the second destination, where there's an existing blob.
2042 // It should be overwritten.
2043 if err := b.Copy(ctx, dstKeyExists, srcKey, nil); err != nil {
2044 t.Errorf("got unexpected error copying blob: %v", err)
2045 }
2046 // Read the copy.
2047 got, err = b.ReadAll(ctx, dstKeyExists)
2048 if err != nil {
2049 t.Fatal(err)
2050 }
2051 if !cmp.Equal(got, contents) {
2052 t.Errorf("got %q want %q", string(got), string(contents))
2053 }
2054 // Verify attributes of the copy.
2055 gotAttr, err = b.Attributes(ctx, dstKeyExists)
2056 if err != nil {
2057 t.Fatal(err)
2058 }
2059 clearUncomparableFields(gotAttr)
2060 if diff := cmp.Diff(gotAttr, wantAttr, cmpopts.IgnoreUnexported(blob.Attributes{})); diff != "" {
2061 t.Errorf("got %v want %v diff %s", gotAttr, wantAttr, diff)
2062 }
2063 })
2064 }
2065
2066 // testDelete tests the functionality of Delete.
2067 func testDelete(t *testing.T, newHarness HarnessMaker) {
2068 t.Helper()
2069
2070 const key = "blob-for-deleting"
2071
2072 ctx := context.Background()
2073 t.Run("NonExistentFails", func(t *testing.T) {
2074 h, err := newHarness(ctx, t)
2075 if err != nil {
2076 t.Fatal(err)
2077 }
2078 defer h.Close()
2079 drv, err := h.MakeDriver(ctx)
2080 if err != nil {
2081 t.Fatal(err)
2082 }
2083 b := blob.NewBucket(drv)
2084 defer b.Close()
2085
2086 err = b.Delete(ctx, "does-not-exist")
2087 if err == nil {
2088 t.Errorf("got nil want error")
2089 } else if gcerrors.Code(err) != gcerrors.NotFound {
2090 t.Errorf("got %v want NotFound error", err)
2091 } else if !strings.Contains(err.Error(), "does-not-exist") {
2092 t.Errorf("got %v want error to include missing key", err)
2093 }
2094 })
2095
2096 t.Run("Works", func(t *testing.T) {
2097 h, err := newHarness(ctx, t)
2098 if err != nil {
2099 t.Fatal(err)
2100 }
2101 defer h.Close()
2102 drv, err := h.MakeDriver(ctx)
2103 if err != nil {
2104 t.Fatal(err)
2105 }
2106 b := blob.NewBucket(drv)
2107 defer b.Close()
2108
2109 // Create the blob.
2110 if err := b.WriteAll(ctx, key, []byte("Hello world"), nil); err != nil {
2111 t.Fatal(err)
2112 }
2113 // Delete it.
2114 if err := b.Delete(ctx, key); err != nil {
2115 t.Errorf("got unexpected error deleting blob: %v", err)
2116 }
2117 // Subsequent read fails with NotFound.
2118 _, err = b.NewReader(ctx, key, nil)
2119 if err == nil {
2120 t.Errorf("read after delete got nil, want error")
2121 } else if gcerrors.Code(err) != gcerrors.NotFound {
2122 t.Errorf("read after delete want NotFound error, got %v", err)
2123 } else if !strings.Contains(err.Error(), key) {
2124 t.Errorf("got %v want error to include missing key", err)
2125 }
2126 // Subsequent delete also fails.
2127 err = b.Delete(ctx, key)
2128 if err == nil {
2129 t.Errorf("delete after delete got nil, want error")
2130 } else if gcerrors.Code(err) != gcerrors.NotFound {
2131 t.Errorf("delete after delete got %v, want NotFound error", err)
2132 } else if !strings.Contains(err.Error(), key) {
2133 t.Errorf("got %v want error to include missing key", err)
2134 }
2135 })
2136 }
2137
2138 // testConcurrentWriteAndRead tests that concurrent writing to multiple blob
2139 // keys and concurrent reading from multiple blob keys works.
2140 func testConcurrentWriteAndRead(t *testing.T, newHarness HarnessMaker) {
2141 t.Helper()
2142
2143 ctx := context.Background()
2144 h, err := newHarness(ctx, t)
2145 if err != nil {
2146 t.Fatal(err)
2147 }
2148 defer h.Close()
2149 drv, err := h.MakeDriver(ctx)
2150 if err != nil {
2151 t.Fatal(err)
2152 }
2153 b := blob.NewBucket(drv)
2154 defer b.Close()
2155
2156 // Prepare data. Each of the numKeys blobs has dataSize bytes, with each byte
2157 // set to the numeric key index. For example, the blob at "key0" consists of
2158 // all dataSize bytes set to 0.
2159 const numKeys = 20
2160 const dataSize = 4 * 1024
2161 keyData := make(map[int][]byte)
2162 for k := range numKeys {
2163 data := make([]byte, dataSize)
2164 for i := range dataSize {
2165 data[i] = byte(k)
2166 }
2167 keyData[k] = data
2168 }
2169
2170 blobName := func(k int) string {
2171 return fmt.Sprintf("key%d", k)
2172 }
2173
2174 var wg sync.WaitGroup
2175
2176 errs := make(chan error, numKeys)
2177
2178 // Write all blobs concurrently.
2179 for k := range numKeys {
2180 wg.Add(1)
2181 go func(key int) {
2182 if err := b.WriteAll(ctx, blobName(key), keyData[key], nil); err != nil {
2183 errs <- fmt.Errorf("WriteAll key=%v: %w", key, err)
2184 }
2185 wg.Done()
2186 }(k)
2187 defer b.Delete(ctx, blobName(k))
2188 }
2189 wg.Wait()
2190
2191 close(errs)
2192
2193 for err := range errs {
2194 t.Fatalf("got error from concurrent blob write: %v", err)
2195 }
2196
2197 errs = make(chan error, numKeys)
2198
2199 // Read all blobs concurrently and verify that they contain the expected data.
2200 for k := range numKeys {
2201 wg.Add(1)
2202 go func(key int) {
2203 buf, err := b.ReadAll(ctx, blobName(key))
2204 if err != nil {
2205 errs <- err
2206 } else if !bytes.Equal(buf, keyData[key]) {
2207 errs <- fmt.Errorf("read data mismatch for key %d", key)
2208 }
2209 wg.Done()
2210 }(k)
2211 }
2212 wg.Wait()
2213
2214 close(errs)
2215
2216 for err := range errs {
2217 t.Fatalf("got error from concurrent blob write: %v", err)
2218 }
2219 }
2220
2221 // testUploadDownload tests that Upload and Download work. For many drivers,
2222 // these are implemented in the concrete type, but drivers that implement Reader.Download
2223 // and/or Writer.Upload will have those called directly.
2224 func testUploadDownload(t *testing.T, newHarness HarnessMaker) {
2225 t.Helper()
2226
2227 const key = "blob-for-upload-download"
2228 const contents = "up and down"
2229 contentsMD5 := md5.Sum([]byte(contents))
2230
2231 ctx := context.Background()
2232 h, err := newHarness(ctx, t)
2233 if err != nil {
2234 t.Fatal(err)
2235 }
2236 defer h.Close()
2237 drv, err := h.MakeDriver(ctx)
2238 if err != nil {
2239 t.Fatal(err)
2240 }
2241 b := blob.NewBucket(drv)
2242 defer b.Close()
2243
2244 // Write a blob using Upload.
2245 if err := b.Upload(ctx, key, strings.NewReader(contents), &blob.WriterOptions{ContentType: "text"}); err != nil {
2246 t.Fatal(err)
2247 }
2248 defer b.Delete(ctx, key)
2249
2250 // Read the blob using Download.
2251 var bb bytes.Buffer
2252 err = b.Download(ctx, key, &bb, nil)
2253 if err != nil {
2254 t.Fatal(err)
2255 }
2256 if bb.String() != contents {
2257 t.Errorf("read data mismatch for key %s", key)
2258 }
2259
2260 // Write another blob using Upload and ContentMD5 checking (this disables the Upload optimization).
2261 if err := b.Upload(ctx, key, strings.NewReader(contents), &blob.WriterOptions{ContentMD5: contentsMD5[:], ContentType: "text"}); err != nil {
2262 t.Fatal(err)
2263 }
2264 defer b.Delete(ctx, key)
2265 }
2266
2267 // testKeys tests a variety of weird keys.
2268 func testKeys(t *testing.T, newHarness HarnessMaker) {
2269 t.Helper()
2270
2271 const keyPrefix = "weird-keys"
2272 content := []byte("hello")
2273 ctx := context.Background()
2274
2275 t.Run("non-UTF8 fails", func(t *testing.T) {
2276 h, err := newHarness(ctx, t)
2277 if err != nil {
2278 t.Fatal(err)
2279 }
2280 defer h.Close()
2281 drv, err := h.MakeDriver(ctx)
2282 if err != nil {
2283 t.Fatal(err)
2284 }
2285 b := blob.NewBucket(drv)
2286 defer b.Close()
2287
2288 // Write the blob.
2289 key := keyPrefix + escape.NonUTF8String
2290 if err := b.WriteAll(ctx, key, content, nil); err == nil {
2291 t.Error("got nil error, expected error for using non-UTF8 string as key")
2292 }
2293 })
2294
2295 for description, key := range escape.WeirdStrings {
2296 t.Run(description, func(t *testing.T) {
2297 h, err := newHarness(ctx, t)
2298 if err != nil {
2299 t.Fatal(err)
2300 }
2301 defer h.Close()
2302 drv, err := h.MakeDriver(ctx)
2303 if err != nil {
2304 t.Fatal(err)
2305 }
2306 b := blob.NewBucket(drv)
2307 defer b.Close()
2308
2309 // Write the blob.
2310 key = keyPrefix + key
2311 if err := b.WriteAll(ctx, key, content, nil); err != nil {
2312 t.Fatal(err)
2313 }
2314
2315 defer func() {
2316 err := b.Delete(ctx, key)
2317 if err != nil {
2318 t.Error(err)
2319 }
2320 }()
2321
2322 // Verify read works.
2323 got, err := b.ReadAll(ctx, key)
2324 if err != nil {
2325 t.Fatal(err)
2326 }
2327 if !cmp.Equal(got, content) {
2328 t.Errorf("got %q want %q", string(got), string(content))
2329 }
2330
2331 // Verify Attributes works.
2332 _, err = b.Attributes(ctx, key)
2333 if err != nil {
2334 t.Error(err)
2335 }
2336
2337 // Verify SignedURL works.
2338 url, err := b.SignedURL(ctx, key, nil)
2339 if gcerrors.Code(err) != gcerrors.Unimplemented {
2340 if err != nil {
2341 t.Error(err)
2342 }
2343 client := h.HTTPClient()
2344 if client == nil {
2345 t.Error("can't verify SignedURL, Harness.HTTPClient() returned nil")
2346 }
2347 resp, err := client.Get(url)
2348 if err != nil {
2349 t.Fatal(err)
2350 }
2351 defer resp.Body.Close()
2352 if resp.StatusCode != 200 {
2353 t.Errorf("got status code %d, want 200", resp.StatusCode)
2354 }
2355 got, err := io.ReadAll(resp.Body)
2356 if err != nil {
2357 t.Fatal(err)
2358 }
2359 if !bytes.Equal(got, content) {
2360 t.Errorf("got body %q, want %q", string(got), string(content))
2361 }
2362 }
2363
2364 // Copy the blob.
2365 // TODO: s3blob's Copy fails on repeatedfwdslashes.
2366 if description != "repeatedfwdslashes" {
2367 copyToKey := key + "-copy"
2368 if err := b.Copy(ctx, copyToKey, key, nil); err != nil {
2369 t.Fatal(err)
2370 }
2371 defer func() {
2372 err := b.Delete(ctx, copyToKey)
2373 if err != nil {
2374 t.Error(err)
2375 }
2376 }()
2377 got, err = b.ReadAll(ctx, copyToKey)
2378 if err != nil {
2379 t.Fatal(err)
2380 }
2381 if !cmp.Equal(got, content) {
2382 t.Errorf("copied got %q want %q", string(got), string(content))
2383 }
2384 }
2385 })
2386 }
2387 }
2388
2389 // testSignedURL tests the functionality of SignedURL.
2390 func testSignedURL(t *testing.T, newHarness HarnessMaker) {
2391 t.Helper()
2392
2393 const key = "blob-for-signing"
2394 const contents = "hello world"
2395
2396 ctx := context.Background()
2397
2398 h, err := newHarness(ctx, t)
2399 if err != nil {
2400 t.Fatal(err)
2401 }
2402 defer h.Close()
2403
2404 drv, err := h.MakeDriver(ctx)
2405 if err != nil {
2406 t.Fatal(err)
2407 }
2408 b := blob.NewBucket(drv)
2409 defer b.Close()
2410
2411 // Verify that a negative Expiry gives an error. This is enforced in the
2412 // portable type, so works regardless of driver support.
2413 _, err = b.SignedURL(ctx, key, &blob.SignedURLOptions{Expiry: -1 * time.Minute})
2414 if err == nil {
2415 t.Error("got nil error, expected error for negative SignedURLOptions.Expiry")
2416 }
2417
2418 // Generate a signed URL for GET.
2419 getURL, err := b.SignedURL(ctx, key, nil)
2420 if err != nil {
2421 if gcerrors.Code(err) == gcerrors.Unimplemented {
2422 t.Skipf("SignedURL not supported")
2423 return
2424 }
2425 t.Fatal(err)
2426 } else if getURL == "" {
2427 t.Fatal("got empty GET url")
2428 }
2429
2430 // Copy getURL, but remove all query params. This URL should not be allowed
2431 // to GET since the client is unauthorized.
2432 getURLNoParamsURL, err := url.Parse(getURL)
2433 if err != nil {
2434 t.Fatalf("failed to parse getURL: %v", err)
2435 }
2436 getURLNoParamsURL.RawQuery = ""
2437 getURLNoParams := getURLNoParamsURL.String()
2438 const (
2439 allowedContentType = "text/plain"
2440 differentContentType = "application/octet-stream"
2441 )
2442
2443 // Generate a signed URL for PUT, with a non-empty ContentType.
2444 putURLWithContentType, err := b.SignedURL(ctx, key, &blob.SignedURLOptions{
2445 Method: http.MethodPut,
2446 ContentType: allowedContentType,
2447 })
2448 if gcerrors.Code(err) == gcerrors.Unimplemented {
2449 t.Log("PUT URLs with content type not supported, skipping")
2450 } else if err != nil {
2451 t.Fatal(err)
2452 } else if putURLWithContentType == "" {
2453 t.Fatal("got empty PUT url")
2454 }
2455
2456 // Generate a signed URL for PUT, with an empty ContentType that's enforced.
2457 putURLEnforcedAbsentContentType, err := b.SignedURL(ctx, key, &blob.SignedURLOptions{
2458 Method: http.MethodPut,
2459 EnforceAbsentContentType: true,
2460 })
2461 if gcerrors.Code(err) == gcerrors.Unimplemented {
2462 t.Log("PUT URLs with enforced absent content type not supported, skipping")
2463 } else if err != nil {
2464 t.Fatal(err)
2465 } else if putURLEnforcedAbsentContentType == "" {
2466 t.Fatal("got empty PUT url")
2467 }
2468
2469 // Same as above, but not enforced.
2470 putURLWithoutContentType, err := b.SignedURL(ctx, key, &blob.SignedURLOptions{
2471 Method: http.MethodPut,
2472 })
2473 if err != nil {
2474 t.Fatal(err)
2475 } else if putURLWithoutContentType == "" {
2476 t.Fatal("got empty PUT url")
2477 }
2478
2479 // Generate a signed URL for DELETE.
2480 deleteURL, err := b.SignedURL(ctx, key, &blob.SignedURLOptions{Method: http.MethodDelete})
2481 if gcerrors.Code(err) == gcerrors.Unimplemented {
2482 t.Log("DELETE URLs not supported, skipping")
2483 } else if err != nil {
2484 t.Fatal(err)
2485 } else if deleteURL == "" {
2486 t.Fatal("got empty DELETE url")
2487 }
2488
2489 client := h.HTTPClient()
2490 if client == nil {
2491 t.Fatal("can't verify SignedURL, Harness.HTTPClient() returned nil")
2492 }
2493
2494 // PUT the blob. Try with all URLs, only putURL should work when given the
2495 // content type used in the signature.
2496 type signedURLTest struct {
2497 urlDescription string
2498 url string
2499 contentType string
2500 wantSuccess bool
2501 }
2502 tests := []signedURLTest{
2503 {"getURL", getURL, "", false},
2504 }
2505 if deleteURL != "" {
2506 tests = append(tests, signedURLTest{"deleteURL", deleteURL, "", false})
2507 }
2508 if putURLWithContentType != "" {
2509 // Allowed content type should work.
2510 // Different or empty content type should fail.
2511 tests = append(tests, signedURLTest{"putURLWithContentType", putURLWithContentType, allowedContentType, true})
2512 tests = append(tests, signedURLTest{"putURLWithContentType", putURLWithContentType, differentContentType, false})
2513 tests = append(tests, signedURLTest{"putURLWithContentType", putURLWithContentType, "", false})
2514 }
2515 if putURLEnforcedAbsentContentType != "" {
2516 // Empty content type should work, non-empty should fail.
2517 tests = append(tests, signedURLTest{"putURLEnforcedAbsentContentType", putURLEnforcedAbsentContentType, "", true})
2518 tests = append(tests, signedURLTest{"putURLEnforcedAbsentContentType", putURLEnforcedAbsentContentType, differentContentType, false})
2519 }
2520 if putURLWithoutContentType != "" {
2521 // Empty content type should work.
2522 tests = append(tests, signedURLTest{"putURLWithoutContentType", putURLWithoutContentType, "", true})
2523 // From the SignedURLOptions docstring:
2524 // If EnforceAbsentContentType is false and ContentType is the empty string,
2525 // then PUTing without a Content-Type header will succeed, but it is
2526 // implementation-specific whether providing a Content-Type header will fail.
2527 // --> so, we don't have a test for putURLWithoutContentType and a non-empty ContentType.
2528 }
2529 for _, test := range tests {
2530 req, err := http.NewRequest(http.MethodPut, test.url, strings.NewReader(contents))
2531 if err != nil {
2532 t.Fatalf("failed to create PUT HTTP request using %q: %v", test.urlDescription, err)
2533 }
2534 if test.contentType != "" {
2535 req.Header.Set("Content-Type", test.contentType)
2536 }
2537 if resp, err := client.Do(req); err != nil {
2538 t.Fatalf("PUT to %q with ContentType %q failed: %v", test.urlDescription, test.contentType, err)
2539 } else {
2540 defer resp.Body.Close()
2541 success := resp.StatusCode >= 200 && resp.StatusCode < 300
2542 if success != test.wantSuccess {
2543 t.Errorf("PUT to %q with ContentType %q got status code %d, wanted 2xx? %v", test.urlDescription, test.contentType, resp.StatusCode, test.wantSuccess)
2544 gotBody, _ := io.ReadAll(resp.Body)
2545 t.Error(string(gotBody))
2546 }
2547 }
2548 }
2549
2550 // GET it. Try with all URLs, only getURL should work.
2551 tests = nil
2552 if deleteURL != "" {
2553 tests = append(tests, signedURLTest{"deleteURL", deleteURL, "", false})
2554 }
2555 tests = append(tests, []signedURLTest{
2556 {"putURLWithoutContentType", putURLWithoutContentType, "", false},
2557 {"getURLNoParams", getURLNoParams, "", false},
2558 {"getURL", getURL, "", true},
2559 }...)
2560 for _, test := range tests {
2561 if resp, err := client.Get(test.url); err != nil {
2562 t.Fatalf("GET with %s URL failed: %v", test.urlDescription, err)
2563 } else {
2564 defer resp.Body.Close()
2565 success := resp.StatusCode >= 200 && resp.StatusCode < 300
2566 if success != test.wantSuccess {
2567 t.Errorf("GET to %q got status code %d, want 2xx? %v", test.urlDescription, resp.StatusCode, test.wantSuccess)
2568 gotBody, _ := io.ReadAll(resp.Body)
2569 t.Error(string(gotBody))
2570 } else if success {
2571 gotBody, err := io.ReadAll(resp.Body)
2572 if err != nil {
2573 t.Errorf("GET to %q failed to read response body: %v", test.urlDescription, err)
2574 } else if gotBodyStr := string(gotBody); gotBodyStr != contents {
2575 t.Errorf("GET to %q got body %q, want %q", test.urlDescription, gotBodyStr, contents)
2576 }
2577 }
2578 }
2579 }
2580
2581 // DELETE it. Try with all URLs, only deleteURL should work.
2582 tests = []signedURLTest{
2583 {"getURL", getURL, "", false},
2584 {"putURLWithoutContentType", putURLWithoutContentType, "", false},
2585 }
2586 if deleteURL != "" {
2587 tests = append(tests, signedURLTest{"deleteURL", deleteURL, "", true})
2588 }
2589 for _, test := range tests {
2590 req, err := http.NewRequest(http.MethodDelete, test.url, nil)
2591 if err != nil {
2592 t.Fatalf("failed to create DELETE HTTP request using %q: %v", test.urlDescription, err)
2593 }
2594 if resp, err := client.Do(req); err != nil {
2595 t.Fatalf("DELETE to %q failed: %v", test.urlDescription, err)
2596 } else {
2597 defer resp.Body.Close()
2598 success := resp.StatusCode >= 200 && resp.StatusCode < 300
2599 if success != test.wantSuccess {
2600 gotBody, _ := io.ReadAll(resp.Body)
2601 t.Error(string(gotBody))
2602 t.Fatalf("DELETE to %q got status code %d, want 2xx? %v", test.urlDescription, resp.StatusCode, test.wantSuccess)
2603 }
2604 }
2605 }
2606
2607 // GET should fail now that the blob has been deleted.
2608 if deleteURL != "" {
2609 if resp, err := client.Get(getURL); err != nil {
2610 t.Errorf("GET after DELETE failed: %v", err)
2611 } else {
2612 defer resp.Body.Close()
2613 if resp.StatusCode != 404 {
2614 t.Errorf("GET after DELETE got status code %d, want 404", resp.StatusCode)
2615 gotBody, _ := io.ReadAll(resp.Body)
2616 t.Error(string(gotBody))
2617 }
2618 }
2619 }
2620 }
2621
2622 // testAs tests the various As functions, using AsTest.
2623 func testAs(t *testing.T, newHarness HarnessMaker, st AsTest) {
2624 t.Helper()
2625
2626 const (
2627 dir = "mydir"
2628 key = dir + "/as-test"
2629 copyKey = dir + "/as-test-copy"
2630 )
2631 content := []byte("hello world")
2632 ctx := context.Background()
2633
2634 h, err := newHarness(ctx, t)
2635 if err != nil {
2636 t.Fatal(err)
2637 }
2638 defer h.Close()
2639
2640 drv, err := h.MakeDriver(ctx)
2641 if err != nil {
2642 t.Fatal(err)
2643 }
2644 b := blob.NewBucket(drv)
2645 defer b.Close()
2646
2647 // Verify Bucket.As.
2648 if err := st.BucketCheck(b); err != nil {
2649 t.Error(err)
2650 }
2651
2652 // Create a blob, using the provided callback.
2653 if err := b.WriteAll(ctx, key, content, &blob.WriterOptions{BeforeWrite: st.BeforeWrite}); err != nil {
2654 t.Error(err)
2655 }
2656 defer func() { _ = b.Delete(ctx, key) }()
2657
2658 // Verify Attributes.As.
2659 attrs, err := b.Attributes(ctx, key)
2660 if err != nil {
2661 t.Fatal(err)
2662 }
2663 if err := st.AttributesCheck(attrs); err != nil {
2664 t.Error(err)
2665 }
2666
2667 // Verify Reader.As.
2668 r, err := b.NewReader(ctx, key, &blob.ReaderOptions{BeforeRead: st.BeforeRead})
2669 if err != nil {
2670 t.Fatal(err)
2671 }
2672 defer r.Close()
2673 if err := st.ReaderCheck(r); err != nil {
2674 t.Error(err)
2675 }
2676
2677 // Verify ListObject.As for the directory.
2678 iter := b.List(&blob.ListOptions{Prefix: dir, Delimiter: "/", BeforeList: st.BeforeList})
2679 found := false
2680 for {
2681 obj, err := iter.Next(ctx)
2682 if err == io.EOF {
2683 break
2684 }
2685 if found {
2686 t.Fatal("got a second object returned from List, only wanted one")
2687 }
2688 found = true
2689 if err != nil {
2690 log.Fatal(err)
2691 }
2692 if err := st.ListObjectCheck(obj); err != nil {
2693 t.Error(err)
2694 }
2695 }
2696
2697 // Verify ListObject.As for the blob.
2698 iter = b.List(&blob.ListOptions{Prefix: key, BeforeList: st.BeforeList})
2699 found = false
2700 for {
2701 obj, err := iter.Next(ctx)
2702 if err == io.EOF {
2703 break
2704 }
2705 if found {
2706 t.Fatal("got a second object returned from List, only wanted one")
2707 }
2708 found = true
2709 if err != nil {
2710 log.Fatal(err)
2711 }
2712 if err := st.ListObjectCheck(obj); err != nil {
2713 t.Error(err)
2714 }
2715 }
2716
2717 _, gotErr := b.NewReader(ctx, "key-does-not-exist", nil)
2718 if gotErr == nil {
2719 t.Fatalf("got nil error from NewReader for nonexistent key, want an error")
2720 }
2721 if err := st.ErrorCheck(b, gotErr); err != nil {
2722 t.Error(err)
2723 }
2724
2725 // Copy the blob, using the provided callback.
2726 if err := b.Copy(ctx, copyKey, key, &blob.CopyOptions{BeforeCopy: st.BeforeCopy}); err != nil {
2727 t.Error(err)
2728 } else {
2729 defer func() { _ = b.Delete(ctx, copyKey) }()
2730 }
2731
2732 for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodDelete} {
2733 _, err = b.SignedURL(ctx, key, &blob.SignedURLOptions{Method: method, BeforeSign: st.BeforeSign})
2734 if err != nil && gcerrors.Code(err) != gcerrors.Unimplemented {
2735 t.Errorf("got err %v when signing url with method %q", err, method)
2736 }
2737 }
2738 }
2739
2740 func testIfNotExist(t *testing.T, newHarness HarnessMaker) {
2741 t.Helper()
2742
2743 const key = "blob-for-if-not-exist"
2744 const contents = "up and down"
2745
2746 ctx := context.Background()
2747 h, err := newHarness(ctx, t)
2748 if err != nil {
2749 t.Fatal(err)
2750 }
2751 defer h.Close()
2752 drv, err := h.MakeDriver(ctx)
2753 if err != nil {
2754 t.Fatal(err)
2755 }
2756 b := blob.NewBucket(drv)
2757 defer func() { _ = b.Close() }()
2758
2759 opts := blob.WriterOptions{
2760 ContentType: "text",
2761 IfNotExist: true,
2762 }
2763
2764 // Create the new blob; expected to work since it doesn't exist.
2765 w1, err := b.NewWriter(ctx, key, &opts)
2766 if err != nil {
2767 t.Fatal(err)
2768 }
2769 defer func() {
2770 _ = b.Delete(ctx, key)
2771 }()
2772 if _, err := w1.Write([]byte(contents)); err != nil {
2773 t.Fatal(err)
2774 }
2775 if err := w1.Close(); err != nil {
2776 t.Fatal(err)
2777 }
2778
2779 // Attempt a second write to the same key; expected to fail in
2780 // either Write or Close, with FailedPrecondition.
2781 w2, err := b.NewWriter(ctx, key, &opts)
2782 if err != nil {
2783 t.Fatal(err)
2784 }
2785 if _, err = w2.Write([]byte(contents)); err == nil {
2786 err = w2.Close()
2787 } else {
2788 _ = w2.Close()
2789 }
2790 if err == nil {
2791 t.Error("expected error rewriting key with IfNotExist, got nil")
2792 }
2793 if code := gcerrors.Code(err); code != gcerrors.FailedPrecondition {
2794 t.Errorf("expected FailedPrecondition error, got %v", code)
2795 }
2796 }
2797
2798 func benchmarkRead(b *testing.B, bkt *blob.Bucket) {
2799 b.Helper()
2800
2801 ctx := context.Background()
2802 const key = "readbenchmark-blob"
2803
2804 content := loadTestData(b, "test-large.jpg")
2805 if err := bkt.WriteAll(ctx, key, content, nil); err != nil {
2806 b.Fatal(err)
2807 }
2808 defer func() {
2809 _ = bkt.Delete(ctx, key)
2810 }()
2811
2812 b.ResetTimer()
2813 b.RunParallel(func(pb *testing.PB) {
2814 var buffer bytes.Buffer
2815 buffer.Grow(len(content))
2816
2817 for pb.Next() {
2818 buffer.Reset()
2819 r, err := bkt.NewReader(ctx, key, nil)
2820 if err != nil {
2821 b.Error(err)
2822 }
2823
2824 if _, err = io.Copy(&buffer, r); err != nil {
2825 b.Error(err)
2826 }
2827 r.Close()
2828 if !bytes.Equal(buffer.Bytes(), content) {
2829 b.Error("read didn't match write")
2830 }
2831 }
2832 })
2833 }
2834
2835 func benchmarkWriteReadDelete(b *testing.B, bkt *blob.Bucket) {
2836 b.Helper()
2837
2838 ctx := context.Background()
2839 const baseKey = "writereaddeletebenchmark-blob-"
2840
2841 content := loadTestData(b, "test-large.jpg")
2842 var nextID uint32
2843
2844 b.ResetTimer()
2845 b.RunParallel(func(pb *testing.PB) {
2846 key := fmt.Sprintf("%s%d", baseKey, atomic.AddUint32(&nextID, 1))
2847 for pb.Next() {
2848 if err := bkt.WriteAll(ctx, key, content, nil); err != nil {
2849 b.Error(err)
2850 continue
2851 }
2852 buf, err := bkt.ReadAll(ctx, key)
2853 if err != nil {
2854 b.Error(err)
2855 }
2856 if !bytes.Equal(buf, content) {
2857 b.Error("read didn't match write")
2858 }
2859 if err := bkt.Delete(ctx, key); err != nil {
2860 b.Error(err)
2861 continue
2862 }
2863 }
2864 })
2865 }