123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479 |
- // Copyright (c) 2015-2019 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
- // resty source code and usage is governed by a MIT style
- // license that can be found in the LICENSE file.
- package resty
- import (
- "bytes"
- "crypto/tls"
- "io"
- "io/ioutil"
- "net"
- "net/http"
- "net/url"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "testing"
- "time"
- )
- type AuthSuccess struct {
- ID, Message string
- }
- type AuthError struct {
- ID, Message string
- }
- func TestGet(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- resp, err := R().
- SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
- Get(ts.URL + "/")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "200 OK", resp.Status())
- assertNotNil(t, resp.Body())
- assertEqual(t, "TestGet: text response", resp.String())
- logResponse(t, resp)
- }
- func TestGetCustomUserAgent(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- resp, err := dcr().
- SetHeader(hdrUserAgentKey, "Test Custom User agent").
- SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
- Get(ts.URL + "/")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "200 OK", resp.Status())
- assertEqual(t, "TestGet: text response", resp.String())
- logResponse(t, resp)
- }
- func TestGetClientParamRequestParam(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- c := dc()
- c.SetQueryParam("client_param", "true").
- SetQueryParams(map[string]string{"req_1": "jeeva", "req_3": "jeeva3"}).
- SetDebug(true).
- SetLogger(ioutil.Discard)
- resp, err := c.R().
- SetQueryParams(map[string]string{"req_1": "req 1 value", "req_2": "req 2 value"}).
- SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
- SetHeader(hdrUserAgentKey, "Test Custom User agent").
- Get(ts.URL + "/")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "200 OK", resp.Status())
- assertEqual(t, "TestGet: text response", resp.String())
- logResponse(t, resp)
- }
- func TestGetRelativePath(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- c := dc()
- c.SetHostURL(ts.URL)
- resp, err := c.R().Get("mypage2")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "TestGet: text response from mypage2", resp.String())
- logResponse(t, resp)
- }
- func TestGet400Error(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- resp, err := dcr().Get(ts.URL + "/mypage")
- assertError(t, err)
- assertEqual(t, http.StatusBadRequest, resp.StatusCode())
- assertEqual(t, "", resp.String())
- logResponse(t, resp)
- }
- func TestPostJSONStringSuccess(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetHeader(hdrContentTypeKey, jsonContentType).
- SetHeaders(map[string]string{hdrUserAgentKey: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) go-resty v0.1", hdrAcceptKey: jsonContentType})
- resp, err := c.R().
- SetBody(`{"username":"testuser", "password":"testpass"}`).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- logResponse(t, resp)
- // PostJSONStringError
- resp, err = c.R().
- SetBody(`{"username":"testuser" "password":"testpass"}`).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusBadRequest, resp.StatusCode())
- logResponse(t, resp)
- }
- func TestPostJSONBytesSuccess(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetHeader(hdrContentTypeKey, jsonContentType).
- SetHeaders(map[string]string{hdrUserAgentKey: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) go-resty v0.7", hdrAcceptKey: jsonContentType})
- resp, err := c.R().
- SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- logResponse(t, resp)
- }
- func TestPostJSONBytesIoReader(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetHeader(hdrContentTypeKey, jsonContentType)
- bodyBytes := []byte(`{"username":"testuser", "password":"testpass"}`)
- resp, err := c.R().
- SetBody(bytes.NewReader(bodyBytes)).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- logResponse(t, resp)
- }
- func TestPostJSONStructSuccess(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- user := &User{Username: "testuser", Password: "testpass"}
- c := dc().SetJSONEscapeHTML(false)
- resp, err := c.R().
- SetHeader(hdrContentTypeKey, jsonContentType).
- SetBody(user).
- SetResult(&AuthSuccess{}).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
- logResponse(t, resp)
- }
- func TestPostJSONRPCStructSuccess(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- user := &User{Username: "testuser", Password: "testpass"}
- c := dc().SetJSONEscapeHTML(false)
- resp, err := c.R().
- SetHeader(hdrContentTypeKey, "application/json-rpc").
- SetBody(user).
- SetResult(&AuthSuccess{}).
- SetQueryParam("ct", "rpc").
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
- logResponse(t, resp)
- }
- func TestPostJSONStructInvalidLogin(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetDebug(false)
- resp, err := c.R().
- SetHeader(hdrContentTypeKey, jsonContentType).
- SetBody(User{Username: "testuser", Password: "testpass1"}).
- SetError(AuthError{}).
- SetJSONEscapeHTML(false).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusUnauthorized, resp.StatusCode())
- authError := resp.Error().(*AuthError)
- assertEqual(t, "unauthorized", authError.ID)
- assertEqual(t, "Invalid credentials", authError.Message)
- t.Logf("Result Error: %q", resp.Error().(*AuthError))
- logResponse(t, resp)
- }
- func TestPostJSONErrorRFC7807(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- c := dc()
- resp, err := c.R().
- SetHeader(hdrContentTypeKey, jsonContentType).
- SetBody(User{Username: "testuser", Password: "testpass1"}).
- SetError(AuthError{}).
- Post(ts.URL + "/login?ct=problem")
- assertError(t, err)
- assertEqual(t, http.StatusUnauthorized, resp.StatusCode())
- authError := resp.Error().(*AuthError)
- assertEqual(t, "unauthorized", authError.ID)
- assertEqual(t, "Invalid credentials", authError.Message)
- t.Logf("Result Error: %q", resp.Error().(*AuthError))
- logResponse(t, resp)
- }
- func TestPostJSONMapSuccess(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetDebug(false)
- resp, err := c.R().
- SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
- SetResult(AuthSuccess{}).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
- logResponse(t, resp)
- }
- func TestPostJSONMapInvalidResponseJson(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- resp, err := dclr().
- SetBody(map[string]interface{}{"username": "testuser", "password": "invalidjson"}).
- SetResult(&AuthSuccess{}).
- Post(ts.URL + "/login")
- assertEqual(t, "invalid character '}' looking for beginning of object key string", err.Error())
- assertEqual(t, http.StatusOK, resp.StatusCode())
- authSuccess := resp.Result().(*AuthSuccess)
- assertEqual(t, "", authSuccess.ID)
- assertEqual(t, "", authSuccess.Message)
- t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
- logResponse(t, resp)
- }
- func TestPostXMLStringSuccess(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetDebug(false)
- resp, err := c.R().
- SetHeader(hdrContentTypeKey, "application/xml").
- SetBody(`<?xml version="1.0" encoding="UTF-8"?><User><Username>testuser</Username><Password>testpass</Password></User>`).
- SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- logResponse(t, resp)
- }
- func TestPostXMLStringError(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- resp, err := dclr().
- SetHeader(hdrContentTypeKey, "application/xml").
- SetBody(`<?xml version="1.0" encoding="UTF-8"?><User><Username>testuser</Username>testpass</Password></User>`).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusBadRequest, resp.StatusCode())
- assertEqual(t, `<?xml version="1.0" encoding="UTF-8"?><AuthError><Id>bad_request</Id><Message>Unable to read user info</Message></AuthError>`, resp.String())
- logResponse(t, resp)
- }
- func TestPostXMLBytesSuccess(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetDebug(false)
- resp, err := c.R().
- SetHeader(hdrContentTypeKey, "application/xml").
- SetBody([]byte(`<?xml version="1.0" encoding="UTF-8"?><User><Username>testuser</Username><Password>testpass</Password></User>`)).
- SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
- SetContentLength(true).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- logResponse(t, resp)
- }
- func TestPostXMLStructSuccess(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- resp, err := dclr().
- SetHeader(hdrContentTypeKey, "application/xml").
- SetBody(User{Username: "testuser", Password: "testpass"}).
- SetContentLength(true).
- SetResult(&AuthSuccess{}).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
- logResponse(t, resp)
- }
- func TestPostXMLStructInvalidLogin(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetError(&AuthError{})
- resp, err := c.R().
- SetHeader(hdrContentTypeKey, "application/xml").
- SetBody(User{Username: "testuser", Password: "testpass1"}).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusUnauthorized, resp.StatusCode())
- assertEqual(t, resp.Header().Get("Www-Authenticate"), "Protected Realm")
- t.Logf("Result Error: %q", resp.Error().(*AuthError))
- logResponse(t, resp)
- }
- func TestPostXMLStructInvalidResponseXml(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- resp, err := dclr().
- SetHeader(hdrContentTypeKey, "application/xml").
- SetBody(User{Username: "testuser", Password: "invalidxml"}).
- SetResult(&AuthSuccess{}).
- Post(ts.URL + "/login")
- assertEqual(t, "XML syntax error on line 1: element <Message> closed by </AuthSuccess>", err.Error())
- assertEqual(t, http.StatusOK, resp.StatusCode())
- t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
- logResponse(t, resp)
- }
- func TestPostXMLMapNotSupported(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- _, err := dclr().
- SetHeader(hdrContentTypeKey, "application/xml").
- SetBody(map[string]interface{}{"Username": "testuser", "Password": "testpass"}).
- Post(ts.URL + "/login")
- assertEqual(t, "unsupported 'Body' type/value", err.Error())
- }
- func TestRequestBasicAuth(t *testing.T) {
- ts := createAuthServer(t)
- defer ts.Close()
- c := dc()
- c.SetHostURL(ts.URL).
- SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
- resp, err := c.R().
- SetBasicAuth("myuser", "basicauth").
- SetResult(&AuthSuccess{}).
- Post("/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
- logResponse(t, resp)
- }
- func TestRequestBasicAuthFail(t *testing.T) {
- ts := createAuthServer(t)
- defer ts.Close()
- c := dc()
- c.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
- SetError(AuthError{})
- resp, err := c.R().
- SetBasicAuth("myuser", "basicauth1").
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusUnauthorized, resp.StatusCode())
- t.Logf("Result Error: %q", resp.Error().(*AuthError))
- logResponse(t, resp)
- }
- func TestRequestAuthToken(t *testing.T) {
- ts := createAuthServer(t)
- defer ts.Close()
- c := dc()
- c.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
- SetAuthToken("004DDB79-6801-4587-B976-F093E6AC44FF")
- resp, err := c.R().
- SetAuthToken("004DDB79-6801-4587-B976-F093E6AC44FF-Request").
- Get(ts.URL + "/profile")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- }
- func TestFormData(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetFormData(map[string]string{"zip_code": "00000", "city": "Los Angeles"}).
- SetContentLength(true).
- SetDebug(true).
- SetLogger(ioutil.Discard)
- resp, err := c.R().
- SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M", "zip_code": "00001"}).
- SetBasicAuth("myuser", "mypass").
- Post(ts.URL + "/profile")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "Success", resp.String())
- }
- func TestMultiValueFormData(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- v := url.Values{
- "search_criteria": []string{"book", "glass", "pencil"},
- }
- c := dc()
- c.SetContentLength(true).
- SetDebug(true).
- SetLogger(ioutil.Discard)
- resp, err := c.R().
- SetMultiValueFormData(v).
- Post(ts.URL + "/search")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "Success", resp.String())
- }
- func TestFormDataDisableWarn(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- c := dc()
- c.SetFormData(map[string]string{"zip_code": "00000", "city": "Los Angeles"}).
- SetContentLength(true).
- SetDebug(true).
- SetLogger(ioutil.Discard).
- SetDisableWarn(true)
- resp, err := c.R().
- SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M", "zip_code": "00001"}).
- SetBasicAuth("myuser", "mypass").
- Post(ts.URL + "/profile")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "Success", resp.String())
- }
- func TestMultiPartUploadFile(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- defer cleanupFiles(".testdata/upload")
- basePath := getTestDataPath()
- c := dc()
- c.SetFormData(map[string]string{"zip_code": "00001", "city": "Los Angeles"})
- resp, err := c.R().
- SetFile("profile_img", filepath.Join(basePath, "test-img.png")).
- SetContentLength(true).
- Post(ts.URL + "/upload")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- }
- func TestMultiPartUploadFileError(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- defer cleanupFiles(".testdata/upload")
- basePath := getTestDataPath()
- c := dc()
- c.SetFormData(map[string]string{"zip_code": "00001", "city": "Los Angeles"})
- resp, err := c.R().
- SetFile("profile_img", filepath.Join(basePath, "test-img-not-exists.png")).
- Post(ts.URL + "/upload")
- if err == nil {
- t.Errorf("Expected [%v], got [%v]", nil, err)
- }
- if resp != nil {
- t.Errorf("Expected [%v], got [%v]", nil, resp)
- }
- }
- func TestMultiPartUploadFiles(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- defer cleanupFiles(".testdata/upload")
- basePath := getTestDataPath()
- resp, err := dclr().
- SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M"}).
- SetFiles(map[string]string{"profile_img": filepath.Join(basePath, "test-img.png"), "notes": filepath.Join(basePath, "text-file.txt")}).
- Post(ts.URL + "/upload")
- responseStr := resp.String()
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, true, strings.Contains(responseStr, "test-img.png"))
- assertEqual(t, true, strings.Contains(responseStr, "text-file.txt"))
- }
- func TestMultiPartIoReaderFiles(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- defer cleanupFiles(".testdata/upload")
- basePath := getTestDataPath()
- profileImgBytes, _ := ioutil.ReadFile(filepath.Join(basePath, "test-img.png"))
- notesBytes, _ := ioutil.ReadFile(filepath.Join(basePath, "text-file.txt"))
- // Just info values
- file := File{
- Name: "test_file_name.jpg",
- ParamName: "test_param",
- Reader: bytes.NewBuffer([]byte("test bytes")),
- }
- t.Logf("File Info: %v", file.String())
- resp, err := dclr().
- SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M"}).
- SetFileReader("profile_img", "test-img.png", bytes.NewReader(profileImgBytes)).
- SetFileReader("notes", "text-file.txt", bytes.NewReader(notesBytes)).
- Post(ts.URL + "/upload")
- responseStr := resp.String()
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, true, strings.Contains(responseStr, "test-img.png"))
- assertEqual(t, true, strings.Contains(responseStr, "text-file.txt"))
- }
- func TestMultiPartUploadFileNotOnGetOrDelete(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- defer cleanupFiles(".testdata/upload")
- basePath := getTestDataPath()
- _, err := dclr().
- SetFile("profile_img", filepath.Join(basePath, "test-img.png")).
- Get(ts.URL + "/upload")
- assertEqual(t, "multipart content is not allowed in HTTP verb [GET]", err.Error())
- _, err = dclr().
- SetFile("profile_img", filepath.Join(basePath, "test-img.png")).
- Delete(ts.URL + "/upload")
- assertEqual(t, "multipart content is not allowed in HTTP verb [DELETE]", err.Error())
- }
- func TestMultiPartMultipartField(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- defer cleanupFiles(".testdata/upload")
- jsonBytes := []byte(`{"input": {"name": "Uploaded document", "_filename" : ["file.txt"]}}`)
- resp, err := dclr().
- SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M"}).
- SetMultipartField("uploadManifest", "upload-file.json", "application/json", bytes.NewReader(jsonBytes)).
- Post(ts.URL + "/upload")
- responseStr := resp.String()
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, true, strings.Contains(responseStr, "upload-file.json"))
- }
- func TestMultiPartMultipartFields(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- defer cleanupFiles(".testdata/upload")
- jsonStr1 := `{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`
- jsonStr2 := `{"input": {"name": "Uploaded document 2", "_filename" : ["file2.txt"]}}`
- fields := []*MultipartField{
- &MultipartField{
- Param: "uploadManifest1",
- FileName: "upload-file-1.json",
- ContentType: "application/json",
- Reader: strings.NewReader(jsonStr1),
- },
- &MultipartField{
- Param: "uploadManifest2",
- FileName: "upload-file-2.json",
- ContentType: "application/json",
- Reader: strings.NewReader(jsonStr2),
- },
- }
- resp, err := dclr().
- SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M"}).
- SetMultipartFields(fields...).
- Post(ts.URL + "/upload")
- responseStr := resp.String()
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, true, strings.Contains(responseStr, "upload-file-1.json"))
- assertEqual(t, true, strings.Contains(responseStr, "upload-file-2.json"))
- }
- func TestGetWithCookie(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- c := dc()
- c.SetHostURL(ts.URL)
- c.SetCookie(&http.Cookie{
- Name: "go-resty-1",
- Value: "This is cookie 1 value",
- Path: "/",
- Domain: "localhost",
- MaxAge: 36000,
- HttpOnly: true,
- Secure: false,
- })
- resp, err := c.R().Get("mypage2")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "TestGet: text response from mypage2", resp.String())
- logResponse(t, resp)
- }
- func TestGetWithCookies(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- var cookies []*http.Cookie
- cookies = append(cookies, &http.Cookie{
- Name: "go-resty-1",
- Value: "This is cookie 1 value",
- Path: "/",
- Domain: "sample.com",
- MaxAge: 36000,
- HttpOnly: true,
- Secure: false,
- })
- cookies = append(cookies, &http.Cookie{
- Name: "go-resty-2",
- Value: "This is cookie 2 value",
- Path: "/",
- Domain: "sample.com",
- MaxAge: 36000,
- HttpOnly: true,
- Secure: false,
- })
- c := dc()
- c.SetHostURL(ts.URL).
- SetCookies(cookies)
- resp, err := c.R().Get("mypage2")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "TestGet: text response from mypage2", resp.String())
- logResponse(t, resp)
- }
- func TestPutPlainString(t *testing.T) {
- ts := createGenServer(t)
- defer ts.Close()
- resp, err := R().
- SetBody("This is plain text body to server").
- Put(ts.URL + "/plaintext")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "TestPut: plain text response", resp.String())
- }
- func TestPutJSONString(t *testing.T) {
- ts := createGenServer(t)
- defer ts.Close()
- DefaultClient.OnBeforeRequest(func(c *Client, r *Request) error {
- r.SetHeader("X-Custom-Request-Middleware", "OnBeforeRequest middleware")
- return nil
- })
- DefaultClient.OnBeforeRequest(func(c *Client, r *Request) error {
- c.SetContentLength(true)
- r.SetHeader("X-ContentLength", "OnBeforeRequest ContentLength set")
- return nil
- })
- DefaultClient.SetDebug(true).SetLogger(ioutil.Discard)
- resp, err := R().
- SetHeaders(map[string]string{hdrContentTypeKey: jsonContentType, hdrAcceptKey: jsonContentType}).
- SetBody(`{"content":"json content sending to server"}`).
- Put(ts.URL + "/json")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, `{"response":"json response"}`, resp.String())
- }
- func TestPutXMLString(t *testing.T) {
- ts := createGenServer(t)
- defer ts.Close()
- resp, err := R().
- SetHeaders(map[string]string{hdrContentTypeKey: "application/xml", hdrAcceptKey: "application/xml"}).
- SetBody(`<?xml version="1.0" encoding="UTF-8"?><Request>XML Content sending to server</Request>`).
- Put(ts.URL + "/xml")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, `<?xml version="1.0" encoding="UTF-8"?><Response>XML response</Response>`, resp.String())
- }
- func TestOnBeforeMiddleware(t *testing.T) {
- ts := createGenServer(t)
- defer ts.Close()
- c := dc()
- c.OnBeforeRequest(func(c *Client, r *Request) error {
- r.SetHeader("X-Custom-Request-Middleware", "OnBeforeRequest middleware")
- return nil
- })
- c.OnBeforeRequest(func(c *Client, r *Request) error {
- c.SetContentLength(true)
- r.SetHeader("X-ContentLength", "OnBeforeRequest ContentLength set")
- return nil
- })
- resp, err := c.R().
- SetBody("OnBeforeRequest: This is plain text body to server").
- Put(ts.URL + "/plaintext")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "TestPut: plain text response", resp.String())
- }
- func TestNoAutoRedirect(t *testing.T) {
- ts := createRedirectServer(t)
- defer ts.Close()
- _, err := R().Get(ts.URL + "/redirect-1")
- assertEqual(t, "Get /redirect-2: auto redirect is disabled", err.Error())
- }
- func TestHTTPAutoRedirectUpTo10(t *testing.T) {
- ts := createRedirectServer(t)
- defer ts.Close()
- c := dc()
- c.SetHTTPMode()
- _, err := c.R().Get(ts.URL + "/redirect-1")
- assertEqual(t, "Get /redirect-11: stopped after 10 redirects", err.Error())
- }
- func TestHostCheckRedirectPolicy(t *testing.T) {
- ts := createRedirectServer(t)
- defer ts.Close()
- c := dc().
- SetRedirectPolicy(DomainCheckRedirectPolicy("127.0.0.1"))
- _, err := c.R().Get(ts.URL + "/redirect-host-check-1")
- assertNotNil(t, err)
- assertEqual(t, true, strings.Contains(err.Error(), "redirect is not allowed as per DomainCheckRedirectPolicy"))
- }
- func TestHeadMethod(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- resp, err := dclr().Head(ts.URL + "/")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- }
- func TestOptionsMethod(t *testing.T) {
- ts := createGenServer(t)
- defer ts.Close()
- resp, err := dclr().Options(ts.URL + "/options")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, resp.Header().Get("Access-Control-Expose-Headers"), "x-go-resty-id")
- }
- func TestPatchMethod(t *testing.T) {
- ts := createGenServer(t)
- defer ts.Close()
- resp, err := dclr().Patch(ts.URL + "/patch")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- resp.body = nil
- assertEqual(t, "", resp.String())
- }
- func TestRawFileUploadByBody(t *testing.T) {
- ts := createFormPostServer(t)
- defer ts.Close()
- file, err := os.Open(filepath.Join(getTestDataPath(), "test-img.png"))
- assertNil(t, err)
- fileBytes, err := ioutil.ReadAll(file)
- assertNil(t, err)
- resp, err := dclr().
- SetBody(fileBytes).
- SetContentLength(true).
- SetAuthToken("004DDB79-6801-4587-B976-F093E6AC44FF").
- Put(ts.URL + "/raw-upload")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "image/png", resp.Request.Header.Get(hdrContentTypeKey))
- }
- func TestProxySetting(t *testing.T) {
- c := dc()
- transport, err := c.getTransport()
- assertNil(t, err)
- assertEqual(t, false, c.IsProxySet())
- assertNil(t, transport.Proxy)
- c.SetProxy("http://sampleproxy:8888")
- assertEqual(t, true, c.IsProxySet())
- assertNotNil(t, transport.Proxy)
- c.SetProxy("//not.a.user@%66%6f%6f.com:8888")
- assertEqual(t, false, c.IsProxySet())
- assertNil(t, transport.Proxy)
- SetProxy("http://sampleproxy:8888")
- assertEqual(t, true, IsProxySet())
- RemoveProxy()
- assertNil(t, DefaultClient.proxyURL)
- assertNil(t, transport.Proxy)
- }
- func TestGetClient(t *testing.T) {
- client := GetClient()
- custom := New()
- customClient := custom.GetClient()
- assertNotNil(t, client)
- assertNotNil(t, customClient)
- assertNotEqual(t, client, http.DefaultClient)
- assertNotEqual(t, customClient, http.DefaultClient)
- assertNotEqual(t, client, customClient)
- assertEqual(t, DefaultClient.httpClient, client)
- }
- func TestIncorrectURL(t *testing.T) {
- _, err := R().Get("//not.a.user@%66%6f%6f.com/just/a/path/also")
- assertEqual(t, true, strings.Contains(err.Error(), "parse //not.a.user@%66%6f%6f.com/just/a/path/also"))
- c := dc()
- c.SetHostURL("//not.a.user@%66%6f%6f.com")
- _, err1 := c.R().Get("/just/a/path/also")
- assertEqual(t, true, strings.Contains(err1.Error(), "parse //not.a.user@%66%6f%6f.com/just/a/path/also"))
- }
- func TestDetectContentTypeForPointer(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- user := &User{Username: "testuser", Password: "testpass"}
- resp, err := dclr().
- SetBody(user).
- SetResult(AuthSuccess{}).
- Post(ts.URL + "/login")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
- logResponse(t, resp)
- }
- type ExampleUser struct {
- FirstName string `json:"frist_name"`
- LastName string `json:"last_name"`
- ZipCode string `json:"zip_code"`
- }
- func TestDetectContentTypeForPointerWithSlice(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- users := &[]ExampleUser{
- {FirstName: "firstname1", LastName: "lastname1", ZipCode: "10001"},
- {FirstName: "firstname2", LastName: "lastname3", ZipCode: "10002"},
- {FirstName: "firstname3", LastName: "lastname3", ZipCode: "10003"},
- }
- resp, err := dclr().
- SetBody(users).
- Post(ts.URL + "/users")
- assertError(t, err)
- assertEqual(t, http.StatusAccepted, resp.StatusCode())
- t.Logf("Result Success: %q", resp)
- logResponse(t, resp)
- }
- func TestDetectContentTypeForPointerWithSliceMap(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- usersmap := map[string]interface{}{
- "user1": ExampleUser{FirstName: "firstname1", LastName: "lastname1", ZipCode: "10001"},
- "user2": &ExampleUser{FirstName: "firstname2", LastName: "lastname3", ZipCode: "10002"},
- "user3": ExampleUser{FirstName: "firstname3", LastName: "lastname3", ZipCode: "10003"},
- }
- var users []map[string]interface{}
- users = append(users, usersmap)
- resp, err := dclr().
- SetBody(&users).
- Post(ts.URL + "/usersmap")
- assertError(t, err)
- assertEqual(t, http.StatusAccepted, resp.StatusCode())
- t.Logf("Result Success: %q", resp)
- logResponse(t, resp)
- }
- func TestDetectContentTypeForSlice(t *testing.T) {
- ts := createPostServer(t)
- defer ts.Close()
- users := []ExampleUser{
- {FirstName: "firstname1", LastName: "lastname1", ZipCode: "10001"},
- {FirstName: "firstname2", LastName: "lastname3", ZipCode: "10002"},
- {FirstName: "firstname3", LastName: "lastname3", ZipCode: "10003"},
- }
- resp, err := dclr().
- SetBody(users).
- Post(ts.URL + "/users")
- assertError(t, err)
- assertEqual(t, http.StatusAccepted, resp.StatusCode())
- t.Logf("Result Success: %q", resp)
- logResponse(t, resp)
- }
- func TestMultiParamsQueryString(t *testing.T) {
- ts1 := createGetServer(t)
- defer ts1.Close()
- client := dc()
- req1 := client.R()
- client.SetQueryParam("status", "open")
- _, _ = req1.SetQueryParam("status", "pending").
- Get(ts1.URL)
- assertEqual(t, true, strings.Contains(req1.URL, "status=pending"))
- // pending overrides open
- assertEqual(t, false, strings.Contains(req1.URL, "status=open"))
- _, _ = req1.SetQueryParam("status", "approved").
- Get(ts1.URL)
- assertEqual(t, true, strings.Contains(req1.URL, "status=approved"))
- // approved overrides pending
- assertEqual(t, false, strings.Contains(req1.URL, "status=pending"))
- ts2 := createGetServer(t)
- defer ts2.Close()
- req2 := client.R()
- v := url.Values{
- "status": []string{"pending", "approved", "reject"},
- }
- _, _ = req2.SetMultiValueQueryParams(v).Get(ts2.URL)
- assertEqual(t, true, strings.Contains(req2.URL, "status=pending"))
- assertEqual(t, true, strings.Contains(req2.URL, "status=approved"))
- assertEqual(t, true, strings.Contains(req2.URL, "status=reject"))
- // because it's removed by key
- assertEqual(t, false, strings.Contains(req2.URL, "status=open"))
- }
- func TestSetQueryStringTypical(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- resp, err := dclr().
- SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more").
- Get(ts.URL)
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "200 OK", resp.Status())
- assertEqual(t, "TestGet: text response", resp.String())
- resp, err = dclr().
- SetQueryString("&%%amp;").
- Get(ts.URL)
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "200 OK", resp.Status())
- assertEqual(t, "TestGet: text response", resp.String())
- }
- func TestOutputFileWithBaseDirAndRelativePath(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- defer cleanupFiles(".testdata/dir-sample")
- DefaultClient = dc()
- SetRedirectPolicy(FlexibleRedirectPolicy(10))
- SetOutputDirectory(filepath.Join(getTestDataPath(), "dir-sample"))
- SetDebug(true)
- SetLogger(ioutil.Discard)
- resp, err := R().
- SetOutput("go-resty/test-img-success.png").
- Get(ts.URL + "/my-image.png")
- assertError(t, err)
- assertEqual(t, true, resp.Size() != 0)
- }
- func TestOutputFileWithBaseDirError(t *testing.T) {
- c := dc().SetRedirectPolicy(FlexibleRedirectPolicy(10)).
- SetOutputDirectory(filepath.Join(getTestDataPath(), `go-resty\0`))
- _ = c
- }
- func TestOutputPathDirNotExists(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- defer cleanupFiles(filepath.Join(".testdata", "not-exists-dir"))
- DefaultClient = dc()
- SetRedirectPolicy(FlexibleRedirectPolicy(10))
- SetOutputDirectory(filepath.Join(getTestDataPath(), "not-exists-dir"))
- resp, err := R().
- SetOutput("test-img-success.png").
- Get(ts.URL + "/my-image.png")
- assertError(t, err)
- assertEqual(t, true, resp.Size() != 0)
- }
- func TestOutputFileAbsPath(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- defer cleanupFiles(filepath.Join(".testdata", "go-resty"))
- _, err := dcr().
- SetOutput(filepath.Join(getTestDataPath(), "go-resty", "test-img-success-2.png")).
- Get(ts.URL + "/my-image.png")
- assertError(t, err)
- }
- func TestContextInternal(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- r := R().
- SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10))
- if r.isContextCancelledIfAvailable() {
- t.Error("isContextCancelledIfAvailable != false for vanilla R()")
- }
- r.addContextIfAvailable()
- resp, err := r.Get(ts.URL + "/")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- }
- func TestSRV(t *testing.T) {
- c := dc().
- SetRedirectPolicy(FlexibleRedirectPolicy(20)).
- SetScheme("http")
- r := c.R().
- SetSRV(&SRVRecord{"xmpp-server", "google.com"})
- assertEqual(t, "xmpp-server", r.SRV.Service)
- assertEqual(t, "google.com", r.SRV.Domain)
- resp, err := r.Get("/")
- if err == nil {
- assertError(t, err)
- assertNotNil(t, resp)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- }
- }
- func TestSRVInvalidService(t *testing.T) {
- _, err := R().
- SetSRV(&SRVRecord{"nonexistantservice", "sampledomain"}).
- Get("/")
- assertNotNil(t, err)
- assertType(t, net.DNSError{}, err)
- }
- func TestDeprecatedCodeCoverage(t *testing.T) {
- var user1 User
- err := Unmarshal("application/json",
- []byte(`{"username":"testuser", "password":"testpass"}`), &user1)
- assertError(t, err)
- assertEqual(t, "testuser", user1.Username)
- assertEqual(t, "testpass", user1.Password)
- var user2 User
- err = Unmarshal("application/xml",
- []byte(`<?xml version="1.0" encoding="UTF-8"?><User><Username>testuser</Username><Password>testpass</Password></User>`),
- &user2)
- assertError(t, err)
- assertEqual(t, "testuser", user1.Username)
- assertEqual(t, "testpass", user1.Password)
- }
- func TestRequestDoNotParseResponse(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- resp, err := dc().R().
- SetDoNotParseResponse(true).
- SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
- Get(ts.URL + "/")
- assertError(t, err)
- buf := acquireBuffer()
- defer releaseBuffer(buf)
- _, _ = io.Copy(buf, resp.RawBody())
- assertEqual(t, "TestGet: text response", buf.String())
- _ = resp.RawBody().Close()
- // Manually setting RawResponse as nil
- resp, err = dc().R().
- SetDoNotParseResponse(true).
- Get(ts.URL + "/")
- assertError(t, err)
- resp.RawResponse = nil
- assertNil(t, resp.RawBody())
- // just set test part
- SetDoNotParseResponse(true)
- assertEqual(t, true, DefaultClient.notParseResponse)
- SetDoNotParseResponse(false)
- }
- type noCtTest struct {
- Response string `json:"response"`
- }
- func TestRequestExpectContentTypeTest(t *testing.T) {
- ts := createGenServer(t)
- defer ts.Close()
- c := dc()
- resp, err := c.R().
- SetResult(noCtTest{}).
- ExpectContentType("application/json").
- Get(ts.URL + "/json-no-set")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertNotNil(t, resp.Result())
- assertEqual(t, "json response no content type set", resp.Result().(*noCtTest).Response)
- assertEqual(t, "", firstNonEmpty("", ""))
- }
- func TestGetPathParams(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- c := dc()
- c.SetHostURL(ts.URL).
- SetPathParams(map[string]string{
- "userId": "sample@sample.com",
- })
- resp, err := c.R().SetPathParams(map[string]string{
- "subAccountId": "100002",
- }).
- Get("/v1/users/{userId}/{subAccountId}/details")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, true, strings.Contains(resp.String(), "TestGetPathParams: text response"))
- assertEqual(t, true, strings.Contains(resp.String(), "/v1/users/sample@sample.com/100002/details"))
- logResponse(t, resp)
- SetPathParams(map[string]string{
- "userId": "sample@sample.com",
- })
- }
- func TestReportMethodSupportsPayload(t *testing.T) {
- ts := createGenServer(t)
- defer ts.Close()
- c := dc()
- resp, err := c.R().
- SetBody("body").
- Execute("REPORT", ts.URL+"/report")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- }
- func TestRequestQueryStringOrder(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- resp, err := New().R().
- SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more").
- Get(ts.URL + "/?UniqueId=ead1d0ed-XXX-XXX-XXX-abb7612b3146&Translate=false&tempauth=eyJ0eXAiOiJKV1QiLC...HZEhwVnJ1d0NSUGVLaUpSaVNLRG5scz0&ApiVersion=2.0")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "200 OK", resp.Status())
- assertNotNil(t, resp.Body())
- assertEqual(t, "TestGet: text response", resp.String())
- logResponse(t, resp)
- }
- func TestRequestOverridesClientAuthorizationHeader(t *testing.T) {
- ts := createAuthServer(t)
- defer ts.Close()
- c := dc()
- c.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
- SetHeader("Authorization", "some token")
- SetHostURL(ts.URL + "/")
- resp, err := c.R().
- SetHeader("Authorization", "Bearer 004DDB79-6801-4587-B976-F093E6AC44FF").
- Get("/profile")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- }
- func TestRequestFileUploadAsReader(t *testing.T) {
- ts := createFilePostServer(t)
- defer ts.Close()
- file, _ := os.Open(filepath.Join(getTestDataPath(), "test-img.png"))
- defer file.Close()
- resp, err := dclr().
- SetBody(file).
- SetHeader("Content-Type", "image/png").
- Post(ts.URL + "/upload")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, true, strings.Contains(resp.String(), "File Uploaded successfully"))
- file, _ = os.Open(filepath.Join(getTestDataPath(), "test-img.png"))
- defer file.Close()
- resp, err = dclr().
- SetBody(file).
- SetHeader("Content-Type", "image/png").
- SetContentLength(true).
- Post(ts.URL + "/upload")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, true, strings.Contains(resp.String(), "File Uploaded successfully"))
- }
- func TestHostHeaderOverride(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- resp, err := R().
- SetHeader("Host", "myhostname").
- Get(ts.URL + "/host-header")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, "200 OK", resp.Status())
- assertNotNil(t, resp.Body())
- assertEqual(t, "myhostname", resp.String())
- logResponse(t, resp)
- }
- func TestPathParamURLInput(t *testing.T) {
- ts := createGetServer(t)
- defer ts.Close()
- c := dc().SetDebug(true).SetLogger(ioutil.Discard)
- c.SetHostURL(ts.URL).
- SetPathParams(map[string]string{
- "userId": "sample@sample.com",
- })
- resp, err := c.R().
- SetPathParams(map[string]string{
- "subAccountId": "100002",
- "website": "https://example.com",
- }).Get("/v1/users/{userId}/{subAccountId}/{website}")
- assertError(t, err)
- assertEqual(t, http.StatusOK, resp.StatusCode())
- assertEqual(t, true, strings.Contains(resp.String(), "TestPathParamURLInput: text response"))
- assertEqual(t, true, strings.Contains(resp.String(), "/v1/users/sample@sample.com/100002/https:%2F%2Fexample.com"))
- logResponse(t, resp)
- }
|