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
|
// +build integration
package storage
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"testing"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/googleapi"
storage "google.golang.org/api/storage/v1"
)
type object struct {
name, contents string
}
var (
projectID string
bucket string
objects = []object{
{"obj1", testContents},
{"obj2", testContents},
{"obj/with/slashes", testContents},
{"resumable", testContents},
{"large", strings.Repeat("a", 514)}, // larger than the first section of content that is sniffed by ContentSniffer.
}
aclObjects = []string{"acl1", "acl2"}
copyObj = "copy-object"
)
const (
envProject = "GCLOUD_TESTS_GOLANG_PROJECT_ID"
envPrivateKey = "GCLOUD_TESTS_GOLANG_KEY"
// NOTE that running this test on a bucket deletes ALL contents of the bucket!
envBucket = "GCLOUD_TESTS_GOLANG_DESTRUCTIVE_TEST_BUCKET_NAME"
testContents = "some text that will be saved to a bucket object"
)
func verifyAcls(obj *storage.Object, wantDomainRole, wantAllUsersRole string) (err error) {
var gotDomainRole, gotAllUsersRole string
for _, acl := range obj.Acl {
if acl.Entity == "domain-google.com" {
gotDomainRole = acl.Role
}
if acl.Entity == "allUsers" {
gotAllUsersRole = acl.Role
}
}
if gotDomainRole != wantDomainRole {
err = fmt.Errorf("domain-google.com role = %q; want %q", gotDomainRole, wantDomainRole)
}
if gotAllUsersRole != wantAllUsersRole {
err = fmt.Errorf("allUsers role = %q; want %q; %v", gotAllUsersRole, wantAllUsersRole, err)
}
return err
}
// TODO(gmlewis): Move this to a common location.
func tokenSource(ctx context.Context, scopes ...string) (oauth2.TokenSource, error) {
keyFile := os.Getenv(envPrivateKey)
if keyFile == "" {
return nil, errors.New(envPrivateKey + " not set")
}
jsonKey, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, fmt.Errorf("unable to read %q: %v", keyFile, err)
}
conf, err := google.JWTConfigFromJSON(jsonKey, scopes...)
if err != nil {
return nil, fmt.Errorf("google.JWTConfigFromJSON: %v", err)
}
return conf.TokenSource(ctx), nil
}
const defaultType = "text/plain; charset=utf-8"
// writeObject writes some data and default metadata to the specified object.
// Resumable upload is used if resumable is true.
// The written data is returned.
func writeObject(s *storage.Service, bucket, obj string, resumable bool, contents string) error {
o := &storage.Object{
Bucket: bucket,
Name: obj,
ContentType: defaultType,
ContentEncoding: "utf-8",
ContentLanguage: "en",
Metadata: map[string]string{"foo": "bar"},
}
f := strings.NewReader(contents)
insert := s.Objects.Insert(bucket, o)
if resumable {
insert.ResumableMedia(context.Background(), f, int64(len(contents)), defaultType)
} else {
insert.Media(f)
}
_, err := insert.Do()
return err
}
func checkMetadata(t *testing.T, s *storage.Service, bucket, obj string) {
o, err := s.Objects.Get(bucket, obj).Do()
if err != nil {
t.Error(err)
}
if got, want := o.Name, obj; got != want {
t.Errorf("name of %q = %q; want %q", obj, got, want)
}
if got, want := o.ContentType, defaultType; got != want {
t.Errorf("contentType of %q = %q; want %q", obj, got, want)
}
if got, want := o.Metadata["foo"], "bar"; got != want {
t.Errorf("metadata entry foo of %q = %q; want %q", obj, got, want)
}
}
func createService() *storage.Service {
if projectID = os.Getenv(envProject); projectID == "" {
log.Print("no project ID specified")
return nil
}
if bucket = os.Getenv(envBucket); bucket == "" {
log.Print("no bucket specified")
return nil
}
ctx := context.Background()
ts, err := tokenSource(ctx, storage.DevstorageFullControlScope)
if err != nil {
log.Printf("tokenSource: %v", err)
return nil
}
client := oauth2.NewClient(ctx, ts)
s, err := storage.New(client)
if err != nil {
log.Printf("unable to create service: %v", err)
return nil
}
return s
}
func TestMain(m *testing.M) {
if err := cleanup(); err != nil {
log.Fatalf("Pre-test cleanup failed: %v", err)
}
exit := m.Run()
if err := cleanup(); err != nil {
log.Fatalf("Post-test cleanup failed: %v", err)
}
os.Exit(exit)
}
func TestContentType(t *testing.T) {
s := createService()
if s == nil {
t.Fatal("Could not create service")
}
type testCase struct {
objectContentType string
useOptionContentType bool
optionContentType string
wantContentType string
}
// The Media method will use resumable upload if the supplied data is
// larger than googleapi.DefaultUploadChunkSize We run the following
// tests with two different file contents: one that will trigger
// resumable upload, and one that won't.
forceResumableData := bytes.Repeat([]byte("a"), googleapi.DefaultUploadChunkSize+1)
smallData := bytes.Repeat([]byte("a"), 2)
// In the following test, the content type, if any, in the Object struct is always "text/plain".
// The content type configured via googleapi.ContentType, if any, is always "text/html".
for _, tc := range []testCase{
// With content type specified in the object struct
// Temporarily disable this test during rollout of strict Content-Type.
// TODO(djd): Re-enable once strict check is 100%.
// {
// objectContentType: "text/plain",
// useOptionContentType: true,
// optionContentType: "text/html",
// wantContentType: "text/html",
// },
{
objectContentType: "text/plain",
useOptionContentType: true,
optionContentType: "",
wantContentType: "text/plain",
},
{
objectContentType: "text/plain",
useOptionContentType: false,
wantContentType: "text/plain",
},
// Without content type specified in the object struct
{
useOptionContentType: true,
optionContentType: "text/html",
wantContentType: "text/html",
},
{
useOptionContentType: true,
optionContentType: "",
wantContentType: "", // Result is an object without a content type.
},
{
useOptionContentType: false,
wantContentType: "text/plain; charset=utf-8", // sniffed.
},
} {
// The behavior should be the same, regardless of whether resumable upload is used or not.
for _, data := range [][]byte{smallData, forceResumableData} {
o := &storage.Object{
Bucket: bucket,
Name: "test-content-type",
ContentType: tc.objectContentType,
}
call := s.Objects.Insert(bucket, o)
var opts []googleapi.MediaOption
if tc.useOptionContentType {
opts = append(opts, googleapi.ContentType(tc.optionContentType))
}
call.Media(bytes.NewReader(data), opts...)
_, err := call.Do()
if err != nil {
t.Fatalf("unable to insert object %q: %v", o.Name, err)
}
readObj, err := s.Objects.Get(bucket, o.Name).Do()
if err != nil {
t.Error(err)
}
if got, want := readObj.ContentType, tc.wantContentType; got != want {
t.Errorf("contentType of %q; got %q; want %q", o.Name, got, want)
}
}
}
}
func TestFunctions(t *testing.T) {
s := createService()
if s == nil {
t.Fatal("Could not create service")
}
t.Logf("Listing buckets for project %q", projectID)
var numBuckets int
pageToken := ""
for {
call := s.Buckets.List(projectID)
if pageToken != "" {
call.PageToken(pageToken)
}
resp, err := call.Do()
if err != nil {
t.Fatalf("unable to list buckets for project %q: %v", projectID, err)
}
numBuckets += len(resp.Items)
if pageToken = resp.NextPageToken; pageToken == "" {
break
}
}
if numBuckets == 0 {
t.Fatalf("no buckets found for project %q", projectID)
}
for _, obj := range objects {
t.Logf("Writing %q", obj.name)
// TODO(mcgreevy): stop relying on "resumable" name to determine whether to
// do a resumable upload.
err := writeObject(s, bucket, obj.name, obj.name == "resumable", obj.contents)
if err != nil {
t.Fatalf("unable to insert object %q: %v", obj.name, err)
}
}
for _, obj := range objects {
t.Logf("Reading %q", obj.name)
resp, err := s.Objects.Get(bucket, obj.name).Download()
if err != nil {
t.Fatalf("unable to get object %q: %v", obj.name, err)
}
slurp, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("unable to read response body %q: %v", obj.name, err)
}
resp.Body.Close()
if got, want := string(slurp), obj.contents; got != want {
t.Errorf("contents of %q = %q; want %q", obj.name, got, want)
}
}
name := "obj-not-exists"
if _, err := s.Objects.Get(bucket, name).Download(); !isError(err, http.StatusNotFound) {
t.Errorf("object %q should not exist, err = %v", name, err)
} else {
t.Log("Successfully tested StatusNotFound.")
}
for _, obj := range objects {
t.Logf("Checking %q metadata", obj.name)
checkMetadata(t, s, bucket, obj.name)
}
name = objects[0].name
t.Logf("Rewriting %q to %q", name, copyObj)
copy, err := s.Objects.Rewrite(bucket, name, bucket, copyObj, nil).Do()
if err != nil {
t.Errorf("unable to rewrite object %q to %q: %v", name, copyObj, err)
}
if copy.Resource.Name != copyObj {
t.Errorf("copy object's name = %q; want %q", copy.Resource.Name, copyObj)
}
if copy.Resource.Bucket != bucket {
t.Errorf("copy object's bucket = %q; want %q", copy.Resource.Bucket, bucket)
}
// Note that arrays such as ACLs below are completely overwritten using Patch
// semantics, so these must be updated in a read-modify-write sequence of operations.
// See https://cloud.google.com/storage/docs/json_api/v1/how-tos/performance#patch-semantics
// for more details.
t.Logf("Updating attributes of %q", name)
obj, err := s.Objects.Get(bucket, name).Projection("full").Fields("acl").Do()
if err != nil {
t.Errorf("Objects.Get(%q, %q): %v", bucket, name, err)
}
if err := verifyAcls(obj, "", ""); err != nil {
t.Errorf("before update ACLs: %v", err)
}
obj.ContentType = "text/html"
for _, entity := range []string{"domain-google.com", "allUsers"} {
obj.Acl = append(obj.Acl, &storage.ObjectAccessControl{Entity: entity, Role: "READER"})
}
updated, err := s.Objects.Patch(bucket, name, obj).Projection("full").Fields("contentType", "acl").Do()
if err != nil {
t.Errorf("Objects.Patch(%q, %q, %#v) failed with %v", bucket, name, obj, err)
}
if want := "text/html"; updated.ContentType != want {
t.Errorf("updated.ContentType == %q; want %q", updated.ContentType, want)
}
if err := verifyAcls(updated, "READER", "READER"); err != nil {
t.Errorf("after update ACLs: %v", err)
}
t.Log("Testing checksums")
checksumCases := []struct {
name string
contents string
size uint64
md5 string
crc32c uint32
}{
{
name: "checksum-object",
contents: "helloworld",
size: 10,
md5: "fc5e038d38a57032085441e7fe7010b0",
crc32c: 1456190592,
},
{
name: "zero-object",
contents: "",
size: 0,
md5: "d41d8cd98f00b204e9800998ecf8427e",
crc32c: 0,
},
}
for _, c := range checksumCases {
f := strings.NewReader(c.contents)
o := &storage.Object{
Bucket: bucket,
Name: c.name,
ContentType: defaultType,
ContentEncoding: "utf-8",
ContentLanguage: "en",
}
obj, err := s.Objects.Insert(bucket, o).Media(f).Do()
if err != nil {
t.Fatalf("unable to insert object %q: %v", obj, err)
}
if got, want := obj.Size, c.size; got != want {
t.Errorf("object %q size = %v; want %v", c.name, got, want)
}
md5, err := base64.StdEncoding.DecodeString(obj.Md5Hash)
if err != nil {
t.Errorf("object %q base64 decode of MD5 %q: %v", c.name, obj.Md5Hash, err)
}
if got, want := fmt.Sprintf("%x", md5), c.md5; got != want {
t.Errorf("object %q MD5 = %q; want %q", c.name, got, want)
}
var crc32c uint32
d, err := base64.StdEncoding.DecodeString(obj.Crc32c)
if err != nil {
t.Errorf("object %q base64 decode of CRC32 %q: %v", c.name, obj.Crc32c, err)
}
if err == nil && len(d) == 4 {
crc32c = uint32(d[0])<<24 + uint32(d[1])<<16 + uint32(d[2])<<8 + uint32(d[3])
}
if got, want := crc32c, c.crc32c; got != want {
t.Errorf("object %q CRC32C = %v; want %v", c.name, got, want)
}
}
}
// cleanup destroys ALL objects in the bucket!
func cleanup() error {
s := createService()
if s == nil {
return errors.New("Could not create service")
}
var pageToken string
var failed bool
for {
call := s.Objects.List(bucket)
if pageToken != "" {
call.PageToken(pageToken)
}
resp, err := call.Do()
if err != nil {
return fmt.Errorf("cleanup list failed: %v", err)
}
for _, obj := range resp.Items {
log.Printf("Cleanup deletion of %q", obj.Name)
if err := s.Objects.Delete(bucket, obj.Name).Do(); err != nil {
// Print the error out, but keep going.
log.Printf("Cleanup deletion of %q failed: %v", obj.Name, err)
failed = true
}
if _, err := s.Objects.Get(bucket, obj.Name).Download(); !isError(err, http.StatusNotFound) {
log.Printf("object %q should not exist, err = %v", obj.Name, err)
failed = true
} else {
log.Printf("Successfully deleted %q.", obj.Name)
}
}
if pageToken = resp.NextPageToken; pageToken == "" {
break
}
}
if failed {
return errors.New("Failed to delete at least one object")
}
return nil
}
func isError(err error, code int) bool {
if err == nil {
return false
}
ae, ok := err.(*googleapi.Error)
return ok && ae.Code == code
}
|