// Verify if the items being read are as expected. func CheckOpsReader(t *testing.T, loader OpsReader) { expectedOpsRead := 0 const startingTs = 1396456709420 for op := loader.Next(); op != nil; op = loader.Next() { expectedOpsRead += 1 ensure.NotNil(t, op) ensure.DeepEqual(t, loader.OpsRead(), expectedOpsRead) // check the "ts" field CheckTime(t, float64(startingTs+loader.OpsRead()), op.Timestamp) // check the insert doc // certain key exists for i := 1; i <= 5; i++ { logTypeKey := fmt.Sprintf("logType%d", i) logType, ok := GetElem(op.InsertDoc, logTypeKey) if i != expectedOpsRead { ensure.False(t, ok) ensure.Nil(t, logType) } else { ensure.True(t, ok) ensure.NotNil(t, logType) } } // check the value for the shared key message := fmt.Sprintf("m%d", expectedOpsRead) actualMessage, ok := GetElem(op.InsertDoc, "message") ensure.True(t, ok) ensure.DeepEqual(t, actualMessage.(string), message) } ensure.DeepEqual(t, expectedOpsRead, 5) }
func TestUploadFiles(t *testing.T) { t.Parallel() h := parsecli.NewHarness(t) defer h.Stop() h.MakeEmptyRoot() createRandomFiles(t, h) names := []string{"a", "b"} ht := parsecli.TransportFunc(func(r *http.Request) (*http.Response, error) { switch filepath.Base(r.URL.Path) { case names[0]: ensure.NotNil(t, r.Header) ensure.DeepEqual(t, r.Header.Get("Key"), "Value") ensure.DeepEqual(t, r.Header.Get("Content-Type"), "application/octet-stream") ensure.DeepEqual(t, r.Header.Get("Content-MD5"), "4JnleFGzGppuArF6N50EWg==") return &http.Response{ StatusCode: http.StatusOK, Body: ioutil.NopCloser(strings.NewReader(`{"status":"success"}`)), }, nil case names[1]: ensure.NotNil(t, r.Header) ensure.DeepEqual(t, r.Header.Get("Key"), "Value") ensure.DeepEqual(t, r.Header.Get("Content-Type"), "application/octet-stream") ensure.DeepEqual(t, r.Header.Get("Content-MD5"), "Fv43qsp6mnGCJlC00VkOcA==") return &http.Response{ StatusCode: http.StatusOK, Body: ioutil.NopCloser(strings.NewReader(`{"status":"success"}`)), }, nil default: return &http.Response{ StatusCode: http.StatusInternalServerError, Body: ioutil.NopCloser(strings.NewReader(`{"error":"something is wrong"}`)), }, nil } }) h.Env.ParseAPIClient = &parsecli.ParseAPIClient{APIClient: &parse.Client{Transport: ht}} var filenames []string for _, name := range names { filenames = append(filenames, filepath.Join(h.Env.Root, name)) } ensure.Nil(t, uploadSymbolFiles(filenames[:], map[string]string{"Key": "Value"}, true, h.Env)) for _, filename := range filenames { _, err := os.Lstat(filename) ensure.NotNil(t, err) ensure.True(t, os.IsNotExist(err)) } }
func TestServerAbort(t *testing.T) { t.Parallel() for _, code := range []int{200, 500} { server := httptest.NewServer( http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Length", "4000") w.WriteHeader(code) w.Write(bytes.Repeat([]byte("a"), 3000)) }, ), ) u, err := url.Parse(server.URL) ensure.Nil(t, err) c := &parse.Client{ Credentials: defaultRestAPIKey, BaseURL: u, } res := make(map[string]interface{}) _, err = c.Get(nil, res) ensure.NotNil(t, err) server.CloseClientConnections() server.Close() } }
func TestProvideWithFields(t *testing.T) { var g inject.Graph a := &TypeAnswerStruct{} err := g.Provide(&inject.Object{Value: a, Fields: map[string]*inject.Object{}}) ensure.NotNil(t, err) ensure.DeepEqual(t, err.Error(), "fields were specified on object *inject_test.TypeAnswerStruct when it was provided") }
func TestServerAbort(t *testing.T) { t.Parallel() for _, code := range []int{200, 500} { server := httptest.NewServer( http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Length", "4000") w.WriteHeader(code) w.Write(bytes.Repeat([]byte("a"), 3000)) }, ), ) u, err := url.Parse(server.URL) ensure.Nil(t, err) c := &fbapi.Client{ BaseURL: u, } _, err = c.Do(&http.Request{Method: "GET"}, nil) ensure.NotNil(t, err) ensure.Err(t, err, regexp.MustCompile("(invalid character|EOF)")) server.CloseClientConnections() server.Close() } }
func TestPrintListNoConfig(t *testing.T) { t.Parallel() h, l := newListCmdHarness(t) h.makeEmptyRoot() defer h.Stop() ensure.NotNil(t, l.printListOfApps(h.env)) ensure.DeepEqual(t, h.Out.String(), "") }
func TestMissingCredentials(t *testing.T) { t.Parallel() var c parse.Client req := http.Request{Method: "GET", URL: &url.URL{Path: "classes/Foo/Bar"}} _, err := c.Do(&req, nil, nil) ensure.NotNil(t, err) ensure.Err(t, err, regexp.MustCompile(`parse: api error with message="unauthorized"`)) }
func TestInheritErrorOnListenUnixWithInvalidCount(t *testing.T) { var n Net os.Setenv(envCountKey, "a") tmpdir, err := ioutil.TempDir("", "TestInheritErrorOnListenUnixWithInvalidCount-") ensure.Nil(t, err) ensure.Nil(t, os.RemoveAll(tmpdir)) _, err = n.Listen("unix", filepath.Join(tmpdir, "socket")) ensure.NotNil(t, err) }
func TestBase64MD5OfFileNoFile(t *testing.T) { t.Parallel() h := parsecli.NewHarness(t) defer h.Stop() h.MakeEmptyRoot() testFile := filepath.Join(h.Env.Root, "test") _, err := base64MD5OfFile(testFile) ensure.NotNil(t, err) }
func TestReleasesCmdError(t *testing.T) { h, c := newReleasesCmdHarness(t) defer h.Stop() ht := parsecli.TransportFunc(func(r *http.Request) (*http.Response, error) { return nil, stackerr.New("Throws error") }) h.Env.ParseAPIClient = &parsecli.ParseAPIClient{APIClient: &parse.Client{Transport: ht}} ensure.NotNil(t, c.run(h.Env, &parsecli.Context{})) }
func TestNewConfig(t *testing.T) { var err error // CASE 1: unmarshalling err _, err = newConfig(strings.NewReader("?????")) ensure.NotNil(t, err) // CASE 2: success! _, err = newConfig(strings.NewReader("")) ensure.Nil(t, err) }
// Start starts server used for MockS3 func (s *MockS3) Start(t *testing.T) { srv, err := s3test.NewServer(s.config) ensure.Nil(t, err) ensure.NotNil(t, srv) s.srv = srv s.region = aws.Region{ Name: "faux-region-1", S3Endpoint: srv.URL(), S3LocationConstraint: true, // s3test server requires a LocationConstraint } }
func CheckSetStartTime(t *testing.T, loader OpsReader) { expectedOpsRead := 0 numSkipped, err := loader.SetStartTime(1396456709424) ensure.Nil(t, err) ensure.DeepEqual(t, numSkipped, int64(4)) for op := loader.Next(); op != nil; op = loader.Next() { expectedOpsRead += 1 ensure.NotNil(t, op) ensure.DeepEqual(t, loader.OpsRead(), expectedOpsRead) } // Verify that only 4 ops are read, since we skipped one ensure.DeepEqual(t, expectedOpsRead, 1) }
func CheckSkipOps(t *testing.T, loader OpsReader) { expectedOpsRead := 0 // Skip a single op loader.SkipOps(1) // Read all remaining ops for op := loader.Next(); op != nil; op = loader.Next() { expectedOpsRead += 1 ensure.NotNil(t, op) ensure.DeepEqual(t, loader.OpsRead(), expectedOpsRead) } // Verify that only 4 ops are read, since we skipped one ensure.DeepEqual(t, expectedOpsRead, 4) }
func TestSafeGetInt(t *testing.T) { val, err := safeGetInt(int32(11)) ensure.Nil(t, err) ensure.DeepEqual(t, val, int(11)) val, err = safeGetInt(int64(11)) ensure.Nil(t, err) ensure.DeepEqual(t, val, int(11)) val, err = safeGetInt(float32(11)) ensure.Nil(t, err) ensure.DeepEqual(t, val, int(11)) val, err = safeGetInt(float64(11)) ensure.Nil(t, err) ensure.DeepEqual(t, val, int(11)) val, err = safeGetInt("a") ensure.NotNil(t, err) }
func TestRunWithAppNamed(t *testing.T) { t.Parallel() h := newHarness(t) defer h.Stop() const appName = "a" c := &parseConfig{ Applications: map[string]*parseAppConfig{ appName: {ApplicationID: "id", MasterKey: "token"}, }, } h.makeWithConfig(jsonStr(t, c)) r := runWithClient(h.env, func(e *env, c *context) error { ensure.NotNil(t, c) return nil }) r(noOpCmd(), []string{"a"}) }
func TestRunWithDefault(t *testing.T) { t.Parallel() h := NewHarness(t) defer h.Stop() const appName = "a" c := &ParseConfig{ Applications: map[string]*ParseAppConfig{ appName: {ApplicationID: "id", MasterKey: "token"}, DefaultKey: {Link: appName}, }, } h.MakeWithConfig(jsonStr(t, c)) r := RunWithClient(h.Env, func(e *Env, c *Context) error { ensure.NotNil(t, c) return nil }) r(noOpCmd(), []string{"a"}) }
func TestParseVersionFromBytes(t *testing.T) { t.Parallel() _, err := parseVersionFromBytes([]byte(`versionCode='a'`)) ensure.NotNil(t, err) tests := []struct { input string expected int }{ {`versionCode='1'`, 1}, {`versionCode='12'`, 12}, {`versionCode='1234'`, 1234}, {`versionCode='12345678'`, 12345678}, } for _, test := range tests { actual, err := parseVersionFromBytes([]byte(test.input)) ensure.Nil(t, err) ensure.DeepEqual(t, actual, test.expected) } }
func TestRunWithAppError(t *testing.T) { t.Parallel() h := newHarness(t) defer h.Stop() const appName = "a" c := &parseConfig{ Applications: map[string]*parseAppConfig{ appName: {ApplicationID: "id", MasterKey: "token"}, }, } h.makeWithConfig(jsonStr(t, c)) h.env.Exit = func(i int) { panic(exitCode(i)) } const message = "hello world" func() { defer ensure.PanicDeepEqual(t, exitCode(1)) r := runWithClient(h.env, func(e *env, c *context) error { ensure.NotNil(t, c) return errors.New(message) }) r(noOpCmd(), []string{"a"}) }() ensure.StringContains(t, h.Err.String(), message) }
// inserting data voilating index clause on a separate connection should fail func TestEnsureIndex(t *testing.T) { t.Parallel() p := NewSingleHarness(t) defer p.Stop() session := p.ProxySession() collection := session.DB("test").C("coll1") index := mgo.Index{ Key: []string{"lastname", "firstname"}, Unique: true, DropDups: true, Background: true, // See notes. Sparse: true, } err := collection.EnsureIndex(index) ensure.Nil(t, err) err = collection.Insert( map[string]string{ "firstname": "harvey", "lastname": "dent", }, ) if err != nil { t.Fatal("insertion error", err) } session.Close() session = p.ProxySession() defer session.Close() collection = session.DB("test").C("coll1") err = collection.Insert( map[string]string{ "firstname": "harvey", "lastname": "dent", }, ) ensure.NotNil(t, err) }
// inserting data voilating index clause on a separate connection should fail func TestEnsureIndex(t *testing.T) { withHarness(t, func(harness *ReplicaSetHarness) { session := harness.ProxySession() collection := session.DB("test").C("testensureindex") collection.DropIndex("lastname", "firstname") index := mgo.Index{ Key: []string{"lastname", "firstname"}, Unique: true, DropDups: true, Background: true, // See notes. Sparse: true, } err := collection.EnsureIndex(index) ensure.Nil(t, err) err = collection.Insert( map[string]string{ "firstname": "harvey", "lastname": "dent", }, ) if err != nil { t.Fatal("insertion error", err) } session.Close() session = harness.ProxySession() defer session.Close() collection = session.DB("test").C("testensureindex") err = collection.Insert( map[string]string{ "firstname": "harvey", "lastname": "dent", }, ) ensure.NotNil(t, err) }) }
func TestNewBlank(t *testing.T) { b, err := blank.NewBlank("", false, "") ensure.NotNil(t, b) ensure.Nil(t, err) }
func TestInheritErrorOnListenTCPWithInvalidCount(t *testing.T) { var n Net os.Setenv(envCountKey, "a") _, err := n.Listen("tcp", ":0") ensure.NotNil(t, err) }
func TestNonNil(t *testing.T) { var c capture ensure.NotNil(&c, nil) c.Equal(t, `ensure_test.go:136: expected a value but got nil`) }
func TestExecution(t *testing.T) { test_db := "test_db_for_executor" test_collection := "c1" session, err := mgo.Dial("localhost") ensure.Nil(t, err) ensure.NotNil(t, session) defer session.Close() err = session.DB(test_db).DropDatabase() ensure.Nil(t, err) testNs := fmt.Sprintf("%s.%s", test_db, test_collection) // insertion insertOp := &Op{ Ns: testNs, Timestamp: time.Unix(1396456709, int64(427*time.Millisecond)), InsertDoc: bson.D{ {"logType", "console"}, {"message", "start"}, {"_id", bson.ObjectIdHex("533c3d03c23fffd217678ee8")}, {"timestamp", bson.D{{"$date", 1396456707977}}}, }, Type: Insert, } normalizeOp(insertOp) logger, err := NewLogger("", "") ensure.Nil(t, err) exec := NewOpsExecutor(session, nil, logger) err = exec.Execute(insertOp) ensure.Nil(t, err) coll := session.DB(test_db).C(test_collection) count, err := coll.Count() ensure.DeepEqual(t, count, 1) // Find findOp := &Op{ Ns: testNs, Timestamp: time.Unix(1396456709, int64(472*time.Millisecond)), QueryDoc: bson.D{ { "$query", bson.D{ {"$or", []bson.D{bson.D{{"_id", bson.ObjectIdHex("533c3d03c23fffd217678ee8")}}}}, }, }, {"$maxScan", 9000000}, }, Type: Query, NToReturn: 1, NToSkip: 0, } normalizeOp(findOp) err = exec.Execute(findOp) ensure.Nil(t, err) findResult := exec.lastResult.(*[]Document) ensure.DeepEqual(t, len(*findResult), 1) exec.lastResult = nil // Update updateOp := &Op{ Ns: testNs, Timestamp: time.Unix(1396456709, int64(472*time.Millisecond)), QueryDoc: bson.D{ {"_id", bson.ObjectIdHex("533c3d03c23fffd217678ee8")}, }, UpdateDoc: bson.D{ {"$set", bson.D{{"logType", "hooo"}}}, }, Type: Update, } normalizeOp(updateOp) err = exec.Execute(updateOp) ensure.Nil(t, err) // Check that the document is updated normalizeOp(findOp) err = exec.Execute(findOp) ensure.Nil(t, err) findResult = exec.lastResult.(*[]Document) ensure.DeepEqual(t, (*findResult)[0]["logType"].(string), "hooo") findResult = nil // findAndModify famOp := &Op{ Ns: fmt.Sprintf("%s.$cmd", test_db), Timestamp: time.Unix(1396456709, int64(472*time.Millisecond)), CommandDoc: bson.D{ {"findandmodify", test_collection}, {"query", bson.D{{"_id", bson.ObjectIdHex("533c3d03c23fffd217678ee8")}}}, {"update", bson.D{{"$set", bson.D{{"logType", "foobar"}}}}}, }, Type: Command, } normalizeOp(famOp) err = exec.Execute(famOp) ensure.Nil(t, err) // check that the doc is modified normalizeOp(findOp) err = exec.Execute(findOp) ensure.Nil(t, err) findResult = exec.lastResult.(*[]Document) ensure.DeepEqual(t, (*findResult)[0]["logType"].(string), "foobar") findResult = nil // Remove removeOp := &Op{ Ns: testNs, Timestamp: time.Unix(1396456709, int64(432*time.Millisecond)), QueryDoc: bson.D{{"_id", bson.ObjectIdHex("533c3d03c23fffd217678ee8")}}, Type: Remove, } normalizeOp(removeOp) err = exec.Execute(removeOp) ensure.Nil(t, err) // check that the doc is gone normalizeOp(findOp) err = exec.Execute(findOp) ensure.Nil(t, err) findResult = exec.lastResult.(*[]Document) ensure.DeepEqual(t, len(*findResult), 0) }
func TestErrorCases(t *testing.T) { cases := []struct { Request *http.Request Body interface{} Error string StatusCode int Transport http.RoundTripper }{ { Request: &http.Request{ Method: "GET", URL: &url.URL{ Scheme: "https", Host: "api.parse.com", Path: "/1/classes/Foo/Bar", }, }, Error: `parse: api error with code=101 and message="object not found for get"`, StatusCode: http.StatusNotFound, Transport: transportFunc(func(r *http.Request) (*http.Response, error) { j := jsonB(t, parse.Error{ Code: 101, Message: "object not found for get", }) return &http.Response{ StatusCode: http.StatusNotFound, Status: "404 Not Found", Body: ioutil.NopCloser(bytes.NewReader(j)), }, nil }), }, { Request: &http.Request{ Method: "GET", URL: &url.URL{ Scheme: "https", Host: "api.parse.com", Path: "/1/classes/Foo/Bar", }, }, Body: map[int]int{}, Error: "unsupported type: map[int]int", Transport: transportFunc(func(r *http.Request) (*http.Response, error) { panic("not reached") }), }, { Request: &http.Request{ Method: "GET", URL: &url.URL{Path: "/"}, }, Error: `error with status=404 and body="<html>`, StatusCode: 404, Transport: transportFunc(func(r *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: http.StatusNotFound, Status: "404 Not Found", Body: ioutil.NopCloser(strings.NewReader("<html>")), }, nil }), }, } t.Parallel() for _, ec := range cases { c := &parse.Client{ Credentials: defaultRestAPIKey, } if !realTransport { c.Transport = ec.Transport } res, err := c.Do(ec.Request, ec.Body, nil) ensure.NotNil(t, err) ensure.StringContains(t, err.Error(), ec.Error, ec) if ec.StatusCode != 0 { ensure.False(t, res == nil, ec) ensure.DeepEqual(t, res.StatusCode, ec.StatusCode, ec) } } }