github.com/go4org/go4@v0.0.0-20200104003542-c7e774b10ea0/wkfs/gcs/gcs_test.go (about) 1 /* 2 Copyright 2015 The Perkeep Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package gcs 18 19 import ( 20 "bytes" 21 "flag" 22 "io" 23 "strings" 24 "testing" 25 26 "cloud.google.com/go/compute/metadata" 27 "cloud.google.com/go/storage" 28 "go4.org/wkfs" 29 "golang.org/x/net/context" 30 "google.golang.org/api/iterator" 31 ) 32 33 var flagBucket = flag.String("bucket", "", "Google Cloud Storage bucket where to run the tests. It should be empty.") 34 35 func TestWriteRead(t *testing.T) { 36 if !metadata.OnGCE() { 37 t.Skipf("Not testing on GCE") 38 } 39 if *flagBucket == "" { 40 t.Skipf("No bucket specified") 41 } 42 ctx := context.Background() 43 cl, err := storage.NewClient(ctx) 44 it := cl.Bucket(*flagBucket).Objects(ctx, nil) 45 if _, err := it.Next(); err != iterator.Done { 46 if err == nil { 47 t.Fatalf("Bucket %v is not empty, aborting test.", *flagBucket) 48 } 49 t.Fatalf("unexpected bucket iteration error: %v", err) 50 } 51 52 // Write to camli-gcs_test.txt 53 filename := "camli-gcs_test.txt" 54 gcsPath := "/gcs/" + *flagBucket + "/" + filename 55 f, err := wkfs.Create(gcsPath) 56 if err != nil { 57 t.Fatalf("error creating %v: %v", gcsPath, err) 58 } 59 defer func() { 60 if err := wkfs.Remove(gcsPath); err != nil { 61 t.Fatalf("error while cleaning up %v: %v", gcsPath, err) 62 } 63 }() 64 65 data := "Hello World" 66 if _, err := io.Copy(f, strings.NewReader(data)); err != nil { 67 t.Fatalf("error writing to %v: %v", gcsPath, err) 68 } 69 if err := f.Close(); err != nil { 70 t.Fatalf("error closing %v: %v", gcsPath, err) 71 } 72 73 // Read back from camli-gcs_test.txt 74 g, err := wkfs.Open(gcsPath) 75 if err != nil { 76 t.Fatalf("error opening %v: %v", gcsPath, err) 77 } 78 defer g.Close() 79 var buf bytes.Buffer 80 if _, err := io.Copy(&buf, g); err != nil { 81 t.Fatalf("error reading %v: %v", gcsPath, err) 82 } 83 if buf.String() != data { 84 t.Fatalf("error with %v contents: got %v, wanted %v", gcsPath, buf.String(), data) 85 } 86 }