From 4deefa3695ca934b901779185cdd60e6d9f658c8 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Tue, 10 Oct 2017 02:14:42 -0700 Subject: [PATCH] tests: Remove dependency on check.v1 (#5034) This PR addresses a long standing dependency on `gopkg.in/check.v1` project used for our tests. All tests are re-written to use the go default testing framework instead. There was no reason for us to use an external package where Go tools are sufficient for this. --- cmd/browser-peer-rpc_test.go | 11 +- cmd/main_test.go | 26 - cmd/net_test.go | 15 + cmd/object_api_suite_test.go | 339 ++++--- cmd/server_test.go | 1242 +++++++++++++------------ cmd/storage-rpc-client_test.go | 9 +- cmd/test-utils_test.go | 19 +- cmd/version_test.go | 19 +- pkg/disk/disk_test.go | 39 +- pkg/quick/quick_test.go | 327 ++++--- pkg/safe/safe_test.go | 164 +++- vendor/gopkg.in/check.v1/LICENSE | 25 - vendor/gopkg.in/check.v1/README.md | 20 - vendor/gopkg.in/check.v1/TODO | 2 - vendor/gopkg.in/check.v1/benchmark.go | 187 ---- vendor/gopkg.in/check.v1/check.go | 954 ------------------- vendor/gopkg.in/check.v1/checkers.go | 458 --------- vendor/gopkg.in/check.v1/helpers.go | 231 ----- vendor/gopkg.in/check.v1/printer.go | 168 ---- vendor/gopkg.in/check.v1/run.go | 175 ---- vendor/vendor.json | 5 - 21 files changed, 1228 insertions(+), 3207 deletions(-) delete mode 100644 cmd/main_test.go delete mode 100644 vendor/gopkg.in/check.v1/LICENSE delete mode 100644 vendor/gopkg.in/check.v1/README.md delete mode 100644 vendor/gopkg.in/check.v1/TODO delete mode 100644 vendor/gopkg.in/check.v1/benchmark.go delete mode 100644 vendor/gopkg.in/check.v1/check.go delete mode 100644 vendor/gopkg.in/check.v1/checkers.go delete mode 100644 vendor/gopkg.in/check.v1/helpers.go delete mode 100644 vendor/gopkg.in/check.v1/printer.go delete mode 100644 vendor/gopkg.in/check.v1/run.go diff --git a/cmd/browser-peer-rpc_test.go b/cmd/browser-peer-rpc_test.go index 4f3a4b122..f587bb330 100644 --- a/cmd/browser-peer-rpc_test.go +++ b/cmd/browser-peer-rpc_test.go @@ -29,8 +29,8 @@ type TestRPCBrowserPeerSuite struct { } // Setting up the test suite and starting the Test server. -func (s *TestRPCBrowserPeerSuite) SetUpSuite(c *testing.T) { - s.testServer = StartTestBrowserPeerRPCServer(c, s.serverType) +func (s *TestRPCBrowserPeerSuite) SetUpSuite(t *testing.T) { + s.testServer = StartTestBrowserPeerRPCServer(t, s.serverType) s.testAuthConf = authConfig{ serverAddr: s.testServer.Server.Listener.Addr().String(), accessKey: s.testServer.AccessKey, @@ -40,10 +40,9 @@ func (s *TestRPCBrowserPeerSuite) SetUpSuite(c *testing.T) { } } -// No longer used with gocheck, but used in explicit teardown code in -// each test function. // Called implicitly by "gopkg.in/check.v1" -// after all tests are run. -func (s *TestRPCBrowserPeerSuite) TearDownSuite(c *testing.T) { +// TeatDownSuite - called implicitly by after all tests are run in +// browser peer rpc suite. +func (s *TestRPCBrowserPeerSuite) TearDownSuite(t *testing.T) { s.testServer.Stop() } diff --git a/cmd/main_test.go b/cmd/main_test.go deleted file mode 100644 index 3fea9bdbc..000000000 --- a/cmd/main_test.go +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Minio Cloud Storage, (C) 2015 Minio, Inc. - * - * 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 cmd - -import ( - "testing" - - . "gopkg.in/check.v1" -) - -// Hook up gocheck into the "go test" runner. -func Test(t *testing.T) { TestingT(t) } diff --git a/cmd/net_test.go b/cmd/net_test.go index a65bcd0ef..e4fc38876 100644 --- a/cmd/net_test.go +++ b/cmd/net_test.go @@ -175,6 +175,21 @@ func TestGetAPIEndpoints(t *testing.T) { } } +// Ask the kernel for a free open port. +func getFreePort() string { + addr, err := net.ResolveTCPAddr("tcp", "localhost:0") + if err != nil { + panic(err) + } + + l, err := net.ListenTCP("tcp", addr) + if err != nil { + panic(err) + } + defer l.Close() + return fmt.Sprintf("%d", l.Addr().(*net.TCPAddr).Port) +} + // Tests for port availability logic written for server startup sequence. func TestCheckPortAvailability(t *testing.T) { // Make a port is not available. diff --git a/cmd/object_api_suite_test.go b/cmd/object_api_suite_test.go index 318382d26..ebbaeb531 100644 --- a/cmd/object_api_suite_test.go +++ b/cmd/object_api_suite_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,10 +21,9 @@ import ( "io" "math/rand" "strconv" + "testing" humanize "github.com/dustin/go-humanize" - - . "gopkg.in/check.v1" ) // Return pointer to testOneByteReadEOF{} @@ -70,35 +69,33 @@ func (r *testOneByteReadNoEOF) Read(p []byte) (n int, err error) { type ObjectLayerAPISuite struct{} -var _ = Suite(&ObjectLayerAPISuite{}) - // Wrapper for calling testMakeBucket for both XL and FS. -func (s *ObjectLayerAPISuite) TestMakeBucket(c *C) { - ExecObjectLayerTest(c, testMakeBucket) +func (s *ObjectLayerAPISuite) TestMakeBucket(t *testing.T) { + ExecObjectLayerTest(t, testMakeBucket) } // Tests validate bucket creation. -func testMakeBucket(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testMakeBucket(obj ObjectLayer, instanceType string, t TestErrHandler) { err := obj.MakeBucketWithLocation("bucket-unknown", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } } // Wrapper for calling testMultipartObjectCreation for both XL and FS. -func (s *ObjectLayerAPISuite) TestMultipartObjectCreation(c *C) { - ExecObjectLayerTest(c, testMultipartObjectCreation) +func (s *ObjectLayerAPISuite) TestMultipartObjectCreation(t *testing.T) { + ExecObjectLayerTest(t, testMultipartObjectCreation) } // Tests validate creation of part files during Multipart operation. -func testMultipartObjectCreation(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testMultipartObjectCreation(obj ObjectLayer, instanceType string, t TestErrHandler) { err := obj.MakeBucketWithLocation("bucket", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } uploadID, err := obj.NewMultipartUpload("bucket", "key", nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } // Create a byte array of 5MiB. data := bytes.Repeat([]byte("0123456789abcdef"), 5*humanize.MiByte/16) @@ -109,10 +106,10 @@ func testMultipartObjectCreation(obj ObjectLayer, instanceType string, c TestErr var calcPartInfo PartInfo calcPartInfo, err = obj.PutObjectPart("bucket", "key", uploadID, i, NewHashReader(bytes.NewBuffer(data), int64(len(data)), expectedETaghex, "")) if err != nil { - c.Errorf("%s: %s", instanceType, err) + t.Errorf("%s: %s", instanceType, err) } if calcPartInfo.ETag != expectedETaghex { - c.Errorf("MD5 Mismatch") + t.Errorf("MD5 Mismatch") } completedParts.Parts = append(completedParts.Parts, completePart{ PartNumber: i, @@ -121,27 +118,27 @@ func testMultipartObjectCreation(obj ObjectLayer, instanceType string, c TestErr } objInfo, err := obj.CompleteMultipartUpload("bucket", "key", uploadID, completedParts.Parts) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if objInfo.ETag != "7d364cb728ce42a74a96d22949beefb2-10" { - c.Errorf("Md5 mismtch") + t.Errorf("Md5 mismtch") } } // Wrapper for calling testMultipartObjectAbort for both XL and FS. -func (s *ObjectLayerAPISuite) TestMultipartObjectAbort(c *C) { - ExecObjectLayerTest(c, testMultipartObjectAbort) +func (s *ObjectLayerAPISuite) TestMultipartObjectAbort(t *testing.T) { + ExecObjectLayerTest(t, testMultipartObjectAbort) } // Tests validate abortion of Multipart operation. -func testMultipartObjectAbort(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testMultipartObjectAbort(obj ObjectLayer, instanceType string, t TestErrHandler) { err := obj.MakeBucketWithLocation("bucket", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } uploadID, err := obj.NewMultipartUpload("bucket", "key", nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } parts := make(map[int]string) @@ -159,30 +156,30 @@ func testMultipartObjectAbort(obj ObjectLayer, instanceType string, c TestErrHan var calcPartInfo PartInfo calcPartInfo, err = obj.PutObjectPart("bucket", "key", uploadID, i, NewHashReader(bytes.NewBufferString(randomString), int64(len(randomString)), expectedETaghex, "")) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if calcPartInfo.ETag != expectedETaghex { - c.Errorf("Md5 Mismatch") + t.Errorf("Md5 Mismatch") } parts[i] = expectedETaghex } err = obj.AbortMultipartUpload("bucket", "key", uploadID) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } } // Wrapper for calling testMultipleObjectCreation for both XL and FS. -func (s *ObjectLayerAPISuite) TestMultipleObjectCreation(c *C) { - ExecObjectLayerTest(c, testMultipleObjectCreation) +func (s *ObjectLayerAPISuite) TestMultipleObjectCreation(t *testing.T) { + ExecObjectLayerTest(t, testMultipleObjectCreation) } // Tests validate object creation. -func testMultipleObjectCreation(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testMultipleObjectCreation(obj ObjectLayer, instanceType string, t TestErrHandler) { objects := make(map[string][]byte) err := obj.MakeBucketWithLocation("bucket", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } for i := 0; i < 10; i++ { randomPerm := rand.Perm(100) @@ -200,10 +197,10 @@ func testMultipleObjectCreation(obj ObjectLayer, instanceType string, c TestErrH var objInfo ObjectInfo objInfo, err = obj.PutObject("bucket", key, NewHashReader(bytes.NewBufferString(randomString), int64(len(randomString)), metadata["etag"], ""), metadata) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if objInfo.ETag != expectedETaghex { - c.Errorf("Md5 Mismatch") + t.Errorf("Md5 Mismatch") } } @@ -211,40 +208,40 @@ func testMultipleObjectCreation(obj ObjectLayer, instanceType string, c TestErrH var byteBuffer bytes.Buffer err = obj.GetObject("bucket", key, 0, int64(len(value)), &byteBuffer) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if !bytes.Equal(byteBuffer.Bytes(), value) { - c.Errorf("%s: Mismatch of GetObject data with the expected one.", instanceType) + t.Errorf("%s: Mismatch of GetObject data with the expected one.", instanceType) } objInfo, err := obj.GetObjectInfo("bucket", key) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if objInfo.Size != int64(len(value)) { - c.Errorf("%s: Size mismatch of the GetObject data.", instanceType) + t.Errorf("%s: Size mismatch of the GetObject data.", instanceType) } } } // Wrapper for calling TestPaging for both XL and FS. -func (s *ObjectLayerAPISuite) TestPaging(c *C) { - ExecObjectLayerTest(c, testPaging) +func (s *ObjectLayerAPISuite) TestPaging(t *testing.T) { + ExecObjectLayerTest(t, testPaging) } // Tests validate creation of objects and the order of listing using various filters for ListObjects operation. -func testPaging(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testPaging(obj ObjectLayer, instanceType string, t TestErrHandler) { obj.MakeBucketWithLocation("bucket", "") result, err := obj.ListObjects("bucket", "", "", "", 0) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(result.Objects) != 0 { - c.Errorf("%s: Number of objects in the result different from expected value.", instanceType) + t.Errorf("%s: Number of objects in the result different from expected value.", instanceType) } if result.IsTruncated { - c.Errorf("%s: Expected IsTruncated to be `false`, but instead found it to be `%v`", instanceType, result.IsTruncated) + t.Errorf("%s: Expected IsTruncated to be `false`, but instead found it to be `%v`", instanceType, result.IsTruncated) } uploadContent := "The specified multipart upload does not exist. The upload ID might be invalid, or the multipart upload might have been aborted or completed." @@ -253,18 +250,18 @@ func testPaging(obj ObjectLayer, instanceType string, c TestErrHandler) { key := "obj" + strconv.Itoa(i) _, err = obj.PutObject("bucket", key, NewHashReader(bytes.NewBufferString(uploadContent), int64(len(uploadContent)), "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } result, err = obj.ListObjects("bucket", "", "", "", 5) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(result.Objects) != i+1 { - c.Errorf("%s: Expected length of objects to be %d, instead found to be %d", instanceType, len(result.Objects), i+1) + t.Errorf("%s: Expected length of objects to be %d, instead found to be %d", instanceType, len(result.Objects), i+1) } if result.IsTruncated { - c.Errorf("%s: Expected IsTruncated to be `false`, but instead found it to be `%v`", instanceType, result.IsTruncated) + t.Errorf("%s: Expected IsTruncated to be `false`, but instead found it to be `%v`", instanceType, result.IsTruncated) } } @@ -273,35 +270,35 @@ func testPaging(obj ObjectLayer, instanceType string, c TestErrHandler) { key := "obj" + strconv.Itoa(i) _, err = obj.PutObject("bucket", key, NewHashReader(bytes.NewBufferString(uploadContent), int64(len(uploadContent)), "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } result, err = obj.ListObjects("bucket", "obj", "", "", 5) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(result.Objects) != 5 { - c.Errorf("%s: Expected length of objects to be %d, instead found to be %d", instanceType, 5, len(result.Objects)) + t.Errorf("%s: Expected length of objects to be %d, instead found to be %d", instanceType, 5, len(result.Objects)) } if !result.IsTruncated { - c.Errorf("%s: Expected IsTruncated to be `true`, but instead found it to be `%v`", instanceType, result.IsTruncated) + t.Errorf("%s: Expected IsTruncated to be `true`, but instead found it to be `%v`", instanceType, result.IsTruncated) } } // check paging with prefix at end returns less objects. { _, err = obj.PutObject("bucket", "newPrefix", NewHashReader(bytes.NewBufferString(uploadContent), int64(len(uploadContent)), "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } _, err = obj.PutObject("bucket", "newPrefix2", NewHashReader(bytes.NewBufferString(uploadContent), int64(len(uploadContent)), "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } result, err = obj.ListObjects("bucket", "new", "", "", 5) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(result.Objects) != 2 { - c.Errorf("%s: Expected length of objects to be %d, instead found to be %d", instanceType, 2, len(result.Objects)) + t.Errorf("%s: Expected length of objects to be %d, instead found to be %d", instanceType, 2, len(result.Objects)) } } @@ -309,22 +306,22 @@ func testPaging(obj ObjectLayer, instanceType string, c TestErrHandler) { { result, err = obj.ListObjects("bucket", "", "", "", 1000) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if result.Objects[0].Name != "newPrefix" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[0].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[0].Name) } if result.Objects[1].Name != "newPrefix2" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[1].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[1].Name) } if result.Objects[2].Name != "obj0" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[2].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[2].Name) } if result.Objects[3].Name != "obj1" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[3].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[3].Name) } if result.Objects[4].Name != "obj10" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[4].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[4].Name) } } @@ -332,21 +329,21 @@ func testPaging(obj ObjectLayer, instanceType string, c TestErrHandler) { { _, err = obj.PutObject("bucket", "this/is/delimited", NewHashReader(bytes.NewBufferString(uploadContent), int64(len(uploadContent)), "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } _, err = obj.PutObject("bucket", "this/is/also/a/delimited/file", NewHashReader(bytes.NewBufferString(uploadContent), int64(len(uploadContent)), "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } result, err = obj.ListObjects("bucket", "this/is/", "", "/", 10) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(result.Objects) != 1 { - c.Errorf("%s: Expected the number of objects in the result to be %d, but instead found %d", instanceType, 1, len(result.Objects)) + t.Errorf("%s: Expected the number of objects in the result to be %d, but instead found %d", instanceType, 1, len(result.Objects)) } if result.Prefixes[0] != "this/is/also/" { - c.Errorf("%s: Expected prefix to be `%s`, but instead found `%s`", instanceType, "this/is/also/", result.Prefixes[0]) + t.Errorf("%s: Expected prefix to be `%s`, but instead found `%s`", instanceType, "this/is/also/", result.Prefixes[0]) } } @@ -354,26 +351,26 @@ func testPaging(obj ObjectLayer, instanceType string, c TestErrHandler) { { result, err = obj.ListObjects("bucket", "", "", "/", 1000) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if result.Objects[0].Name != "newPrefix" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[0].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[0].Name) } if result.Objects[1].Name != "newPrefix2" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[1].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[1].Name) } if result.Objects[2].Name != "obj0" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[2].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[2].Name) } if result.Objects[3].Name != "obj1" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[3].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[3].Name) } if result.Objects[4].Name != "obj10" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[4].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[4].Name) } if result.Prefixes[0] != "this/" { - c.Errorf("%s: Expected the prefix to be `%s`, but instead found `%s`", instanceType, "this/", result.Prefixes[0]) + t.Errorf("%s: Expected the prefix to be `%s`, but instead found `%s`", instanceType, "this/", result.Prefixes[0]) } } @@ -382,181 +379,181 @@ func testPaging(obj ObjectLayer, instanceType string, c TestErrHandler) { result, err = obj.ListObjects("bucket", "", "newPrefix", "", 3) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if result.Objects[0].Name != "newPrefix2" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix2", result.Objects[0].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix2", result.Objects[0].Name) } if result.Objects[1].Name != "obj0" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj0", result.Objects[1].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj0", result.Objects[1].Name) } if result.Objects[2].Name != "obj1" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj1", result.Objects[2].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj1", result.Objects[2].Name) } } // check ordering of results with prefix. { result, err = obj.ListObjects("bucket", "obj", "", "", 1000) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if result.Objects[0].Name != "obj0" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj0", result.Objects[0].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj0", result.Objects[0].Name) } if result.Objects[1].Name != "obj1" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj1", result.Objects[1].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj1", result.Objects[1].Name) } if result.Objects[2].Name != "obj10" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj10", result.Objects[2].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj10", result.Objects[2].Name) } if result.Objects[3].Name != "obj2" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj2", result.Objects[3].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj2", result.Objects[3].Name) } if result.Objects[4].Name != "obj3" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj3", result.Objects[4].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "obj3", result.Objects[4].Name) } } // check ordering of results with prefix and no paging. { result, err = obj.ListObjects("bucket", "new", "", "", 5) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if result.Objects[0].Name != "newPrefix" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[0].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix", result.Objects[0].Name) } if result.Objects[1].Name != "newPrefix2" { - c.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix2", result.Objects[0].Name) + t.Errorf("%s: Expected the object name to be `%s`, but instead found `%s`", instanceType, "newPrefix2", result.Objects[0].Name) } } } // Wrapper for calling testObjectOverwriteWorks for both XL and FS. -func (s *ObjectLayerAPISuite) TestObjectOverwriteWorks(c *C) { - ExecObjectLayerTest(c, testObjectOverwriteWorks) +func (s *ObjectLayerAPISuite) TestObjectOverwriteWorks(t *testing.T) { + ExecObjectLayerTest(t, testObjectOverwriteWorks) } // Tests validate overwriting of an existing object. -func testObjectOverwriteWorks(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testObjectOverwriteWorks(obj ObjectLayer, instanceType string, t TestErrHandler) { err := obj.MakeBucketWithLocation("bucket", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } uploadContent := "The list of parts was not in ascending order. The parts list must be specified in order by part number." length := int64(len(uploadContent)) _, err = obj.PutObject("bucket", "object", NewHashReader(bytes.NewBufferString(uploadContent), length, "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } uploadContent = "The specified multipart upload does not exist. The upload ID might be invalid, or the multipart upload might have been aborted or completed." length = int64(len(uploadContent)) _, err = obj.PutObject("bucket", "object", NewHashReader(bytes.NewBufferString(uploadContent), length, "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } var bytesBuffer bytes.Buffer err = obj.GetObject("bucket", "object", 0, length, &bytesBuffer) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if string(bytesBuffer.Bytes()) != "The specified multipart upload does not exist. The upload ID might be invalid, or the multipart upload might have been aborted or completed." { - c.Errorf("%s: Invalid upload ID error mismatch.", instanceType) + t.Errorf("%s: Invalid upload ID error mismatch.", instanceType) } } // Wrapper for calling testNonExistantBucketOperations for both XL and FS. -func (s *ObjectLayerAPISuite) TestNonExistantBucketOperations(c *C) { - ExecObjectLayerTest(c, testNonExistantBucketOperations) +func (s *ObjectLayerAPISuite) TestNonExistantBucketOperations(t *testing.T) { + ExecObjectLayerTest(t, testNonExistantBucketOperations) } // Tests validate that bucket operation on non-existent bucket fails. -func testNonExistantBucketOperations(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testNonExistantBucketOperations(obj ObjectLayer, instanceType string, t TestErrHandler) { _, err := obj.PutObject("bucket1", "object", NewHashReader(bytes.NewBufferString("one"), int64(len("one")), "", ""), nil) if err == nil { - c.Fatal("Expected error but found nil") + t.Fatal("Expected error but found nil") } if err.Error() != "Bucket not found: bucket1" { - c.Errorf("%s: Expected the error msg to be `%s`, but instead found `%s`", instanceType, "Bucket not found: bucket1", err.Error()) + t.Errorf("%s: Expected the error msg to be `%s`, but instead found `%s`", instanceType, "Bucket not found: bucket1", err.Error()) } } // Wrapper for calling testBucketRecreateFails for both XL and FS. -func (s *ObjectLayerAPISuite) TestBucketRecreateFails(c *C) { - ExecObjectLayerTest(c, testBucketRecreateFails) +func (s *ObjectLayerAPISuite) TestBucketRecreateFails(t *testing.T) { + ExecObjectLayerTest(t, testBucketRecreateFails) } // Tests validate that recreation of the bucket fails. -func testBucketRecreateFails(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testBucketRecreateFails(obj ObjectLayer, instanceType string, t TestErrHandler) { err := obj.MakeBucketWithLocation("string", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } err = obj.MakeBucketWithLocation("string", "") if err == nil { - c.Fatalf("%s: Expected error but found nil.", instanceType) + t.Fatalf("%s: Expected error but found nil.", instanceType) } if err.Error() != "Bucket exists: string" { - c.Errorf("%s: Expected the error message to be `%s`, but instead found `%s`", instanceType, "Bucket exists: string", err.Error()) + t.Errorf("%s: Expected the error message to be `%s`, but instead found `%s`", instanceType, "Bucket exists: string", err.Error()) } } // Wrapper for calling testPutObject for both XL and FS. -func (s *ObjectLayerAPISuite) TestPutObject(c *C) { - ExecObjectLayerTest(c, testPutObject) +func (s *ObjectLayerAPISuite) TestPutObject(t *testing.T) { + ExecObjectLayerTest(t, testPutObject) } // Tests validate PutObject without prefix. -func testPutObject(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testPutObject(obj ObjectLayer, instanceType string, t TestErrHandler) { content := []byte("testcontent") length := int64(len(content)) readerEOF := newTestReaderEOF(content) readerNoEOF := newTestReaderNoEOF(content) err := obj.MakeBucketWithLocation("bucket", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } var bytesBuffer1 bytes.Buffer _, err = obj.PutObject("bucket", "object", NewHashReader(readerEOF, length, "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } err = obj.GetObject("bucket", "object", 0, length, &bytesBuffer1) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(bytesBuffer1.Bytes()) != len(content) { - c.Errorf("%s: Expected content length to be `%d`, but instead found `%d`", instanceType, len(content), len(bytesBuffer1.Bytes())) + t.Errorf("%s: Expected content length to be `%d`, but instead found `%d`", instanceType, len(content), len(bytesBuffer1.Bytes())) } var bytesBuffer2 bytes.Buffer _, err = obj.PutObject("bucket", "object", NewHashReader(readerNoEOF, length, "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } err = obj.GetObject("bucket", "object", 0, length, &bytesBuffer2) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(bytesBuffer2.Bytes()) != len(content) { - c.Errorf("%s: Expected content length to be `%d`, but instead found `%d`", instanceType, len(content), len(bytesBuffer2.Bytes())) + t.Errorf("%s: Expected content length to be `%d`, but instead found `%d`", instanceType, len(content), len(bytesBuffer2.Bytes())) } } // Wrapper for calling testPutObjectInSubdir for both XL and FS. -func (s *ObjectLayerAPISuite) TestPutObjectInSubdir(c *C) { - ExecObjectLayerTest(c, testPutObjectInSubdir) +func (s *ObjectLayerAPISuite) TestPutObjectInSubdir(t *testing.T) { + ExecObjectLayerTest(t, testPutObjectInSubdir) } // Tests validate PutObject with subdirectory prefix. -func testPutObjectInSubdir(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testPutObjectInSubdir(obj ObjectLayer, instanceType string, t TestErrHandler) { err := obj.MakeBucketWithLocation("bucket", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } uploadContent := `The specified multipart upload does not exist. The upload ID might be invalid, or the multipart @@ -564,180 +561,180 @@ func testPutObjectInSubdir(obj ObjectLayer, instanceType string, c TestErrHandle length := int64(len(uploadContent)) _, err = obj.PutObject("bucket", "dir1/dir2/object", NewHashReader(bytes.NewBufferString(uploadContent), length, "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } var bytesBuffer bytes.Buffer err = obj.GetObject("bucket", "dir1/dir2/object", 0, length, &bytesBuffer) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(bytesBuffer.Bytes()) != len(uploadContent) { - c.Errorf("%s: Expected length of downloaded data to be `%d`, but instead found `%d`", + t.Errorf("%s: Expected length of downloaded data to be `%d`, but instead found `%d`", instanceType, len(uploadContent), len(bytesBuffer.Bytes())) } } // Wrapper for calling testListBuckets for both XL and FS. -func (s *ObjectLayerAPISuite) TestListBuckets(c *C) { - ExecObjectLayerTest(c, testListBuckets) +func (s *ObjectLayerAPISuite) TestListBuckets(t *testing.T) { + ExecObjectLayerTest(t, testListBuckets) } // Tests validate ListBuckets. -func testListBuckets(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testListBuckets(obj ObjectLayer, instanceType string, t TestErrHandler) { // test empty list. buckets, err := obj.ListBuckets() if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(buckets) != 0 { - c.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 0, len(buckets)) + t.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 0, len(buckets)) } // add one and test exists. err = obj.MakeBucketWithLocation("bucket1", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } buckets, err = obj.ListBuckets() if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(buckets) != 1 { - c.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 1, len(buckets)) + t.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 1, len(buckets)) } // add two and test exists. err = obj.MakeBucketWithLocation("bucket2", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } buckets, err = obj.ListBuckets() if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(buckets) != 2 { - c.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 2, len(buckets)) + t.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 2, len(buckets)) } // add three and test exists + prefix. err = obj.MakeBucketWithLocation("bucket22", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } buckets, err = obj.ListBuckets() if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(buckets) != 3 { - c.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 3, len(buckets)) + t.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 3, len(buckets)) } } // Wrapper for calling testListBucketsOrder for both XL and FS. -func (s *ObjectLayerAPISuite) TestListBucketsOrder(c *C) { - ExecObjectLayerTest(c, testListBucketsOrder) +func (s *ObjectLayerAPISuite) TestListBucketsOrder(t *testing.T) { + ExecObjectLayerTest(t, testListBucketsOrder) } // Tests validate the order of result of ListBuckets. -func testListBucketsOrder(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testListBucketsOrder(obj ObjectLayer, instanceType string, t TestErrHandler) { // if implementation contains a map, order of map keys will vary. // this ensures they return in the same order each time. // add one and test exists. err := obj.MakeBucketWithLocation("bucket1", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } err = obj.MakeBucketWithLocation("bucket2", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } buckets, err := obj.ListBuckets() if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if len(buckets) != 2 { - c.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 2, len(buckets)) + t.Errorf("%s: Expected number of bucket to be `%d`, but instead found `%d`", instanceType, 2, len(buckets)) } if buckets[0].Name != "bucket1" { - c.Errorf("%s: Expected bucket name to be `%s`, but instead found `%s`", instanceType, "bucket1", buckets[0].Name) + t.Errorf("%s: Expected bucket name to be `%s`, but instead found `%s`", instanceType, "bucket1", buckets[0].Name) } if buckets[1].Name != "bucket2" { - c.Errorf("%s: Expected bucket name to be `%s`, but instead found `%s`", instanceType, "bucket2", buckets[1].Name) + t.Errorf("%s: Expected bucket name to be `%s`, but instead found `%s`", instanceType, "bucket2", buckets[1].Name) } } // Wrapper for calling testListObjectsTestsForNonExistantBucket for both XL and FS. -func (s *ObjectLayerAPISuite) TestListObjectsTestsForNonExistantBucket(c *C) { - ExecObjectLayerTest(c, testListObjectsTestsForNonExistantBucket) +func (s *ObjectLayerAPISuite) TestListObjectsTestsForNonExistantBucket(t *testing.T) { + ExecObjectLayerTest(t, testListObjectsTestsForNonExistantBucket) } // Tests validate that ListObjects operation on a non-existent bucket fails as expected. -func testListObjectsTestsForNonExistantBucket(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testListObjectsTestsForNonExistantBucket(obj ObjectLayer, instanceType string, t TestErrHandler) { result, err := obj.ListObjects("bucket", "", "", "", 1000) if err == nil { - c.Fatalf("%s: Expected error but found nil.", instanceType) + t.Fatalf("%s: Expected error but found nil.", instanceType) } if len(result.Objects) != 0 { - c.Fatalf("%s: Expected number of objects in the result to be `%d`, but instead found `%d`", instanceType, 0, len(result.Objects)) + t.Fatalf("%s: Expected number of objects in the result to be `%d`, but instead found `%d`", instanceType, 0, len(result.Objects)) } if result.IsTruncated { - c.Fatalf("%s: Expected IsTruncated to be `false`, but instead found it to be `%v`", instanceType, result.IsTruncated) + t.Fatalf("%s: Expected IsTruncated to be `false`, but instead found it to be `%v`", instanceType, result.IsTruncated) } if err.Error() != "Bucket not found: bucket" { - c.Errorf("%s: Expected the error msg to be `%s`, but instead found `%s`", instanceType, "Bucket not found: bucket", err.Error()) + t.Errorf("%s: Expected the error msg to be `%s`, but instead found `%s`", instanceType, "Bucket not found: bucket", err.Error()) } } // Wrapper for calling testNonExistantObjectInBucket for both XL and FS. -func (s *ObjectLayerAPISuite) TestNonExistantObjectInBucket(c *C) { - ExecObjectLayerTest(c, testNonExistantObjectInBucket) +func (s *ObjectLayerAPISuite) TestNonExistantObjectInBucket(t *testing.T) { + ExecObjectLayerTest(t, testNonExistantObjectInBucket) } // Tests validate that GetObject fails on a non-existent bucket as expected. -func testNonExistantObjectInBucket(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testNonExistantObjectInBucket(obj ObjectLayer, instanceType string, t TestErrHandler) { err := obj.MakeBucketWithLocation("bucket", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } _, err = obj.GetObjectInfo("bucket", "dir1") if err == nil { - c.Fatalf("%s: Expected error but found nil", instanceType) + t.Fatalf("%s: Expected error but found nil", instanceType) } if isErrObjectNotFound(err) { if err.Error() != "Object not found: bucket#dir1" { - c.Errorf("%s: Expected the Error message to be `%s`, but instead found `%s`", instanceType, "Object not found: bucket#dir1", err.Error()) + t.Errorf("%s: Expected the Error message to be `%s`, but instead found `%s`", instanceType, "Object not found: bucket#dir1", err.Error()) } } else { if err.Error() != "fails" { - c.Errorf("%s: Expected the Error message to be `%s`, but instead found it to be `%s`", instanceType, "fails", err.Error()) + t.Errorf("%s: Expected the Error message to be `%s`, but instead found it to be `%s`", instanceType, "fails", err.Error()) } } } // Wrapper for calling testGetDirectoryReturnsObjectNotFound for both XL and FS. -func (s *ObjectLayerAPISuite) TestGetDirectoryReturnsObjectNotFound(c *C) { - ExecObjectLayerTest(c, testGetDirectoryReturnsObjectNotFound) +func (s *ObjectLayerAPISuite) TestGetDirectoryReturnsObjectNotFound(t *testing.T) { + ExecObjectLayerTest(t, testGetDirectoryReturnsObjectNotFound) } // Tests validate that GetObject on an existing directory fails as expected. -func testGetDirectoryReturnsObjectNotFound(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testGetDirectoryReturnsObjectNotFound(obj ObjectLayer, instanceType string, t TestErrHandler) { bucketName := "bucket" err := obj.MakeBucketWithLocation(bucketName, "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } content := "One or more of the specified parts could not be found. The part might not have been uploaded, or the specified entity tag might not have matched the part's entity tag." length := int64(len(content)) _, err = obj.PutObject(bucketName, "dir1/dir3/object", NewHashReader(bytes.NewBufferString(content), length, "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } testCases := []struct { @@ -759,35 +756,35 @@ func testGetDirectoryReturnsObjectNotFound(obj ObjectLayer, instanceType string, if expectedErr != nil { expectedErr = errorCause(expectedErr) if expectedErr.Error() != testCase.err.Error() { - c.Errorf("Test %d, %s: Expected error %s, got %s", i+1, instanceType, testCase.err, expectedErr) + t.Errorf("Test %d, %s: Expected error %s, got %s", i+1, instanceType, testCase.err, expectedErr) } } } } // Wrapper for calling testContentType for both XL and FS. -func (s *ObjectLayerAPISuite) TestContentType(c *C) { - ExecObjectLayerTest(c, testContentType) +func (s *ObjectLayerAPISuite) TestContentType(t *testing.T) { + ExecObjectLayerTest(t, testContentType) } // Test content-type. -func testContentType(obj ObjectLayer, instanceType string, c TestErrHandler) { +func testContentType(obj ObjectLayer, instanceType string, t TestErrHandler) { err := obj.MakeBucketWithLocation("bucket", "") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } uploadContent := "The specified multipart upload does not exist. The upload ID might be invalid, or the multipart upload might have been aborted or completed." // Test empty. _, err = obj.PutObject("bucket", "minio.png", NewHashReader(bytes.NewBufferString(uploadContent), int64(len(uploadContent)), "", ""), nil) if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } objInfo, err := obj.GetObjectInfo("bucket", "minio.png") if err != nil { - c.Fatalf("%s: %s", instanceType, err) + t.Fatalf("%s: %s", instanceType, err) } if objInfo.ContentType != "image/png" { - c.Errorf("%s: Expected Content type to be `%s`, but instead found `%s`", instanceType, "image/png", objInfo.ContentType) + t.Errorf("%s: Expected Content type to be `%s`, but instead found `%s`", instanceType, "image/png", objInfo.ContentType) } } diff --git a/cmd/server_test.go b/cmd/server_test.go index 8dd59b54c..6442660e0 100644 --- a/cmd/server_test.go +++ b/cmd/server_test.go @@ -27,13 +27,13 @@ import ( "math/rand" "net/http" "net/url" + "reflect" "strings" "sync" + "testing" "time" humanize "github.com/dustin/go-humanize" - - . "gopkg.in/check.v1" ) // API suite container common to both FS and XL. @@ -48,35 +48,101 @@ type TestSuiteCommon struct { transport *http.Transport } -// Init and run test on FS backend. -var _ = Suite(&TestSuiteCommon{serverType: "FS", signer: signerV4}) - -// Init and run test on FS backend with AWS signature v2. -var _ = Suite(&TestSuiteCommon{serverType: "FS", signer: signerV2}) - -// Init and run test on FS backend, with tls enabled. -var _ = Suite(&TestSuiteCommon{serverType: "FS", signer: signerV4, secure: true}) +type check struct { + *testing.T + testType string +} -// Init and run test on XL backend. -var _ = Suite(&TestSuiteCommon{serverType: "XL", signer: signerV4}) +// Assert - checks if gotValue is same as expectedValue, if not fails the test. +func (c *check) Assert(gotValue interface{}, expectedValue interface{}) { + if !reflect.DeepEqual(gotValue, expectedValue) { + c.Fatalf("Test %s: expected %v, got %v", c.testType, expectedValue, gotValue) + } +} -func verifyError(c *C, response *http.Response, code, description string, statusCode int) { +func verifyError(c *check, response *http.Response, code, description string, statusCode int) { data, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) errorResponse := APIErrorResponse{} err = xml.Unmarshal(data, &errorResponse) - c.Assert(err, IsNil) - c.Assert(errorResponse.Code, Equals, code) - c.Assert(errorResponse.Message, Equals, description) - c.Assert(response.StatusCode, Equals, statusCode) + c.Assert(err, nil) + c.Assert(errorResponse.Code, code) + c.Assert(errorResponse.Message, description) + c.Assert(response.StatusCode, statusCode) +} + +func runAllTests(suite *TestSuiteCommon, c *check) { + suite.SetUpSuite(c) + suite.TestBucketSQSNotificationWebHook(c) + suite.TestObjectDir(c) + suite.TestBucketSQSNotificationAMQP(c) + suite.TestBucketPolicy(c) + suite.TestDeleteBucket(c) + suite.TestDeleteBucketNotEmpty(c) + suite.TestListenBucketNotificationHandler(c) + suite.TestDeleteMultipleObjects(c) + suite.TestDeleteObject(c) + suite.TestNonExistentBucket(c) + suite.TestEmptyObject(c) + suite.TestBucket(c) + suite.TestObjectGetAnonymous(c) + suite.TestObjectGet(c) + suite.TestMultipleObjects(c) + suite.TestNotImplemented(c) + suite.TestHeader(c) + suite.TestPutBucket(c) + suite.TestCopyObject(c) + suite.TestPutObject(c) + suite.TestListBuckets(c) + suite.TestValidateSignature(c) + suite.TestSHA256Mismatch(c) + suite.TestPutObjectLongName(c) + suite.TestNotBeAbleToCreateObjectInNonexistentBucket(c) + suite.TestHeadOnObjectLastModified(c) + suite.TestHeadOnBucket(c) + suite.TestContentTypePersists(c) + suite.TestPartialContent(c) + suite.TestListObjectsHandler(c) + suite.TestListObjectsHandlerErrors(c) + suite.TestPutBucketErrors(c) + suite.TestGetObjectLarge10MiB(c) + suite.TestGetObjectLarge11MiB(c) + suite.TestGetPartialObjectMisAligned(c) + suite.TestGetPartialObjectLarge11MiB(c) + suite.TestGetPartialObjectLarge10MiB(c) + suite.TestGetObjectErrors(c) + suite.TestGetObjectRangeErrors(c) + suite.TestObjectMultipartAbort(c) + suite.TestBucketMultipartList(c) + suite.TestValidateObjectMultipartUploadID(c) + suite.TestObjectMultipartListError(c) + suite.TestObjectValidMD5(c) + suite.TestObjectMultipart(c) + suite.TearDownSuite(c) +} + +func TestServerSuite(t *testing.T) { + testCases := []*TestSuiteCommon{ + // Init and run test on FS backend with signature v4. + &TestSuiteCommon{serverType: "FS", signer: signerV4}, + // Init and run test on FS backend with signature v2. + &TestSuiteCommon{serverType: "FS", signer: signerV2}, + // Init and run test on FS backend, with tls enabled. + &TestSuiteCommon{serverType: "FS", signer: signerV4, secure: true}, + // Init and run test on XL backend. + &TestSuiteCommon{serverType: "XL", signer: signerV4}, + } + for _, testCase := range testCases { + runAllTests(testCase, &check{t, testCase.serverType}) + } } // Setting up the test suite. // Starting the Test server with temporary FS backend. -func (s *TestSuiteCommon) SetUpSuite(c *C) { +func (s *TestSuiteCommon) SetUpSuite(c *check) { if s.secure { cert, key, err := generateTLSCertKey("127.0.0.1") - c.Assert(err, IsNil) + c.Assert(err, nil) s.testServer = StartTestTLSServer(c, s.serverType, cert, key) @@ -100,11 +166,11 @@ func (s *TestSuiteCommon) SetUpSuite(c *C) { } // Called implicitly by "gopkg.in/check.v1" after all tests are run. -func (s *TestSuiteCommon) TearDownSuite(c *C) { +func (s *TestSuiteCommon) TearDownSuite(c *check) { s.testServer.Stop() } -func (s *TestSuiteCommon) TestBucketSQSNotificationWebHook(c *C) { +func (s *TestSuiteCommon) TestBucketSQSNotificationWebHook(c *check) { // Sample bucket notification. bucketNotificationBuf := `s3:ObjectCreated:Putprefiximages/1arn:minio:sqs:us-east-1:444455556666:webhook` // generate a random bucket Name. @@ -112,58 +178,58 @@ func (s *TestSuiteCommon) TestBucketSQSNotificationWebHook(c *C) { // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) request, err = newTestSignedRequest("PUT", getPutNotificationURL(s.endPoint, bucketName), int64(len(bucketNotificationBuf)), bytes.NewReader([]byte(bucketNotificationBuf)), s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "InvalidArgument", "A specified destination ARN does not exist or is not well-formed. Verify the destination ARN.", http.StatusBadRequest) } -func (s *TestSuiteCommon) TestObjectDir(c *C) { +func (s *TestSuiteCommon) TestObjectDir(c *check) { bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, "my-object-directory/"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, "my-object-directory/"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) helloReader := bytes.NewReader([]byte("Hello, World")) request.ContentLength = helloReader.Size() @@ -173,44 +239,44 @@ func (s *TestSuiteCommon) TestObjectDir(c *C) { // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "XMinioInvalidObjectName", "Object name contains unsupported characters.", http.StatusBadRequest) request, err = newTestSignedRequest("HEAD", getHeadObjectURL(s.endPoint, bucketName, "my-object-directory/"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusNotFound) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusNotFound) request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, "my-object-directory/"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusNotFound) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusNotFound) request, err = newTestSignedRequest("DELETE", getDeleteObjectURL(s.endPoint, bucketName, "my-object-directory/"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusNoContent) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusNoContent) } -func (s *TestSuiteCommon) TestBucketSQSNotificationAMQP(c *C) { +func (s *TestSuiteCommon) TestBucketSQSNotificationAMQP(c *check) { // Sample bucket notification. bucketNotificationBuf := `s3:ObjectCreated:Putprefiximages/1arn:minio:sqs:us-east-1:444455556666:amqp` // generate a random bucket Name. @@ -218,31 +284,31 @@ func (s *TestSuiteCommon) TestBucketSQSNotificationAMQP(c *C) { // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) request, err = newTestSignedRequest("PUT", getPutNotificationURL(s.endPoint, bucketName), int64(len(bucketNotificationBuf)), bytes.NewReader([]byte(bucketNotificationBuf)), s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "InvalidArgument", "A specified destination ARN does not exist or is not well-formed. Verify the destination ARN.", http.StatusBadRequest) } // TestBucketPolicy - Inserts the bucket policy and verifies it by fetching the policy back. // Deletes the policy and verifies the deletion by fetching it back. -func (s *TestSuiteCommon) TestBucketPolicy(c *C) { +func (s *TestSuiteCommon) TestBucketPolicy(c *check) { // Sample bucket policy. bucketPolicyBuf := `{"Version":"2012-10-17","Statement":[{"Action":["s3:GetBucketLocation","s3:ListBucket"],"Effect":"Allow","Principal":{"AWS":["*"]},"Resource":["arn:aws:s3:::%s"],"Sid":""},{"Action":["s3:GetObject"],"Effect":"Allow","Principal":{"AWS":["*"]},"Resource":["arn:aws:s3:::%s/this*"],"Sid":""}]}` @@ -253,148 +319,148 @@ func (s *TestSuiteCommon) TestBucketPolicy(c *C) { // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) /// Put a new bucket policy. request, err = newTestSignedRequest("PUT", getPutPolicyURL(s.endPoint, bucketName), int64(len(bucketPolicyStr)), bytes.NewReader([]byte(bucketPolicyStr)), s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusNoContent) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusNoContent) // Fetch the uploaded policy. request, err = newTestSignedRequest("GET", getGetPolicyURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) bucketPolicyReadBuf, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) // Verify if downloaded policy matches with previousy uploaded. - c.Assert(bytes.Equal([]byte(bucketPolicyStr), bucketPolicyReadBuf), Equals, true) + c.Assert(bytes.Equal([]byte(bucketPolicyStr), bucketPolicyReadBuf), true) // Delete policy. request, err = newTestSignedRequest("DELETE", getDeletePolicyURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusNoContent) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusNoContent) // Verify if the policy was indeed deleted. request, err = newTestSignedRequest("GET", getGetPolicyURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusNotFound) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusNotFound) } // TestDeleteBucket - validates DELETE bucket operation. -func (s *TestSuiteCommon) TestDeleteBucket(c *C) { +func (s *TestSuiteCommon) TestDeleteBucket(c *check) { bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // construct request to delete the bucket. request, err = newTestSignedRequest("DELETE", getDeleteBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Assert the response status code. - c.Assert(response.StatusCode, Equals, http.StatusNoContent) + c.Assert(response.StatusCode, http.StatusNoContent) } // TestDeleteBucketNotEmpty - Validates the operation during an attempt to delete a non-empty bucket. -func (s *TestSuiteCommon) TestDeleteBucketNotEmpty(c *C) { +func (s *TestSuiteCommon) TestDeleteBucketNotEmpty(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // generate http request for an object upload. // "test-object" is the object name. objectName := "test-object" request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the request to complete object upload. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the status code of the response. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // constructing http request to delete the bucket. // making an attempt to delete an non-empty bucket. // expected to fail. request, err = newTestSignedRequest("DELETE", getDeleteBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusConflict) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusConflict) } -func (s *TestSuiteCommon) TestListenBucketNotificationHandler(c *C) { +func (s *TestSuiteCommon) TestListenBucketNotificationHandler(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. req, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the request. response, err := client.Do(req) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) invalidBucket := "Invalid\\Bucket" tooByte := bytes.Repeat([]byte("a"), 1025) @@ -405,45 +471,45 @@ func (s *TestSuiteCommon) TestListenBucketNotificationHandler(c *C) { req, err = newTestSignedRequest("GET", getListenBucketNotificationURL(s.endPoint, invalidBucket, []string{}, []string{}, []string{}), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the request. response, err = client.Do(req) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "InvalidBucketName", "The specified bucket is not valid.", http.StatusBadRequest) req, err = newTestSignedRequest("GET", getListenBucketNotificationURL(s.endPoint, bucketName, []string{}, []string{}, invalidEvents), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the request. response, err = client.Do(req) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "InvalidArgument", "A specified event is not supported for notifications.", http.StatusBadRequest) req, err = newTestSignedRequest("GET", getListenBucketNotificationURL(s.endPoint, bucketName, []string{tooBigPrefix}, []string{}, validEvents), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the request. response, err = client.Do(req) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "InvalidArgument", "Size of filter rule value cannot exceed 1024 bytes in UTF-8 representation", http.StatusBadRequest) req, err = newTestSignedBadSHARequest("GET", getListenBucketNotificationURL(s.endPoint, bucketName, []string{}, []string{}, validEvents), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the request. response, err = client.Do(req) - c.Assert(err, IsNil) + c.Assert(err, nil) if s.signer == signerV4 { verifyError(c, response, "XAmzContentSHA256Mismatch", "The provided 'x-amz-content-sha256' header does not match what was computed.", http.StatusBadRequest) } @@ -453,12 +519,12 @@ func (s *TestSuiteCommon) TestListenBucketNotificationHandler(c *C) { req, err = newTestSignedRequest("GET", getListenBucketNotificationURL(s.endPoint, bucketName, []string{}, []string{}, validEvents), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the request. response, err = client.Do(req) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // FIXME: uncomment this in future when we have a code to read notifications from. // go func() { // buf := bytes.NewReader(tooByte) @@ -470,26 +536,26 @@ func (s *TestSuiteCommon) TestListenBucketNotificationHandler(c *C) { // // execute the request. // resp, rerr := client.Do(rreq) // c.Assert(rerr, IsNil) - // c.Assert(resp.StatusCode, Equals, http.StatusOK) + // c.Assert(resp.StatusCode, http.StatusOK) // }() response.Body.Close() // FIXME. Find a way to read from the returned body. } // Test deletes multple objects and verifies server resonse. -func (s *TestSuiteCommon) TestDeleteMultipleObjects(c *C) { +func (s *TestSuiteCommon) TestDeleteMultipleObjects(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) objectName := "prefix/myobject" delObjReq := DeleteObjectsRequest{ @@ -501,14 +567,14 @@ func (s *TestSuiteCommon) TestDeleteMultipleObjects(c *C) { objName := fmt.Sprintf("%d/%s", i, objectName) request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the http request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the status of http response. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // Append all objects. delObjReq.Objects = append(delObjReq.Objects, ObjectIdentifier{ ObjectName: objName, @@ -516,286 +582,286 @@ func (s *TestSuiteCommon) TestDeleteMultipleObjects(c *C) { } // Marshal delete request. deleteReqBytes, err := xml.Marshal(delObjReq) - c.Assert(err, IsNil) + c.Assert(err, nil) // Delete list of objects. request, err = newTestSignedRequest("POST", getMultiDeleteObjectURL(s.endPoint, bucketName), int64(len(deleteReqBytes)), bytes.NewReader(deleteReqBytes), s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) var deleteResp = DeleteObjectsResponse{} delRespBytes, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) err = xml.Unmarshal(delRespBytes, &deleteResp) - c.Assert(err, IsNil) + c.Assert(err, nil) for i := 0; i < 10; i++ { // All the objects should be under deleted list (including non-existent object) - c.Assert(deleteResp.DeletedObjects[i], DeepEquals, delObjReq.Objects[i]) + c.Assert(deleteResp.DeletedObjects[i], delObjReq.Objects[i]) } - c.Assert(len(deleteResp.Errors), Equals, 0) + c.Assert(len(deleteResp.Errors), 0) // Attempt second time results should be same, NoSuchKey for objects not found // shouldn't be set. request, err = newTestSignedRequest("POST", getMultiDeleteObjectURL(s.endPoint, bucketName), int64(len(deleteReqBytes)), bytes.NewReader(deleteReqBytes), s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) deleteResp = DeleteObjectsResponse{} delRespBytes, err = ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) err = xml.Unmarshal(delRespBytes, &deleteResp) - c.Assert(err, IsNil) + c.Assert(err, nil) for i := 0; i < 10; i++ { - c.Assert(deleteResp.DeletedObjects[i], DeepEquals, delObjReq.Objects[i]) + c.Assert(deleteResp.DeletedObjects[i], delObjReq.Objects[i]) } - c.Assert(len(deleteResp.Errors), Equals, 0) + c.Assert(len(deleteResp.Errors), 0) } // Tests delete object responses and success. -func (s *TestSuiteCommon) TestDeleteObject(c *C) { +func (s *TestSuiteCommon) TestDeleteObject(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) objectName := "prefix/myobject" // obtain http request to upload object. // object Name contains a prefix. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the http request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the status of http response. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // object name was "prefix/myobject", an attempt to delelte "prefix" // Should not delete "prefix/myobject" request, err = newTestSignedRequest("DELETE", getDeleteObjectURL(s.endPoint, bucketName, "prefix"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusNoContent) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusNoContent) // create http request to HEAD on the object. // this helps to validate the existence of the bucket. request, err = newTestSignedRequest("HEAD", getHeadObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Assert the HTTP response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // create HTTP request to delete the object. request, err = newTestSignedRequest("DELETE", getDeleteObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the http request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusNoContent) + c.Assert(response.StatusCode, http.StatusNoContent) // Delete of non-existent data should return success. request, err = newTestSignedRequest("DELETE", getDeleteObjectURL(s.endPoint, bucketName, "prefix/myobject1"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the http request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status. - c.Assert(response.StatusCode, Equals, http.StatusNoContent) + c.Assert(response.StatusCode, http.StatusNoContent) } // TestNonExistentBucket - Asserts response for HEAD on non-existent bucket. -func (s *TestSuiteCommon) TestNonExistentBucket(c *C) { +func (s *TestSuiteCommon) TestNonExistentBucket(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // create request to HEAD on the bucket. // HEAD on an bucket helps validate the existence of the bucket. request, err := newTestSignedRequest("HEAD", getHEADBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the http request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Assert the response. - c.Assert(response.StatusCode, Equals, http.StatusNotFound) + c.Assert(response.StatusCode, http.StatusNotFound) } // TestEmptyObject - Asserts the response for operation on a 0 byte object. -func (s *TestSuiteCommon) TestEmptyObject(c *C) { +func (s *TestSuiteCommon) TestEmptyObject(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the http request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) objectName := "test-object" // construct http request for uploading the object. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the upload request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // make HTTP request to fetch the object. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the http request to fetch object. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) var buffer bytes.Buffer // extract the body of the response. responseBody, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response body content. - c.Assert(true, Equals, bytes.Equal(responseBody, buffer.Bytes())) + c.Assert(true, bytes.Equal(responseBody, buffer.Bytes())) } -func (s *TestSuiteCommon) TestBucket(c *C) { +func (s *TestSuiteCommon) TestBucket(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) request, err = newTestSignedRequest("HEAD", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) } // Tests get anonymous object. -func (s *TestSuiteCommon) TestObjectGetAnonymous(c *C) { +func (s *TestSuiteCommon) TestObjectGetAnonymous(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() buffer := bytes.NewReader([]byte("hello world")) // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the make bucket http request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the response http status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) objectName := "testObject" // create HTTP request to upload the object. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer.Len()), buffer, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to upload the object. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the HTTP response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // initiate anonymous HTTP request to fetch the object which does not exist. We need to return AccessDenied. response, err = client.Get(getGetObjectURL(s.endPoint, bucketName, objectName+".1")) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. verifyError(c, response, "AccessDenied", "Access Denied.", http.StatusForbidden) // initiate anonymous HTTP request to fetch the object which does exist. We need to return AccessDenied. response, err = client.Get(getGetObjectURL(s.endPoint, bucketName, objectName)) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the http response status code. verifyError(c, response, "AccessDenied", "Access Denied.", http.StatusForbidden) } // TestGetObject - Tests fetching of a small object after its insertion into the bucket. -func (s *TestSuiteCommon) TestObjectGet(c *C) { +func (s *TestSuiteCommon) TestObjectGet(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() buffer := bytes.NewReader([]byte("hello world")) // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the make bucket http request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the response http status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) objectName := "testObject" // create HTTP request to upload the object. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer.Len()), buffer, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to upload the object. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the HTTP response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // concurrently reading the object, safety check for races. var wg sync.WaitGroup for i := 0; i < testConcurrencyLevel; i++ { @@ -806,21 +872,21 @@ func (s *TestSuiteCommon) TestObjectGet(c *C) { // create HTTP request to fetch the object. getRequest, err := newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) reqClient := http.Client{Transport: s.transport} // execute the http request to fetch the object. getResponse, err := reqClient.Do(getRequest) - c.Assert(err, IsNil) + c.Assert(err, nil) defer getResponse.Body.Close() // assert the http response status code. - c.Assert(getResponse.StatusCode, Equals, http.StatusOK) + c.Assert(getResponse.StatusCode, http.StatusOK) // extract response body content. responseBody, err := ioutil.ReadAll(getResponse.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the HTTP response body content with the expected content. - c.Assert(responseBody, DeepEquals, []byte("hello world")) + c.Assert(responseBody, []byte("hello world")) }() } @@ -828,31 +894,31 @@ func (s *TestSuiteCommon) TestObjectGet(c *C) { } // TestMultipleObjects - Validates upload and fetching of multiple object into the bucket. -func (s *TestSuiteCommon) TestMultipleObjects(c *C) { +func (s *TestSuiteCommon) TestMultipleObjects(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create the bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // constructing HTTP request to fetch a non-existent object. // expected to fail, error response asserted for expected error values later. objectName := "testObject" request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Asserting the error response with the expected values. verifyError(c, response, "NoSuchKey", "The specified key does not exist.", http.StatusNotFound) @@ -862,124 +928,124 @@ func (s *TestSuiteCommon) TestMultipleObjects(c *C) { // create HTTP request for the object upload. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request for object upload. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the returned values. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // create HTTP request to fetch the object which was uploaded above. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert whether 200 OK response status is obtained. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // extract the response body. responseBody, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the content body for the expected object data. - c.Assert(true, Equals, bytes.Equal(responseBody, []byte("hello one"))) + c.Assert(true, bytes.Equal(responseBody, []byte("hello one"))) // data for new object to be uploaded. buffer2 := bytes.NewReader([]byte("hello two")) objectName = "testObject2" request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer2.Len()), buffer2, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request for object upload. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the response status code for expected value 200 OK. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // fetch the object which was uploaded above. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to fetch the object. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // assert the response status code for expected value 200 OK. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // verify response data responseBody, err = ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) - c.Assert(true, Equals, bytes.Equal(responseBody, []byte("hello two"))) + c.Assert(err, nil) + c.Assert(true, bytes.Equal(responseBody, []byte("hello two"))) // data for new object to be uploaded. buffer3 := bytes.NewReader([]byte("hello three")) objectName = "testObject3" request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer3.Len()), buffer3, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // verify the response code with the expected value of 200 OK. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // fetch the object which was uploaded above. request, err = newTestSignedRequest("GET", getPutObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // verify object. responseBody, err = ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) - c.Assert(true, Equals, bytes.Equal(responseBody, []byte("hello three"))) + c.Assert(err, nil) + c.Assert(true, bytes.Equal(responseBody, []byte("hello three"))) } // TestNotImplemented - validates if object policy is implemented, should return 'NotImplemented'. -func (s *TestSuiteCommon) TestNotImplemented(c *C) { +func (s *TestSuiteCommon) TestNotImplemented(c *check) { // Generate a random bucket name. bucketName := getRandomBucketName() request, err := newTestSignedRequest("GET", s.endPoint+"/"+bucketName+"/object?policy", 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusNotImplemented) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusNotImplemented) } // TestHeader - Validates the error response for an attempt to fetch non-existent object. -func (s *TestSuiteCommon) TestHeader(c *C) { +func (s *TestSuiteCommon) TestHeader(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // obtain HTTP request to fetch an object from non-existent bucket/object. request, err := newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, "testObject"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // asserting for the expected error response. verifyError(c, response, "NoSuchBucket", "The specified bucket does not exist", http.StatusNotFound) } -func (s *TestSuiteCommon) TestPutBucket(c *C) { +func (s *TestSuiteCommon) TestPutBucket(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // Block 1: Testing for racey access @@ -994,7 +1060,7 @@ func (s *TestSuiteCommon) TestPutBucket(c *C) { // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} response, err := client.Do(request) @@ -1011,12 +1077,12 @@ func (s *TestSuiteCommon) TestPutBucket(c *C) { // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) response.Body.Close() } @@ -1026,19 +1092,19 @@ func (s *TestSuiteCommon) TestPutBucket(c *C) { // 2. Insert Object. // 3. Use "X-Amz-Copy-Source" header to copy the previously created object. // 4. Validate the content of copied object. -func (s *TestSuiteCommon) TestCopyObject(c *C) { +func (s *TestSuiteCommon) TestCopyObject(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // content for the object to be created. buffer1 := bytes.NewReader([]byte("hello world")) @@ -1048,20 +1114,20 @@ func (s *TestSuiteCommon) TestCopyObject(c *C) { int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) request.Header.Set("Content-Type", "application/json") if s.signer == signerV2 { - c.Assert(err, IsNil) + c.Assert(err, nil) err = signRequestV2(request, s.accessKey, s.secretKey) } - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request for object upload. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) objectName2 := "testObject2" // Unlike the actual PUT object request, the request to Copy Object doesn't contain request body, // empty body with the "X-Amz-Copy-Source" header pointing to the object to copies it in the backend. request, err = newTestRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName2), 0, nil) - c.Assert(err, IsNil) + c.Assert(err, nil) // setting the "X-Amz-Copy-Source" to allow copying the content of previously uploaded object. request.Header.Set("X-Amz-Copy-Source", url.QueryEscape("/"+bucketName+"/"+objectName)) if s.signer == signerV4 { @@ -1069,43 +1135,43 @@ func (s *TestSuiteCommon) TestCopyObject(c *C) { } else { err = signRequestV2(request, s.accessKey, s.secretKey) } - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request. // the content is expected to have the content of previous disk. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // creating HTTP request to fetch the previously uploaded object. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName2), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // executing the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // validating the response status code. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // reading the response body. // response body is expected to have the copied content of the first uploaded object. object, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) - c.Assert(string(object), Equals, "hello world") + c.Assert(err, nil) + c.Assert(string(object), "hello world") } // TestPutObject - Tests successful put object request. -func (s *TestSuiteCommon) TestPutObject(c *C) { +func (s *TestSuiteCommon) TestPutObject(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // content for new object upload. buffer1 := bytes.NewReader([]byte("hello world")) @@ -1113,28 +1179,28 @@ func (s *TestSuiteCommon) TestPutObject(c *C) { // creating HTTP request for object upload. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request for object upload. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // fetch the object back and verify its contents. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request to fetch the object. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) - c.Assert(response.ContentLength, Equals, int64(len([]byte("hello world")))) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) + c.Assert(response.ContentLength, int64(len([]byte("hello world")))) var buffer2 bytes.Buffer // retrive the contents of response body. n, err := io.Copy(&buffer2, response.Body) - c.Assert(err, IsNil) - c.Assert(n, Equals, int64(len([]byte("hello world")))) + c.Assert(err, nil) + c.Assert(n, int64(len([]byte("hello world")))) // asserted the contents of the fetched object with the expected result. - c.Assert(true, Equals, bytes.Equal(buffer2.Bytes(), []byte("hello world"))) + c.Assert(true, bytes.Equal(buffer2.Bytes(), []byte("hello world"))) // Test the response when object name ends with a slash. // This is a special case with size as '0' and object ends with @@ -1146,51 +1212,51 @@ func (s *TestSuiteCommon) TestPutObject(c *C) { request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) if s.signer == signerV2 { - c.Assert(err, IsNil) + c.Assert(err, nil) err = signRequestV2(request, s.accessKey, s.secretKey) } - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request for object upload. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // The response Etag header should contain Md5sum of an empty string. - c.Assert(response.Header.Get("Etag"), Equals, "\""+emptyETag+"\"") + c.Assert(response.Header.Get("Etag"), "\""+emptyETag+"\"") } // TestListBuckets - Make request for listing of all buckets. // XML response is parsed. // Its success verifies the format of the response. -func (s *TestSuiteCommon) TestListBuckets(c *C) { +func (s *TestSuiteCommon) TestListBuckets(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to list buckets. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // create HTTP request for listing buckets. request, err = newTestSignedRequest("GET", getListBucketURL(s.endPoint), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to list buckets. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) var results ListBucketsResponse // parse the list bucket response. decoder := xml.NewDecoder(response.Body) err = decoder.Decode(&results) // validating that the xml-decoding/parsing was successful. - c.Assert(err, IsNil) + c.Assert(err, nil) // Fetch the bucket created above var createdBucket Bucket @@ -1199,32 +1265,32 @@ func (s *TestSuiteCommon) TestListBuckets(c *C) { createdBucket = b } } - c.Assert(createdBucket.Name != "", Equals, true) + c.Assert(createdBucket.Name != "", true) // Parse the bucket modtime creationTime, err := time.Parse(timeFormatAMZLong, createdBucket.CreationDate) - c.Assert(err, IsNil) + c.Assert(err, nil) // Check if bucket modtime is consistent (not less than current time and not late more than 5 minutes) timeNow := time.Now().UTC() - c.Assert(creationTime.Before(timeNow), Equals, true) - c.Assert(timeNow.Sub(creationTime) < time.Minute*5, Equals, true) + c.Assert(creationTime.Before(timeNow), true) + c.Assert(timeNow.Sub(creationTime) < time.Minute*5, true) } // This tests validate if PUT handler can successfully detect signature mismatch. -func (s *TestSuiteCommon) TestValidateSignature(c *C) { +func (s *TestSuiteCommon) TestValidateSignature(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // Execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) objName := "test-object" @@ -1233,26 +1299,26 @@ func (s *TestSuiteCommon) TestValidateSignature(c *C) { // Create new HTTP request with incorrect secretKey to generate an incorrect signature. secretKey := s.secretKey + "a" request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objName), 0, nil, s.accessKey, secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "SignatureDoesNotMatch", "The request signature we calculated does not match the signature you provided. Check your key and signing method.", http.StatusForbidden) } // This tests validate if PUT handler can successfully detect SHA256 mismatch. -func (s *TestSuiteCommon) TestSHA256Mismatch(c *C) { +func (s *TestSuiteCommon) TestSHA256Mismatch(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // Execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) objName := "test-object" @@ -1261,16 +1327,16 @@ func (s *TestSuiteCommon) TestSHA256Mismatch(c *C) { // Create new HTTP request with incorrect secretKey to generate an incorrect signature. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objName), 0, nil, s.accessKey, s.secretKey, s.signer) if s.signer == signerV4 { - c.Assert(request.Header.Get("x-amz-content-sha256"), Equals, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") + c.Assert(request.Header.Get("x-amz-content-sha256"), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") } // Set the body to generate signature mismatch. helloReader := bytes.NewReader([]byte("Hello, World")) request.ContentLength = helloReader.Size() request.Body = ioutil.NopCloser(helloReader) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) if s.signer == signerV4 { verifyError(c, response, "XAmzContentSHA256Mismatch", "The provided 'x-amz-content-sha256' header does not match what was computed.", http.StatusBadRequest) } @@ -1278,19 +1344,19 @@ func (s *TestSuiteCommon) TestSHA256Mismatch(c *C) { // TestPutObjectLongName - Validates the error response // on an attempt to upload an object with long name. -func (s *TestSuiteCommon) TestPutObjectLongName(c *C) { +func (s *TestSuiteCommon) TestPutObjectLongName(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // Execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // Content for the object to be uploaded. buffer := bytes.NewReader([]byte("hello world")) // make long object name. @@ -1301,26 +1367,26 @@ func (s *TestSuiteCommon) TestPutObjectLongName(c *C) { // create new HTTP request to insert the object. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, longObjName), int64(buffer.Len()), buffer, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // make long object name. longObjName = fmt.Sprintf("%0256d", 1) buffer = bytes.NewReader([]byte("hello world")) request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, longObjName), int64(buffer.Len()), buffer, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "XMinioInvalidObjectName", "Object name contains unsupported characters.", http.StatusBadRequest) } // TestNotBeAbleToCreateObjectInNonexistentBucket - Validates the error response // on an attempt to upload an object into a non-existent bucket. -func (s *TestSuiteCommon) TestNotBeAbleToCreateObjectInNonexistentBucket(c *C) { +func (s *TestSuiteCommon) TestNotBeAbleToCreateObjectInNonexistentBucket(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // content of the object to be uploaded. @@ -1330,12 +1396,12 @@ func (s *TestSuiteCommon) TestNotBeAbleToCreateObjectInNonexistentBucket(c *C) { objectName := "test-object" request, err := newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // Execute the HTTP request. response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Assert the response error message. verifyError(c, response, "NoSuchBucket", "The specified bucket does not exist", http.StatusNotFound) } @@ -1346,19 +1412,19 @@ func (s *TestSuiteCommon) TestNotBeAbleToCreateObjectInNonexistentBucket(c *C) { // and If-Unmodified-Since headers set are validated. // If-Modified-Since - Return the object only if it has been modified since the specified time, else return a 304 (not modified). // If-Unmodified-Since - Return the object only if it has not been modified since the specified time, else return a 412 (precondition failed). -func (s *TestSuiteCommon) TestHeadOnObjectLastModified(c *C) { +func (s *TestSuiteCommon) TestHeadOnObjectLastModified(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // preparing for object upload. objectName := "test-object" @@ -1367,107 +1433,107 @@ func (s *TestSuiteCommon) TestHeadOnObjectLastModified(c *C) { // obtaining URL for uploading the object. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // executing the HTTP request to download the object. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // make HTTP request to obtain object info. request, err = newTestSignedRequest("HEAD", getHeadObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // verify the status of the HTTP response. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // retrive the info of last modification time of the object from the response header. lastModified := response.Header.Get("Last-Modified") // Parse it into time.Time structure. t, err := time.Parse(http.TimeFormat, lastModified) - c.Assert(err, IsNil) + c.Assert(err, nil) // make HTTP request to obtain object info. // But this time set the "If-Modified-Since" header to be 10 minute more than the actual // last modified time of the object. request, err = newTestSignedRequest("HEAD", getHeadObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) request.Header.Set("If-Modified-Since", t.Add(10*time.Minute).UTC().Format(http.TimeFormat)) response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Since the "If-Modified-Since" header was ahead in time compared to the actual // modified time of the object expecting the response status to be http.StatusNotModified. - c.Assert(response.StatusCode, Equals, http.StatusNotModified) + c.Assert(response.StatusCode, http.StatusNotModified) // Again, obtain the object info. // This time setting "If-Unmodified-Since" to a time after the object is modified. // As documented above, expecting http.StatusPreconditionFailed. request, err = newTestSignedRequest("HEAD", getHeadObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) request.Header.Set("If-Unmodified-Since", t.Add(-10*time.Minute).UTC().Format(http.TimeFormat)) response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusPreconditionFailed) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusPreconditionFailed) // make HTTP request to obtain object info. // But this time set a date with unrecognized format to the "If-Modified-Since" header request, err = newTestSignedRequest("HEAD", getHeadObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) request.Header.Set("If-Unmodified-Since", "Mon, 02 Jan 2006 15:04:05 +00:00") response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Since the "If-Modified-Since" header was ahead in time compared to the actual // modified time of the object expecting the response status to be http.StatusNotModified. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) } // TestHeadOnBucket - Validates response for HEAD on the bucket. // HEAD request on the bucket validates the existence of the bucket. -func (s *TestSuiteCommon) TestHeadOnBucket(c *C) { +func (s *TestSuiteCommon) TestHeadOnBucket(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getHEADBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // make HEAD request on the bucket. request, err = newTestSignedRequest("HEAD", getHEADBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Asserting the response status for expected value of http.StatusOK. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) } // TestContentTypePersists - Object upload with different Content-type is first done. // And then a HEAD and GET request on these objects are done to validate if the same Content-Type set during upload persists. -func (s *TestSuiteCommon) TestContentTypePersists(c *C) { +func (s *TestSuiteCommon) TestContentTypePersists(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // Uploading a new object with Content-Type "image/png". // content for the object to be uploaded. @@ -1476,233 +1542,233 @@ func (s *TestSuiteCommon) TestContentTypePersists(c *C) { // constructing HTTP request for object upload. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) request.Header.Set("Content-Type", "image/png") if s.signer == signerV2 { err = signRequestV2(request, s.accessKey, s.secretKey) - c.Assert(err, IsNil) + c.Assert(err, nil) } client = http.Client{Transport: s.transport} // execute the HTTP request for object upload. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // Fetching the object info using HEAD request for the object which was uploaded above. request, err = newTestSignedRequest("HEAD", getHeadObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // Execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Verify if the Content-Type header is set during the object persists. - c.Assert(response.Header.Get("Content-Type"), Equals, "image/png") + c.Assert(response.Header.Get("Content-Type"), "image/png") // Fetching the object itself and then verify the Content-Type header. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // Execute the HTTP to fetch the object. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // Verify if the Content-Type header is set during the object persists. - c.Assert(response.Header.Get("Content-Type"), Equals, "image/png") + c.Assert(response.Header.Get("Content-Type"), "image/png") // Uploading a new object with Content-Type "application/json". objectName = "test-object.json" buffer2 := bytes.NewReader([]byte("hello world")) request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer2.Len()), buffer2, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // setting the request header to be application/json. request.Header.Set("Content-Type", "application/json") if s.signer == signerV2 { err = signRequestV2(request, s.accessKey, s.secretKey) - c.Assert(err, IsNil) + c.Assert(err, nil) } // Execute the HTTP request to upload the object. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // Obtain the info of the object which was uploaded above using HEAD request. request, err = newTestSignedRequest("HEAD", getHeadObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // Execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Assert if the content-type header set during the object upload persists. - c.Assert(response.Header.Get("Content-Type"), Equals, "application/json") + c.Assert(response.Header.Get("Content-Type"), "application/json") // Fetch the object and assert whether the Content-Type header persists. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // Execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Assert if the content-type header set during the object upload persists. - c.Assert(response.Header.Get("Content-Type"), Equals, "application/json") + c.Assert(response.Header.Get("Content-Type"), "application/json") } // TestPartialContent - Validating for GetObject with partial content request. // By setting the Range header, A request to send specific bytes range of data from an // already uploaded object can be done. -func (s *TestSuiteCommon) TestPartialContent(c *C) { +func (s *TestSuiteCommon) TestPartialContent(c *check) { bucketName := getRandomBucketName() request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) buffer1 := bytes.NewReader([]byte("Hello World")) request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, "bar"), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // Prepare request request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, "bar"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) request.Header.Add("Range", "bytes=6-7") client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusPartialContent) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusPartialContent) partialObject, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) - c.Assert(string(partialObject), Equals, "Wo") + c.Assert(string(partialObject), "Wo") } // TestListObjectsHandler - Setting valid parameters to List Objects // and then asserting the response with the expected one. -func (s *TestSuiteCommon) TestListObjectsHandler(c *C) { +func (s *TestSuiteCommon) TestListObjectsHandler(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) buffer1 := bytes.NewReader([]byte("Hello World")) request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, "bar"), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // create listObjectsV1 request with valid parameters request, err = newTestSignedRequest("GET", getListObjectsV1URL(s.endPoint, bucketName, "1000"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) getContent, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) - c.Assert(strings.Contains(string(getContent), "bar"), Equals, true) + c.Assert(err, nil) + c.Assert(strings.Contains(string(getContent), "bar"), true) // create listObjectsV2 request with valid parameters request, err = newTestSignedRequest("GET", getListObjectsV2URL(s.endPoint, bucketName, "1000", ""), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) getContent, err = ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) - c.Assert(strings.Contains(string(getContent), "bar"), Equals, true) - c.Assert(strings.Contains(string(getContent), ""), Equals, true) + c.Assert(err, nil) + c.Assert(strings.Contains(string(getContent), "bar"), true) + c.Assert(strings.Contains(string(getContent), ""), true) // create listObjectsV2 request with valid parameters and fetch-owner activated request, err = newTestSignedRequest("GET", getListObjectsV2URL(s.endPoint, bucketName, "1000", "true"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) getContent, err = ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) - c.Assert(strings.Contains(string(getContent), "bar"), Equals, true) + c.Assert(strings.Contains(string(getContent), "bar"), true) c.Assert(strings.Contains(string(getContent), fmt.Sprintf("%s", - globalMinioDefaultOwnerID)), Equals, true) + globalMinioDefaultOwnerID)), true) } // TestListObjectsHandlerErrors - Setting invalid parameters to List Objects // and then asserting the error response with the expected one. -func (s *TestSuiteCommon) TestListObjectsHandlerErrors(c *C) { +func (s *TestSuiteCommon) TestListObjectsHandlerErrors(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // create listObjectsV1 request with invalid value of max-keys parameter. max-keys is set to -2. request, err = newTestSignedRequest("GET", getListObjectsV1URL(s.endPoint, bucketName, "-2"), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // validating the error response. verifyError(c, response, "InvalidArgument", "Argument maxKeys must be an integer between 0 and 2147483647", http.StatusBadRequest) // create listObjectsV2 request with invalid value of max-keys parameter. max-keys is set to -2. request, err = newTestSignedRequest("GET", getListObjectsV2URL(s.endPoint, bucketName, "-2", ""), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // validating the error response. verifyError(c, response, "InvalidArgument", "Argument maxKeys must be an integer between 0 and 2147483647", http.StatusBadRequest) @@ -1710,38 +1776,38 @@ func (s *TestSuiteCommon) TestListObjectsHandlerErrors(c *C) { // TestPutBucketErrors - request for non valid bucket operation // and validate it with expected error result. -func (s *TestSuiteCommon) TestPutBucketErrors(c *C) { +func (s *TestSuiteCommon) TestPutBucketErrors(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // generating a HTTP request to create bucket. // using invalid bucket name. request, err := newTestSignedRequest("PUT", s.endPoint+"/putbucket-.", 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} response, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // expected to fail with error message "InvalidBucketName". verifyError(c, response, "InvalidBucketName", "The specified bucket is not valid.", http.StatusBadRequest) // HTTP request to create the bucket. request, err = newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // make HTTP request to create the same bucket again. // expected to fail with error message "BucketAlreadyOwnedByYou". request, err = newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "BucketAlreadyOwnedByYou", "Your previous request to create the named bucket succeeded and you already own it.", http.StatusConflict) @@ -1749,26 +1815,26 @@ func (s *TestSuiteCommon) TestPutBucketErrors(c *C) { // Since Minio server doesn't support ACL's the request is expected to fail with "NotImplemented" error message. request, err = newTestSignedRequest("PUT", s.endPoint+"/"+bucketName+"?acl", 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "NotImplemented", "A header you provided implies functionality that is not implemented", http.StatusNotImplemented) } -func (s *TestSuiteCommon) TestGetObjectLarge10MiB(c *C) { +func (s *TestSuiteCommon) TestGetObjectLarge10MiB(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // form HTTP reqest to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create the bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) var buffer bytes.Buffer line := `1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890, @@ -1792,47 +1858,47 @@ func (s *TestSuiteCommon) TestGetObjectLarge10MiB(c *C) { // create HTTP request for object upload. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buf.Len()), buf, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Assert the status code to verify successful upload. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // prepare HTTP requests to download the object. request, err = newTestSignedRequest("GET", getPutObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to download the object. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // extract the content from response body. getContent, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) // Compare putContent and getContent. - c.Assert(string(getContent), Equals, putContent) + c.Assert(string(getContent), putContent) } // TestGetObjectLarge11MiB - Tests validate fetching of an object of size 11MB. -func (s *TestSuiteCommon) TestGetObjectLarge11MiB(c *C) { +func (s *TestSuiteCommon) TestGetObjectLarge11MiB(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) var buffer bytes.Buffer line := `1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890, @@ -1857,51 +1923,51 @@ func (s *TestSuiteCommon) TestGetObjectLarge11MiB(c *C) { // create HTTP request foe object upload. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buf.Len()), buf, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request for object upload. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // create HTTP request to download the object. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // fetch the content from response body. getContent, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) // Get etag of the response content. getMD5 := getMD5Hash(getContent) // Compare putContent and getContent. - c.Assert(putMD5, Equals, getMD5) + c.Assert(putMD5, getMD5) } // TestGetPartialObjectMisAligned - tests get object partially mis-aligned. // create a large buffer of mis-aligned data and upload it. // then make partial range requests to while fetching it back and assert the response content. -func (s *TestSuiteCommon) TestGetPartialObjectMisAligned(c *C) { +func (s *TestSuiteCommon) TestGetPartialObjectMisAligned(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create the bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) var buffer bytes.Buffer // data to be written into buffer. @@ -1925,13 +1991,13 @@ func (s *TestSuiteCommon) TestGetPartialObjectMisAligned(c *C) { // HTTP request to upload the object. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buf.Len()), buf, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to upload the object. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // test Cases containing data to make partial range requests. // also has expected response data. @@ -1956,39 +2022,39 @@ func (s *TestSuiteCommon) TestGetPartialObjectMisAligned(c *C) { // HTTP request to download the object. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // Get partial content based on the byte range set. request.Header.Add("Range", "bytes="+t.byteRange) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Since only part of the object is requested, expecting response status to be http.StatusPartialContent . - c.Assert(response.StatusCode, Equals, http.StatusPartialContent) + c.Assert(response.StatusCode, http.StatusPartialContent) // parse the HTTP response body. getContent, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) // Compare putContent and getContent. - c.Assert(string(getContent), Equals, t.expectedString) + c.Assert(string(getContent), t.expectedString) } } // TestGetPartialObjectLarge11MiB - Test validates partial content request for a 11MiB object. -func (s *TestSuiteCommon) TestGetPartialObjectLarge11MiB(c *C) { +func (s *TestSuiteCommon) TestGetPartialObjectLarge11MiB(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create the bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) var buffer bytes.Buffer line := `234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890, @@ -2014,51 +2080,51 @@ func (s *TestSuiteCommon) TestGetPartialObjectLarge11MiB(c *C) { // HTTP request to upload the object. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buf.Len()), buf, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to upload the object. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // HTTP request to download the object. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // This range spans into first two blocks. request.Header.Add("Range", "bytes=10485750-10485769") client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Since only part of the object is requested, expecting response status to be http.StatusPartialContent . - c.Assert(response.StatusCode, Equals, http.StatusPartialContent) + c.Assert(response.StatusCode, http.StatusPartialContent) // read the downloaded content from the response body. getContent, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) // Compare putContent and getContent. - c.Assert(string(getContent), Equals, putContent[10485750:10485770]) + c.Assert(string(getContent), putContent[10485750:10485770]) } // TestGetPartialObjectLarge11MiB - Test validates partial content request for a 10MiB object. -func (s *TestSuiteCommon) TestGetPartialObjectLarge10MiB(c *C) { +func (s *TestSuiteCommon) TestGetPartialObjectLarge10MiB(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) // expecting the error to be nil. - c.Assert(err, IsNil) + c.Assert(err, nil) // expecting the HTTP response status code to 200 OK. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) var buffer bytes.Buffer line := `1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890, @@ -2083,51 +2149,51 @@ func (s *TestSuiteCommon) TestGetPartialObjectLarge10MiB(c *C) { // HTTP request to upload the object. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buf.Len()), buf, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to upload the object. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // verify whether upload was successful. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // HTTP request to download the object. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // Get partial content based on the byte range set. request.Header.Add("Range", "bytes=2048-2058") client = http.Client{Transport: s.transport} // execute the HTTP request to download the partila content. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Since only part of the object is requested, expecting response status to be http.StatusPartialContent . - c.Assert(response.StatusCode, Equals, http.StatusPartialContent) + c.Assert(response.StatusCode, http.StatusPartialContent) // read the downloaded content from the response body. getContent, err := ioutil.ReadAll(response.Body) - c.Assert(err, IsNil) + c.Assert(err, nil) // Compare putContent and getContent. - c.Assert(string(getContent), Equals, putContent[2048:2059]) + c.Assert(string(getContent), putContent[2048:2059]) } // TestGetObjectErrors - Tests validate error response for invalid object operations. -func (s *TestSuiteCommon) TestGetObjectErrors(c *C) { +func (s *TestSuiteCommon) TestGetObjectErrors(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) objectName := "test-non-exitent-object" // HTTP request to download the object. @@ -2135,39 +2201,39 @@ func (s *TestSuiteCommon) TestGetObjectErrors(c *C) { // expected to fail with error message "NoSuchKey" request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) verifyError(c, response, "NoSuchKey", "The specified key does not exist.", http.StatusNotFound) // request to download an object, but an invalid bucket name is set. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, "getobjecterrors-.", objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // expected to fail with "InvalidBucketName". verifyError(c, response, "InvalidBucketName", "The specified bucket is not valid.", http.StatusBadRequest) } // TestGetObjectRangeErrors - Validate error response when object is fetched with incorrect byte range value. -func (s *TestSuiteCommon) TestGetObjectRangeErrors(c *C) { +func (s *TestSuiteCommon) TestGetObjectRangeErrors(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // content for the object to be uploaded. buffer1 := bytes.NewReader([]byte("Hello World")) @@ -2176,44 +2242,44 @@ func (s *TestSuiteCommon) TestGetObjectRangeErrors(c *C) { // HTTP request to upload the object. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to upload the object. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // verify whether upload was successful. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // HTTP request to download the object. request, err = newTestSignedRequest("GET", getGetObjectURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) // Invalid byte range set. request.Header.Add("Range", "bytes=-0") - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // expected to fail with "InvalidRange" error message. verifyError(c, response, "InvalidRange", "The requested range is not satisfiable", http.StatusRequestedRangeNotSatisfiable) } // TestObjectMultipartAbort - Test validates abortion of a multipart upload after uploading 2 parts. -func (s *TestSuiteCommon) TestObjectMultipartAbort(c *C) { +func (s *TestSuiteCommon) TestObjectMultipartAbort(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) objectName := "test-multipart-object" @@ -2227,38 +2293,38 @@ func (s *TestSuiteCommon) TestObjectMultipartAbort(c *C) { // construct HTTP request to initiate a NewMultipart upload. request, err = newTestSignedRequest("POST", getNewMultipartURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request initiating the new multipart upload. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // parse the response body and obtain the new upload ID. decoder := xml.NewDecoder(response.Body) newResponse := &InitiateMultipartUploadResponse{} err = decoder.Decode(newResponse) - c.Assert(err, IsNil) - c.Assert(len(newResponse.UploadID) > 0, Equals, true) + c.Assert(err, nil) + c.Assert(len(newResponse.UploadID) > 0, true) // construct HTTP request to initiate a NewMultipart upload. request, err = newTestSignedRequest("POST", getNewMultipartURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request initiating the new multipart upload. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // parse the response body and obtain the new upload ID. decoder = xml.NewDecoder(response.Body) newResponse = &InitiateMultipartUploadResponse{} err = decoder.Decode(newResponse) - c.Assert(err, IsNil) - c.Assert(len(newResponse.UploadID) > 0, Equals, true) + c.Assert(err, nil) + c.Assert(len(newResponse.UploadID) > 0, true) // uploadID to be used for rest of the multipart operations on the object. uploadID := newResponse.UploadID @@ -2267,67 +2333,67 @@ func (s *TestSuiteCommon) TestObjectMultipartAbort(c *C) { // HTTP request for the part to be uploaded. request, err = newTestSignedRequest("PUT", getPartUploadURL(s.endPoint, bucketName, objectName, uploadID, "1"), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request to upload the first part. response1, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response1.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response1.StatusCode, http.StatusOK) // content for the second part to be uploaded. buffer2 := bytes.NewReader([]byte("hello world")) // HTTP request for the second part to be uploaded. request, err = newTestSignedRequest("PUT", getPartUploadURL(s.endPoint, bucketName, objectName, uploadID, "2"), int64(buffer2.Len()), buffer2, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request to upload the second part. response2, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response2.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response2.StatusCode, http.StatusOK) // HTTP request for aborting the multipart upload. request, err = newTestSignedRequest("DELETE", getAbortMultipartUploadURL(s.endPoint, bucketName, objectName, uploadID), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request to abort the multipart upload. response3, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // expecting the response status code to be http.StatusNoContent. // The assertion validates the success of Abort Multipart operation. - c.Assert(response3.StatusCode, Equals, http.StatusNoContent) + c.Assert(response3.StatusCode, http.StatusNoContent) } // TestBucketMultipartList - Initiates a NewMultipart upload, uploads parts and validates listing of the parts. -func (s *TestSuiteCommon) TestBucketMultipartList(c *C) { +func (s *TestSuiteCommon) TestBucketMultipartList(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, 200) + c.Assert(err, nil) + c.Assert(response.StatusCode, 200) objectName := "test-multipart-object" // construct HTTP request to initiate a NewMultipart upload. request, err = newTestSignedRequest("POST", getNewMultipartURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request initiating the new multipart upload. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // expecting the response status code to be http.StatusOK(200 OK) . - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // parse the response body and obtain the new upload ID. decoder := xml.NewDecoder(response.Body) newResponse := &InitiateMultipartUploadResponse{} err = decoder.Decode(newResponse) - c.Assert(err, IsNil) - c.Assert(len(newResponse.UploadID) > 0, Equals, true) + c.Assert(err, nil) + c.Assert(len(newResponse.UploadID) > 0, true) // uploadID to be used for rest of the multipart operations on the object. uploadID := newResponse.UploadID @@ -2336,31 +2402,31 @@ func (s *TestSuiteCommon) TestBucketMultipartList(c *C) { // HTTP request for the part to be uploaded. request, err = newTestSignedRequest("PUT", getPartUploadURL(s.endPoint, bucketName, objectName, uploadID, "1"), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request to upload the first part. response1, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response1.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response1.StatusCode, http.StatusOK) // content for the second part to be uploaded. buffer2 := bytes.NewReader([]byte("hello world")) // HTTP request for the second part to be uploaded. request, err = newTestSignedRequest("PUT", getPartUploadURL(s.endPoint, bucketName, objectName, uploadID, "2"), int64(buffer2.Len()), buffer2, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request to upload the second part. response2, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response2.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response2.StatusCode, http.StatusOK) // HTTP request to ListMultipart Uploads. request, err = newTestSignedRequest("GET", getListMultipartURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request. response3, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response3.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response3.StatusCode, http.StatusOK) // The reason to duplicate this structure here is to verify if the // unmarshalling works from a client perspective, specifically @@ -2401,80 +2467,80 @@ func (s *TestSuiteCommon) TestBucketMultipartList(c *C) { decoder = xml.NewDecoder(response3.Body) newResponse3 := &listMultipartUploadsResponse{} err = decoder.Decode(newResponse3) - c.Assert(err, IsNil) + c.Assert(err, nil) // Assert the bucket name in the response with the expected bucketName. - c.Assert(newResponse3.Bucket, Equals, bucketName) + c.Assert(newResponse3.Bucket, bucketName) // Assert the bucket name in the response with the expected bucketName. - c.Assert(newResponse3.IsTruncated, Equals, false) + c.Assert(newResponse3.IsTruncated, false) } // TestValidateObjectMultipartUploadID - Test Initiates a new multipart upload and validates the uploadID. -func (s *TestSuiteCommon) TestValidateObjectMultipartUploadID(c *C) { +func (s *TestSuiteCommon) TestValidateObjectMultipartUploadID(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, 200) + c.Assert(err, nil) + c.Assert(response.StatusCode, 200) objectName := "directory1/directory2/object" // construct HTTP request to initiate a NewMultipart upload. request, err = newTestSignedRequest("POST", getNewMultipartURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request initiating the new multipart upload. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // parse the response body and obtain the new upload ID. decoder := xml.NewDecoder(response.Body) newResponse := &InitiateMultipartUploadResponse{} err = decoder.Decode(newResponse) // expecting the decoding error to be nil. - c.Assert(err, IsNil) + c.Assert(err, nil) // Verifying for Upload ID value to be greater than 0. - c.Assert(len(newResponse.UploadID) > 0, Equals, true) + c.Assert(len(newResponse.UploadID) > 0, true) } // TestObjectMultipartListError - Initiates a NewMultipart upload, uploads parts and validates // error response for an incorrect max-parts parameter . -func (s *TestSuiteCommon) TestObjectMultipartListError(c *C) { +func (s *TestSuiteCommon) TestObjectMultipartListError(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, 200) + c.Assert(err, nil) + c.Assert(response.StatusCode, 200) objectName := "test-multipart-object" // construct HTTP request to initiate a NewMultipart upload. request, err = newTestSignedRequest("POST", getNewMultipartURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request initiating the new multipart upload. response, err = client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response.StatusCode, http.StatusOK) // parse the response body and obtain the new upload ID. decoder := xml.NewDecoder(response.Body) newResponse := &InitiateMultipartUploadResponse{} err = decoder.Decode(newResponse) - c.Assert(err, IsNil) - c.Assert(len(newResponse.UploadID) > 0, Equals, true) + c.Assert(err, nil) + c.Assert(len(newResponse.UploadID) > 0, true) // uploadID to be used for rest of the multipart operations on the object. uploadID := newResponse.UploadID @@ -2483,42 +2549,42 @@ func (s *TestSuiteCommon) TestObjectMultipartListError(c *C) { // HTTP request for the part to be uploaded. request, err = newTestSignedRequest("PUT", getPartUploadURL(s.endPoint, bucketName, objectName, uploadID, "1"), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request to upload the first part. response1, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response1.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response1.StatusCode, http.StatusOK) // content for the second part to be uploaded. buffer2 := bytes.NewReader([]byte("hello world")) // HTTP request for the second part to be uploaded. request, err = newTestSignedRequest("PUT", getPartUploadURL(s.endPoint, bucketName, objectName, uploadID, "2"), int64(buffer2.Len()), buffer2, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request to upload the second part. response2, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response2.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response2.StatusCode, http.StatusOK) // HTTP request to ListMultipart Uploads. // max-keys is set to valid value of 1 request, err = newTestSignedRequest("GET", getListMultipartURLWithParams(s.endPoint, bucketName, objectName, uploadID, "1", "", ""), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request. response3, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response3.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response3.StatusCode, http.StatusOK) // HTTP request to ListMultipart Uploads. // max-keys is set to invalid value of -2. request, err = newTestSignedRequest("GET", getListMultipartURLWithParams(s.endPoint, bucketName, objectName, uploadID, "-2", "", ""), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // execute the HTTP request. response4, err := client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Since max-keys parameter in the ListMultipart request set to invalid value of -2, // its expected to fail with error message "InvalidArgument". verifyError(c, response4, "InvalidArgument", "Argument max-parts must be an integer between 0 and 2147483647", http.StatusBadRequest) @@ -2526,19 +2592,19 @@ func (s *TestSuiteCommon) TestObjectMultipartListError(c *C) { // TestObjectValidMD5 - First uploads an object with a valid Content-Md5 header and verifies the status, // then upload an object in a wrong Content-Md5 and validate the error response. -func (s *TestSuiteCommon) TestObjectValidMD5(c *C) { +func (s *TestSuiteCommon) TestObjectValidMD5(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, 200) + c.Assert(err, nil) + c.Assert(response.StatusCode, 200) // Create a byte array of 5MB. // content for the object to be uploaded. @@ -2551,65 +2617,65 @@ func (s *TestSuiteCommon) TestObjectValidMD5(c *C) { // HTTP request for the object to be uploaded. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // set the Content-Md5 to be the hash to content. request.Header.Set("Content-Md5", etagBase64) client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // expecting a successful upload. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) objectName = "test-2-object" buffer1 = bytes.NewReader(data) // HTTP request for the object to be uploaded. request, err = newTestSignedRequest("PUT", getPutObjectURL(s.endPoint, bucketName, objectName), int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // set Content-Md5 to invalid value. request.Header.Set("Content-Md5", "kvLTlMrX9NpYDQlEIFlnDA==") // expecting a failure during upload. client = http.Client{Transport: s.transport} response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // Since Content-Md5 header was wrong, expecting to fail with "SignatureDoesNotMatch" error. verifyError(c, response, "SignatureDoesNotMatch", "The request signature we calculated does not match the signature you provided. Check your key and signing method.", http.StatusForbidden) } // TestObjectMultipart - Initiates a NewMultipart upload, uploads 2 parts, // completes the multipart upload and validates the status of the operation. -func (s *TestSuiteCommon) TestObjectMultipart(c *C) { +func (s *TestSuiteCommon) TestObjectMultipart(c *check) { // generate a random bucket name. bucketName := getRandomBucketName() // HTTP request to create the bucket. request, err := newTestSignedRequest("PUT", getMakeBucketURL(s.endPoint, bucketName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client := http.Client{Transport: s.transport} // execute the HTTP request to create bucket. response, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response.StatusCode, Equals, 200) + c.Assert(err, nil) + c.Assert(response.StatusCode, 200) objectName := "test-multipart-object" // construct HTTP request to initiate a NewMultipart upload. request, err = newTestSignedRequest("POST", getNewMultipartURL(s.endPoint, bucketName, objectName), 0, nil, s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request initiating the new multipart upload. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // expecting the response status code to be http.StatusOK(200 OK). - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) // parse the response body and obtain the new upload ID. decoder := xml.NewDecoder(response.Body) newResponse := &InitiateMultipartUploadResponse{} err = decoder.Decode(newResponse) - c.Assert(err, IsNil) - c.Assert(len(newResponse.UploadID) > 0, Equals, true) + c.Assert(err, nil) + c.Assert(len(newResponse.UploadID) > 0, true) // uploadID to be used for rest of the multipart operations on the object. uploadID := newResponse.UploadID @@ -2625,13 +2691,13 @@ func (s *TestSuiteCommon) TestObjectMultipart(c *C) { int64(buffer1.Len()), buffer1, s.accessKey, s.secretKey, s.signer) // set the Content-Md5 header to the base64 encoding the etag of the content. request.Header.Set("Content-Md5", md5SumBase64) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to upload the first part. response1, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response1.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response1.StatusCode, http.StatusOK) // content for the second part to be uploaded. // Create a byte array of 1 byte. @@ -2646,13 +2712,13 @@ func (s *TestSuiteCommon) TestObjectMultipart(c *C) { int64(buffer2.Len()), buffer2, s.accessKey, s.secretKey, s.signer) // set the Content-Md5 header to the base64 encoding the etag of the content. request.Header.Set("Content-Md5", md5SumBase64) - c.Assert(err, IsNil) + c.Assert(err, nil) client = http.Client{Transport: s.transport} // execute the HTTP request to upload the second part. response2, err := client.Do(request) - c.Assert(err, IsNil) - c.Assert(response2.StatusCode, Equals, http.StatusOK) + c.Assert(err, nil) + c.Assert(response2.StatusCode, http.StatusOK) // Complete multipart upload completeUploads := &completeMultipartUpload{ @@ -2669,22 +2735,22 @@ func (s *TestSuiteCommon) TestObjectMultipart(c *C) { } completeBytes, err := xml.Marshal(completeUploads) - c.Assert(err, IsNil) + c.Assert(err, nil) // Indicating that all parts are uploaded and initiating completeMultipartUpload. request, err = newTestSignedRequest("POST", getCompleteMultipartUploadURL(s.endPoint, bucketName, objectName, uploadID), int64(len(completeBytes)), bytes.NewReader(completeBytes), s.accessKey, s.secretKey, s.signer) - c.Assert(err, IsNil) + c.Assert(err, nil) // Execute the complete multipart request. response, err = client.Do(request) - c.Assert(err, IsNil) + c.Assert(err, nil) // verify whether complete multipart was successful. - c.Assert(response.StatusCode, Equals, http.StatusOK) + c.Assert(response.StatusCode, http.StatusOK) var parts []completePart for _, part := range completeUploads.Parts { part.ETag = canonicalizeETag(part.ETag) parts = append(parts, part) } etag, err := getCompleteMultipartMD5(parts) - c.Assert(err, IsNil) - c.Assert(canonicalizeETag(response.Header.Get("Etag")), Equals, etag) + c.Assert(err, nil) + c.Assert(canonicalizeETag(response.Header.Get("Etag")), etag) } diff --git a/cmd/storage-rpc-client_test.go b/cmd/storage-rpc-client_test.go index eda9b5150..6660ad4eb 100644 --- a/cmd/storage-rpc-client_test.go +++ b/cmd/storage-rpc-client_test.go @@ -219,8 +219,8 @@ type TestRPCStorageSuite struct { // Setting up the test suite. // Starting the Test server with temporary FS backend. -func (s *TestRPCStorageSuite) SetUpSuite(c *testing.T) { - s.testServer = StartTestStorageRPCServer(c, s.serverType, 1) +func (s *TestRPCStorageSuite) SetUpSuite(t *testing.T) { + s.testServer = StartTestStorageRPCServer(t, s.serverType, 1) listenAddress := s.testServer.Server.Listener.Addr().String() for _, ep := range s.testServer.Disks { @@ -236,9 +236,8 @@ func (s *TestRPCStorageSuite) SetUpSuite(c *testing.T) { } // No longer used with gocheck, but used in explicit teardown code in -// each test function. // Called implicitly by "gopkg.in/check.v1" -// after all tests are run. -func (s *TestRPCStorageSuite) TearDownSuite(c *testing.T) { +// each test function. Called implicitly by after all tests are run. +func (s *TestRPCStorageSuite) TearDownSuite(t *testing.T) { s.testServer.Stop() } diff --git a/cmd/test-utils_test.go b/cmd/test-utils_test.go index efaa68083..bc0c408ee 100644 --- a/cmd/test-utils_test.go +++ b/cmd/test-utils_test.go @@ -74,9 +74,7 @@ func init() { } // concurreny level for certain parallel tests. -const ( - testConcurrencyLevel = 10 -) +const testConcurrencyLevel = 10 /// /// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258 @@ -147,21 +145,6 @@ func calculateStreamContentLength(dataLen, chunkSize int64) int64 { return streamLen } -// Ask the kernel for a free open port. -func getFreePort() string { - addr, err := net.ResolveTCPAddr("tcp", "localhost:0") - if err != nil { - panic(err) - } - - l, err := net.ListenTCP("tcp", addr) - if err != nil { - panic(err) - } - defer l.Close() - return fmt.Sprintf("%d", l.Addr().(*net.TCPAddr).Port) -} - func prepareFS() (ObjectLayer, string, error) { nDisks := 1 fsDirs, err := getRandomDisks(nDisks) diff --git a/cmd/version_test.go b/cmd/version_test.go index 37e6ef710..62383c6c7 100644 --- a/cmd/version_test.go +++ b/cmd/version_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,14 @@ package cmd import ( - "net/http" + "testing" "time" - - . "gopkg.in/check.v1" ) -type VersionSuite struct{} - -var _ = Suite(&VersionSuite{}) - -func (s *VersionSuite) TestVersion(c *C) { - _, err := time.Parse(Version, http.TimeFormat) - c.Assert(err, NotNil) +func TestVersion(t *testing.T) { + Version = "2017-05-07T06:37:49Z" + _, err := time.Parse(time.RFC3339, Version) + if err != nil { + t.Fatal(err) + } } diff --git a/pkg/disk/disk_test.go b/pkg/disk/disk_test.go index a1a4915b1..415a36242 100644 --- a/pkg/disk/disk_test.go +++ b/pkg/disk/disk_test.go @@ -24,26 +24,33 @@ import ( "testing" "github.com/minio/minio/pkg/disk" - - . "gopkg.in/check.v1" ) -func Test(t *testing.T) { TestingT(t) } - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - -func (s *MySuite) TestFree(c *C) { +func TestFree(t *testing.T) { path, err := ioutil.TempDir(os.TempDir(), "minio-") defer os.RemoveAll(path) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } di, err := disk.GetInfo(path) - c.Assert(err, IsNil) - c.Assert(di.Total, Not(Equals), 0) - c.Assert(di.Free, Not(Equals), 0) - c.Assert(di.Files, Not(Equals), 0) - c.Assert(di.Ffree, Not(Equals), 0) - c.Assert(di.FSType, Not(Equals), "UNKNOWN") + if err != nil { + t.Fatal(err) + } + + if di.Total <= 0 { + t.Error("Unexpected Total", di.Total) + } + if di.Free <= 0 { + t.Error("Unexpected Free", di.Free) + } + if di.Files <= 0 { + t.Error("Unexpected Files", di.Files) + } + if di.Ffree <= 0 { + t.Error("Unexpected Ffree", di.Ffree) + } + if di.FSType == "UNKNOWN" { + t.Error("Unexpected FSType", di.FSType) + } } diff --git a/pkg/quick/quick_test.go b/pkg/quick/quick_test.go index c1b3c70d4..3eec610c7 100644 --- a/pkg/quick/quick_test.go +++ b/pkg/quick/quick_test.go @@ -1,7 +1,7 @@ /* * Quick - Quick key value store for config files and persistent state files * - * Quick (C) 2015 Minio, Inc. + * Quick (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package quick import ( + "bytes" "encoding/json" "io/ioutil" "os" @@ -26,70 +27,87 @@ import ( "runtime" "strings" "testing" - - . "gopkg.in/check.v1" ) -func Test(t *testing.T) { TestingT(t) } - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - -func (s *MySuite) TestReadVersion(c *C) { +func TestReadVersion(t *testing.T) { type myStruct struct { Version string } saveMe := myStruct{"1"} config, err := New(&saveMe) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } err = config.Save("test.json") - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } version, err := GetVersion("test.json") - c.Assert(err, IsNil) - c.Assert(version, Equals, "1") + if err != nil { + t.Fatal(err) + } + if version != "1" { + t.Fatalf("Expected version '1', got '%v'", version) + } } -func (s *MySuite) TestReadVersionErr(c *C) { +func TestReadVersionErr(t *testing.T) { type myStruct struct { Version int } saveMe := myStruct{1} _, err := New(&saveMe) - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal("Unexpected should fail in initialization for bad input") + } err = ioutil.WriteFile("test.json", []byte("{ \"version\":2,"), 0644) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } _, err = GetVersion("test.json") - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal("Unexpected should fail to fetch version") + } err = ioutil.WriteFile("test.json", []byte("{ \"version\":2 }"), 0644) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } _, err = GetVersion("test.json") - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal("Unexpected should fail to fetch version") + } } -func (s *MySuite) TestSaveFailOnDir(c *C) { - defer os.RemoveAll("test.json") - e := os.MkdirAll("test.json", 0644) - c.Assert(e, IsNil) +func TestSaveFailOnDir(t *testing.T) { + defer os.RemoveAll("test-1.json") + err := os.MkdirAll("test-1.json", 0644) + if err != nil { + t.Fatal(err) + } type myStruct struct { Version string } saveMe := myStruct{"1"} config, err := New(&saveMe) - c.Assert(err, IsNil) - c.Assert(config, Not(IsNil)) - err = config.Save("test.json") - c.Assert(err, Not(IsNil)) + if err != nil { + t.Fatal(err) + } + err = config.Save("test-1.json") + if err == nil { + t.Fatal("Unexpected should fail to save if test-1.json is a directory") + } } -func (s *MySuite) TestCheckData(c *C) { +func TestCheckData(t *testing.T) { err := checkData(nil) - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal("Unexpected should fail") + } type myStructBadNoVersion struct { User string @@ -98,7 +116,9 @@ func (s *MySuite) TestCheckData(c *C) { } saveMeBadNoVersion := myStructBadNoVersion{"guest", "nopassword", []string{"Work", "Documents", "Music"}} err = checkData(&saveMeBadNoVersion) - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal("Unexpected should fail if Version is not set") + } type myStructBadVersionInt struct { Version int @@ -107,7 +127,9 @@ func (s *MySuite) TestCheckData(c *C) { } saveMeBadVersionInt := myStructBadVersionInt{1, "guest", "nopassword"} err = checkData(&saveMeBadVersionInt) - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal("Unexpected should fail if Version is integer") + } type myStructGood struct { Version string @@ -118,10 +140,12 @@ func (s *MySuite) TestCheckData(c *C) { saveMeGood := myStructGood{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} err = checkData(&saveMeGood) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } } -func (s *MySuite) TestLoadFile(c *C) { +func TestLoadFile(t *testing.T) { type myStruct struct { Version string User string @@ -130,38 +154,64 @@ func (s *MySuite) TestLoadFile(c *C) { } saveMe := myStruct{} _, err := Load("test.json", &saveMe) - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal(err) + } file, err := os.Create("test.json") - c.Assert(err, IsNil) - c.Assert(file.Close(), IsNil) + if err != nil { + t.Fatal(err) + } + if err = file.Close(); err != nil { + t.Fatal(err) + } _, err = Load("test.json", &saveMe) - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal("Unexpected should fail to load empty JSON") + } config, err := New(&saveMe) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } err = config.Load("test-non-exist.json") - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal("Unexpected should fail to Load non-existent config") + } + err = config.Load("test.json") - c.Assert(err, Not(IsNil)) + if err == nil { + t.Fatal("Unexpected should fail to load empty JSON") + } saveMe = myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} config, err = New(&saveMe) - c.Assert(err, IsNil) - c.Assert(config, Not(IsNil)) + if err != nil { + t.Fatal(err) + } err = config.Save("test.json") - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } saveMe1 := myStruct{} _, err = Load("test.json", &saveMe1) - c.Assert(err, IsNil) - c.Assert(saveMe1, DeepEquals, saveMe) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(saveMe1, saveMe) { + t.Fatalf("Expected %v, got %v", saveMe1, saveMe) + } saveMe2 := myStruct{} err = json.Unmarshal([]byte(config.String()), &saveMe2) - c.Assert(err, IsNil) - c.Assert(saveMe2, DeepEquals, saveMe1) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(saveMe2, saveMe1) { + t.Fatalf("Expected %v, got %v", saveMe2, saveMe1) + } } -func (s *MySuite) TestYAMLFormat(c *C) { +func TestYAMLFormat(t *testing.T) { testYAML := "test.yaml" defer os.RemoveAll(testYAML) @@ -189,28 +239,43 @@ directories: // Save format using config, err := New(&saveMe) - c.Assert(err, IsNil) - c.Assert(config, Not(IsNil)) + if err != nil { + t.Fatal(err) + } err = config.Save(testYAML) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } // Check if the saved structure in actually an YAML format - bytes, err := ioutil.ReadFile(testYAML) - c.Assert(err, IsNil) + b, err := ioutil.ReadFile(testYAML) + if err != nil { + t.Fatal(err) + } - c.Assert(plainYAML, Equals, string(bytes)) + if !bytes.Equal([]byte(plainYAML), b) { + t.Fatalf("Expected %v, got %v", plainYAML, string(b)) + } // Check if the loaded data is the same as the saved one loadMe := myStruct{} config, err = New(&loadMe) + if err != nil { + t.Fatal(err) + } + err = config.Load(testYAML) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } - c.Assert(reflect.DeepEqual(saveMe, loadMe), Equals, true) + if !reflect.DeepEqual(saveMe, loadMe) { + t.Fatalf("Expected %v, got %v", saveMe, loadMe) + } } -func (s *MySuite) TestJSONFormat(c *C) { +func TestJSONFormat(t *testing.T) { testJSON := "test.json" defer os.RemoveAll(testJSON) @@ -240,28 +305,42 @@ func (s *MySuite) TestJSONFormat(c *C) { // Save format using config, err := New(&saveMe) - c.Assert(err, IsNil) - c.Assert(config, Not(IsNil)) + if err != nil { + t.Fatal(err) + } err = config.Save(testJSON) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } // Check if the saved structure in actually an JSON format - bytes, err := ioutil.ReadFile(testJSON) - c.Assert(err, IsNil) + b, err := ioutil.ReadFile(testJSON) + if err != nil { + t.Fatal(err) + } - c.Assert(plainJSON, Equals, string(bytes)) + if !bytes.Equal([]byte(plainJSON), b) { + t.Fatalf("Expected %v, got %v", plainJSON, string(b)) + } // Check if the loaded data is the same as the saved one loadMe := myStruct{} config, err = New(&loadMe) + if err != nil { + t.Fatal(err) + } err = config.Load(testJSON) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } - c.Assert(reflect.DeepEqual(saveMe, loadMe), Equals, true) + if !reflect.DeepEqual(saveMe, loadMe) { + t.Fatalf("Expected %v, got %v", saveMe, loadMe) + } } -func (s *MySuite) TestSaveLoad(c *C) { +func TestSaveLoad(t *testing.T) { defer os.RemoveAll("test.json") type myStruct struct { Version string @@ -271,26 +350,38 @@ func (s *MySuite) TestSaveLoad(c *C) { } saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} config, err := New(&saveMe) - c.Assert(err, IsNil) - c.Assert(config, Not(IsNil)) + if err != nil { + t.Fatal(err) + } err = config.Save("test.json") - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } loadMe := myStruct{Version: "1"} newConfig, err := New(&loadMe) - c.Assert(err, IsNil) - c.Assert(newConfig, Not(IsNil)) + if err != nil { + t.Fatal(err) + } err = newConfig.Load("test.json") - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } - c.Assert(config.Data(), DeepEquals, newConfig.Data()) - c.Assert(config.Data(), DeepEquals, &loadMe) + if !reflect.DeepEqual(config.Data(), newConfig.Data()) { + t.Fatalf("Expected %v, got %v", config.Data(), newConfig.Data()) + } + if !reflect.DeepEqual(config.Data(), &loadMe) { + t.Fatalf("Expected %v, got %v", config.Data(), &loadMe) + } mismatch := myStruct{"1.1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} - c.Assert(newConfig.Data(), Not(DeepEquals), &mismatch) + if reflect.DeepEqual(config.Data(), &mismatch) { + t.Fatal("Expected to mismatch but succeeded instead") + } } -func (s *MySuite) TestSaveBackup(c *C) { +func TestSaveBackup(t *testing.T) { defer os.RemoveAll("test.json") defer os.RemoveAll("test.json.old") type myStruct struct { @@ -301,31 +392,47 @@ func (s *MySuite) TestSaveBackup(c *C) { } saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} config, err := New(&saveMe) - c.Assert(err, IsNil) - c.Assert(config, Not(IsNil)) + if err != nil { + t.Fatal(err) + } err = config.Save("test.json") - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } loadMe := myStruct{Version: "1"} newConfig, err := New(&loadMe) - c.Assert(err, IsNil) - c.Assert(newConfig, Not(IsNil)) + if err != nil { + t.Fatal(err) + } err = newConfig.Load("test.json") - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } - c.Assert(config.Data(), DeepEquals, newConfig.Data()) - c.Assert(config.Data(), DeepEquals, &loadMe) + if !reflect.DeepEqual(config.Data(), newConfig.Data()) { + t.Fatalf("Expected %v, got %v", config.Data(), newConfig.Data()) + } + if !reflect.DeepEqual(config.Data(), &loadMe) { + t.Fatalf("Expected %v, got %v", config.Data(), &loadMe) + } mismatch := myStruct{"1.1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} - c.Assert(newConfig.Data(), Not(DeepEquals), &mismatch) + if reflect.DeepEqual(newConfig.Data(), &mismatch) { + t.Fatal("Expected to mismatch but succeeded instead") + } + config, err = New(&mismatch) - c.Assert(err, IsNil) - c.Assert(config, Not(IsNil)) + if err != nil { + t.Fatal(err) + } err = config.Save("test.json") - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } } -func (s *MySuite) TestDiff(c *C) { +func TestDiff(t *testing.T) { type myStruct struct { Version string User string @@ -334,8 +441,9 @@ func (s *MySuite) TestDiff(c *C) { } saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} config, err := New(&saveMe) - c.Assert(err, IsNil) - c.Assert(config, Not(IsNil)) + if err != nil { + t.Fatal(err) + } type myNewStruct struct { Version string @@ -346,12 +454,17 @@ func (s *MySuite) TestDiff(c *C) { mismatch := myNewStruct{"1", "nopassword", []string{"Work", "documents", "Music"}} newConfig, err := New(&mismatch) - c.Assert(err, IsNil) - c.Assert(newConfig, Not(IsNil)) + if err != nil { + t.Fatal(err) + } - fields, ok := config.Diff(newConfig) - c.Assert(ok, IsNil) - c.Assert(len(fields), Equals, 1) + fields, err := config.Diff(newConfig) + if err != nil { + t.Fatal(err) + } + if len(fields) != 1 { + t.Fatalf("Expected len 1, got %v", len(fields)) + } // Uncomment for debugging // for i, field := range fields { @@ -359,7 +472,7 @@ func (s *MySuite) TestDiff(c *C) { // } } -func (s *MySuite) TestDeepDiff(c *C) { +func TestDeepDiff(t *testing.T) { type myStruct struct { Version string User string @@ -368,17 +481,23 @@ func (s *MySuite) TestDeepDiff(c *C) { } saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} config, err := New(&saveMe) - c.Assert(err, IsNil) - c.Assert(config, Not(IsNil)) + if err != nil { + t.Fatal(err) + } mismatch := myStruct{"1", "Guest", "nopassword", []string{"Work", "documents", "Music"}} newConfig, err := New(&mismatch) - c.Assert(err, IsNil) - c.Assert(newConfig, Not(IsNil)) + if err != nil { + t.Fatal(err) + } fields, err := config.DeepDiff(newConfig) - c.Assert(err, IsNil) - c.Assert(len(fields), Equals, 2) + if err != nil { + t.Fatal(err) + } + if len(fields) != 2 { + t.Fatalf("Expected len 2, got %v", len(fields)) + } // Uncomment for debugging // for i, field := range fields { diff --git a/pkg/safe/safe_test.go b/pkg/safe/safe_test.go index 02dfa4103..5d20b7058 100644 --- a/pkg/safe/safe_test.go +++ b/pkg/safe/safe_test.go @@ -23,82 +23,172 @@ import ( "testing" os2 "github.com/minio/minio/pkg/x/os" - . "gopkg.in/check.v1" ) -func Test(t *testing.T) { TestingT(t) } - type MySuite struct { root string } -var _ = Suite(&MySuite{}) - -func (s *MySuite) SetUpSuite(c *C) { +func (s *MySuite) SetUpSuite(t *testing.T) { root, err := ioutil.TempDir(os.TempDir(), "safe_test.go.") - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } s.root = root } -func (s *MySuite) TearDownSuite(c *C) { - err := os.Remove(s.root) - c.Assert(err, IsNil) +func (s *MySuite) TearDownSuite(t *testing.T) { + err := os.RemoveAll(s.root) + if err != nil { + t.Fatal(err) + } } -func (s *MySuite) TestSafeAbort(c *C) { +func TestSafeAbort(t *testing.T) { + s := &MySuite{} + s.SetUpSuite(t) + defer s.TearDownSuite(t) + f, err := CreateFile(path.Join(s.root, "testfile-abort")) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + _, err = os2.Stat(path.Join(s.root, "testfile-abort")) - c.Assert(err, Not(IsNil)) + if !os.IsNotExist(err) { + t.Fatal(err) + } err = f.Abort() - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } err = f.Close() - c.Assert(err.Error(), Equals, "close on aborted file") + if err != nil { + if err.Error() != "close on aborted file" { + t.Fatal(err) + } + } } -func (s *MySuite) TestSafeClose(c *C) { +func TestSafeClose(t *testing.T) { + s := &MySuite{} + s.SetUpSuite(t) + defer s.TearDownSuite(t) + f, err := CreateFile(path.Join(s.root, "testfile-close")) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + _, err = os2.Stat(path.Join(s.root, "testfile-close")) - c.Assert(err, Not(IsNil)) + if !os.IsNotExist(err) { + t.Fatal(err) + } + err = f.Close() - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + _, err = os2.Stat(path.Join(s.root, "testfile-close")) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + err = os.Remove(path.Join(s.root, "testfile-close")) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + err = f.Abort() - c.Assert(err.Error(), Equals, "abort on closed file") + if err != nil { + if err.Error() != "abort on closed file" { + t.Fatal(err) + } + } } -func (s *MySuite) TestSafe(c *C) { +func TestSafe(t *testing.T) { + s := &MySuite{} + s.SetUpSuite(t) + defer s.TearDownSuite(t) + f, err := CreateFile(path.Join(s.root, "testfile-safe")) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + _, err = os2.Stat(path.Join(s.root, "testfile-safe")) - c.Assert(err, Not(IsNil)) + if !os.IsNotExist(err) { + t.Fatal(err) + } + err = f.Close() - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + _, err = f.Write([]byte("Test")) - c.Assert(err.Error(), Equals, "write on closed file") + if err != nil { + if err.Error() != "write on closed file" { + t.Fatal(err) + } + } + err = f.Close() - c.Assert(err.Error(), Equals, "close on closed file") + if err != nil { + if err.Error() != "close on closed file" { + t.Fatal(err) + } + } + _, err = os2.Stat(path.Join(s.root, "testfile-safe")) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + err = os.Remove(path.Join(s.root, "testfile-safe")) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } } -func (s *MySuite) TestSafeAbortWrite(c *C) { +func TestSafeAbortWrite(t *testing.T) { + s := &MySuite{} + s.SetUpSuite(t) + defer s.TearDownSuite(t) + f, err := CreateFile(path.Join(s.root, "purgefile-abort")) - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + _, err = os2.Stat(path.Join(s.root, "purgefile-abort")) - c.Assert(err, Not(IsNil)) + if !os.IsNotExist(err) { + t.Fatal(err) + } + err = f.Abort() - c.Assert(err, IsNil) + if err != nil { + t.Fatal(err) + } + _, err = os2.Stat(path.Join(s.root, "purgefile-abort")) - c.Assert(err, Not(IsNil)) + if !os.IsNotExist(err) { + t.Fatal(err) + } + err = f.Abort() - c.Assert(err.Error(), Equals, "abort on aborted file") + if err != nil { + if err.Error() != "abort on aborted file" { + t.Fatal(err) + } + } + _, err = f.Write([]byte("Test")) - c.Assert(err.Error(), Equals, "write on aborted file") + if err != nil { + if err.Error() != "write on aborted file" { + t.Fatal(err) + } + } } diff --git a/vendor/gopkg.in/check.v1/LICENSE b/vendor/gopkg.in/check.v1/LICENSE deleted file mode 100644 index 545cf2d33..000000000 --- a/vendor/gopkg.in/check.v1/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Gocheck - A rich testing framework for Go - -Copyright (c) 2010-2013 Gustavo Niemeyer - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/gopkg.in/check.v1/README.md b/vendor/gopkg.in/check.v1/README.md deleted file mode 100644 index 0ca9e5726..000000000 --- a/vendor/gopkg.in/check.v1/README.md +++ /dev/null @@ -1,20 +0,0 @@ -Instructions -============ - -Install the package with: - - go get gopkg.in/check.v1 - -Import it with: - - import "gopkg.in/check.v1" - -and use _check_ as the package name inside the code. - -For more details, visit the project page: - -* http://labix.org/gocheck - -and the API documentation: - -* https://gopkg.in/check.v1 diff --git a/vendor/gopkg.in/check.v1/TODO b/vendor/gopkg.in/check.v1/TODO deleted file mode 100644 index 33498270e..000000000 --- a/vendor/gopkg.in/check.v1/TODO +++ /dev/null @@ -1,2 +0,0 @@ -- Assert(slice, Contains, item) -- Parallel test support diff --git a/vendor/gopkg.in/check.v1/benchmark.go b/vendor/gopkg.in/check.v1/benchmark.go deleted file mode 100644 index 46ea9dc6d..000000000 --- a/vendor/gopkg.in/check.v1/benchmark.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) 2012 The Go Authors. All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package check - -import ( - "fmt" - "runtime" - "time" -) - -var memStats runtime.MemStats - -// testingB is a type passed to Benchmark functions to manage benchmark -// timing and to specify the number of iterations to run. -type timer struct { - start time.Time // Time test or benchmark started - duration time.Duration - N int - bytes int64 - timerOn bool - benchTime time.Duration - // The initial states of memStats.Mallocs and memStats.TotalAlloc. - startAllocs uint64 - startBytes uint64 - // The net total of this test after being run. - netAllocs uint64 - netBytes uint64 -} - -// StartTimer starts timing a test. This function is called automatically -// before a benchmark starts, but it can also used to resume timing after -// a call to StopTimer. -func (c *C) StartTimer() { - if !c.timerOn { - c.start = time.Now() - c.timerOn = true - - runtime.ReadMemStats(&memStats) - c.startAllocs = memStats.Mallocs - c.startBytes = memStats.TotalAlloc - } -} - -// StopTimer stops timing a test. This can be used to pause the timer -// while performing complex initialization that you don't -// want to measure. -func (c *C) StopTimer() { - if c.timerOn { - c.duration += time.Now().Sub(c.start) - c.timerOn = false - runtime.ReadMemStats(&memStats) - c.netAllocs += memStats.Mallocs - c.startAllocs - c.netBytes += memStats.TotalAlloc - c.startBytes - } -} - -// ResetTimer sets the elapsed benchmark time to zero. -// It does not affect whether the timer is running. -func (c *C) ResetTimer() { - if c.timerOn { - c.start = time.Now() - runtime.ReadMemStats(&memStats) - c.startAllocs = memStats.Mallocs - c.startBytes = memStats.TotalAlloc - } - c.duration = 0 - c.netAllocs = 0 - c.netBytes = 0 -} - -// SetBytes informs the number of bytes that the benchmark processes -// on each iteration. If this is called in a benchmark it will also -// report MB/s. -func (c *C) SetBytes(n int64) { - c.bytes = n -} - -func (c *C) nsPerOp() int64 { - if c.N <= 0 { - return 0 - } - return c.duration.Nanoseconds() / int64(c.N) -} - -func (c *C) mbPerSec() float64 { - if c.bytes <= 0 || c.duration <= 0 || c.N <= 0 { - return 0 - } - return (float64(c.bytes) * float64(c.N) / 1e6) / c.duration.Seconds() -} - -func (c *C) timerString() string { - if c.N <= 0 { - return fmt.Sprintf("%3.3fs", float64(c.duration.Nanoseconds())/1e9) - } - mbs := c.mbPerSec() - mb := "" - if mbs != 0 { - mb = fmt.Sprintf("\t%7.2f MB/s", mbs) - } - nsop := c.nsPerOp() - ns := fmt.Sprintf("%10d ns/op", nsop) - if c.N > 0 && nsop < 100 { - // The format specifiers here make sure that - // the ones digits line up for all three possible formats. - if nsop < 10 { - ns = fmt.Sprintf("%13.2f ns/op", float64(c.duration.Nanoseconds())/float64(c.N)) - } else { - ns = fmt.Sprintf("%12.1f ns/op", float64(c.duration.Nanoseconds())/float64(c.N)) - } - } - memStats := "" - if c.benchMem { - allocedBytes := fmt.Sprintf("%8d B/op", int64(c.netBytes)/int64(c.N)) - allocs := fmt.Sprintf("%8d allocs/op", int64(c.netAllocs)/int64(c.N)) - memStats = fmt.Sprintf("\t%s\t%s", allocedBytes, allocs) - } - return fmt.Sprintf("%8d\t%s%s%s", c.N, ns, mb, memStats) -} - -func min(x, y int) int { - if x > y { - return y - } - return x -} - -func max(x, y int) int { - if x < y { - return y - } - return x -} - -// roundDown10 rounds a number down to the nearest power of 10. -func roundDown10(n int) int { - var tens = 0 - // tens = floor(log_10(n)) - for n > 10 { - n = n / 10 - tens++ - } - // result = 10^tens - result := 1 - for i := 0; i < tens; i++ { - result *= 10 - } - return result -} - -// roundUp rounds x up to a number of the form [1eX, 2eX, 5eX]. -func roundUp(n int) int { - base := roundDown10(n) - if n < (2 * base) { - return 2 * base - } - if n < (5 * base) { - return 5 * base - } - return 10 * base -} diff --git a/vendor/gopkg.in/check.v1/check.go b/vendor/gopkg.in/check.v1/check.go deleted file mode 100644 index c99392a25..000000000 --- a/vendor/gopkg.in/check.v1/check.go +++ /dev/null @@ -1,954 +0,0 @@ -// Package check is a rich testing extension for Go's testing package. -// -// For details about the project, see: -// -// http://labix.org/gocheck -// -package check - -import ( - "bytes" - "errors" - "fmt" - "io" - "math/rand" - "os" - "path" - "path/filepath" - "reflect" - "regexp" - "runtime" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" -) - -// ----------------------------------------------------------------------- -// Internal type which deals with suite method calling. - -const ( - fixtureKd = iota - testKd -) - -type funcKind int - -const ( - succeededSt = iota - failedSt - skippedSt - panickedSt - fixturePanickedSt - missedSt -) - -type funcStatus uint32 - -// A method value can't reach its own Method structure. -type methodType struct { - reflect.Value - Info reflect.Method -} - -func newMethod(receiver reflect.Value, i int) *methodType { - return &methodType{receiver.Method(i), receiver.Type().Method(i)} -} - -func (method *methodType) PC() uintptr { - return method.Info.Func.Pointer() -} - -func (method *methodType) suiteName() string { - t := method.Info.Type.In(0) - if t.Kind() == reflect.Ptr { - t = t.Elem() - } - return t.Name() -} - -func (method *methodType) String() string { - return method.suiteName() + "." + method.Info.Name -} - -func (method *methodType) matches(re *regexp.Regexp) bool { - return (re.MatchString(method.Info.Name) || - re.MatchString(method.suiteName()) || - re.MatchString(method.String())) -} - -type C struct { - method *methodType - kind funcKind - testName string - _status funcStatus - logb *logger - logw io.Writer - done chan *C - reason string - mustFail bool - tempDir *tempDir - benchMem bool - startTime time.Time - timer -} - -func (c *C) status() funcStatus { - return funcStatus(atomic.LoadUint32((*uint32)(&c._status))) -} - -func (c *C) setStatus(s funcStatus) { - atomic.StoreUint32((*uint32)(&c._status), uint32(s)) -} - -func (c *C) stopNow() { - runtime.Goexit() -} - -// logger is a concurrency safe byte.Buffer -type logger struct { - sync.Mutex - writer bytes.Buffer -} - -func (l *logger) Write(buf []byte) (int, error) { - l.Lock() - defer l.Unlock() - return l.writer.Write(buf) -} - -func (l *logger) WriteTo(w io.Writer) (int64, error) { - l.Lock() - defer l.Unlock() - return l.writer.WriteTo(w) -} - -func (l *logger) String() string { - l.Lock() - defer l.Unlock() - return l.writer.String() -} - -// ----------------------------------------------------------------------- -// Handling of temporary files and directories. - -type tempDir struct { - sync.Mutex - path string - counter int -} - -func (td *tempDir) newPath() string { - td.Lock() - defer td.Unlock() - if td.path == "" { - var err error - for i := 0; i != 100; i++ { - path := fmt.Sprintf("%s%ccheck-%d", os.TempDir(), os.PathSeparator, rand.Int()) - if err = os.Mkdir(path, 0700); err == nil { - td.path = path - break - } - } - if td.path == "" { - panic("Couldn't create temporary directory: " + err.Error()) - } - } - result := filepath.Join(td.path, strconv.Itoa(td.counter)) - td.counter += 1 - return result -} - -func (td *tempDir) removeAll() { - td.Lock() - defer td.Unlock() - if td.path != "" { - err := os.RemoveAll(td.path) - if err != nil { - fmt.Fprintf(os.Stderr, "WARNING: Error cleaning up temporaries: "+err.Error()) - } - } -} - -// Create a new temporary directory which is automatically removed after -// the suite finishes running. -func (c *C) MkDir() string { - path := c.tempDir.newPath() - if err := os.Mkdir(path, 0700); err != nil { - panic(fmt.Sprintf("Couldn't create temporary directory %s: %s", path, err.Error())) - } - return path -} - -// ----------------------------------------------------------------------- -// Low-level logging functions. - -func (c *C) log(args ...interface{}) { - c.writeLog([]byte(fmt.Sprint(args...) + "\n")) -} - -func (c *C) logf(format string, args ...interface{}) { - c.writeLog([]byte(fmt.Sprintf(format+"\n", args...))) -} - -func (c *C) logNewLine() { - c.writeLog([]byte{'\n'}) -} - -func (c *C) writeLog(buf []byte) { - c.logb.Write(buf) - if c.logw != nil { - c.logw.Write(buf) - } -} - -func hasStringOrError(x interface{}) (ok bool) { - _, ok = x.(fmt.Stringer) - if ok { - return - } - _, ok = x.(error) - return -} - -func (c *C) logValue(label string, value interface{}) { - if label == "" { - if hasStringOrError(value) { - c.logf("... %#v (%q)", value, value) - } else { - c.logf("... %#v", value) - } - } else if value == nil { - c.logf("... %s = nil", label) - } else { - if hasStringOrError(value) { - fv := fmt.Sprintf("%#v", value) - qv := fmt.Sprintf("%q", value) - if fv != qv { - c.logf("... %s %s = %s (%s)", label, reflect.TypeOf(value), fv, qv) - return - } - } - if s, ok := value.(string); ok && isMultiLine(s) { - c.logf(`... %s %s = "" +`, label, reflect.TypeOf(value)) - c.logMultiLine(s) - } else { - c.logf("... %s %s = %#v", label, reflect.TypeOf(value), value) - } - } -} - -func (c *C) logMultiLine(s string) { - b := make([]byte, 0, len(s)*2) - i := 0 - n := len(s) - for i < n { - j := i + 1 - for j < n && s[j-1] != '\n' { - j++ - } - b = append(b, "... "...) - b = strconv.AppendQuote(b, s[i:j]) - if j < n { - b = append(b, " +"...) - } - b = append(b, '\n') - i = j - } - c.writeLog(b) -} - -func isMultiLine(s string) bool { - for i := 0; i+1 < len(s); i++ { - if s[i] == '\n' { - return true - } - } - return false -} - -func (c *C) logString(issue string) { - c.log("... ", issue) -} - -func (c *C) logCaller(skip int) { - // This is a bit heavier than it ought to be. - skip += 1 // Our own frame. - pc, callerFile, callerLine, ok := runtime.Caller(skip) - if !ok { - return - } - var testFile string - var testLine int - testFunc := runtime.FuncForPC(c.method.PC()) - if runtime.FuncForPC(pc) != testFunc { - for { - skip += 1 - if pc, file, line, ok := runtime.Caller(skip); ok { - // Note that the test line may be different on - // distinct calls for the same test. Showing - // the "internal" line is helpful when debugging. - if runtime.FuncForPC(pc) == testFunc { - testFile, testLine = file, line - break - } - } else { - break - } - } - } - if testFile != "" && (testFile != callerFile || testLine != callerLine) { - c.logCode(testFile, testLine) - } - c.logCode(callerFile, callerLine) -} - -func (c *C) logCode(path string, line int) { - c.logf("%s:%d:", nicePath(path), line) - code, err := printLine(path, line) - if code == "" { - code = "..." // XXX Open the file and take the raw line. - if err != nil { - code += err.Error() - } - } - c.log(indent(code, " ")) -} - -var valueGo = filepath.Join("reflect", "value.go") -var asmGo = filepath.Join("runtime", "asm_") - -func (c *C) logPanic(skip int, value interface{}) { - skip++ // Our own frame. - initialSkip := skip - for ; ; skip++ { - if pc, file, line, ok := runtime.Caller(skip); ok { - if skip == initialSkip { - c.logf("... Panic: %s (PC=0x%X)\n", value, pc) - } - name := niceFuncName(pc) - path := nicePath(file) - if strings.Contains(path, "/gopkg.in/check.v") { - continue - } - if name == "Value.call" && strings.HasSuffix(path, valueGo) { - continue - } - if (name == "call16" || name == "call32") && strings.Contains(path, asmGo) { - continue - } - c.logf("%s:%d\n in %s", nicePath(file), line, name) - } else { - break - } - } -} - -func (c *C) logSoftPanic(issue string) { - c.log("... Panic: ", issue) -} - -func (c *C) logArgPanic(method *methodType, expectedType string) { - c.logf("... Panic: %s argument should be %s", - niceFuncName(method.PC()), expectedType) -} - -// ----------------------------------------------------------------------- -// Some simple formatting helpers. - -var initWD, initWDErr = os.Getwd() - -func init() { - if initWDErr == nil { - initWD = strings.Replace(initWD, "\\", "/", -1) + "/" - } -} - -func nicePath(path string) string { - if initWDErr == nil { - if strings.HasPrefix(path, initWD) { - return path[len(initWD):] - } - } - return path -} - -func niceFuncPath(pc uintptr) string { - function := runtime.FuncForPC(pc) - if function != nil { - filename, line := function.FileLine(pc) - return fmt.Sprintf("%s:%d", nicePath(filename), line) - } - return "" -} - -func niceFuncName(pc uintptr) string { - function := runtime.FuncForPC(pc) - if function != nil { - name := path.Base(function.Name()) - if i := strings.Index(name, "."); i > 0 { - name = name[i+1:] - } - if strings.HasPrefix(name, "(*") { - if i := strings.Index(name, ")"); i > 0 { - name = name[2:i] + name[i+1:] - } - } - if i := strings.LastIndex(name, ".*"); i != -1 { - name = name[:i] + "." + name[i+2:] - } - if i := strings.LastIndex(name, "ยท"); i != -1 { - name = name[:i] + "." + name[i+2:] - } - return name - } - return "" -} - -// ----------------------------------------------------------------------- -// Result tracker to aggregate call results. - -type Result struct { - Succeeded int - Failed int - Skipped int - Panicked int - FixturePanicked int - ExpectedFailures int - Missed int // Not even tried to run, related to a panic in the fixture. - RunError error // Houston, we've got a problem. - WorkDir string // If KeepWorkDir is true -} - -type resultTracker struct { - result Result - _lastWasProblem bool - _waiting int - _missed int - _expectChan chan *C - _doneChan chan *C - _stopChan chan bool -} - -func newResultTracker() *resultTracker { - return &resultTracker{_expectChan: make(chan *C), // Synchronous - _doneChan: make(chan *C, 32), // Asynchronous - _stopChan: make(chan bool)} // Synchronous -} - -func (tracker *resultTracker) start() { - go tracker._loopRoutine() -} - -func (tracker *resultTracker) waitAndStop() { - <-tracker._stopChan -} - -func (tracker *resultTracker) expectCall(c *C) { - tracker._expectChan <- c -} - -func (tracker *resultTracker) callDone(c *C) { - tracker._doneChan <- c -} - -func (tracker *resultTracker) _loopRoutine() { - for { - var c *C - if tracker._waiting > 0 { - // Calls still running. Can't stop. - select { - // XXX Reindent this (not now to make diff clear) - case c = <-tracker._expectChan: - tracker._waiting += 1 - case c = <-tracker._doneChan: - tracker._waiting -= 1 - switch c.status() { - case succeededSt: - if c.kind == testKd { - if c.mustFail { - tracker.result.ExpectedFailures++ - } else { - tracker.result.Succeeded++ - } - } - case failedSt: - tracker.result.Failed++ - case panickedSt: - if c.kind == fixtureKd { - tracker.result.FixturePanicked++ - } else { - tracker.result.Panicked++ - } - case fixturePanickedSt: - // Track it as missed, since the panic - // was on the fixture, not on the test. - tracker.result.Missed++ - case missedSt: - tracker.result.Missed++ - case skippedSt: - if c.kind == testKd { - tracker.result.Skipped++ - } - } - } - } else { - // No calls. Can stop, but no done calls here. - select { - case tracker._stopChan <- true: - return - case c = <-tracker._expectChan: - tracker._waiting += 1 - case c = <-tracker._doneChan: - panic("Tracker got an unexpected done call.") - } - } - } -} - -// ----------------------------------------------------------------------- -// The underlying suite runner. - -type suiteRunner struct { - suite interface{} - setUpSuite, tearDownSuite *methodType - setUpTest, tearDownTest *methodType - tests []*methodType - tracker *resultTracker - tempDir *tempDir - keepDir bool - output *outputWriter - reportedProblemLast bool - benchTime time.Duration - benchMem bool -} - -type RunConf struct { - Output io.Writer - Stream bool - Verbose bool - Filter string - Benchmark bool - BenchmarkTime time.Duration // Defaults to 1 second - BenchmarkMem bool - KeepWorkDir bool -} - -// Create a new suiteRunner able to run all methods in the given suite. -func newSuiteRunner(suite interface{}, runConf *RunConf) *suiteRunner { - var conf RunConf - if runConf != nil { - conf = *runConf - } - if conf.Output == nil { - conf.Output = os.Stdout - } - if conf.Benchmark { - conf.Verbose = true - } - - suiteType := reflect.TypeOf(suite) - suiteNumMethods := suiteType.NumMethod() - suiteValue := reflect.ValueOf(suite) - - runner := &suiteRunner{ - suite: suite, - output: newOutputWriter(conf.Output, conf.Stream, conf.Verbose), - tracker: newResultTracker(), - benchTime: conf.BenchmarkTime, - benchMem: conf.BenchmarkMem, - tempDir: &tempDir{}, - keepDir: conf.KeepWorkDir, - tests: make([]*methodType, 0, suiteNumMethods), - } - if runner.benchTime == 0 { - runner.benchTime = 1 * time.Second - } - - var filterRegexp *regexp.Regexp - if conf.Filter != "" { - if regexp, err := regexp.Compile(conf.Filter); err != nil { - msg := "Bad filter expression: " + err.Error() - runner.tracker.result.RunError = errors.New(msg) - return runner - } else { - filterRegexp = regexp - } - } - - for i := 0; i != suiteNumMethods; i++ { - method := newMethod(suiteValue, i) - switch method.Info.Name { - case "SetUpSuite": - runner.setUpSuite = method - case "TearDownSuite": - runner.tearDownSuite = method - case "SetUpTest": - runner.setUpTest = method - case "TearDownTest": - runner.tearDownTest = method - default: - prefix := "Test" - if conf.Benchmark { - prefix = "Benchmark" - } - if !strings.HasPrefix(method.Info.Name, prefix) { - continue - } - if filterRegexp == nil || method.matches(filterRegexp) { - runner.tests = append(runner.tests, method) - } - } - } - return runner -} - -// Run all methods in the given suite. -func (runner *suiteRunner) run() *Result { - if runner.tracker.result.RunError == nil && len(runner.tests) > 0 { - runner.tracker.start() - if runner.checkFixtureArgs() { - c := runner.runFixture(runner.setUpSuite, "", nil) - if c == nil || c.status() == succeededSt { - for i := 0; i != len(runner.tests); i++ { - c := runner.runTest(runner.tests[i]) - if c.status() == fixturePanickedSt { - runner.skipTests(missedSt, runner.tests[i+1:]) - break - } - } - } else if c != nil && c.status() == skippedSt { - runner.skipTests(skippedSt, runner.tests) - } else { - runner.skipTests(missedSt, runner.tests) - } - runner.runFixture(runner.tearDownSuite, "", nil) - } else { - runner.skipTests(missedSt, runner.tests) - } - runner.tracker.waitAndStop() - if runner.keepDir { - runner.tracker.result.WorkDir = runner.tempDir.path - } else { - runner.tempDir.removeAll() - } - } - return &runner.tracker.result -} - -// Create a call object with the given suite method, and fork a -// goroutine with the provided dispatcher for running it. -func (runner *suiteRunner) forkCall(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C { - var logw io.Writer - if runner.output.Stream { - logw = runner.output - } - if logb == nil { - logb = new(logger) - } - c := &C{ - method: method, - kind: kind, - testName: testName, - logb: logb, - logw: logw, - tempDir: runner.tempDir, - done: make(chan *C, 1), - timer: timer{benchTime: runner.benchTime}, - startTime: time.Now(), - benchMem: runner.benchMem, - } - runner.tracker.expectCall(c) - go (func() { - runner.reportCallStarted(c) - defer runner.callDone(c) - dispatcher(c) - })() - return c -} - -// Same as forkCall(), but wait for call to finish before returning. -func (runner *suiteRunner) runFunc(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C { - c := runner.forkCall(method, kind, testName, logb, dispatcher) - <-c.done - return c -} - -// Handle a finished call. If there were any panics, update the call status -// accordingly. Then, mark the call as done and report to the tracker. -func (runner *suiteRunner) callDone(c *C) { - value := recover() - if value != nil { - switch v := value.(type) { - case *fixturePanic: - if v.status == skippedSt { - c.setStatus(skippedSt) - } else { - c.logSoftPanic("Fixture has panicked (see related PANIC)") - c.setStatus(fixturePanickedSt) - } - default: - c.logPanic(1, value) - c.setStatus(panickedSt) - } - } - if c.mustFail { - switch c.status() { - case failedSt: - c.setStatus(succeededSt) - case succeededSt: - c.setStatus(failedSt) - c.logString("Error: Test succeeded, but was expected to fail") - c.logString("Reason: " + c.reason) - } - } - - runner.reportCallDone(c) - c.done <- c -} - -// Runs a fixture call synchronously. The fixture will still be run in a -// goroutine like all suite methods, but this method will not return -// while the fixture goroutine is not done, because the fixture must be -// run in a desired order. -func (runner *suiteRunner) runFixture(method *methodType, testName string, logb *logger) *C { - if method != nil { - c := runner.runFunc(method, fixtureKd, testName, logb, func(c *C) { - c.ResetTimer() - c.StartTimer() - defer c.StopTimer() - c.method.Call([]reflect.Value{reflect.ValueOf(c)}) - }) - return c - } - return nil -} - -// Run the fixture method with runFixture(), but panic with a fixturePanic{} -// in case the fixture method panics. This makes it easier to track the -// fixture panic together with other call panics within forkTest(). -func (runner *suiteRunner) runFixtureWithPanic(method *methodType, testName string, logb *logger, skipped *bool) *C { - if skipped != nil && *skipped { - return nil - } - c := runner.runFixture(method, testName, logb) - if c != nil && c.status() != succeededSt { - if skipped != nil { - *skipped = c.status() == skippedSt - } - panic(&fixturePanic{c.status(), method}) - } - return c -} - -type fixturePanic struct { - status funcStatus - method *methodType -} - -// Run the suite test method, together with the test-specific fixture, -// asynchronously. -func (runner *suiteRunner) forkTest(method *methodType) *C { - testName := method.String() - return runner.forkCall(method, testKd, testName, nil, func(c *C) { - var skipped bool - defer runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, &skipped) - defer c.StopTimer() - benchN := 1 - for { - runner.runFixtureWithPanic(runner.setUpTest, testName, c.logb, &skipped) - mt := c.method.Type() - if mt.NumIn() != 1 || mt.In(0) != reflect.TypeOf(c) { - // Rather than a plain panic, provide a more helpful message when - // the argument type is incorrect. - c.setStatus(panickedSt) - c.logArgPanic(c.method, "*check.C") - return - } - if strings.HasPrefix(c.method.Info.Name, "Test") { - c.ResetTimer() - c.StartTimer() - c.method.Call([]reflect.Value{reflect.ValueOf(c)}) - return - } - if !strings.HasPrefix(c.method.Info.Name, "Benchmark") { - panic("unexpected method prefix: " + c.method.Info.Name) - } - - runtime.GC() - c.N = benchN - c.ResetTimer() - c.StartTimer() - c.method.Call([]reflect.Value{reflect.ValueOf(c)}) - c.StopTimer() - if c.status() != succeededSt || c.duration >= c.benchTime || benchN >= 1e9 { - return - } - perOpN := int(1e9) - if c.nsPerOp() != 0 { - perOpN = int(c.benchTime.Nanoseconds() / c.nsPerOp()) - } - - // Logic taken from the stock testing package: - // - Run more iterations than we think we'll need for a second (1.5x). - // - Don't grow too fast in case we had timing errors previously. - // - Be sure to run at least one more than last time. - benchN = max(min(perOpN+perOpN/2, 100*benchN), benchN+1) - benchN = roundUp(benchN) - - skipped = true // Don't run the deferred one if this panics. - runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, nil) - skipped = false - } - }) -} - -// Same as forkTest(), but wait for the test to finish before returning. -func (runner *suiteRunner) runTest(method *methodType) *C { - c := runner.forkTest(method) - <-c.done - return c -} - -// Helper to mark tests as skipped or missed. A bit heavy for what -// it does, but it enables homogeneous handling of tracking, including -// nice verbose output. -func (runner *suiteRunner) skipTests(status funcStatus, methods []*methodType) { - for _, method := range methods { - runner.runFunc(method, testKd, "", nil, func(c *C) { - c.setStatus(status) - }) - } -} - -// Verify if the fixture arguments are *check.C. In case of errors, -// log the error as a panic in the fixture method call, and return false. -func (runner *suiteRunner) checkFixtureArgs() bool { - succeeded := true - argType := reflect.TypeOf(&C{}) - for _, method := range []*methodType{runner.setUpSuite, runner.tearDownSuite, runner.setUpTest, runner.tearDownTest} { - if method != nil { - mt := method.Type() - if mt.NumIn() != 1 || mt.In(0) != argType { - succeeded = false - runner.runFunc(method, fixtureKd, "", nil, func(c *C) { - c.logArgPanic(method, "*check.C") - c.setStatus(panickedSt) - }) - } - } - } - return succeeded -} - -func (runner *suiteRunner) reportCallStarted(c *C) { - runner.output.WriteCallStarted("START", c) -} - -func (runner *suiteRunner) reportCallDone(c *C) { - runner.tracker.callDone(c) - switch c.status() { - case succeededSt: - if c.mustFail { - runner.output.WriteCallSuccess("FAIL EXPECTED", c) - } else { - runner.output.WriteCallSuccess("PASS", c) - } - case skippedSt: - runner.output.WriteCallSuccess("SKIP", c) - case failedSt: - runner.output.WriteCallProblem("FAIL", c) - case panickedSt: - runner.output.WriteCallProblem("PANIC", c) - case fixturePanickedSt: - // That's a testKd call reporting that its fixture - // has panicked. The fixture call which caused the - // panic itself was tracked above. We'll report to - // aid debugging. - runner.output.WriteCallProblem("PANIC", c) - case missedSt: - runner.output.WriteCallSuccess("MISS", c) - } -} - -// ----------------------------------------------------------------------- -// Output writer manages atomic output writing according to settings. - -type outputWriter struct { - m sync.Mutex - writer io.Writer - wroteCallProblemLast bool - Stream bool - Verbose bool -} - -func newOutputWriter(writer io.Writer, stream, verbose bool) *outputWriter { - return &outputWriter{writer: writer, Stream: stream, Verbose: verbose} -} - -func (ow *outputWriter) Write(content []byte) (n int, err error) { - ow.m.Lock() - n, err = ow.writer.Write(content) - ow.m.Unlock() - return -} - -func (ow *outputWriter) WriteCallStarted(label string, c *C) { - if ow.Stream { - header := renderCallHeader(label, c, "", "\n") - ow.m.Lock() - ow.writer.Write([]byte(header)) - ow.m.Unlock() - } -} - -func (ow *outputWriter) WriteCallProblem(label string, c *C) { - var prefix string - if !ow.Stream { - prefix = "\n-----------------------------------" + - "-----------------------------------\n" - } - header := renderCallHeader(label, c, prefix, "\n\n") - ow.m.Lock() - ow.wroteCallProblemLast = true - ow.writer.Write([]byte(header)) - if !ow.Stream { - c.logb.WriteTo(ow.writer) - } - ow.m.Unlock() -} - -func (ow *outputWriter) WriteCallSuccess(label string, c *C) { - if ow.Stream || (ow.Verbose && c.kind == testKd) { - // TODO Use a buffer here. - var suffix string - if c.reason != "" { - suffix = " (" + c.reason + ")" - } - if c.status() == succeededSt { - suffix += "\t" + c.timerString() - } - suffix += "\n" - if ow.Stream { - suffix += "\n" - } - header := renderCallHeader(label, c, "", suffix) - ow.m.Lock() - // Resist temptation of using line as prefix above due to race. - if !ow.Stream && ow.wroteCallProblemLast { - header = "\n-----------------------------------" + - "-----------------------------------\n" + - header - } - ow.wroteCallProblemLast = false - ow.writer.Write([]byte(header)) - ow.m.Unlock() - } -} - -func renderCallHeader(label string, c *C, prefix, suffix string) string { - pc := c.method.PC() - return fmt.Sprintf("%s%s: %s: %s%s", prefix, label, niceFuncPath(pc), - niceFuncName(pc), suffix) -} diff --git a/vendor/gopkg.in/check.v1/checkers.go b/vendor/gopkg.in/check.v1/checkers.go deleted file mode 100644 index bac338729..000000000 --- a/vendor/gopkg.in/check.v1/checkers.go +++ /dev/null @@ -1,458 +0,0 @@ -package check - -import ( - "fmt" - "reflect" - "regexp" -) - -// ----------------------------------------------------------------------- -// CommentInterface and Commentf helper, to attach extra information to checks. - -type comment struct { - format string - args []interface{} -} - -// Commentf returns an infomational value to use with Assert or Check calls. -// If the checker test fails, the provided arguments will be passed to -// fmt.Sprintf, and will be presented next to the logged failure. -// -// For example: -// -// c.Assert(v, Equals, 42, Commentf("Iteration #%d failed.", i)) -// -// Note that if the comment is constant, a better option is to -// simply use a normal comment right above or next to the line, as -// it will also get printed with any errors: -// -// c.Assert(l, Equals, 8192) // Ensure buffer size is correct (bug #123) -// -func Commentf(format string, args ...interface{}) CommentInterface { - return &comment{format, args} -} - -// CommentInterface must be implemented by types that attach extra -// information to failed checks. See the Commentf function for details. -type CommentInterface interface { - CheckCommentString() string -} - -func (c *comment) CheckCommentString() string { - return fmt.Sprintf(c.format, c.args...) -} - -// ----------------------------------------------------------------------- -// The Checker interface. - -// The Checker interface must be provided by checkers used with -// the Assert and Check verification methods. -type Checker interface { - Info() *CheckerInfo - Check(params []interface{}, names []string) (result bool, error string) -} - -// See the Checker interface. -type CheckerInfo struct { - Name string - Params []string -} - -func (info *CheckerInfo) Info() *CheckerInfo { - return info -} - -// ----------------------------------------------------------------------- -// Not checker logic inverter. - -// The Not checker inverts the logic of the provided checker. The -// resulting checker will succeed where the original one failed, and -// vice-versa. -// -// For example: -// -// c.Assert(a, Not(Equals), b) -// -func Not(checker Checker) Checker { - return ¬Checker{checker} -} - -type notChecker struct { - sub Checker -} - -func (checker *notChecker) Info() *CheckerInfo { - info := *checker.sub.Info() - info.Name = "Not(" + info.Name + ")" - return &info -} - -func (checker *notChecker) Check(params []interface{}, names []string) (result bool, error string) { - result, error = checker.sub.Check(params, names) - result = !result - return -} - -// ----------------------------------------------------------------------- -// IsNil checker. - -type isNilChecker struct { - *CheckerInfo -} - -// The IsNil checker tests whether the obtained value is nil. -// -// For example: -// -// c.Assert(err, IsNil) -// -var IsNil Checker = &isNilChecker{ - &CheckerInfo{Name: "IsNil", Params: []string{"value"}}, -} - -func (checker *isNilChecker) Check(params []interface{}, names []string) (result bool, error string) { - return isNil(params[0]), "" -} - -func isNil(obtained interface{}) (result bool) { - if obtained == nil { - result = true - } else { - switch v := reflect.ValueOf(obtained); v.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - } - return -} - -// ----------------------------------------------------------------------- -// NotNil checker. Alias for Not(IsNil), since it's so common. - -type notNilChecker struct { - *CheckerInfo -} - -// The NotNil checker verifies that the obtained value is not nil. -// -// For example: -// -// c.Assert(iface, NotNil) -// -// This is an alias for Not(IsNil), made available since it's a -// fairly common check. -// -var NotNil Checker = ¬NilChecker{ - &CheckerInfo{Name: "NotNil", Params: []string{"value"}}, -} - -func (checker *notNilChecker) Check(params []interface{}, names []string) (result bool, error string) { - return !isNil(params[0]), "" -} - -// ----------------------------------------------------------------------- -// Equals checker. - -type equalsChecker struct { - *CheckerInfo -} - -// The Equals checker verifies that the obtained value is equal to -// the expected value, according to usual Go semantics for ==. -// -// For example: -// -// c.Assert(value, Equals, 42) -// -var Equals Checker = &equalsChecker{ - &CheckerInfo{Name: "Equals", Params: []string{"obtained", "expected"}}, -} - -func (checker *equalsChecker) Check(params []interface{}, names []string) (result bool, error string) { - defer func() { - if v := recover(); v != nil { - result = false - error = fmt.Sprint(v) - } - }() - return params[0] == params[1], "" -} - -// ----------------------------------------------------------------------- -// DeepEquals checker. - -type deepEqualsChecker struct { - *CheckerInfo -} - -// The DeepEquals checker verifies that the obtained value is deep-equal to -// the expected value. The check will work correctly even when facing -// slices, interfaces, and values of different types (which always fail -// the test). -// -// For example: -// -// c.Assert(value, DeepEquals, 42) -// c.Assert(array, DeepEquals, []string{"hi", "there"}) -// -var DeepEquals Checker = &deepEqualsChecker{ - &CheckerInfo{Name: "DeepEquals", Params: []string{"obtained", "expected"}}, -} - -func (checker *deepEqualsChecker) Check(params []interface{}, names []string) (result bool, error string) { - return reflect.DeepEqual(params[0], params[1]), "" -} - -// ----------------------------------------------------------------------- -// HasLen checker. - -type hasLenChecker struct { - *CheckerInfo -} - -// The HasLen checker verifies that the obtained value has the -// provided length. In many cases this is superior to using Equals -// in conjuction with the len function because in case the check -// fails the value itself will be printed, instead of its length, -// providing more details for figuring the problem. -// -// For example: -// -// c.Assert(list, HasLen, 5) -// -var HasLen Checker = &hasLenChecker{ - &CheckerInfo{Name: "HasLen", Params: []string{"obtained", "n"}}, -} - -func (checker *hasLenChecker) Check(params []interface{}, names []string) (result bool, error string) { - n, ok := params[1].(int) - if !ok { - return false, "n must be an int" - } - value := reflect.ValueOf(params[0]) - switch value.Kind() { - case reflect.Map, reflect.Array, reflect.Slice, reflect.Chan, reflect.String: - default: - return false, "obtained value type has no length" - } - return value.Len() == n, "" -} - -// ----------------------------------------------------------------------- -// ErrorMatches checker. - -type errorMatchesChecker struct { - *CheckerInfo -} - -// The ErrorMatches checker verifies that the error value -// is non nil and matches the regular expression provided. -// -// For example: -// -// c.Assert(err, ErrorMatches, "perm.*denied") -// -var ErrorMatches Checker = errorMatchesChecker{ - &CheckerInfo{Name: "ErrorMatches", Params: []string{"value", "regex"}}, -} - -func (checker errorMatchesChecker) Check(params []interface{}, names []string) (result bool, errStr string) { - if params[0] == nil { - return false, "Error value is nil" - } - err, ok := params[0].(error) - if !ok { - return false, "Value is not an error" - } - params[0] = err.Error() - names[0] = "error" - return matches(params[0], params[1]) -} - -// ----------------------------------------------------------------------- -// Matches checker. - -type matchesChecker struct { - *CheckerInfo -} - -// The Matches checker verifies that the string provided as the obtained -// value (or the string resulting from obtained.String()) matches the -// regular expression provided. -// -// For example: -// -// c.Assert(err, Matches, "perm.*denied") -// -var Matches Checker = &matchesChecker{ - &CheckerInfo{Name: "Matches", Params: []string{"value", "regex"}}, -} - -func (checker *matchesChecker) Check(params []interface{}, names []string) (result bool, error string) { - return matches(params[0], params[1]) -} - -func matches(value, regex interface{}) (result bool, error string) { - reStr, ok := regex.(string) - if !ok { - return false, "Regex must be a string" - } - valueStr, valueIsStr := value.(string) - if !valueIsStr { - if valueWithStr, valueHasStr := value.(fmt.Stringer); valueHasStr { - valueStr, valueIsStr = valueWithStr.String(), true - } - } - if valueIsStr { - matches, err := regexp.MatchString("^"+reStr+"$", valueStr) - if err != nil { - return false, "Can't compile regex: " + err.Error() - } - return matches, "" - } - return false, "Obtained value is not a string and has no .String()" -} - -// ----------------------------------------------------------------------- -// Panics checker. - -type panicsChecker struct { - *CheckerInfo -} - -// The Panics checker verifies that calling the provided zero-argument -// function will cause a panic which is deep-equal to the provided value. -// -// For example: -// -// c.Assert(func() { f(1, 2) }, Panics, &SomeErrorType{"BOOM"}). -// -// -var Panics Checker = &panicsChecker{ - &CheckerInfo{Name: "Panics", Params: []string{"function", "expected"}}, -} - -func (checker *panicsChecker) Check(params []interface{}, names []string) (result bool, error string) { - f := reflect.ValueOf(params[0]) - if f.Kind() != reflect.Func || f.Type().NumIn() != 0 { - return false, "Function must take zero arguments" - } - defer func() { - // If the function has not panicked, then don't do the check. - if error != "" { - return - } - params[0] = recover() - names[0] = "panic" - result = reflect.DeepEqual(params[0], params[1]) - }() - f.Call(nil) - return false, "Function has not panicked" -} - -type panicMatchesChecker struct { - *CheckerInfo -} - -// The PanicMatches checker verifies that calling the provided zero-argument -// function will cause a panic with an error value matching -// the regular expression provided. -// -// For example: -// -// c.Assert(func() { f(1, 2) }, PanicMatches, `open.*: no such file or directory`). -// -// -var PanicMatches Checker = &panicMatchesChecker{ - &CheckerInfo{Name: "PanicMatches", Params: []string{"function", "expected"}}, -} - -func (checker *panicMatchesChecker) Check(params []interface{}, names []string) (result bool, errmsg string) { - f := reflect.ValueOf(params[0]) - if f.Kind() != reflect.Func || f.Type().NumIn() != 0 { - return false, "Function must take zero arguments" - } - defer func() { - // If the function has not panicked, then don't do the check. - if errmsg != "" { - return - } - obtained := recover() - names[0] = "panic" - if e, ok := obtained.(error); ok { - params[0] = e.Error() - } else if _, ok := obtained.(string); ok { - params[0] = obtained - } else { - errmsg = "Panic value is not a string or an error" - return - } - result, errmsg = matches(params[0], params[1]) - }() - f.Call(nil) - return false, "Function has not panicked" -} - -// ----------------------------------------------------------------------- -// FitsTypeOf checker. - -type fitsTypeChecker struct { - *CheckerInfo -} - -// The FitsTypeOf checker verifies that the obtained value is -// assignable to a variable with the same type as the provided -// sample value. -// -// For example: -// -// c.Assert(value, FitsTypeOf, int64(0)) -// c.Assert(value, FitsTypeOf, os.Error(nil)) -// -var FitsTypeOf Checker = &fitsTypeChecker{ - &CheckerInfo{Name: "FitsTypeOf", Params: []string{"obtained", "sample"}}, -} - -func (checker *fitsTypeChecker) Check(params []interface{}, names []string) (result bool, error string) { - obtained := reflect.ValueOf(params[0]) - sample := reflect.ValueOf(params[1]) - if !obtained.IsValid() { - return false, "" - } - if !sample.IsValid() { - return false, "Invalid sample value" - } - return obtained.Type().AssignableTo(sample.Type()), "" -} - -// ----------------------------------------------------------------------- -// Implements checker. - -type implementsChecker struct { - *CheckerInfo -} - -// The Implements checker verifies that the obtained value -// implements the interface specified via a pointer to an interface -// variable. -// -// For example: -// -// var e os.Error -// c.Assert(err, Implements, &e) -// -var Implements Checker = &implementsChecker{ - &CheckerInfo{Name: "Implements", Params: []string{"obtained", "ifaceptr"}}, -} - -func (checker *implementsChecker) Check(params []interface{}, names []string) (result bool, error string) { - obtained := reflect.ValueOf(params[0]) - ifaceptr := reflect.ValueOf(params[1]) - if !obtained.IsValid() { - return false, "" - } - if !ifaceptr.IsValid() || ifaceptr.Kind() != reflect.Ptr || ifaceptr.Elem().Kind() != reflect.Interface { - return false, "ifaceptr should be a pointer to an interface variable" - } - return obtained.Type().Implements(ifaceptr.Elem().Type()), "" -} diff --git a/vendor/gopkg.in/check.v1/helpers.go b/vendor/gopkg.in/check.v1/helpers.go deleted file mode 100644 index 58a733b50..000000000 --- a/vendor/gopkg.in/check.v1/helpers.go +++ /dev/null @@ -1,231 +0,0 @@ -package check - -import ( - "fmt" - "strings" - "time" -) - -// TestName returns the current test name in the form "SuiteName.TestName" -func (c *C) TestName() string { - return c.testName -} - -// ----------------------------------------------------------------------- -// Basic succeeding/failing logic. - -// Failed returns whether the currently running test has already failed. -func (c *C) Failed() bool { - return c.status() == failedSt -} - -// Fail marks the currently running test as failed. -// -// Something ought to have been previously logged so the developer can tell -// what went wrong. The higher level helper functions will fail the test -// and do the logging properly. -func (c *C) Fail() { - c.setStatus(failedSt) -} - -// FailNow marks the currently running test as failed and stops running it. -// Something ought to have been previously logged so the developer can tell -// what went wrong. The higher level helper functions will fail the test -// and do the logging properly. -func (c *C) FailNow() { - c.Fail() - c.stopNow() -} - -// Succeed marks the currently running test as succeeded, undoing any -// previous failures. -func (c *C) Succeed() { - c.setStatus(succeededSt) -} - -// SucceedNow marks the currently running test as succeeded, undoing any -// previous failures, and stops running the test. -func (c *C) SucceedNow() { - c.Succeed() - c.stopNow() -} - -// ExpectFailure informs that the running test is knowingly broken for -// the provided reason. If the test does not fail, an error will be reported -// to raise attention to this fact. This method is useful to temporarily -// disable tests which cover well known problems until a better time to -// fix the problem is found, without forgetting about the fact that a -// failure still exists. -func (c *C) ExpectFailure(reason string) { - if reason == "" { - panic("Missing reason why the test is expected to fail") - } - c.mustFail = true - c.reason = reason -} - -// Skip skips the running test for the provided reason. If run from within -// SetUpTest, the individual test being set up will be skipped, and if run -// from within SetUpSuite, the whole suite is skipped. -func (c *C) Skip(reason string) { - if reason == "" { - panic("Missing reason why the test is being skipped") - } - c.reason = reason - c.setStatus(skippedSt) - c.stopNow() -} - -// ----------------------------------------------------------------------- -// Basic logging. - -// GetTestLog returns the current test error output. -func (c *C) GetTestLog() string { - return c.logb.String() -} - -// Log logs some information into the test error output. -// The provided arguments are assembled together into a string with fmt.Sprint. -func (c *C) Log(args ...interface{}) { - c.log(args...) -} - -// Log logs some information into the test error output. -// The provided arguments are assembled together into a string with fmt.Sprintf. -func (c *C) Logf(format string, args ...interface{}) { - c.logf(format, args...) -} - -// Output enables *C to be used as a logger in functions that require only -// the minimum interface of *log.Logger. -func (c *C) Output(calldepth int, s string) error { - d := time.Now().Sub(c.startTime) - msec := d / time.Millisecond - sec := d / time.Second - min := d / time.Minute - - c.Logf("[LOG] %d:%02d.%03d %s", min, sec%60, msec%1000, s) - return nil -} - -// Error logs an error into the test error output and marks the test as failed. -// The provided arguments are assembled together into a string with fmt.Sprint. -func (c *C) Error(args ...interface{}) { - c.logCaller(1) - c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...))) - c.logNewLine() - c.Fail() -} - -// Errorf logs an error into the test error output and marks the test as failed. -// The provided arguments are assembled together into a string with fmt.Sprintf. -func (c *C) Errorf(format string, args ...interface{}) { - c.logCaller(1) - c.logString(fmt.Sprintf("Error: "+format, args...)) - c.logNewLine() - c.Fail() -} - -// Fatal logs an error into the test error output, marks the test as failed, and -// stops the test execution. The provided arguments are assembled together into -// a string with fmt.Sprint. -func (c *C) Fatal(args ...interface{}) { - c.logCaller(1) - c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...))) - c.logNewLine() - c.FailNow() -} - -// Fatlaf logs an error into the test error output, marks the test as failed, and -// stops the test execution. The provided arguments are assembled together into -// a string with fmt.Sprintf. -func (c *C) Fatalf(format string, args ...interface{}) { - c.logCaller(1) - c.logString(fmt.Sprint("Error: ", fmt.Sprintf(format, args...))) - c.logNewLine() - c.FailNow() -} - -// ----------------------------------------------------------------------- -// Generic checks and assertions based on checkers. - -// Check verifies if the first value matches the expected value according -// to the provided checker. If they do not match, an error is logged, the -// test is marked as failed, and the test execution continues. -// -// Some checkers may not need the expected argument (e.g. IsNil). -// -// Extra arguments provided to the function are logged next to the reported -// problem when the matching fails. -func (c *C) Check(obtained interface{}, checker Checker, args ...interface{}) bool { - return c.internalCheck("Check", obtained, checker, args...) -} - -// Assert ensures that the first value matches the expected value according -// to the provided checker. If they do not match, an error is logged, the -// test is marked as failed, and the test execution stops. -// -// Some checkers may not need the expected argument (e.g. IsNil). -// -// Extra arguments provided to the function are logged next to the reported -// problem when the matching fails. -func (c *C) Assert(obtained interface{}, checker Checker, args ...interface{}) { - if !c.internalCheck("Assert", obtained, checker, args...) { - c.stopNow() - } -} - -func (c *C) internalCheck(funcName string, obtained interface{}, checker Checker, args ...interface{}) bool { - if checker == nil { - c.logCaller(2) - c.logString(fmt.Sprintf("%s(obtained, nil!?, ...):", funcName)) - c.logString("Oops.. you've provided a nil checker!") - c.logNewLine() - c.Fail() - return false - } - - // If the last argument is a bug info, extract it out. - var comment CommentInterface - if len(args) > 0 { - if c, ok := args[len(args)-1].(CommentInterface); ok { - comment = c - args = args[:len(args)-1] - } - } - - params := append([]interface{}{obtained}, args...) - info := checker.Info() - - if len(params) != len(info.Params) { - names := append([]string{info.Params[0], info.Name}, info.Params[1:]...) - c.logCaller(2) - c.logString(fmt.Sprintf("%s(%s):", funcName, strings.Join(names, ", "))) - c.logString(fmt.Sprintf("Wrong number of parameters for %s: want %d, got %d", info.Name, len(names), len(params)+1)) - c.logNewLine() - c.Fail() - return false - } - - // Copy since it may be mutated by Check. - names := append([]string{}, info.Params...) - - // Do the actual check. - result, error := checker.Check(params, names) - if !result || error != "" { - c.logCaller(2) - for i := 0; i != len(params); i++ { - c.logValue(names[i], params[i]) - } - if comment != nil { - c.logString(comment.CheckCommentString()) - } - if error != "" { - c.logString(error) - } - c.logNewLine() - c.Fail() - return false - } - return true -} diff --git a/vendor/gopkg.in/check.v1/printer.go b/vendor/gopkg.in/check.v1/printer.go deleted file mode 100644 index e0f7557b5..000000000 --- a/vendor/gopkg.in/check.v1/printer.go +++ /dev/null @@ -1,168 +0,0 @@ -package check - -import ( - "bytes" - "go/ast" - "go/parser" - "go/printer" - "go/token" - "os" -) - -func indent(s, with string) (r string) { - eol := true - for i := 0; i != len(s); i++ { - c := s[i] - switch { - case eol && c == '\n' || c == '\r': - case c == '\n' || c == '\r': - eol = true - case eol: - eol = false - s = s[:i] + with + s[i:] - i += len(with) - } - } - return s -} - -func printLine(filename string, line int) (string, error) { - fset := token.NewFileSet() - file, err := os.Open(filename) - if err != nil { - return "", err - } - fnode, err := parser.ParseFile(fset, filename, file, parser.ParseComments) - if err != nil { - return "", err - } - config := &printer.Config{Mode: printer.UseSpaces, Tabwidth: 4} - lp := &linePrinter{fset: fset, fnode: fnode, line: line, config: config} - ast.Walk(lp, fnode) - result := lp.output.Bytes() - // Comments leave \n at the end. - n := len(result) - for n > 0 && result[n-1] == '\n' { - n-- - } - return string(result[:n]), nil -} - -type linePrinter struct { - config *printer.Config - fset *token.FileSet - fnode *ast.File - line int - output bytes.Buffer - stmt ast.Stmt -} - -func (lp *linePrinter) emit() bool { - if lp.stmt != nil { - lp.trim(lp.stmt) - lp.printWithComments(lp.stmt) - lp.stmt = nil - return true - } - return false -} - -func (lp *linePrinter) printWithComments(n ast.Node) { - nfirst := lp.fset.Position(n.Pos()).Line - nlast := lp.fset.Position(n.End()).Line - for _, g := range lp.fnode.Comments { - cfirst := lp.fset.Position(g.Pos()).Line - clast := lp.fset.Position(g.End()).Line - if clast == nfirst-1 && lp.fset.Position(n.Pos()).Column == lp.fset.Position(g.Pos()).Column { - for _, c := range g.List { - lp.output.WriteString(c.Text) - lp.output.WriteByte('\n') - } - } - if cfirst >= nfirst && cfirst <= nlast && n.End() <= g.List[0].Slash { - // The printer will not include the comment if it starts past - // the node itself. Trick it into printing by overlapping the - // slash with the end of the statement. - g.List[0].Slash = n.End() - 1 - } - } - node := &printer.CommentedNode{n, lp.fnode.Comments} - lp.config.Fprint(&lp.output, lp.fset, node) -} - -func (lp *linePrinter) Visit(n ast.Node) (w ast.Visitor) { - if n == nil { - if lp.output.Len() == 0 { - lp.emit() - } - return nil - } - first := lp.fset.Position(n.Pos()).Line - last := lp.fset.Position(n.End()).Line - if first <= lp.line && last >= lp.line { - // Print the innermost statement containing the line. - if stmt, ok := n.(ast.Stmt); ok { - if _, ok := n.(*ast.BlockStmt); !ok { - lp.stmt = stmt - } - } - if first == lp.line && lp.emit() { - return nil - } - return lp - } - return nil -} - -func (lp *linePrinter) trim(n ast.Node) bool { - stmt, ok := n.(ast.Stmt) - if !ok { - return true - } - line := lp.fset.Position(n.Pos()).Line - if line != lp.line { - return false - } - switch stmt := stmt.(type) { - case *ast.IfStmt: - stmt.Body = lp.trimBlock(stmt.Body) - case *ast.SwitchStmt: - stmt.Body = lp.trimBlock(stmt.Body) - case *ast.TypeSwitchStmt: - stmt.Body = lp.trimBlock(stmt.Body) - case *ast.CaseClause: - stmt.Body = lp.trimList(stmt.Body) - case *ast.CommClause: - stmt.Body = lp.trimList(stmt.Body) - case *ast.BlockStmt: - stmt.List = lp.trimList(stmt.List) - } - return true -} - -func (lp *linePrinter) trimBlock(stmt *ast.BlockStmt) *ast.BlockStmt { - if !lp.trim(stmt) { - return lp.emptyBlock(stmt) - } - stmt.Rbrace = stmt.Lbrace - return stmt -} - -func (lp *linePrinter) trimList(stmts []ast.Stmt) []ast.Stmt { - for i := 0; i != len(stmts); i++ { - if !lp.trim(stmts[i]) { - stmts[i] = lp.emptyStmt(stmts[i]) - break - } - } - return stmts -} - -func (lp *linePrinter) emptyStmt(n ast.Node) *ast.ExprStmt { - return &ast.ExprStmt{&ast.Ellipsis{n.Pos(), nil}} -} - -func (lp *linePrinter) emptyBlock(n ast.Node) *ast.BlockStmt { - p := n.Pos() - return &ast.BlockStmt{p, []ast.Stmt{lp.emptyStmt(n)}, p} -} diff --git a/vendor/gopkg.in/check.v1/run.go b/vendor/gopkg.in/check.v1/run.go deleted file mode 100644 index da8fd7987..000000000 --- a/vendor/gopkg.in/check.v1/run.go +++ /dev/null @@ -1,175 +0,0 @@ -package check - -import ( - "bufio" - "flag" - "fmt" - "os" - "testing" - "time" -) - -// ----------------------------------------------------------------------- -// Test suite registry. - -var allSuites []interface{} - -// Suite registers the given value as a test suite to be run. Any methods -// starting with the Test prefix in the given value will be considered as -// a test method. -func Suite(suite interface{}) interface{} { - allSuites = append(allSuites, suite) - return suite -} - -// ----------------------------------------------------------------------- -// Public running interface. - -var ( - oldFilterFlag = flag.String("gocheck.f", "", "Regular expression selecting which tests and/or suites to run") - oldVerboseFlag = flag.Bool("gocheck.v", false, "Verbose mode") - oldStreamFlag = flag.Bool("gocheck.vv", false, "Super verbose mode (disables output caching)") - oldBenchFlag = flag.Bool("gocheck.b", false, "Run benchmarks") - oldBenchTime = flag.Duration("gocheck.btime", 1*time.Second, "approximate run time for each benchmark") - oldListFlag = flag.Bool("gocheck.list", false, "List the names of all tests that will be run") - oldWorkFlag = flag.Bool("gocheck.work", false, "Display and do not remove the test working directory") - - newFilterFlag = flag.String("check.f", "", "Regular expression selecting which tests and/or suites to run") - newVerboseFlag = flag.Bool("check.v", false, "Verbose mode") - newStreamFlag = flag.Bool("check.vv", false, "Super verbose mode (disables output caching)") - newBenchFlag = flag.Bool("check.b", false, "Run benchmarks") - newBenchTime = flag.Duration("check.btime", 1*time.Second, "approximate run time for each benchmark") - newBenchMem = flag.Bool("check.bmem", false, "Report memory benchmarks") - newListFlag = flag.Bool("check.list", false, "List the names of all tests that will be run") - newWorkFlag = flag.Bool("check.work", false, "Display and do not remove the test working directory") -) - -// TestingT runs all test suites registered with the Suite function, -// printing results to stdout, and reporting any failures back to -// the "testing" package. -func TestingT(testingT *testing.T) { - benchTime := *newBenchTime - if benchTime == 1*time.Second { - benchTime = *oldBenchTime - } - conf := &RunConf{ - Filter: *oldFilterFlag + *newFilterFlag, - Verbose: *oldVerboseFlag || *newVerboseFlag, - Stream: *oldStreamFlag || *newStreamFlag, - Benchmark: *oldBenchFlag || *newBenchFlag, - BenchmarkTime: benchTime, - BenchmarkMem: *newBenchMem, - KeepWorkDir: *oldWorkFlag || *newWorkFlag, - } - if *oldListFlag || *newListFlag { - w := bufio.NewWriter(os.Stdout) - for _, name := range ListAll(conf) { - fmt.Fprintln(w, name) - } - w.Flush() - return - } - result := RunAll(conf) - println(result.String()) - if !result.Passed() { - testingT.Fail() - } -} - -// RunAll runs all test suites registered with the Suite function, using the -// provided run configuration. -func RunAll(runConf *RunConf) *Result { - result := Result{} - for _, suite := range allSuites { - result.Add(Run(suite, runConf)) - } - return &result -} - -// Run runs the provided test suite using the provided run configuration. -func Run(suite interface{}, runConf *RunConf) *Result { - runner := newSuiteRunner(suite, runConf) - return runner.run() -} - -// ListAll returns the names of all the test functions registered with the -// Suite function that will be run with the provided run configuration. -func ListAll(runConf *RunConf) []string { - var names []string - for _, suite := range allSuites { - names = append(names, List(suite, runConf)...) - } - return names -} - -// List returns the names of the test functions in the given -// suite that will be run with the provided run configuration. -func List(suite interface{}, runConf *RunConf) []string { - var names []string - runner := newSuiteRunner(suite, runConf) - for _, t := range runner.tests { - names = append(names, t.String()) - } - return names -} - -// ----------------------------------------------------------------------- -// Result methods. - -func (r *Result) Add(other *Result) { - r.Succeeded += other.Succeeded - r.Skipped += other.Skipped - r.Failed += other.Failed - r.Panicked += other.Panicked - r.FixturePanicked += other.FixturePanicked - r.ExpectedFailures += other.ExpectedFailures - r.Missed += other.Missed - if r.WorkDir != "" && other.WorkDir != "" { - r.WorkDir += ":" + other.WorkDir - } else if other.WorkDir != "" { - r.WorkDir = other.WorkDir - } -} - -func (r *Result) Passed() bool { - return (r.Failed == 0 && r.Panicked == 0 && - r.FixturePanicked == 0 && r.Missed == 0 && - r.RunError == nil) -} - -func (r *Result) String() string { - if r.RunError != nil { - return "ERROR: " + r.RunError.Error() - } - - var value string - if r.Failed == 0 && r.Panicked == 0 && r.FixturePanicked == 0 && - r.Missed == 0 { - value = "OK: " - } else { - value = "OOPS: " - } - value += fmt.Sprintf("%d passed", r.Succeeded) - if r.Skipped != 0 { - value += fmt.Sprintf(", %d skipped", r.Skipped) - } - if r.ExpectedFailures != 0 { - value += fmt.Sprintf(", %d expected failures", r.ExpectedFailures) - } - if r.Failed != 0 { - value += fmt.Sprintf(", %d FAILED", r.Failed) - } - if r.Panicked != 0 { - value += fmt.Sprintf(", %d PANICKED", r.Panicked) - } - if r.FixturePanicked != 0 { - value += fmt.Sprintf(", %d FIXTURE-PANICKED", r.FixturePanicked) - } - if r.Missed != 0 { - value += fmt.Sprintf(", %d MISSED", r.Missed) - } - if r.WorkDir != "" { - value += "\nWORK=" + r.WorkDir - } - return value -} diff --git a/vendor/vendor.json b/vendor/vendor.json index ee4d58dda..a29c7073d 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -871,11 +871,6 @@ "revision": "bd61cae2be85fa6ff40eb23dcdd24567967ac2ae", "revisionTime": "2016-08-30T13:25:53Z" }, - { - "path": "gopkg.in/check.v1", - "revision": "11d3bc7aa68e238947792f30573146a3231fc0f1", - "revisionTime": "2015-07-29T10:04:31+02:00" - }, { "checksumSHA1": "lLdKOn9RPtFoTtPUNq5+sIInAiE=", "path": "gopkg.in/olivere/elastic.v3/backoff",