func TestOrderCount(t *testing.T) { setup() defer teardown() httpmock.RegisterResponder("GET", "https://fooshop.myshopify.com/admin/orders/count.json", httpmock.NewStringResponder(200, `{"count": 7}`)) httpmock.RegisterResponder("GET", "https://fooshop.myshopify.com/admin/orders/count.json?created_at_min=2016-01-01T00%3A00%3A00Z", httpmock.NewStringResponder(200, `{"count": 2}`)) cnt, err := client.Order.Count(nil) if err != nil { t.Errorf("Order.Count returned error: %v", err) } expected := 7 if cnt != expected { t.Errorf("Order.Count returned %d, expected %d", cnt, expected) } date := time.Date(2016, time.January, 1, 0, 0, 0, 0, time.UTC) cnt, err = client.Order.Count(CountOptions{CreatedAtMin: date}) if err != nil { t.Errorf("Order.Count returned error: %v", err) } expected = 2 if cnt != expected { t.Errorf("Order.Count returned %d, expected %d", cnt, expected) } }
func TestWebhookCount(t *testing.T) { setup() defer teardown() httpmock.RegisterResponder("GET", "https://fooshop.myshopify.com/admin/webhooks/count.json", httpmock.NewStringResponder(200, `{"count": 7}`)) httpmock.RegisterResponder("GET", "https://fooshop.myshopify.com/admin/webhooks/count.json?topic=orders%2Fpaid", httpmock.NewStringResponder(200, `{"count": 2}`)) cnt, err := client.Webhook.Count(nil) if err != nil { t.Errorf("Webhook.Count returned error: %v", err) } expected := 7 if cnt != expected { t.Errorf("Webhook.Count returned %d, expected %d", cnt, expected) } options := WebhookOptions{Topic: "orders/paid"} cnt, err = client.Webhook.Count(options) if err != nil { t.Errorf("Webhook.Count returned error: %v", err) } expected = 2 if cnt != expected { t.Errorf("Webhook.Count returned %d, expected %d", cnt, expected) } }
func TestCount(t *testing.T) { setup() defer teardown() httpmock.RegisterResponder("GET", "https://fooshop.myshopify.com/foocount", httpmock.NewStringResponder(200, `{"count": 5}`)) httpmock.RegisterResponder("GET", "https://fooshop.myshopify.com/foocount?created_at_min=2016-01-01T00%3A00%3A00Z", httpmock.NewStringResponder(200, `{"count": 2}`)) // Test without options cnt, err := client.Count("foocount", nil) if err != nil { t.Errorf("Client.Count returned error: %v", err) } expected := 5 if cnt != expected { t.Errorf("Client.Count returned %d, expected %d", cnt, expected) } // Test with options date := time.Date(2016, time.January, 1, 0, 0, 0, 0, time.UTC) cnt, err = client.Count("foocount", CountOptions{CreatedAtMin: date}) if err != nil { t.Errorf("Client.Count returned error: %v", err) } expected = 2 if cnt != expected { t.Errorf("Client.Count returned %d, expected %d", cnt, expected) } }
func TestListTemplatesSortedByName(t *testing.T) { assert := assert.New(t) output := new(bytes.Buffer) httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", "https://api.github.com/repos/github/gitignore/contents/", httpmock.NewStringResponder(200, `[ { "name": "C.gitignore" }, { "name": "A.gitignore" } ] `)) httpmock.RegisterResponder("GET", "https://api.github.com/repos/github/gitignore/contents/Global", httpmock.NewStringResponder(200, `[ { "name": "B.gitignore" } ] `)) app([]string{"chtignore", "list"}, output) assert.ThatString(output.String()).IsEqualTo(fmt.Sprintln("A, B, C, JetBrains-build")) }
func setHasMoreResponderPutValid() { httpmock.RegisterResponder("POST", "http://arangodb:8000/_db/dbName/path", httpmock.NewStringResponder(200, `{"error": false, "errorMessage": "", "result": [{}], "hasMore":true, "id":"1000"}`)) httpmock.RegisterResponder("PUT", "http://arangodb:8000/_db/dbName/path/1000", httpmock.NewStringResponder(200, `{"error": false, "errorMessage": "", "result": [{}], "hasMore":false}`)) }
// TestQueryRun runs tests on the Query Run method. func TestQueryRun(t *testing.T) { a := assert.New(t) r := require.New(t) httpmock.Activate() defer httpmock.DeactivateAndReset() db := New().LoggerOptions(false, false, false) db.Connect("http://arangodb:8000", "dbName", "foo", "bar") result, err := db.Run(NewQuery(shortQuery)) r.Error(err) a.Nil(result) httpmock.RegisterResponder("POST", "http://arangodb:8000/_db/dbName/_api/cursor", httpmock.NewStringResponder(200, `{"error": false, "errorMessage": "", "result": []}`)) result, err = db.Run(NewQuery("")) r.NoError(err) a.Equal("[]", string(result)) result, err = db.Run(NewQuery(shortQuery).Cache(true).BatchSize(500)) r.NoError(err) a.Equal("[]", string(result)) httpmock.RegisterResponder("POST", "http://arangodb:8000/_db/dbName/_api/cursor", httpmock.NewStringResponder(200, `{"error": false, "errorMessage": "", "result": [{}], "hasMore":true, "id":"1000"}`)) httpmock.RegisterResponder("PUT", "http://arangodb:8000/_db/dbName/_api/cursor/1000", httpmock.NewStringResponder(200, `{"error": false, "errorMessage": "", "result": [{}], "hasMore":false}`)) result, err = db.Run(NewQuery("")) r.NoError(err) a.Equal("[{},{}]", string(result)) q := NewQuery(` FOR d IN documents FILTER d._key == @key RETURN d `) q.Bind("key", 1000) result, err = db.Run(q) r.NoError(err) a.Equal("[{},{}]", string(result)) httpmock.RegisterResponder("POST", "http://arangodb:8000/_db/dbName/_api/cursor", httpmock.NewStringResponder(500, `{"error": true, "errorMessage": "error !"}`)) result, err = db.Run(NewQuery(shortQuery)) r.Error(err) a.Nil(result) }
func TestImportTaskWithSuccess(t *testing.T) { httpmock.Activate() httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterNoResponder(httpmock.NewStringResponder(200, `{"meta":{"status":200},"data":{"id":176,"file":{"name":"string.po","format":"GNU_PO","locale":{"code":"en-US","english_name":"English (United States)","local_name":"English (United States)","locale":"en","region":"US"}},"string_count":236,"word_count":1260,"status":"in-progress","created_at":"2013-10-07T15:27:10+0000","created_at_timestamp":1381159630}}`)) client := Client{APIKey: "abcdef", Secret: "abcdef", ProjectID: 1} res, err := client.ImportTask(1) assert.Nil(t, err) assert.Equal(t, TaskData{ ID: 176, OriginalID: float64(176), File: TaskFile{ Name: "string.po", Format: "GNU_PO", Locale: Language{ Code: "en-US", EnglishName: "English (United States)", LocalName: "English (United States)", Locale: "en", Region: "US", }, }, StringCount: 236, WordCount: 1260, Status: "in-progress", CreateddAt: "2013-10-07T15:27:10+0000", CreateddAtTimestamp: 1381159630, }, res) }
func TestImportTasksWithSuccess(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterNoResponder(httpmock.NewStringResponder(200, `{"meta":{"status":200},"data":[{"id":"177","file":{"name":"string2.po"},"status":"in-progress","created_at":"2013-10-07T15:25:00+0000","created_at_timestamp":1381159500},{"id":"176","file":{"name":"string.po"},"status":"in-progress","created_at":"2013-10-07T15:27:10+0000","created_at_timestamp":1381159630}]}`)) client := Client{APIKey: "abcdef", Secret: "abcdef", ProjectID: 1} res, err := client.ImportTasks(map[string]interface{}{"page": 1, "per_page": 50, "status": "in-progress"}) assert.Nil(t, err) assert.Equal(t, []TaskData{ TaskData{ ID: 177, OriginalID: "177", File: TaskFile{ Name: "string2.po", }, Status: "in-progress", CreateddAt: "2013-10-07T15:25:00+0000", CreateddAtTimestamp: 1381159500, }, TaskData{ ID: 176, OriginalID: "176", File: TaskFile{ Name: "string.po", }, Status: "in-progress", CreateddAt: "2013-10-07T15:27:10+0000", CreateddAtTimestamp: 1381159630, }, }, res) }
func TestGetTranslationsStatusWithSuccess(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterNoResponder(httpmock.NewStringResponder(200, `{"meta":{"status":200},"data":{"file_name":"string.po","locale":{"code":"ja-JP","english_name":"Japanese","local_name":"\u65e5\u672c\u8a9e","locale":"ja","region":"JP"},"progress":"92%","string_count":1359,"word_count":3956}}`)) client := Client{APIKey: "abcdef", Secret: "abcdef", ProjectID: 1} res, err := client.GetTranslationsStatus("string.po", "ja-JP") assert.Nil(t, err) assert.Equal(t, TranslationsStatus{ FileName: "string.po", Locale: Language{ Code: "ja-JP", EnglishName: "Japanese", LocalName: "日本語", CustomLocale: "", Locale: "ja", Region: "JP", }, Progress: "92%", StringCount: 1359, WordCount: 3956, }, res) }
func dataMarshalling(t *testing.T) { httpmock.RegisterResponder("GET", fetcher.generateURL(), httpmock.NewStringResponder(200, "{\"response\": {\"games\": [{\"appid\": 10, \"name\": \"game\", \"playtime_forever\": 32}]}}")) fetcher.getOwnedGames() assert.Equal(t, 10, fetcher.OwnedGames.Response.Games[0].ID) }
func TestUploadFileWithSuccess(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterNoResponder(httpmock.NewStringResponder(201, `{"meta":{"status":201},"data":{"name":"string.po","format":"GNU_PO","language":{"code":"en-US","english_name":"English (United States)","local_name":"English (United States)","locale":"en","region":"US"},"import":{"id":154,"created_at":"2013-10-07T15:27:10+0000","created_at_timestamp":1381159630}}}`)) client := Client{APIKey: "abcdef", Secret: "abcdef", ProjectID: 1} tmpdir, err := ioutil.TempDir("", "") assert.Nil(t, err) defer os.RemoveAll(tmpdir) filename := path.Join(tmpdir, "string.po") ioutil.WriteFile(filename, []byte("test"), 0666) res, err := client.UploadFile(filename, "GNU_PO", "en_US", true) assert.Nil(t, err) assert.Equal(t, UploadData{ Name: "string.po", Format: "GNU_PO", Language: Language{ Code: "en-US", EnglishName: "English (United States)", LocalName: "English (United States)", Locale: "en", Region: "US", }, Import: TaskData{ ID: 154, OriginalID: 154.0, CreateddAt: "2013-10-07T15:27:10+0000", CreateddAtTimestamp: 1381159630, }, }, res) }
func TestGetBookmarkCounts(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() res := ` { "https://github.com":111, "https://bitbucket.org":222, "http://stackoverflow.com":333 } ` httpmock.RegisterResponder( "GET", "http://api.b.st-hatena.com/entry.counts?url=https%3A%2F%2Fgithub.com&url=https%3A%2F%2Fbitbucket.org&url=http%3A%2F%2Fstackoverflow.com", httpmock.NewStringResponder(200, res)) input := []string{ "https://github.com", "https://bitbucket.org", "http://stackoverflow.com", } expected := map[string]int{} json.Unmarshal([]byte(res), &expected) counts, err := GetBookmarkCounts(input) if err != nil { t.Errorf("fail mock: %#v\n", input) } for url, count := range counts { if count != expected[url] { t.Errorf("expected count %d, but got %d\n", expected[url], count) } } }
func TestGetMultipleTemplates(t *testing.T) { assert := assert.New(t) output := new(bytes.Buffer) httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", templateUrl("Java.gitignore"), httpmock.NewStringResponder(200, "*.class")) httpmock.RegisterResponder("GET", templateUrl("Go.gitignore"), httpmock.NewStringResponder(200, "*.o")) app([]string{"chtignore", "Java", "Go"}, output) assert.ThatString(output.String()). Contains(fmt.Sprintln("# Java\n*.class")). Contains(fmt.Sprintln("# Go\n*.o")) }
func TestCJCourier(t *testing.T) { // create cj courier courier, _ := New("CJ") // create http mock httpmock.Activate() defer httpmock.DeactivateAndReset() invalidTrackingNumber := "cj_invalid" startTrackingNumber := "cj_start" completeTrackingNumber := "cj_complete" httpmock.RegisterResponder("GET", fmt.Sprintf(Cj{}.TrackingUrl(), invalidTrackingNumber), httpmock.NewStringResponder(200, readTestResponseFile(invalidTrackingNumber+".html"))) httpmock.RegisterResponder("GET", fmt.Sprintf(Cj{}.TrackingUrl(), startTrackingNumber), httpmock.NewStringResponder(200, readTestResponseFile(startTrackingNumber+".html"))) httpmock.RegisterResponder("GET", fmt.Sprintf(Cj{}.TrackingUrl(), completeTrackingNumber), httpmock.NewStringResponder(200, readTestResponseFile(completeTrackingNumber+".html"))) Convey("CJ test", t, func() { Convey("Invalid tracking number test", func() { _, err := courier.Parse(invalidTrackingNumber) So(err, ShouldNotBeNil) }) Convey("Start courier test", func() { data, _ := courier.Parse(startTrackingNumber) So(data.StatusCode, ShouldEqual, delibird.DeleveryStart) So(data.Sender, ShouldEqual, "홈*럼") So(data.Receiver, ShouldEqual, "테*트") So(data.Signer, ShouldEqual, "") So(data.CompanyCode, ShouldEqual, "CJ") }) Convey("Complete courier test", func() { data, _ := courier.Parse(completeTrackingNumber) So(data.StatusCode, ShouldEqual, delibird.DeleveryComplete) So(data.Sender, ShouldEqual, "홈*럼") So(data.Receiver, ShouldEqual, "테*트") So(data.Signer, ShouldEqual, "본인") So(data.CompanyCode, ShouldEqual, "CJ") }) }) }
func TestGetUniqueGlobalTemplate(t *testing.T) { assert := assert.New(t) output := new(bytes.Buffer) httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", templateUrl("Vagrant.gitignore"), httpmock.NewStringResponder(404, "Not Found")) httpmock.RegisterResponder("GET", templateUrl("Global/Vagrant.gitignore"), httpmock.NewStringResponder(200, ".vagrant/")) app([]string{"chtignore", "Vagrant"}, output) assert.ThatString(output.String()).IsEqualTo( `# Vagrant .vagrant/ `) }
// ReturnString causes this expectation to resolve to a string-based body with // the provided status code. func (ce *ClientExpectation) ReturnString( status int, body string, ) *ClientExpectation { return ce.Return( httpmock.NewStringResponder(status, body), ) }
func TestDo(t *testing.T) { setup() defer teardown() type MyStruct struct { Foo string `json:"foo"` } cases := []struct { url string responder httpmock.Responder expected interface{} }{ { "foo/1", httpmock.NewStringResponder(200, `{"foo": "bar"}`), &MyStruct{Foo: "bar"}, }, { "foo/2", httpmock.NewStringResponder(404, `{"error": "does not exist"}`), ResponseError{Status: 404, Message: "does not exist"}, }, { "foo/3", httpmock.NewStringResponder(400, `{"errors": {"title": ["wrong"]}}`), ResponseError{Status: 400, Message: "wrong", Errors: []string{"title: wrong"}}, }, } for _, c := range cases { shopUrl := fmt.Sprintf("https://fooshop.myshopify.com/%v", c.url) httpmock.RegisterResponder("GET", shopUrl, c.responder) body := new(MyStruct) req, _ := client.NewRequest("GET", c.url, nil, nil) err := client.Do(req, body) if err != nil && !reflect.DeepEqual(err, c.expected) { t.Errorf("Do(): expected error %#v, actual %#v", c.expected, err) } else if err == nil && !reflect.DeepEqual(body, c.expected) { t.Errorf("Do(): expected %#v, actual %#v", c.expected, body) } } }
func TestSendEcoSMSSuccess(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("POST", "https://api.smsapi.pl/sms.do", httpmock.NewStringResponder(200, `OK:1013211`)) object := New("testuser", "testpasswd") err := object.SendEcoSMS("XXXXXXXXX", "test message") assert.NoError(t, err) }
func TestListFilesWithFailure(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterNoResponder(httpmock.NewStringResponder(500, "")) client := Client{APIKey: "abcdef", Secret: "abcdef", ProjectID: 1} _, err := client.ListFiles(1, 1) assert.Equal(t, err, fmt.Errorf("bad status: %d", 500)) }
func TestGetTranslationsStatusWithFailure(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterNoResponder(httpmock.NewStringResponder(500, "")) client := Client{APIKey: "abcdef", Secret: "abcdef", ProjectID: 1} _, err := client.GetTranslationsStatus("string.po", "ja-JP") assert.Equal(t, err, fmt.Errorf("bad status: %d", 500)) }
func TestImportTasksWithFailure(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterNoResponder(httpmock.NewStringResponder(500, "")) client := Client{APIKey: "abcdef", Secret: "abcdef", ProjectID: 1} _, err := client.ImportTasks(map[string]interface{}{"page": 1, "per_page": 50, "status": "all"}) assert.Equal(t, err, fmt.Errorf("bad status: %d", 500)) }
func TestDeleteFileWithSuccess(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterNoResponder(httpmock.NewStringResponder(200, "")) client := Client{APIKey: "abcdef", Secret: "abcdef", ProjectID: 1} err := client.DeleteFile("test.yml") assert.Nil(t, err) }
func TestKGCourier(t *testing.T) { // create kg courier courier, _ := New("KG") // create http mock httpmock.Activate() defer httpmock.DeactivateAndReset() invalidTrackingNumber := "kg_invalid" invalidTrackingNumber2 := "kg_invalid2" completeTrackingNumber := "kg_complete" httpmock.RegisterResponder("GET", fmt.Sprintf(Kg{}.TrackingUrl(), invalidTrackingNumber), httpmock.NewStringResponder(200, readTestResponseFile(invalidTrackingNumber+".html"))) httpmock.RegisterResponder("GET", fmt.Sprintf(Kg{}.TrackingUrl(), invalidTrackingNumber2), httpmock.NewStringResponder(200, readTestResponseFile(invalidTrackingNumber2+".html"))) httpmock.RegisterResponder("GET", fmt.Sprintf(Kg{}.TrackingUrl(), completeTrackingNumber), httpmock.NewStringResponder(200, readTestResponseFile(completeTrackingNumber+".html"))) Convey("KG test", t, func() { Convey("Invalid tracking number test", func() { _, err := courier.Parse(invalidTrackingNumber) So(err, ShouldNotBeNil) }) Convey("Invalid tracking number test2", func() { _, err := courier.Parse(invalidTrackingNumber2) So(err, ShouldNotBeNil) }) Convey("Complete courier test", func() { data, _ := courier.Parse(completeTrackingNumber) So(data.StatusCode, ShouldEqual, delibird.DeleveryComplete) So(data.Sender, ShouldEqual, "웨일런샵 님") So(data.Receiver, ShouldEqual, "김예준 님") So(data.CompanyCode, ShouldEqual, "KG") }) }) }
func TestTagsRename(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", "https://api.pinboard.in/v1/tags/rename?auth_token=user%3Atoken&new=new&old=old", httpmock.NewStringResponder(200, readFixture("ok"))) _, err := client.Tags.Rename("new", "old") if err != nil { t.Error(err) } }
func TestPostsDelete(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", "https://api.pinboard.in/v1/posts/delete?auth_token=user%3Atoken&url=http%3A%2F%2Fexample.org", httpmock.NewStringResponder(200, readFixture("ok"))) _, err := client.Posts.Delete("http://example.org") if err != nil { t.Error(err) } }
func TestTagsDelete(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", "https://api.pinboard.in/v1/tags/delete?auth_token=user%3Atoken&tag=fooo", httpmock.NewStringResponder(200, readFixture("ok"))) _, err := client.Tags.Delete("fooo") if err != nil { t.Error(err) } }
func TestDownloadFileWithSuccess(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterNoResponder(httpmock.NewStringResponder(200, `test: translatedTest`)) client := Client{APIKey: "abcdef", Secret: "abcdef", ProjectID: 1} res, err := client.DownloadFile("test.yml", "en_US") fmt.Println(res) assert.Nil(t, err) assert.Equal(t, `test: translatedTest`, res) }
func TestPostsAdd(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", "https://api.pinboard.in/v1/posts/add?auth_token=user%3Atoken&description=Title&dt=2009-11-10T23%3A00%3A00Z&extended=Description&replace=true&shared=true&tags=one&tags=two&tags=three&tags=four&toread=true&url=http%3A%2F%2Fexample.org", httpmock.NewStringResponder(200, readFixture("ok"))) tags := []string{"one", "two", "three", "four"} _, err := client.Posts.Add("http://example.org", "Title", "Description", tags, &time1, true, true, true) if err != nil { t.Error(err) } }
func TestErrorIsNilWhenOkResponse(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("POST", "https://www.dummy-address.com/sendMessages", httpmock.NewStringResponder(200, `{"batchReference":"123abc","messageStatus":[]}`)) gatewayClient := smsgwclient.MakeSmsGatewayClient("https://www.dummy-address.com", 0, "", "") messages := []smsgwclient.Message{smsgwclient.Message{}} if _, err := gatewayClient.Send(messages); err != nil { t.FailNow() } }
func TestErrorIsNotNilWhenErrorResponse(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("POST", "https://www.dummy-address.com/sendMessages", httpmock.NewStringResponder(500, "")) gatewayClient := smsgwclient.MakeSmsGatewayClient("https://www.dummy-address.com", 0, "", "") messages := []smsgwclient.Message{smsgwclient.Message{}} if _, err := gatewayClient.Send(messages); err == nil { t.FailNow() } }