/
integration_test.go
3788 lines (3462 loc) · 111 KB
/
integration_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
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 2014 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package storage
import (
"bytes"
"compress/gzip"
"context"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"log"
"math/rand"
"mime/multipart"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"testing"
"time"
"cloud.google.com/go/httpreplay"
"cloud.google.com/go/iam"
"cloud.google.com/go/internal/testutil"
"cloud.google.com/go/internal/uid"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"golang.org/x/oauth2/google"
"google.golang.org/api/googleapi"
"google.golang.org/api/iterator"
itesting "google.golang.org/api/iterator/testing"
"google.golang.org/api/option"
)
const (
testPrefix = "go-integration-test"
replayFilename = "storage.replay"
// TODO(jba): move to testutil, factor out from firestore/integration_test.go.
envFirestoreProjID = "GCLOUD_TESTS_GOLANG_FIRESTORE_PROJECT_ID"
envFirestorePrivateKey = "GCLOUD_TESTS_GOLANG_FIRESTORE_KEY"
)
var (
record = flag.Bool("record", false, "record RPCs")
uidSpace *uid.Space
bucketName string
// Use our own random number generator to isolate the sequence of random numbers from
// other packages. This makes it possible to use HTTP replay and draw the same sequence
// of numbers as during recording.
rng *rand.Rand
newTestClient func(ctx context.Context, opts ...option.ClientOption) (*Client, error)
replaying bool
testTime time.Time
)
func TestMain(m *testing.M) {
cleanup := initIntegrationTest()
exit := m.Run()
if err := cleanup(); err != nil {
// Don't fail the test if cleanup fails.
log.Printf("Post-test cleanup failed: %v", err)
}
os.Exit(exit)
}
// If integration tests will be run, create a unique bucket for them.
// Also, set newTestClient to handle record/replay.
// Return a cleanup function.
func initIntegrationTest() func() error {
flag.Parse() // needed for testing.Short()
switch {
case testing.Short() && *record:
log.Fatal("cannot combine -short and -record")
return nil
case testing.Short() && httpreplay.Supported() && testutil.CanReplay(replayFilename) && testutil.ProjID() != "":
// go test -short with a replay file will replay the integration tests, if
// the appropriate environment variables have been set.
replaying = true
httpreplay.DebugHeaders()
replayer, err := httpreplay.NewReplayer(replayFilename)
if err != nil {
log.Fatal(err)
}
var t time.Time
if err := json.Unmarshal(replayer.Initial(), &t); err != nil {
log.Fatal(err)
}
initUIDsAndRand(t)
newTestClient = func(ctx context.Context, _ ...option.ClientOption) (*Client, error) {
hc, err := replayer.Client(ctx) // no creds needed
if err != nil {
return nil, err
}
return NewClient(ctx, option.WithHTTPClient(hc))
}
log.Printf("replaying from %s", replayFilename)
return func() error { return replayer.Close() }
case testing.Short():
// go test -short without a replay file skips the integration tests.
if testutil.CanReplay(replayFilename) && testutil.ProjID() != "" {
log.Print("replay not supported for Go versions before 1.8")
}
newTestClient = nil
return func() error { return nil }
default: // Run integration tests against a real backend.
now := time.Now().UTC()
initUIDsAndRand(now)
var cleanup func() error
if *record && httpreplay.Supported() {
// Remember the time for replay.
nowBytes, err := json.Marshal(now)
if err != nil {
log.Fatal(err)
}
recorder, err := httpreplay.NewRecorder(replayFilename, nowBytes)
if err != nil {
log.Fatalf("could not record: %v", err)
}
newTestClient = func(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
hc, err := recorder.Client(ctx, opts...)
if err != nil {
return nil, err
}
return NewClient(ctx, option.WithHTTPClient(hc))
}
cleanup = func() error {
err1 := cleanupBuckets()
err2 := recorder.Close()
if err1 != nil {
return err1
}
return err2
}
log.Printf("recording to %s", replayFilename)
} else {
if *record {
log.Print("record not supported for Go versions before 1.8")
}
newTestClient = NewClient
cleanup = cleanupBuckets
}
ctx := context.Background()
client := config(ctx)
if client == nil {
return func() error { return nil }
}
defer client.Close()
if err := client.Bucket(bucketName).Create(ctx, testutil.ProjID(), nil); err != nil {
log.Fatalf("creating bucket %q: %v", bucketName, err)
}
return cleanup
}
}
func initUIDsAndRand(t time.Time) {
uidSpace = uid.NewSpace(testPrefix, &uid.Options{Time: t})
bucketName = uidSpace.New()
// Use our own random source, to avoid other parts of the program taking
// random numbers from the global source and putting record and replay
// out of sync.
rng = testutil.NewRand(t)
testTime = t
}
// testConfig returns the Client used to access GCS. testConfig skips
// the current test if credentials are not available or when being run
// in Short mode.
func testConfig(ctx context.Context, t *testing.T) *Client {
if testing.Short() && !replaying {
t.Skip("Integration tests skipped in short mode")
}
client := config(ctx)
if client == nil {
t.Skip("Integration tests skipped. See CONTRIBUTING.md for details")
}
return client
}
// config is like testConfig, but it doesn't need a *testing.T.
func config(ctx context.Context) *Client {
ts := testutil.TokenSource(ctx, ScopeFullControl)
if ts == nil {
return nil
}
client, err := newTestClient(ctx, option.WithTokenSource(ts))
if err != nil {
log.Fatalf("NewClient: %v", err)
}
return client
}
func TestIntegration_BucketMethods(t *testing.T) {
ctx := context.Background()
client := testConfig(ctx, t)
defer client.Close()
h := testHelper{t}
projectID := testutil.ProjID()
newBucketName := uidSpace.New()
b := client.Bucket(newBucketName)
// Test Create and Delete.
h.mustCreate(b, projectID, nil)
attrs := h.mustBucketAttrs(b)
if got, want := attrs.MetaGeneration, int64(1); got != want {
t.Errorf("got metagen %d, want %d", got, want)
}
if got, want := attrs.StorageClass, "STANDARD"; got != want {
t.Errorf("got storage class %q, want %q", got, want)
}
if attrs.VersioningEnabled {
t.Error("got versioning enabled, wanted it disabled")
}
if attrs.LocationType == "" {
t.Error("got an empty LocationType")
}
h.mustDeleteBucket(b)
// Test Create and Delete with attributes.
labels := map[string]string{
"l1": "v1",
"empty": "",
}
attrs = &BucketAttrs{
StorageClass: "NEARLINE",
VersioningEnabled: true,
Labels: labels,
Lifecycle: Lifecycle{
Rules: []LifecycleRule{{
Action: LifecycleAction{
Type: SetStorageClassAction,
StorageClass: "NEARLINE",
},
Condition: LifecycleCondition{
AgeInDays: 10,
Liveness: Archived,
CreatedBefore: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
MatchesStorageClasses: []string{"STANDARD"},
NumNewerVersions: 3,
},
}, {
Action: LifecycleAction{
Type: SetStorageClassAction,
StorageClass: "ARCHIVE",
},
Condition: LifecycleCondition{
CustomTimeBefore: time.Date(2020, 1, 2, 3, 0, 0, 0, time.UTC),
DaysSinceCustomTime: 20,
Liveness: Live,
MatchesStorageClasses: []string{"STANDARD"},
},
}, {
Action: LifecycleAction{
Type: DeleteAction,
},
Condition: LifecycleCondition{
DaysSinceNoncurrentTime: 30,
Liveness: Live,
NoncurrentTimeBefore: time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC),
MatchesStorageClasses: []string{"NEARLINE"},
NumNewerVersions: 10,
},
}},
},
}
h.mustCreate(b, projectID, attrs)
attrs = h.mustBucketAttrs(b)
if got, want := attrs.MetaGeneration, int64(1); got != want {
t.Errorf("got metagen %d, want %d", got, want)
}
if got, want := attrs.StorageClass, "NEARLINE"; got != want {
t.Errorf("got storage class %q, want %q", got, want)
}
if !attrs.VersioningEnabled {
t.Error("got versioning disabled, wanted it enabled")
}
if got, want := attrs.Labels, labels; !testutil.Equal(got, want) {
t.Errorf("labels: got %v, want %v", got, want)
}
if attrs.LocationType == "" {
t.Error("got an empty LocationType")
}
h.mustDeleteBucket(b)
}
func TestIntegration_BucketUpdate(t *testing.T) {
ctx := context.Background()
client := testConfig(ctx, t)
defer client.Close()
h := testHelper{t}
b := client.Bucket(uidSpace.New())
h.mustCreate(b, testutil.ProjID(), nil)
defer h.mustDeleteBucket(b)
attrs := h.mustBucketAttrs(b)
if attrs.VersioningEnabled {
t.Fatal("bucket should not have versioning by default")
}
if len(attrs.Labels) > 0 {
t.Fatal("bucket should not have labels initially")
}
// Using empty BucketAttrsToUpdate should be a no-nop.
attrs = h.mustUpdateBucket(b, BucketAttrsToUpdate{})
if attrs.VersioningEnabled {
t.Fatal("should not have versioning")
}
if len(attrs.Labels) > 0 {
t.Fatal("should not have labels")
}
// Turn on versioning, add some labels.
ua := BucketAttrsToUpdate{VersioningEnabled: true}
ua.SetLabel("l1", "v1")
ua.SetLabel("empty", "")
attrs = h.mustUpdateBucket(b, ua)
if !attrs.VersioningEnabled {
t.Fatal("should have versioning now")
}
wantLabels := map[string]string{
"l1": "v1",
"empty": "",
}
if !testutil.Equal(attrs.Labels, wantLabels) {
t.Fatalf("got %v, want %v", attrs.Labels, wantLabels)
}
// Turn off versioning again; add and remove some more labels.
ua = BucketAttrsToUpdate{VersioningEnabled: false}
ua.SetLabel("l1", "v2") // update
ua.SetLabel("new", "new") // create
ua.DeleteLabel("empty") // delete
ua.DeleteLabel("absent") // delete non-existent
attrs = h.mustUpdateBucket(b, ua)
if attrs.VersioningEnabled {
t.Fatal("should have versioning off")
}
wantLabels = map[string]string{
"l1": "v2",
"new": "new",
}
if !testutil.Equal(attrs.Labels, wantLabels) {
t.Fatalf("got %v, want %v", attrs.Labels, wantLabels)
}
// Configure a lifecycle
wantLifecycle := Lifecycle{
Rules: []LifecycleRule{
{
Action: LifecycleAction{Type: "Delete"},
Condition: LifecycleCondition{AgeInDays: 30},
},
},
}
ua = BucketAttrsToUpdate{Lifecycle: &wantLifecycle}
attrs = h.mustUpdateBucket(b, ua)
if !testutil.Equal(attrs.Lifecycle, wantLifecycle) {
t.Fatalf("got %v, want %v", attrs.Lifecycle, wantLifecycle)
}
// Check that StorageClass has "STANDARD" value for unset field by default
// before passing new value.
wantStorageClass := "STANDARD"
if !testutil.Equal(attrs.StorageClass, wantStorageClass) {
t.Fatalf("got %v, want %v", attrs.StorageClass, wantStorageClass)
}
wantStorageClass = "NEARLINE"
ua = BucketAttrsToUpdate{StorageClass: wantStorageClass}
attrs = h.mustUpdateBucket(b, ua)
if !testutil.Equal(attrs.StorageClass, wantStorageClass) {
t.Fatalf("got %v, want %v", attrs.StorageClass, wantStorageClass)
}
}
func TestIntegration_BucketPolicyOnly(t *testing.T) {
ctx := context.Background()
client := testConfig(ctx, t)
defer client.Close()
h := testHelper{t}
bkt := client.Bucket(bucketName)
// Insert an object with custom ACL.
o := bkt.Object("bucketPolicyOnly")
defer func() {
if err := o.Delete(ctx); err != nil {
log.Printf("failed to delete test object: %v", err)
}
}()
wc := o.NewWriter(ctx)
wc.ContentType = "text/plain"
h.mustWrite(wc, []byte("test"))
a := o.ACL()
aclEntity := ACLEntity("user-test@example.com")
err := a.Set(ctx, aclEntity, RoleReader)
if err != nil {
t.Fatalf("set ACL failed: %v", err)
}
// Enable BucketPolicyOnly.
ua := BucketAttrsToUpdate{BucketPolicyOnly: &BucketPolicyOnly{Enabled: true}}
attrs := h.mustUpdateBucket(bkt, ua)
if got, want := attrs.BucketPolicyOnly.Enabled, true; got != want {
t.Fatalf("got %v, want %v", got, want)
}
if got := attrs.BucketPolicyOnly.LockedTime; got.IsZero() {
t.Fatal("got a zero time value, want a populated value")
}
// Confirm BucketAccessControl returns error.
err = retry(ctx, func() error {
_, err = bkt.ACL().List(ctx)
return nil
}, func() error {
if err == nil {
return fmt.Errorf("ACL.List: expected bucket ACL list to fail")
}
return nil
})
if err != nil {
t.Fatal(err)
}
// Confirm ObjectAccessControl returns error.
err = retry(ctx, func() error {
_, err = o.ACL().List(ctx)
return nil
}, func() error {
if err == nil {
return fmt.Errorf("ACL.List: expected object ACL list to fail")
}
return nil
})
if err != nil {
t.Fatal(err)
}
// Disable BucketPolicyOnly.
ua = BucketAttrsToUpdate{BucketPolicyOnly: &BucketPolicyOnly{Enabled: false}}
attrs = h.mustUpdateBucket(bkt, ua)
if got, want := attrs.BucketPolicyOnly.Enabled, false; got != want {
t.Fatalf("got %v, want %v", got, want)
}
// Check that the object ACLs are the same.
var acls []ACLRule
err = retry(ctx, func() error {
acls, err = o.ACL().List(ctx)
if err != nil {
return fmt.Errorf("ACL.List: object ACL list failed: %v", err)
}
return nil
}, func() error {
if !containsACL(acls, aclEntity, RoleReader) {
return fmt.Errorf("containsACL: expected ACLs %v to include custom ACL entity %v", acls, aclEntity)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
func TestIntegration_UniformBucketLevelAccess(t *testing.T) {
ctx := context.Background()
client := testConfig(ctx, t)
defer client.Close()
h := testHelper{t}
bkt := client.Bucket(uidSpace.New())
h.mustCreate(bkt, testutil.ProjID(), nil)
defer h.mustDeleteBucket(bkt)
// Insert an object with custom ACL.
o := bkt.Object("uniformBucketLevelAccess")
defer func() {
if err := o.Delete(ctx); err != nil {
log.Printf("failed to delete test object: %v", err)
}
}()
wc := o.NewWriter(ctx)
wc.ContentType = "text/plain"
h.mustWrite(wc, []byte("test"))
a := o.ACL()
aclEntity := ACLEntity("user-test@example.com")
err := a.Set(ctx, aclEntity, RoleReader)
if err != nil {
t.Fatalf("set ACL failed: %v", err)
}
// Enable UniformBucketLevelAccess.
ua := BucketAttrsToUpdate{UniformBucketLevelAccess: &UniformBucketLevelAccess{Enabled: true}}
attrs := h.mustUpdateBucket(bkt, ua)
if got, want := attrs.UniformBucketLevelAccess.Enabled, true; got != want {
t.Fatalf("got %v, want %v", got, want)
}
if got := attrs.UniformBucketLevelAccess.LockedTime; got.IsZero() {
t.Fatal("got a zero time value, want a populated value")
}
// Confirm BucketAccessControl returns error.
err = retry(ctx, func() error {
_, err = bkt.ACL().List(ctx)
return nil
}, func() error {
if err == nil {
return fmt.Errorf("ACL.List: expected bucket ACL list to fail")
}
return nil
})
if err != nil {
t.Fatal(err)
}
// Confirm ObjectAccessControl returns error.
err = retry(ctx, func() error {
_, err = o.ACL().List(ctx)
return nil
}, func() error {
if err == nil {
return fmt.Errorf("ACL.List: expected object ACL list to fail")
}
return nil
})
if err != nil {
t.Fatal(err)
}
// Disable UniformBucketLevelAccess.
ua = BucketAttrsToUpdate{UniformBucketLevelAccess: &UniformBucketLevelAccess{Enabled: false}}
attrs = h.mustUpdateBucket(bkt, ua)
if got, want := attrs.UniformBucketLevelAccess.Enabled, false; got != want {
t.Fatalf("got %v, want %v", got, want)
}
// Check that the object ACLs are the same.
var acls []ACLRule
err = retry(ctx, func() error {
acls, err = o.ACL().List(ctx)
if err != nil {
return fmt.Errorf("ACL.List: object ACL list failed: %v", err)
}
return nil
}, func() error {
if !containsACL(acls, aclEntity, RoleReader) {
return fmt.Errorf("containsACL: expected ACLs %v to include custom ACL entity %v", acls, aclEntity)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
func TestIntegration_ConditionalDelete(t *testing.T) {
ctx := context.Background()
client := testConfig(ctx, t)
defer client.Close()
h := testHelper{t}
o := client.Bucket(bucketName).Object("conddel")
wc := o.NewWriter(ctx)
wc.ContentType = "text/plain"
h.mustWrite(wc, []byte("foo"))
gen := wc.Attrs().Generation
metaGen := wc.Attrs().Metageneration
if err := o.Generation(gen - 1).Delete(ctx); err == nil {
t.Fatalf("Unexpected successful delete with Generation")
}
if err := o.If(Conditions{MetagenerationMatch: metaGen + 1}).Delete(ctx); err == nil {
t.Fatalf("Unexpected successful delete with IfMetaGenerationMatch")
}
if err := o.If(Conditions{MetagenerationNotMatch: metaGen}).Delete(ctx); err == nil {
t.Fatalf("Unexpected successful delete with IfMetaGenerationNotMatch")
}
if err := o.Generation(gen).Delete(ctx); err != nil {
t.Fatalf("final delete failed: %v", err)
}
}
func TestIntegration_ObjectsRangeReader(t *testing.T) {
ctx := context.Background()
client := testConfig(ctx, t)
defer client.Close()
bkt := client.Bucket(bucketName)
objName := uidSpace.New()
obj := bkt.Object(objName)
contents := []byte("Hello, world this is a range request")
if err := retry(ctx, func() error {
w := obj.NewWriter(ctx)
if _, err := w.Write(contents); err != nil {
return fmt.Errorf("Failed to write contents: %v", err)
}
if err := w.Close(); err != nil {
return fmt.Errorf("Failed to close writer: %v", err)
}
return nil
}, nil); err != nil {
t.Fatal(err)
}
last5s := []struct {
name string
start int64
length int64
}{
{name: "negative offset", start: -5, length: -1},
{name: "offset with specified length", start: int64(len(contents)) - 5, length: 5},
{name: "offset and read till end", start: int64(len(contents)) - 5, length: -1},
}
for _, last5 := range last5s {
t.Run(last5.name, func(t *testing.T) {
r, err := obj.NewRangeReader(ctx, last5.start, last5.length)
if err != nil {
t.Fatalf("Failed to make range read: %v", err)
}
defer r.Close()
if got, want := r.Attrs.StartOffset, int64(len(contents))-5; got != want {
t.Fatalf("StartOffset mismatch, got %d want %d", got, want)
}
nr, _ := io.Copy(ioutil.Discard, r)
if got, want := nr, int64(5); got != want {
t.Fatalf("Body length mismatch, got %d want %d", got, want)
}
})
}
}
func TestIntegration_Objects(t *testing.T) {
// TODO(jba): Use subtests (Go 1.7).
ctx := context.Background()
client := testConfig(ctx, t)
defer client.Close()
// Reset testTime, 'cause object last modification time should be within 5 min
// from test (test iteration if -count passed) start time.
testTime = time.Now().UTC()
newBucketName := uidSpace.New()
h := testHelper{t}
bkt := client.Bucket(newBucketName)
h.mustCreate(bkt, testutil.ProjID(), nil)
defer func() {
if err := killBucket(ctx, client, newBucketName); err != nil {
log.Printf("deleting %q: %v", newBucketName, err)
}
}()
const defaultType = "text/plain"
// Populate object names and make a map for their contents.
objects := []string{
"obj1",
"obj2",
"obj/with/slashes",
}
contents := make(map[string][]byte)
// Test Writer.
for _, obj := range objects {
c := randomContents()
if err := writeObject(ctx, bkt.Object(obj), defaultType, c); err != nil {
t.Errorf("Write for %v failed with %v", obj, err)
}
contents[obj] = c
}
testObjectIterator(t, bkt, objects)
testObjectsIterateSelectedAttrs(t, bkt, objects)
testObjectsIterateAllSelectedAttrs(t, bkt, objects)
testObjectIteratorWithOffset(t, bkt, objects)
t.Run("testObjectsIterateSelectedAttrsDelimiter", func(t *testing.T) {
query := &Query{Prefix: "", Delimiter: "/"}
if err := query.SetAttrSelection([]string{"Name"}); err != nil {
t.Fatalf("selecting query attrs: %v", err)
}
var gotNames []string
var gotPrefixes []string
it := bkt.Objects(context.Background(), query)
for {
attrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
t.Fatalf("iterator.Next: %v", err)
}
if attrs.Name != "" {
gotNames = append(gotNames, attrs.Name)
} else if attrs.Prefix != "" {
gotPrefixes = append(gotPrefixes, attrs.Prefix)
}
if attrs.Bucket != "" {
t.Errorf("Bucket field not selected, want empty, got = %v", attrs.Bucket)
}
}
sortedNames := []string{"obj1", "obj2"}
if !cmp.Equal(sortedNames, gotNames) {
t.Errorf("names = %v, want %v", gotNames, sortedNames)
}
sortedPrefixes := []string{"obj/"}
if !cmp.Equal(sortedPrefixes, gotPrefixes) {
t.Errorf("prefixes = %v, want %v", gotPrefixes, sortedPrefixes)
}
})
// Test Reader.
for _, obj := range objects {
rc, err := bkt.Object(obj).NewReader(ctx)
if err != nil {
t.Errorf("Can't create a reader for %v, errored with %v", obj, err)
continue
}
if !rc.checkCRC {
t.Errorf("%v: not checking CRC", obj)
}
slurp, err := ioutil.ReadAll(rc)
if err != nil {
t.Errorf("Can't ReadAll object %v, errored with %v", obj, err)
}
if got, want := slurp, contents[obj]; !bytes.Equal(got, want) {
t.Errorf("Contents (%q) = %q; want %q", obj, got, want)
}
if got, want := rc.Size(), len(contents[obj]); got != int64(want) {
t.Errorf("Size (%q) = %d; want %d", obj, got, want)
}
if got, want := rc.ContentType(), "text/plain"; got != want {
t.Errorf("ContentType (%q) = %q; want %q", obj, got, want)
}
if got, want := rc.CacheControl(), "public, max-age=60"; got != want {
t.Errorf("CacheControl (%q) = %q; want %q", obj, got, want)
}
// We just wrote these objects, so they should have a recent last-modified time.
lm, err := rc.LastModified()
// Accept a time within +/- of the test time, to account for natural
// variation and the fact that testTime is set at the start of the test run.
expectedVariance := 5 * time.Minute
if err != nil {
t.Errorf("LastModified (%q): got error %v", obj, err)
} else if lm.Before(testTime.Add(-expectedVariance)) || lm.After(testTime.Add(expectedVariance)) {
t.Errorf("LastModified (%q): got %s, which not the %v from now (%v)", obj, lm, expectedVariance, testTime)
}
rc.Close()
// Check early close.
buf := make([]byte, 1)
rc, err = bkt.Object(obj).NewReader(ctx)
if err != nil {
t.Fatalf("%v: %v", obj, err)
}
_, err = rc.Read(buf)
if err != nil {
t.Fatalf("%v: %v", obj, err)
}
if got, want := buf, contents[obj][:1]; !bytes.Equal(got, want) {
t.Errorf("Contents[0] (%q) = %q; want %q", obj, got, want)
}
if err := rc.Close(); err != nil {
t.Errorf("%v Close: %v", obj, err)
}
}
obj := objects[0]
objlen := int64(len(contents[obj]))
// Test Range Reader.
for i, r := range []struct {
offset, length, want int64
}{
{0, objlen, objlen},
{0, objlen / 2, objlen / 2},
{objlen / 2, objlen, objlen / 2},
{0, 0, 0},
{objlen / 2, 0, 0},
{objlen / 2, -1, objlen / 2},
{0, objlen * 2, objlen},
{-2, -1, 2},
{-objlen, -1, objlen},
{-(objlen / 2), -1, objlen / 2},
} {
rc, err := bkt.Object(obj).NewRangeReader(ctx, r.offset, r.length)
if err != nil {
t.Errorf("%+v: Can't create a range reader for %v, errored with %v", i, obj, err)
continue
}
if rc.Size() != objlen {
t.Errorf("%+v: Reader has a content-size of %d, want %d", i, rc.Size(), objlen)
}
if rc.Remain() != r.want {
t.Errorf("%+v: Reader's available bytes reported as %d, want %d", i, rc.Remain(), r.want)
}
slurp, err := ioutil.ReadAll(rc)
if err != nil {
t.Errorf("%+v: can't ReadAll object %v, errored with %v", r, obj, err)
continue
}
if len(slurp) != int(r.want) {
t.Errorf("%+v: RangeReader (%d, %d): Read %d bytes, wanted %d bytes", i, r.offset, r.length, len(slurp), r.want)
continue
}
switch {
case r.offset < 0: // The case of reading the last N bytes.
start := objlen + r.offset
if got, want := slurp, contents[obj][start:]; !bytes.Equal(got, want) {
t.Errorf("RangeReader (%d, %d) = %q; want %q", r.offset, r.length, got, want)
}
default:
if got, want := slurp, contents[obj][r.offset:r.offset+r.want]; !bytes.Equal(got, want) {
t.Errorf("RangeReader (%d, %d) = %q; want %q", r.offset, r.length, got, want)
}
}
rc.Close()
}
objName := objects[0]
// Test NewReader googleapi.Error.
// Since a 429 or 5xx is hard to cause, we trigger a 416.
realLen := len(contents[objName])
_, err := bkt.Object(objName).NewRangeReader(ctx, int64(realLen*2), 10)
if err, ok := err.(*googleapi.Error); !ok {
t.Error("NewRangeReader did not return a googleapi.Error")
} else {
if err.Code != 416 {
t.Errorf("Code = %d; want %d", err.Code, 416)
}
if len(err.Header) == 0 {
t.Error("Missing googleapi.Error.Header")
}
if len(err.Body) == 0 {
t.Error("Missing googleapi.Error.Body")
}
}
// Test StatObject.
o := h.mustObjectAttrs(bkt.Object(objName))
if got, want := o.Name, objName; got != want {
t.Errorf("Name (%v) = %q; want %q", objName, got, want)
}
if got, want := o.ContentType, defaultType; got != want {
t.Errorf("ContentType (%v) = %q; want %q", objName, got, want)
}
created := o.Created
// Check that the object is newer than its containing bucket.
bAttrs := h.mustBucketAttrs(bkt)
if o.Created.Before(bAttrs.Created) {
t.Errorf("Object %v is older than its containing bucket, %v", o, bAttrs)
}
// Test object copy.
copyName := "copy-" + objName
copyObj, err := bkt.Object(copyName).CopierFrom(bkt.Object(objName)).Run(ctx)
if err != nil {
t.Errorf("Copier.Run failed with %v", err)
} else if !namesEqual(copyObj, newBucketName, copyName) {
t.Errorf("Copy object bucket, name: got %q.%q, want %q.%q",
copyObj.Bucket, copyObj.Name, newBucketName, copyName)
}
// Copying with attributes.
const contentEncoding = "identity"
copier := bkt.Object(copyName).CopierFrom(bkt.Object(objName))
copier.ContentEncoding = contentEncoding
copyObj, err = copier.Run(ctx)
if err != nil {
t.Errorf("Copier.Run failed with %v", err)
} else {
if !namesEqual(copyObj, newBucketName, copyName) {
t.Errorf("Copy object bucket, name: got %q.%q, want %q.%q",
copyObj.Bucket, copyObj.Name, newBucketName, copyName)
}
if copyObj.ContentEncoding != contentEncoding {
t.Errorf("Copy ContentEncoding: got %q, want %q", copyObj.ContentEncoding, contentEncoding)
}
}
// Test UpdateAttrs.
metadata := map[string]string{"key": "value"}
updated := h.mustUpdateObject(bkt.Object(objName), ObjectAttrsToUpdate{
ContentType: "text/html",
ContentLanguage: "en",
Metadata: metadata,
ACL: []ACLRule{{Entity: "domain-google.com", Role: RoleReader}},
})
if got, want := updated.ContentType, "text/html"; got != want {
t.Errorf("updated.ContentType == %q; want %q", got, want)
}
if got, want := updated.ContentLanguage, "en"; got != want {
t.Errorf("updated.ContentLanguage == %q; want %q", updated.ContentLanguage, want)
}
if got, want := updated.Metadata, metadata; !testutil.Equal(got, want) {
t.Errorf("updated.Metadata == %+v; want %+v", updated.Metadata, want)
}
if got, want := updated.Created, created; got != want {
t.Errorf("updated.Created == %q; want %q", got, want)
}
if !updated.Created.Before(updated.Updated) {
t.Errorf("updated.Updated should be newer than update.Created")
}
// Delete ContentType and ContentLanguage.
updated = h.mustUpdateObject(bkt.Object(objName), ObjectAttrsToUpdate{
ContentType: "",
ContentLanguage: "",
Metadata: map[string]string{},
})
if got, want := updated.ContentType, ""; got != want {
t.Errorf("updated.ContentType == %q; want %q", got, want)
}
if got, want := updated.ContentLanguage, ""; got != want {
t.Errorf("updated.ContentLanguage == %q; want %q", updated.ContentLanguage, want)
}
if updated.Metadata != nil {
t.Errorf("updated.Metadata == %+v; want nil", updated.Metadata)
}
if got, want := updated.Created, created; got != want {
t.Errorf("updated.Created == %q; want %q", got, want)
}
if !updated.Created.Before(updated.Updated) {
t.Errorf("updated.Updated should be newer than update.Created")
}
// Test checksums.
checksumCases := []struct {
name string
contents [][]byte
size int64
md5 string
crc32c uint32
}{
{
name: "checksum-object",
contents: [][]byte{[]byte("hello"), []byte("world")},
size: 10,
md5: "fc5e038d38a57032085441e7fe7010b0",
crc32c: 1456190592,
},
{
name: "zero-object",
contents: [][]byte{},
size: 0,
md5: "d41d8cd98f00b204e9800998ecf8427e",
crc32c: 0,
},
}
for _, c := range checksumCases {
wc := bkt.Object(c.name).NewWriter(ctx)
for _, data := range c.contents {
if _, err := wc.Write(data); err != nil {
t.Errorf("Write(%q) failed with %q", data, err)
}
}
if err = wc.Close(); err != nil {
t.Errorf("%q: close failed with %q", c.name, err)
}
obj := wc.Attrs()
if got, want := obj.Size, c.size; got != want {
t.Errorf("Object (%q) Size = %v; want %v", c.name, got, want)
}
if got, want := fmt.Sprintf("%x", obj.MD5), c.md5; got != want {
t.Errorf("Object (%q) MD5 = %q; want %q", c.name, got, want)
}
if got, want := obj.CRC32C, c.crc32c; got != want {
t.Errorf("Object (%q) CRC32C = %v; want %v", c.name, got, want)
}
}