forked from GoogleCloudPlatform/gcsfuse
/
bucket_tests.go
4460 lines (3642 loc) · 105 KB
/
bucket_tests.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 2023 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Tests registered by RegisterBucketTests.
package testing
import (
"context"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"hash/crc32"
"io"
"log"
"math"
"sort"
"strings"
"testing/iotest"
"time"
"unicode"
"github.com/Tulsishah/gcsfuse-tulsishah7/internal/storage/gcs"
"github.com/Tulsishah/gcsfuse-tulsishah7/internal/storage/storageutil"
. "github.com/jacobsa/oglematchers"
. "github.com/jacobsa/ogletest"
"github.com/jacobsa/syncutil"
"github.com/jacobsa/timeutil"
"golang.org/x/sys/unix"
)
////////////////////////////////////////////////////////////////////////
// Initialization
////////////////////////////////////////////////////////////////////////
// Make sure we can use a decent degree of parallelism when talking to GCS
// without getting "too many open files" errors, especially on OS X where the
// default rlimit is very low (256 as of 10.10.3).
func init() {
var rlim unix.Rlimit
var err error
err = unix.Getrlimit(unix.RLIMIT_NOFILE, &rlim)
if err != nil {
panic(err)
}
before := rlim.Cur
rlim.Cur = rlim.Max
err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlim)
if err != nil {
panic(err)
}
log.Printf("Raised RLIMIT_NOFILE from %d to %d.", before, rlim.Cur)
}
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
func createEmpty(
ctx context.Context,
bucket gcs.Bucket,
objectNames []string) error {
err := storageutil.CreateEmptyObjects(ctx, bucket, objectNames)
return err
}
func computeCrc32C(s string) uint32 {
return crc32.Checksum([]byte(s), crc32.MakeTable(crc32.Castagnoli))
}
func makeStringPtr(s string) *string {
return &s
}
// Return a list of object names that might be problematic for GCS or the Go
// client but are nevertheless documented to be legal.
//
// Useful links:
//
// https://cloud.google.com/storage/docs/bucket-naming
// http://www.unicode.org/Public/7.0.0/ucd/UnicodeData.txt
// http://www.unicode.org/versions/Unicode7.0.0/ch02.pdf (Table 2-3)
func interestingNames() (names []string) {
const maxLegalLength = 1024
names = []string{
// Characters specifically mentioned by RFC 3986, i.e. that might be
// important in URL encoding/decoding.
"foo : bar",
"foo / bar",
"foo ? bar",
"foo # bar",
"foo [ bar",
"foo ] bar",
"foo @ bar",
"foo ! bar",
"foo $ bar",
"foo & bar",
"foo ' bar",
"foo ( bar",
"foo ) bar",
"foo * bar",
"foo + bar",
"foo , bar",
"foo ; bar",
"foo = bar",
"foo - bar",
"foo . bar",
"foo _ bar",
"foo ~ bar",
// Other tricky URL cases.
"foo () bar",
"foo [] bar",
"foo // bar",
"foo %?/ bar",
"foo http://google.com/search?q=foo&bar=baz#qux bar",
"foo ?bar",
"foo? bar",
"foo/ bar",
"foo /bar",
// Non-Roman scripts
"타코",
"世界",
// Longest legal name
strings.Repeat("a", maxLegalLength),
// Null byte.
"foo \u0000 bar",
// Non-control characters that are discouraged, but not forbidden,
// according to the documentation.
"foo # bar",
"foo []*? bar",
// Angstrom symbol singleton and normalized forms.
// Cf. http://unicode.org/reports/tr15/
"foo \u212b bar",
"foo \u0041\u030a bar",
"foo \u00c5 bar",
// Hangul separating jamo
// Cf. http://www.unicode.org/versions/Unicode7.0.0/ch18.pdf (Table 18-10)
"foo \u3131\u314f bar",
"foo \u1100\u1161 bar",
"foo \uac00 bar",
// Unicode specials
// Cf. http://en.wikipedia.org/wiki/Specials_%28Unicode_block%29
"foo \ufff9 bar",
"foo \ufffa bar",
"foo \ufffb bar",
"foo \ufffc bar",
"foo \ufffd bar",
}
// All codepoints in Unicode general categories C* (control and special) and
// Z* (space), except for:
//
// * Cn (non-character and reserved), which is not included in unicode.C.
// * Co (private usage), which is large.
// * Cs (surrages), which is large.
// * U+000A and U+000D, which are forbidden by the docs.
//
for r := rune(0); r <= unicode.MaxRune; r++ {
if !unicode.In(r, unicode.C) && !unicode.In(r, unicode.Z) {
continue
}
if unicode.In(r, unicode.Co) {
continue
}
if unicode.In(r, unicode.Cs) {
continue
}
if r == 0x0a || r == 0x0d {
continue
}
names = append(names, fmt.Sprintf("foo %s bar", string(r)))
}
return
}
// Return a list of object names that are illegal in GCS.
// Cf. https://cloud.google.com/storage/docs/bucket-naming
func illegalNames() (names []string) {
const maxLegalLength = 1024
names = []string{
// Empty and too long
"",
strings.Repeat("a", maxLegalLength+1),
// Not valid UTF-8
"foo\xff",
// Carriage return and line feed
"foo\u000abar",
"foo\u000dbar",
}
return
}
// Given lists of strings A and B, return those values that are in A but not in
// B. If A contains duplicates of a value V not in B, the only guarantee is
// that V is returned at least once.
func listDifference(a []string, b []string) (res []string) {
// This is slow, but more obviously correct than the fast algorithm.
m := make(map[string]struct{})
for _, s := range b {
m[s] = struct{}{}
}
for _, s := range a {
if _, ok := m[s]; !ok {
res = append(res, s)
}
}
return
}
// Issue all of the supplied read requests with some degree of parallelism.
func readMultiple(
ctx context.Context,
bucket gcs.Bucket,
reqs []*gcs.ReadObjectRequest) (contents [][]byte, errs []error) {
b := syncutil.NewBundle(ctx)
// Feed indices into a channel.
indices := make(chan int, len(reqs))
for i := range reqs {
indices <- i
}
close(indices)
// Set up a function that deals with one request.
contents = make([][]byte, len(reqs))
errs = make([]error, len(reqs))
handleRequest := func(ctx context.Context, i int) {
var b []byte
var err error
defer func() {
contents[i] = b
errs[i] = err
}()
// Open a reader.
rc, err := bucket.NewReader(ctx, reqs[i])
if err != nil {
err = fmt.Errorf("NewReader: %v", err)
return
}
// Read from it.
b, err = io.ReadAll(rc)
if err != nil {
err = fmt.Errorf("ReadAll: %v", err)
return
}
// Close it.
err = rc.Close()
if err != nil {
err = fmt.Errorf("Close: %v", err)
return
}
}
// Run several workers.
const parallelsim = 32
for i := 0; i < parallelsim; i++ {
b.Add(func(ctx context.Context) (err error) {
for i := range indices {
handleRequest(ctx, i)
}
return
})
}
AssertEq(nil, b.Join())
return
}
// Invoke the supplied function for each string, with some degree of
// parallelism.
func forEachString(
ctx context.Context,
strings []string,
f func(context.Context, string) error) (err error) {
b := syncutil.NewBundle(ctx)
// Feed strings into a channel.
c := make(chan string, len(strings))
for _, s := range strings {
c <- s
}
close(c)
// Consume the strings.
const parallelism = 128
for i := 0; i < parallelism; i++ {
b.Add(func(ctx context.Context) (err error) {
for s := range c {
err = f(ctx, s)
if err != nil {
return
}
}
return
})
}
err = b.Join()
return
}
////////////////////////////////////////////////////////////////////////
// Common
////////////////////////////////////////////////////////////////////////
type bucketTest struct {
ctx context.Context
bucket gcs.Bucket
clock timeutil.Clock
supportsCancellation bool
buffersEntireContentsForCreate bool
}
var _ bucketTestSetUpInterface = &bucketTest{}
func (t *bucketTest) setUpBucketTest(deps BucketTestDeps) {
t.ctx = deps.ctx
t.bucket = deps.Bucket
t.clock = deps.Clock
t.supportsCancellation = deps.SupportsCancellation
t.buffersEntireContentsForCreate = deps.BuffersEntireContentsForCreate
}
func (t *bucketTest) createObject(name string, contents string) error {
_, err := storageutil.CreateObject(
t.ctx,
t.bucket,
name,
[]byte(contents))
return err
}
func (t *bucketTest) readObject(objectName string) (contents string, err error) {
// Open a reader.
req := &gcs.ReadObjectRequest{
Name: objectName,
}
reader, err := t.bucket.NewReader(t.ctx, req)
if err != nil {
return
}
defer func() {
AssertEq(nil, reader.Close())
}()
// Read the contents of the object.
slice, err := io.ReadAll(reader)
if err != nil {
return
}
// Transform to a string.
contents = string(slice)
return
}
// Ensure that the clock will report a different time after returning.
func (t *bucketTest) advanceTime() {
// For simulated clocks, we can just advance the time.
if c, ok := t.clock.(*timeutil.SimulatedClock); ok {
c.AdvanceTime(time.Second)
return
}
// Otherwise, sleep a moment.
time.Sleep(time.Millisecond)
}
// Return a matcher that matches event times as reported by the bucket
// corresponding to the supplied start time as measured by the test.
func (t *bucketTest) matchesStartTime(start time.Time) Matcher {
// For simulated clocks we can use exact equality.
if _, ok := t.clock.(*timeutil.SimulatedClock); ok {
return timeutil.TimeEq(start)
}
// Otherwise, we need to take into account latency between the start of our
// call and the time the server actually executed the operation.
const slop = 60 * time.Second
return timeutil.TimeNear(start, slop)
}
////////////////////////////////////////////////////////////////////////
// Create
////////////////////////////////////////////////////////////////////////
type createTest struct {
bucketTest
}
func (t *createTest) EmptyObject() {
// Create the object.
AssertEq(nil, t.createObject("foo", ""))
// Ensure it shows up in a listing.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
AssertEq(1, len(listing.Objects))
o := listing.Objects[0]
AssertEq("foo", o.Name)
ExpectEq(0, o.Size)
}
func (t *createTest) NonEmptyObject() {
// Create the object.
AssertEq(nil, t.createObject("foo", "taco"))
// Ensure it shows up in a listing.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
AssertEq(1, len(listing.Objects))
o := listing.Objects[0]
AssertEq("foo", o.Name)
ExpectEq(len("taco"), o.Size)
}
func (t *createTest) Overwrite() {
var err error
// Create a first version of an object, with some custom metadata.
_, err = t.bucket.CreateObject(
t.ctx,
&gcs.CreateObjectRequest{
Name: "foo",
Metadata: map[string]string{
"foo": "bar",
},
Contents: strings.NewReader("taco"),
})
AssertEq(nil, err)
// Overwrite it with another version.
_, err = t.bucket.CreateObject(
t.ctx,
&gcs.CreateObjectRequest{
Name: "foo",
Contents: strings.NewReader("burrito"),
})
AssertEq(nil, err)
// The second version should show up in a listing.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
AssertEq(1, len(listing.Objects))
o := listing.Objects[0]
AssertEq("foo", o.Name)
ExpectEq(len("burrito"), o.Size)
ExpectEq(0, len(o.Metadata))
// The second version should be what we get when we read the object.
contents, err := t.readObject("foo")
AssertEq(nil, err)
ExpectEq("burrito", contents)
}
func (t *createTest) ObjectAttributes_Default() {
// Create an object with default attributes aside from the name.
createTime := t.clock.Now()
o, err := storageutil.CreateObject(t.ctx, t.bucket, "foo", []byte("taco"))
AssertEq(nil, err)
// Ensure the time below doesn't match exactly.
t.advanceTime()
// Check the Object struct.
ExpectEq("foo", o.Name)
ExpectEq("", o.ContentType)
ExpectEq("", o.ContentLanguage)
ExpectEq("", o.CacheControl)
ExpectThat(o.Owner, MatchesRegexp("^user-.*"))
ExpectEq(len("taco"), o.Size)
ExpectEq("", o.ContentEncoding)
ExpectEq(1, o.ComponentCount)
ExpectThat(o.MD5, Pointee(DeepEquals(md5.Sum([]byte("taco")))))
ExpectEq(computeCrc32C("taco"), *o.CRC32C)
ExpectThat(o.MediaLink, MatchesRegexp("download/storage.*foo"))
ExpectEq(nil, o.Metadata)
ExpectLt(0, o.Generation)
ExpectEq(1, o.MetaGeneration)
ExpectEq("STANDARD", o.StorageClass)
ExpectThat(o.Deleted, timeutil.TimeEq(time.Time{}))
ExpectThat(o.Updated, t.matchesStartTime(createTime))
// Make sure it matches what is in a listing.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
AssertEq(1, len(listing.Objects))
ExpectThat(listing.Objects[0], DeepEquals(o))
}
func (t *createTest) ObjectAttributes_Explicit() {
// Create an object with explicit attributes set.
createTime := t.clock.Now()
req := &gcs.CreateObjectRequest{
Name: "foo",
ContentType: "image/png",
ContentLanguage: "fr",
ContentEncoding: "gzip",
CacheControl: "public",
Metadata: map[string]string{
"foo": "bar",
"baz": "qux",
},
Contents: strings.NewReader("taco"),
}
o, err := t.bucket.CreateObject(t.ctx, req)
AssertEq(nil, err)
// Ensure the time below doesn't match exactly.
t.advanceTime()
// Check the Object struct.
ExpectEq("foo", o.Name)
ExpectEq("image/png", o.ContentType)
ExpectEq("fr", o.ContentLanguage)
ExpectEq("public", o.CacheControl)
ExpectThat(o.Owner, MatchesRegexp("^user-.*"))
ExpectEq(len("taco"), o.Size)
ExpectEq("gzip", o.ContentEncoding)
ExpectEq(1, o.ComponentCount)
ExpectThat(o.MD5, Pointee(DeepEquals(md5.Sum([]byte("taco")))))
ExpectEq(computeCrc32C("taco"), *o.CRC32C)
ExpectThat(o.MediaLink, MatchesRegexp("download/storage.*foo"))
ExpectThat(o.Metadata, DeepEquals(req.Metadata))
ExpectLt(0, o.Generation)
ExpectEq(1, o.MetaGeneration)
ExpectEq("STANDARD", o.StorageClass)
ExpectThat(o.Deleted, DeepEquals(time.Time{}))
ExpectThat(o.Deleted, timeutil.TimeEq(time.Time{}))
ExpectThat(o.Updated, t.matchesStartTime(createTime))
// Make sure it matches what is in a listing.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
AssertEq(1, len(listing.Objects))
ExpectThat(listing.Objects[0], DeepEquals(o))
}
func (t *createTest) ErrorAfterPartialContents() {
const contents = "tacoburritoenchilada"
// Set up a reader that will return some successful data, then an error.
req := &gcs.CreateObjectRequest{
Name: "foo",
Contents: iotest.TimeoutReader(
iotest.OneByteReader(
strings.NewReader(contents))),
}
// An attempt to create the object should fail.
_, err := t.bucket.CreateObject(t.ctx, req)
AssertNe(nil, err)
ExpectThat(err, Error(HasSubstr("timeout")))
// The object should not show up in a listing.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
ExpectThat(listing.Objects, ElementsAre())
}
func (t *createTest) InterestingNames() {
var err error
// Grab a list of interesting legal names.
names := interestingNames()
// Make sure we can create each name.
err = forEachString(
t.ctx,
names,
func(ctx context.Context, name string) (err error) {
err = t.createObject(name, name)
if err != nil {
err = fmt.Errorf("Failed to create %q: %v", name, err)
return
}
return
})
AssertEq(nil, err)
// Make sure we can read each, and that we get back the content we created
// above.
err = forEachString(
t.ctx,
names,
func(ctx context.Context, name string) (err error) {
contents, err := t.readObject(name)
if err != nil {
err = fmt.Errorf("Failed to read %q: %v", name, err)
return
}
if contents != name {
err = fmt.Errorf(
"Incorrect contents for %q: %q",
name,
contents)
return
}
return
})
AssertEq(nil, err)
// Grab a listing and extract the names.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
var listingNames []string
for _, o := range listing.Objects {
listingNames = append(listingNames, o.Name)
}
// The names should have come back sorted by their UTF-8 encodings.
AssertTrue(sort.IsSorted(sort.StringSlice(listingNames)))
// Make sure all and only the expected names exist.
if diff := listDifference(listingNames, names); len(diff) != 0 {
var dumps []string
for _, n := range diff {
dumps = append(dumps, hex.Dump([]byte(n)))
}
AddFailure(
"Unexpected names in listing:\n%s",
strings.Join(dumps, "\n"))
}
if diff := listDifference(names, listingNames); len(diff) != 0 {
var dumps []string
for _, n := range diff {
dumps = append(dumps, hex.Dump([]byte(n)))
}
AddFailure(
"Names missing from listing:\n%s",
strings.Join(dumps, "\n"))
}
}
func (t *createTest) IllegalNames() {
var err error
// Make sure we cannot create any of the names above.
err = forEachString(
t.ctx,
illegalNames(),
func(ctx context.Context, name string) (err error) {
err = t.createObject(name, "")
if err == nil {
err = fmt.Errorf("Expected to not be able to create %q", name)
return
}
if name == "" {
if !strings.Contains(err.Error(), "Invalid") &&
!strings.Contains(err.Error(), "Required") {
err = fmt.Errorf("Unexpected error for %q: %v", name, err)
return
}
} else {
if !strings.Contains(err.Error(), "Invalid") {
err = fmt.Errorf("Unexpected error for %q: %v", name, err)
return
}
}
err = nil
return
})
AssertEq(nil, err)
// No objects should have been created.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
ExpectThat(listing.Objects, ElementsAre())
}
func (t *createTest) IncorrectCRC32C() {
const name = "foo"
const contents = "taco"
var err error
// Attempt to create with the wrong checksum.
crc32c := storageutil.CRC32C([]byte(contents))
*crc32c++
req := &gcs.CreateObjectRequest{
Name: name,
Contents: strings.NewReader(contents),
CRC32C: crc32c,
}
_, err = t.bucket.CreateObject(t.ctx, req)
AssertThat(err, Error(HasSubstr("CRC32C")))
AssertThat(err, Error(HasSubstr("match")))
// It should not have been created.
statReq := &gcs.StatObjectRequest{
Name: name,
}
_, _, err = t.bucket.StatObject(t.ctx, statReq)
ExpectThat(err, HasSameTypeAs(&gcs.NotFoundError{}))
}
func (t *createTest) CorrectCRC32C() {
const name = "foo"
const contents = "taco"
var err error
// Create
req := &gcs.CreateObjectRequest{
Name: name,
Contents: strings.NewReader(contents),
CRC32C: storageutil.CRC32C([]byte(contents)),
}
o, err := t.bucket.CreateObject(t.ctx, req)
AssertEq(nil, err)
ExpectEq(len(contents), o.Size)
}
func (t *createTest) IncorrectMD5() {
const name = "foo"
const contents = "taco"
var err error
// Attempt to create with the wrong checksum.
md5 := storageutil.MD5([]byte(contents))
(*md5)[13]++
req := &gcs.CreateObjectRequest{
Name: name,
Contents: strings.NewReader(contents),
MD5: md5,
}
_, err = t.bucket.CreateObject(t.ctx, req)
AssertThat(err, Error(HasSubstr("MD5")))
AssertThat(err, Error(HasSubstr("match")))
// It should not have been created.
statReq := &gcs.StatObjectRequest{
Name: name,
}
_, _, err = t.bucket.StatObject(t.ctx, statReq)
ExpectThat(err, HasSameTypeAs(&gcs.NotFoundError{}))
}
func (t *createTest) CorrectMD5() {
const name = "foo"
const contents = "taco"
var err error
// Create
req := &gcs.CreateObjectRequest{
Name: name,
Contents: strings.NewReader(contents),
MD5: storageutil.MD5([]byte(contents)),
}
o, err := t.bucket.CreateObject(t.ctx, req)
AssertEq(nil, err)
ExpectEq(len(contents), o.Size)
}
func (t *createTest) CorrectCRC32CAndMD5() {
const name = "foo"
const contents = "taco"
var err error
// Create
req := &gcs.CreateObjectRequest{
Name: name,
Contents: strings.NewReader(contents),
CRC32C: storageutil.CRC32C([]byte(contents)),
MD5: storageutil.MD5([]byte(contents)),
}
o, err := t.bucket.CreateObject(t.ctx, req)
AssertEq(nil, err)
ExpectEq(len(contents), o.Size)
}
func (t *createTest) GenerationPrecondition_Zero_Unsatisfied() {
// Create an existing object.
o, err := storageutil.CreateObject(
t.ctx,
t.bucket,
"foo",
[]byte("taco"))
AssertEq(nil, err)
// Request to create another version of the object, with a precondition
// saying it shouldn't exist. The request should fail.
var gen int64 = 0
req := &gcs.CreateObjectRequest{
Name: "foo",
Contents: strings.NewReader("burrito"),
GenerationPrecondition: &gen,
}
_, err = t.bucket.CreateObject(t.ctx, req)
AssertThat(err, HasSameTypeAs(&gcs.PreconditionError{}))
ExpectThat(err, Error(MatchesRegexp("object exists|googleapi.*412")))
// The old version should show up in a listing.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
AssertEq(1, len(listing.Objects))
AssertEq("foo", listing.Objects[0].Name)
ExpectEq(o.Generation, listing.Objects[0].Generation)
ExpectEq(len("taco"), listing.Objects[0].Size)
// We should see the old contents when we read.
contents, err := t.readObject("foo")
AssertEq(nil, err)
ExpectEq("taco", string(contents))
}
func (t *createTest) GenerationPrecondition_Zero_Satisfied() {
// Request to create an object with a precondition saying it shouldn't exist.
// The request should succeed.
var gen int64 = 0
req := &gcs.CreateObjectRequest{
Name: "foo",
Contents: strings.NewReader("burrito"),
GenerationPrecondition: &gen,
}
o, err := t.bucket.CreateObject(t.ctx, req)
AssertEq(nil, err)
ExpectEq(len("burrito"), o.Size)
ExpectNe(0, o.Generation)
// The object should show up in a listing.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
AssertEq(1, len(listing.Objects))
AssertEq("foo", listing.Objects[0].Name)
ExpectEq(o.Generation, listing.Objects[0].Generation)
ExpectEq(len("burrito"), listing.Objects[0].Size)
// We should see the new contents when we read.
contents, err := t.readObject("foo")
AssertEq(nil, err)
ExpectEq("burrito", string(contents))
}
func (t *createTest) GenerationPrecondition_NonZero_Unsatisfied_Missing() {
// Request to create a non-existent object with a precondition saying it
// should already exist with some generation number. The request should fail.
var gen int64 = 17
req := &gcs.CreateObjectRequest{
Name: "foo",
Contents: strings.NewReader("burrito"),
GenerationPrecondition: &gen,
}
_, err := t.bucket.CreateObject(t.ctx, req)
AssertThat(err, HasSameTypeAs(&gcs.PreconditionError{}))
ExpectThat(err, Error(MatchesRegexp("object doesn't exist|googleapi.*412")))
// Nothing should show up in a listing.
listing, err := t.bucket.ListObjects(t.ctx, &gcs.ListObjectsRequest{})
AssertEq(nil, err)
AssertThat(listing.CollapsedRuns, ElementsAre())
AssertEq("", listing.ContinuationToken)
ExpectEq(0, len(listing.Objects))
}
func (t *createTest) GenerationPrecondition_NonZero_Unsatisfied_Present() {
// Create an existing object.
o, err := storageutil.CreateObject(
t.ctx,
t.bucket,
"foo",
[]byte("taco"))
AssertEq(nil, err)
// Request to create another version of the object, with a precondition for
// the wrong generation. The request should fail.
var gen int64 = o.Generation + 1
req := &gcs.CreateObjectRequest{
Name: "foo",
Contents: strings.NewReader("burrito"),
GenerationPrecondition: &gen,
}
_, err = t.bucket.CreateObject(t.ctx, req)
AssertThat(err, HasSameTypeAs(&gcs.PreconditionError{}))
ExpectThat(err, Error(MatchesRegexp("generation|googleapi.*412")))
// The old version should show up in a listing.