forked from googleapis/google-cloud-go
/
writer_test.go
178 lines (154 loc) · 5.7 KB
/
writer_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
// 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 (
"context"
"crypto/sha256"
"encoding/base64"
"net/http"
"strings"
"testing"
"cloud.google.com/go/internal/testutil"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
)
var testEncryptionKey = []byte("secret-key-that-is-32-bytes-long")
func TestErrorOnObjectsInsertCall(t *testing.T) {
t.Skip("Should be re-enabled after https://github.com/googleapis/google-cloud-go/pull/5210")
t.Parallel()
ctx := context.Background()
const contents = "hello world"
doWrite := func(mt *mockTransport) *Writer {
client := mockClient(t, mt)
wc := client.Bucket("bucketname").Object("filename1").NewWriter(ctx)
wc.ContentType = "text/plain"
// We can't check that the Write fails, since it depends on the write to the
// underling mockTransport failing which is racy.
wc.Write([]byte(contents))
return wc
}
wc := doWrite(&mockTransport{})
// Close must always return an error though since it waits for the transport to
// have closed.
if err := wc.Close(); err == nil {
t.Errorf("expected error on close, got nil")
}
// Retry on 5xx
mt := &mockTransport{}
mt.addResult(&http.Response{StatusCode: 503, Body: bodyReader("")}, nil)
mt.addResult(&http.Response{StatusCode: 200, Body: bodyReader("{}")}, nil)
wc = doWrite(mt)
if err := wc.Close(); err != nil {
t.Errorf("got %v, want nil", err)
}
got := string(mt.gotBody)
if !strings.Contains(got, contents) {
t.Errorf("got body %q, which does not contain %q", got, contents)
}
}
func TestEncryption(t *testing.T) {
t.Parallel()
ctx := context.Background()
mt := &mockTransport{}
mt.addResult(&http.Response{StatusCode: 200, Body: bodyReader("{}")}, nil)
client := mockClient(t, mt)
obj := client.Bucket("bucketname").Object("filename1")
wc := obj.Key(testEncryptionKey).NewWriter(ctx)
if _, err := wc.Write([]byte("hello world")); err != nil {
t.Fatal(err)
}
if err := wc.Close(); err != nil {
t.Fatal(err)
}
if got, want := mt.gotReq.Header.Get("x-goog-encryption-algorithm"), "AES256"; got != want {
t.Errorf("algorithm: got %q, want %q", got, want)
}
gotKey, err := base64.StdEncoding.DecodeString(mt.gotReq.Header.Get("x-goog-encryption-key"))
if err != nil {
t.Fatalf("decoding key: %v", err)
}
if !testutil.Equal(gotKey, testEncryptionKey) {
t.Errorf("key: got %v, want %v", gotKey, testEncryptionKey)
}
wantHash := sha256.Sum256(testEncryptionKey)
gotHash, err := base64.StdEncoding.DecodeString(mt.gotReq.Header.Get("x-goog-encryption-key-sha256"))
if err != nil {
t.Fatalf("decoding hash: %v", err)
}
if !testutil.Equal(gotHash, wantHash[:]) { // wantHash is an array
t.Errorf("hash: got\n%v, want\n%v", gotHash, wantHash)
}
// Using a customer-supplied encryption key and a KMS key together is an error.
checkKMSError := func(msg string, err error) {
if err == nil {
t.Errorf("%s: got nil, want error", msg)
} else if !strings.Contains(err.Error(), "KMS") {
t.Errorf(`%s: got %q, want it to contain "KMS"`, msg, err)
}
}
wc = obj.Key(testEncryptionKey).NewWriter(ctx)
wc.KMSKeyName = "key"
_, err = wc.Write([]byte{})
checkKMSError("Write", err)
checkKMSError("Close", wc.Close())
}
// This test demonstrates the data race on Writer.err that can happen when the
// Writer's context is cancelled. To see the race, comment out the w.mu.Lock/Unlock
// lines in writer.go and run this test with -race.
func TestRaceOnCancel(t *testing.T) {
client := mockClient(t, &mockTransport{})
cctx, cancel := context.WithCancel(context.Background())
w := client.Bucket("b").Object("o").NewWriter(cctx)
w.ChunkSize = googleapi.MinUploadChunkSize
buf := make([]byte, w.ChunkSize)
// This Write starts the goroutine in Writer.open. That reads the first chunk in its entirety
// before sending the request (see google.golang.org/api/gensupport.PrepareUpload),
// so to exhibit the race we must provide ChunkSize bytes. The goroutine then makes the RPC (L137).
w.Write(buf)
// Canceling the context causes the call to return context.Canceled, which makes the open goroutine
// write to w.err (L151).
cancel()
// This call to Write concurrently reads w.err (L169).
w.Write([]byte(nil))
}
func TestCancelDoesNotLeak(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
const contents = "hello world"
mt := mockTransport{}
client, err := NewClient(ctx, option.WithHTTPClient(&http.Client{Transport: &mt}))
if err != nil {
t.Fatal(err)
}
wc := client.Bucket("bucketname").Object("filename1").NewWriter(ctx)
wc.ContentType = "text/plain"
// We can't check that the Write fails, since it depends on the write to the
// underling mockTransport failing which is racy.
wc.Write([]byte(contents))
cancel()
}
func TestCloseDoesNotLeak(t *testing.T) {
ctx := context.Background()
const contents = "hello world"
mt := mockTransport{}
client, err := NewClient(ctx, option.WithHTTPClient(&http.Client{Transport: &mt}))
if err != nil {
t.Fatal(err)
}
wc := client.Bucket("bucketname").Object("filename1").NewWriter(ctx)
wc.ContentType = "text/plain"
// We can't check that the Write fails, since it depends on the write to the
// underling mockTransport failing which is racy.
wc.Write([]byte(contents))
wc.Close()
}