request_test.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. // Copyright (c) 2015-2019 Jeevanandam M (jeeva@myjeeva.com), All rights reserved.
  2. // resty source code and usage is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package resty
  5. import (
  6. "bytes"
  7. "crypto/tls"
  8. "io"
  9. "io/ioutil"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "testing"
  18. "time"
  19. )
  20. type AuthSuccess struct {
  21. ID, Message string
  22. }
  23. type AuthError struct {
  24. ID, Message string
  25. }
  26. func TestGet(t *testing.T) {
  27. ts := createGetServer(t)
  28. defer ts.Close()
  29. resp, err := R().
  30. SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
  31. Get(ts.URL + "/")
  32. assertError(t, err)
  33. assertEqual(t, http.StatusOK, resp.StatusCode())
  34. assertEqual(t, "200 OK", resp.Status())
  35. assertNotNil(t, resp.Body())
  36. assertEqual(t, "TestGet: text response", resp.String())
  37. logResponse(t, resp)
  38. }
  39. func TestGetCustomUserAgent(t *testing.T) {
  40. ts := createGetServer(t)
  41. defer ts.Close()
  42. resp, err := dcr().
  43. SetHeader(hdrUserAgentKey, "Test Custom User agent").
  44. SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
  45. Get(ts.URL + "/")
  46. assertError(t, err)
  47. assertEqual(t, http.StatusOK, resp.StatusCode())
  48. assertEqual(t, "200 OK", resp.Status())
  49. assertEqual(t, "TestGet: text response", resp.String())
  50. logResponse(t, resp)
  51. }
  52. func TestGetClientParamRequestParam(t *testing.T) {
  53. ts := createGetServer(t)
  54. defer ts.Close()
  55. c := dc()
  56. c.SetQueryParam("client_param", "true").
  57. SetQueryParams(map[string]string{"req_1": "jeeva", "req_3": "jeeva3"}).
  58. SetDebug(true).
  59. SetLogger(ioutil.Discard)
  60. resp, err := c.R().
  61. SetQueryParams(map[string]string{"req_1": "req 1 value", "req_2": "req 2 value"}).
  62. SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
  63. SetHeader(hdrUserAgentKey, "Test Custom User agent").
  64. Get(ts.URL + "/")
  65. assertError(t, err)
  66. assertEqual(t, http.StatusOK, resp.StatusCode())
  67. assertEqual(t, "200 OK", resp.Status())
  68. assertEqual(t, "TestGet: text response", resp.String())
  69. logResponse(t, resp)
  70. }
  71. func TestGetRelativePath(t *testing.T) {
  72. ts := createGetServer(t)
  73. defer ts.Close()
  74. c := dc()
  75. c.SetHostURL(ts.URL)
  76. resp, err := c.R().Get("mypage2")
  77. assertError(t, err)
  78. assertEqual(t, http.StatusOK, resp.StatusCode())
  79. assertEqual(t, "TestGet: text response from mypage2", resp.String())
  80. logResponse(t, resp)
  81. }
  82. func TestGet400Error(t *testing.T) {
  83. ts := createGetServer(t)
  84. defer ts.Close()
  85. resp, err := dcr().Get(ts.URL + "/mypage")
  86. assertError(t, err)
  87. assertEqual(t, http.StatusBadRequest, resp.StatusCode())
  88. assertEqual(t, "", resp.String())
  89. logResponse(t, resp)
  90. }
  91. func TestPostJSONStringSuccess(t *testing.T) {
  92. ts := createPostServer(t)
  93. defer ts.Close()
  94. c := dc()
  95. c.SetHeader(hdrContentTypeKey, jsonContentType).
  96. SetHeaders(map[string]string{hdrUserAgentKey: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) go-resty v0.1", hdrAcceptKey: jsonContentType})
  97. resp, err := c.R().
  98. SetBody(`{"username":"testuser", "password":"testpass"}`).
  99. Post(ts.URL + "/login")
  100. assertError(t, err)
  101. assertEqual(t, http.StatusOK, resp.StatusCode())
  102. logResponse(t, resp)
  103. // PostJSONStringError
  104. resp, err = c.R().
  105. SetBody(`{"username":"testuser" "password":"testpass"}`).
  106. Post(ts.URL + "/login")
  107. assertError(t, err)
  108. assertEqual(t, http.StatusBadRequest, resp.StatusCode())
  109. logResponse(t, resp)
  110. }
  111. func TestPostJSONBytesSuccess(t *testing.T) {
  112. ts := createPostServer(t)
  113. defer ts.Close()
  114. c := dc()
  115. c.SetHeader(hdrContentTypeKey, jsonContentType).
  116. SetHeaders(map[string]string{hdrUserAgentKey: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) go-resty v0.7", hdrAcceptKey: jsonContentType})
  117. resp, err := c.R().
  118. SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
  119. Post(ts.URL + "/login")
  120. assertError(t, err)
  121. assertEqual(t, http.StatusOK, resp.StatusCode())
  122. logResponse(t, resp)
  123. }
  124. func TestPostJSONBytesIoReader(t *testing.T) {
  125. ts := createPostServer(t)
  126. defer ts.Close()
  127. c := dc()
  128. c.SetHeader(hdrContentTypeKey, jsonContentType)
  129. bodyBytes := []byte(`{"username":"testuser", "password":"testpass"}`)
  130. resp, err := c.R().
  131. SetBody(bytes.NewReader(bodyBytes)).
  132. Post(ts.URL + "/login")
  133. assertError(t, err)
  134. assertEqual(t, http.StatusOK, resp.StatusCode())
  135. logResponse(t, resp)
  136. }
  137. func TestPostJSONStructSuccess(t *testing.T) {
  138. ts := createPostServer(t)
  139. defer ts.Close()
  140. user := &User{Username: "testuser", Password: "testpass"}
  141. c := dc().SetJSONEscapeHTML(false)
  142. resp, err := c.R().
  143. SetHeader(hdrContentTypeKey, jsonContentType).
  144. SetBody(user).
  145. SetResult(&AuthSuccess{}).
  146. Post(ts.URL + "/login")
  147. assertError(t, err)
  148. assertEqual(t, http.StatusOK, resp.StatusCode())
  149. t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
  150. logResponse(t, resp)
  151. }
  152. func TestPostJSONRPCStructSuccess(t *testing.T) {
  153. ts := createPostServer(t)
  154. defer ts.Close()
  155. user := &User{Username: "testuser", Password: "testpass"}
  156. c := dc().SetJSONEscapeHTML(false)
  157. resp, err := c.R().
  158. SetHeader(hdrContentTypeKey, "application/json-rpc").
  159. SetBody(user).
  160. SetResult(&AuthSuccess{}).
  161. SetQueryParam("ct", "rpc").
  162. Post(ts.URL + "/login")
  163. assertError(t, err)
  164. assertEqual(t, http.StatusOK, resp.StatusCode())
  165. t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
  166. logResponse(t, resp)
  167. }
  168. func TestPostJSONStructInvalidLogin(t *testing.T) {
  169. ts := createPostServer(t)
  170. defer ts.Close()
  171. c := dc()
  172. c.SetDebug(false)
  173. resp, err := c.R().
  174. SetHeader(hdrContentTypeKey, jsonContentType).
  175. SetBody(User{Username: "testuser", Password: "testpass1"}).
  176. SetError(AuthError{}).
  177. SetJSONEscapeHTML(false).
  178. Post(ts.URL + "/login")
  179. assertError(t, err)
  180. assertEqual(t, http.StatusUnauthorized, resp.StatusCode())
  181. authError := resp.Error().(*AuthError)
  182. assertEqual(t, "unauthorized", authError.ID)
  183. assertEqual(t, "Invalid credentials", authError.Message)
  184. t.Logf("Result Error: %q", resp.Error().(*AuthError))
  185. logResponse(t, resp)
  186. }
  187. func TestPostJSONErrorRFC7807(t *testing.T) {
  188. ts := createPostServer(t)
  189. defer ts.Close()
  190. c := dc()
  191. resp, err := c.R().
  192. SetHeader(hdrContentTypeKey, jsonContentType).
  193. SetBody(User{Username: "testuser", Password: "testpass1"}).
  194. SetError(AuthError{}).
  195. Post(ts.URL + "/login?ct=problem")
  196. assertError(t, err)
  197. assertEqual(t, http.StatusUnauthorized, resp.StatusCode())
  198. authError := resp.Error().(*AuthError)
  199. assertEqual(t, "unauthorized", authError.ID)
  200. assertEqual(t, "Invalid credentials", authError.Message)
  201. t.Logf("Result Error: %q", resp.Error().(*AuthError))
  202. logResponse(t, resp)
  203. }
  204. func TestPostJSONMapSuccess(t *testing.T) {
  205. ts := createPostServer(t)
  206. defer ts.Close()
  207. c := dc()
  208. c.SetDebug(false)
  209. resp, err := c.R().
  210. SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
  211. SetResult(AuthSuccess{}).
  212. Post(ts.URL + "/login")
  213. assertError(t, err)
  214. assertEqual(t, http.StatusOK, resp.StatusCode())
  215. t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
  216. logResponse(t, resp)
  217. }
  218. func TestPostJSONMapInvalidResponseJson(t *testing.T) {
  219. ts := createPostServer(t)
  220. defer ts.Close()
  221. resp, err := dclr().
  222. SetBody(map[string]interface{}{"username": "testuser", "password": "invalidjson"}).
  223. SetResult(&AuthSuccess{}).
  224. Post(ts.URL + "/login")
  225. assertEqual(t, "invalid character '}' looking for beginning of object key string", err.Error())
  226. assertEqual(t, http.StatusOK, resp.StatusCode())
  227. authSuccess := resp.Result().(*AuthSuccess)
  228. assertEqual(t, "", authSuccess.ID)
  229. assertEqual(t, "", authSuccess.Message)
  230. t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
  231. logResponse(t, resp)
  232. }
  233. func TestPostXMLStringSuccess(t *testing.T) {
  234. ts := createPostServer(t)
  235. defer ts.Close()
  236. c := dc()
  237. c.SetDebug(false)
  238. resp, err := c.R().
  239. SetHeader(hdrContentTypeKey, "application/xml").
  240. SetBody(`<?xml version="1.0" encoding="UTF-8"?><User><Username>testuser</Username><Password>testpass</Password></User>`).
  241. SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
  242. Post(ts.URL + "/login")
  243. assertError(t, err)
  244. assertEqual(t, http.StatusOK, resp.StatusCode())
  245. logResponse(t, resp)
  246. }
  247. func TestPostXMLStringError(t *testing.T) {
  248. ts := createPostServer(t)
  249. defer ts.Close()
  250. resp, err := dclr().
  251. SetHeader(hdrContentTypeKey, "application/xml").
  252. SetBody(`<?xml version="1.0" encoding="UTF-8"?><User><Username>testuser</Username>testpass</Password></User>`).
  253. Post(ts.URL + "/login")
  254. assertError(t, err)
  255. assertEqual(t, http.StatusBadRequest, resp.StatusCode())
  256. assertEqual(t, `<?xml version="1.0" encoding="UTF-8"?><AuthError><Id>bad_request</Id><Message>Unable to read user info</Message></AuthError>`, resp.String())
  257. logResponse(t, resp)
  258. }
  259. func TestPostXMLBytesSuccess(t *testing.T) {
  260. ts := createPostServer(t)
  261. defer ts.Close()
  262. c := dc()
  263. c.SetDebug(false)
  264. resp, err := c.R().
  265. SetHeader(hdrContentTypeKey, "application/xml").
  266. SetBody([]byte(`<?xml version="1.0" encoding="UTF-8"?><User><Username>testuser</Username><Password>testpass</Password></User>`)).
  267. SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
  268. SetContentLength(true).
  269. Post(ts.URL + "/login")
  270. assertError(t, err)
  271. assertEqual(t, http.StatusOK, resp.StatusCode())
  272. logResponse(t, resp)
  273. }
  274. func TestPostXMLStructSuccess(t *testing.T) {
  275. ts := createPostServer(t)
  276. defer ts.Close()
  277. resp, err := dclr().
  278. SetHeader(hdrContentTypeKey, "application/xml").
  279. SetBody(User{Username: "testuser", Password: "testpass"}).
  280. SetContentLength(true).
  281. SetResult(&AuthSuccess{}).
  282. Post(ts.URL + "/login")
  283. assertError(t, err)
  284. assertEqual(t, http.StatusOK, resp.StatusCode())
  285. t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
  286. logResponse(t, resp)
  287. }
  288. func TestPostXMLStructInvalidLogin(t *testing.T) {
  289. ts := createPostServer(t)
  290. defer ts.Close()
  291. c := dc()
  292. c.SetError(&AuthError{})
  293. resp, err := c.R().
  294. SetHeader(hdrContentTypeKey, "application/xml").
  295. SetBody(User{Username: "testuser", Password: "testpass1"}).
  296. Post(ts.URL + "/login")
  297. assertError(t, err)
  298. assertEqual(t, http.StatusUnauthorized, resp.StatusCode())
  299. assertEqual(t, resp.Header().Get("Www-Authenticate"), "Protected Realm")
  300. t.Logf("Result Error: %q", resp.Error().(*AuthError))
  301. logResponse(t, resp)
  302. }
  303. func TestPostXMLStructInvalidResponseXml(t *testing.T) {
  304. ts := createPostServer(t)
  305. defer ts.Close()
  306. resp, err := dclr().
  307. SetHeader(hdrContentTypeKey, "application/xml").
  308. SetBody(User{Username: "testuser", Password: "invalidxml"}).
  309. SetResult(&AuthSuccess{}).
  310. Post(ts.URL + "/login")
  311. assertEqual(t, "XML syntax error on line 1: element <Message> closed by </AuthSuccess>", err.Error())
  312. assertEqual(t, http.StatusOK, resp.StatusCode())
  313. t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
  314. logResponse(t, resp)
  315. }
  316. func TestPostXMLMapNotSupported(t *testing.T) {
  317. ts := createPostServer(t)
  318. defer ts.Close()
  319. _, err := dclr().
  320. SetHeader(hdrContentTypeKey, "application/xml").
  321. SetBody(map[string]interface{}{"Username": "testuser", "Password": "testpass"}).
  322. Post(ts.URL + "/login")
  323. assertEqual(t, "unsupported 'Body' type/value", err.Error())
  324. }
  325. func TestRequestBasicAuth(t *testing.T) {
  326. ts := createAuthServer(t)
  327. defer ts.Close()
  328. c := dc()
  329. c.SetHostURL(ts.URL).
  330. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
  331. resp, err := c.R().
  332. SetBasicAuth("myuser", "basicauth").
  333. SetResult(&AuthSuccess{}).
  334. Post("/login")
  335. assertError(t, err)
  336. assertEqual(t, http.StatusOK, resp.StatusCode())
  337. t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
  338. logResponse(t, resp)
  339. }
  340. func TestRequestBasicAuthFail(t *testing.T) {
  341. ts := createAuthServer(t)
  342. defer ts.Close()
  343. c := dc()
  344. c.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
  345. SetError(AuthError{})
  346. resp, err := c.R().
  347. SetBasicAuth("myuser", "basicauth1").
  348. Post(ts.URL + "/login")
  349. assertError(t, err)
  350. assertEqual(t, http.StatusUnauthorized, resp.StatusCode())
  351. t.Logf("Result Error: %q", resp.Error().(*AuthError))
  352. logResponse(t, resp)
  353. }
  354. func TestRequestAuthToken(t *testing.T) {
  355. ts := createAuthServer(t)
  356. defer ts.Close()
  357. c := dc()
  358. c.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
  359. SetAuthToken("004DDB79-6801-4587-B976-F093E6AC44FF")
  360. resp, err := c.R().
  361. SetAuthToken("004DDB79-6801-4587-B976-F093E6AC44FF-Request").
  362. Get(ts.URL + "/profile")
  363. assertError(t, err)
  364. assertEqual(t, http.StatusOK, resp.StatusCode())
  365. }
  366. func TestFormData(t *testing.T) {
  367. ts := createFormPostServer(t)
  368. defer ts.Close()
  369. c := dc()
  370. c.SetFormData(map[string]string{"zip_code": "00000", "city": "Los Angeles"}).
  371. SetContentLength(true).
  372. SetDebug(true).
  373. SetLogger(ioutil.Discard)
  374. resp, err := c.R().
  375. SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M", "zip_code": "00001"}).
  376. SetBasicAuth("myuser", "mypass").
  377. Post(ts.URL + "/profile")
  378. assertError(t, err)
  379. assertEqual(t, http.StatusOK, resp.StatusCode())
  380. assertEqual(t, "Success", resp.String())
  381. }
  382. func TestMultiValueFormData(t *testing.T) {
  383. ts := createFormPostServer(t)
  384. defer ts.Close()
  385. v := url.Values{
  386. "search_criteria": []string{"book", "glass", "pencil"},
  387. }
  388. c := dc()
  389. c.SetContentLength(true).
  390. SetDebug(true).
  391. SetLogger(ioutil.Discard)
  392. resp, err := c.R().
  393. SetMultiValueFormData(v).
  394. Post(ts.URL + "/search")
  395. assertError(t, err)
  396. assertEqual(t, http.StatusOK, resp.StatusCode())
  397. assertEqual(t, "Success", resp.String())
  398. }
  399. func TestFormDataDisableWarn(t *testing.T) {
  400. ts := createFormPostServer(t)
  401. defer ts.Close()
  402. c := dc()
  403. c.SetFormData(map[string]string{"zip_code": "00000", "city": "Los Angeles"}).
  404. SetContentLength(true).
  405. SetDebug(true).
  406. SetLogger(ioutil.Discard).
  407. SetDisableWarn(true)
  408. resp, err := c.R().
  409. SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M", "zip_code": "00001"}).
  410. SetBasicAuth("myuser", "mypass").
  411. Post(ts.URL + "/profile")
  412. assertError(t, err)
  413. assertEqual(t, http.StatusOK, resp.StatusCode())
  414. assertEqual(t, "Success", resp.String())
  415. }
  416. func TestMultiPartUploadFile(t *testing.T) {
  417. ts := createFormPostServer(t)
  418. defer ts.Close()
  419. defer cleanupFiles(".testdata/upload")
  420. basePath := getTestDataPath()
  421. c := dc()
  422. c.SetFormData(map[string]string{"zip_code": "00001", "city": "Los Angeles"})
  423. resp, err := c.R().
  424. SetFile("profile_img", filepath.Join(basePath, "test-img.png")).
  425. SetContentLength(true).
  426. Post(ts.URL + "/upload")
  427. assertError(t, err)
  428. assertEqual(t, http.StatusOK, resp.StatusCode())
  429. }
  430. func TestMultiPartUploadFileError(t *testing.T) {
  431. ts := createFormPostServer(t)
  432. defer ts.Close()
  433. defer cleanupFiles(".testdata/upload")
  434. basePath := getTestDataPath()
  435. c := dc()
  436. c.SetFormData(map[string]string{"zip_code": "00001", "city": "Los Angeles"})
  437. resp, err := c.R().
  438. SetFile("profile_img", filepath.Join(basePath, "test-img-not-exists.png")).
  439. Post(ts.URL + "/upload")
  440. if err == nil {
  441. t.Errorf("Expected [%v], got [%v]", nil, err)
  442. }
  443. if resp != nil {
  444. t.Errorf("Expected [%v], got [%v]", nil, resp)
  445. }
  446. }
  447. func TestMultiPartUploadFiles(t *testing.T) {
  448. ts := createFormPostServer(t)
  449. defer ts.Close()
  450. defer cleanupFiles(".testdata/upload")
  451. basePath := getTestDataPath()
  452. resp, err := dclr().
  453. SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M"}).
  454. SetFiles(map[string]string{"profile_img": filepath.Join(basePath, "test-img.png"), "notes": filepath.Join(basePath, "text-file.txt")}).
  455. Post(ts.URL + "/upload")
  456. responseStr := resp.String()
  457. assertError(t, err)
  458. assertEqual(t, http.StatusOK, resp.StatusCode())
  459. assertEqual(t, true, strings.Contains(responseStr, "test-img.png"))
  460. assertEqual(t, true, strings.Contains(responseStr, "text-file.txt"))
  461. }
  462. func TestMultiPartIoReaderFiles(t *testing.T) {
  463. ts := createFormPostServer(t)
  464. defer ts.Close()
  465. defer cleanupFiles(".testdata/upload")
  466. basePath := getTestDataPath()
  467. profileImgBytes, _ := ioutil.ReadFile(filepath.Join(basePath, "test-img.png"))
  468. notesBytes, _ := ioutil.ReadFile(filepath.Join(basePath, "text-file.txt"))
  469. // Just info values
  470. file := File{
  471. Name: "test_file_name.jpg",
  472. ParamName: "test_param",
  473. Reader: bytes.NewBuffer([]byte("test bytes")),
  474. }
  475. t.Logf("File Info: %v", file.String())
  476. resp, err := dclr().
  477. SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M"}).
  478. SetFileReader("profile_img", "test-img.png", bytes.NewReader(profileImgBytes)).
  479. SetFileReader("notes", "text-file.txt", bytes.NewReader(notesBytes)).
  480. Post(ts.URL + "/upload")
  481. responseStr := resp.String()
  482. assertError(t, err)
  483. assertEqual(t, http.StatusOK, resp.StatusCode())
  484. assertEqual(t, true, strings.Contains(responseStr, "test-img.png"))
  485. assertEqual(t, true, strings.Contains(responseStr, "text-file.txt"))
  486. }
  487. func TestMultiPartUploadFileNotOnGetOrDelete(t *testing.T) {
  488. ts := createFormPostServer(t)
  489. defer ts.Close()
  490. defer cleanupFiles(".testdata/upload")
  491. basePath := getTestDataPath()
  492. _, err := dclr().
  493. SetFile("profile_img", filepath.Join(basePath, "test-img.png")).
  494. Get(ts.URL + "/upload")
  495. assertEqual(t, "multipart content is not allowed in HTTP verb [GET]", err.Error())
  496. _, err = dclr().
  497. SetFile("profile_img", filepath.Join(basePath, "test-img.png")).
  498. Delete(ts.URL + "/upload")
  499. assertEqual(t, "multipart content is not allowed in HTTP verb [DELETE]", err.Error())
  500. }
  501. func TestMultiPartMultipartField(t *testing.T) {
  502. ts := createFormPostServer(t)
  503. defer ts.Close()
  504. defer cleanupFiles(".testdata/upload")
  505. jsonBytes := []byte(`{"input": {"name": "Uploaded document", "_filename" : ["file.txt"]}}`)
  506. resp, err := dclr().
  507. SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M"}).
  508. SetMultipartField("uploadManifest", "upload-file.json", "application/json", bytes.NewReader(jsonBytes)).
  509. Post(ts.URL + "/upload")
  510. responseStr := resp.String()
  511. assertError(t, err)
  512. assertEqual(t, http.StatusOK, resp.StatusCode())
  513. assertEqual(t, true, strings.Contains(responseStr, "upload-file.json"))
  514. }
  515. func TestMultiPartMultipartFields(t *testing.T) {
  516. ts := createFormPostServer(t)
  517. defer ts.Close()
  518. defer cleanupFiles(".testdata/upload")
  519. jsonStr1 := `{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`
  520. jsonStr2 := `{"input": {"name": "Uploaded document 2", "_filename" : ["file2.txt"]}}`
  521. fields := []*MultipartField{
  522. &MultipartField{
  523. Param: "uploadManifest1",
  524. FileName: "upload-file-1.json",
  525. ContentType: "application/json",
  526. Reader: strings.NewReader(jsonStr1),
  527. },
  528. &MultipartField{
  529. Param: "uploadManifest2",
  530. FileName: "upload-file-2.json",
  531. ContentType: "application/json",
  532. Reader: strings.NewReader(jsonStr2),
  533. },
  534. }
  535. resp, err := dclr().
  536. SetFormData(map[string]string{"first_name": "Jeevanandam", "last_name": "M"}).
  537. SetMultipartFields(fields...).
  538. Post(ts.URL + "/upload")
  539. responseStr := resp.String()
  540. assertError(t, err)
  541. assertEqual(t, http.StatusOK, resp.StatusCode())
  542. assertEqual(t, true, strings.Contains(responseStr, "upload-file-1.json"))
  543. assertEqual(t, true, strings.Contains(responseStr, "upload-file-2.json"))
  544. }
  545. func TestGetWithCookie(t *testing.T) {
  546. ts := createGetServer(t)
  547. defer ts.Close()
  548. c := dc()
  549. c.SetHostURL(ts.URL)
  550. c.SetCookie(&http.Cookie{
  551. Name: "go-resty-1",
  552. Value: "This is cookie 1 value",
  553. Path: "/",
  554. Domain: "localhost",
  555. MaxAge: 36000,
  556. HttpOnly: true,
  557. Secure: false,
  558. })
  559. resp, err := c.R().Get("mypage2")
  560. assertError(t, err)
  561. assertEqual(t, http.StatusOK, resp.StatusCode())
  562. assertEqual(t, "TestGet: text response from mypage2", resp.String())
  563. logResponse(t, resp)
  564. }
  565. func TestGetWithCookies(t *testing.T) {
  566. ts := createGetServer(t)
  567. defer ts.Close()
  568. var cookies []*http.Cookie
  569. cookies = append(cookies, &http.Cookie{
  570. Name: "go-resty-1",
  571. Value: "This is cookie 1 value",
  572. Path: "/",
  573. Domain: "sample.com",
  574. MaxAge: 36000,
  575. HttpOnly: true,
  576. Secure: false,
  577. })
  578. cookies = append(cookies, &http.Cookie{
  579. Name: "go-resty-2",
  580. Value: "This is cookie 2 value",
  581. Path: "/",
  582. Domain: "sample.com",
  583. MaxAge: 36000,
  584. HttpOnly: true,
  585. Secure: false,
  586. })
  587. c := dc()
  588. c.SetHostURL(ts.URL).
  589. SetCookies(cookies)
  590. resp, err := c.R().Get("mypage2")
  591. assertError(t, err)
  592. assertEqual(t, http.StatusOK, resp.StatusCode())
  593. assertEqual(t, "TestGet: text response from mypage2", resp.String())
  594. logResponse(t, resp)
  595. }
  596. func TestPutPlainString(t *testing.T) {
  597. ts := createGenServer(t)
  598. defer ts.Close()
  599. resp, err := R().
  600. SetBody("This is plain text body to server").
  601. Put(ts.URL + "/plaintext")
  602. assertError(t, err)
  603. assertEqual(t, http.StatusOK, resp.StatusCode())
  604. assertEqual(t, "TestPut: plain text response", resp.String())
  605. }
  606. func TestPutJSONString(t *testing.T) {
  607. ts := createGenServer(t)
  608. defer ts.Close()
  609. DefaultClient.OnBeforeRequest(func(c *Client, r *Request) error {
  610. r.SetHeader("X-Custom-Request-Middleware", "OnBeforeRequest middleware")
  611. return nil
  612. })
  613. DefaultClient.OnBeforeRequest(func(c *Client, r *Request) error {
  614. c.SetContentLength(true)
  615. r.SetHeader("X-ContentLength", "OnBeforeRequest ContentLength set")
  616. return nil
  617. })
  618. DefaultClient.SetDebug(true).SetLogger(ioutil.Discard)
  619. resp, err := R().
  620. SetHeaders(map[string]string{hdrContentTypeKey: jsonContentType, hdrAcceptKey: jsonContentType}).
  621. SetBody(`{"content":"json content sending to server"}`).
  622. Put(ts.URL + "/json")
  623. assertError(t, err)
  624. assertEqual(t, http.StatusOK, resp.StatusCode())
  625. assertEqual(t, `{"response":"json response"}`, resp.String())
  626. }
  627. func TestPutXMLString(t *testing.T) {
  628. ts := createGenServer(t)
  629. defer ts.Close()
  630. resp, err := R().
  631. SetHeaders(map[string]string{hdrContentTypeKey: "application/xml", hdrAcceptKey: "application/xml"}).
  632. SetBody(`<?xml version="1.0" encoding="UTF-8"?><Request>XML Content sending to server</Request>`).
  633. Put(ts.URL + "/xml")
  634. assertError(t, err)
  635. assertEqual(t, http.StatusOK, resp.StatusCode())
  636. assertEqual(t, `<?xml version="1.0" encoding="UTF-8"?><Response>XML response</Response>`, resp.String())
  637. }
  638. func TestOnBeforeMiddleware(t *testing.T) {
  639. ts := createGenServer(t)
  640. defer ts.Close()
  641. c := dc()
  642. c.OnBeforeRequest(func(c *Client, r *Request) error {
  643. r.SetHeader("X-Custom-Request-Middleware", "OnBeforeRequest middleware")
  644. return nil
  645. })
  646. c.OnBeforeRequest(func(c *Client, r *Request) error {
  647. c.SetContentLength(true)
  648. r.SetHeader("X-ContentLength", "OnBeforeRequest ContentLength set")
  649. return nil
  650. })
  651. resp, err := c.R().
  652. SetBody("OnBeforeRequest: This is plain text body to server").
  653. Put(ts.URL + "/plaintext")
  654. assertError(t, err)
  655. assertEqual(t, http.StatusOK, resp.StatusCode())
  656. assertEqual(t, "TestPut: plain text response", resp.String())
  657. }
  658. func TestNoAutoRedirect(t *testing.T) {
  659. ts := createRedirectServer(t)
  660. defer ts.Close()
  661. _, err := R().Get(ts.URL + "/redirect-1")
  662. assertEqual(t, "Get /redirect-2: auto redirect is disabled", err.Error())
  663. }
  664. func TestHTTPAutoRedirectUpTo10(t *testing.T) {
  665. ts := createRedirectServer(t)
  666. defer ts.Close()
  667. c := dc()
  668. c.SetHTTPMode()
  669. _, err := c.R().Get(ts.URL + "/redirect-1")
  670. assertEqual(t, "Get /redirect-11: stopped after 10 redirects", err.Error())
  671. }
  672. func TestHostCheckRedirectPolicy(t *testing.T) {
  673. ts := createRedirectServer(t)
  674. defer ts.Close()
  675. c := dc().
  676. SetRedirectPolicy(DomainCheckRedirectPolicy("127.0.0.1"))
  677. _, err := c.R().Get(ts.URL + "/redirect-host-check-1")
  678. assertNotNil(t, err)
  679. assertEqual(t, true, strings.Contains(err.Error(), "redirect is not allowed as per DomainCheckRedirectPolicy"))
  680. }
  681. func TestHeadMethod(t *testing.T) {
  682. ts := createGetServer(t)
  683. defer ts.Close()
  684. resp, err := dclr().Head(ts.URL + "/")
  685. assertError(t, err)
  686. assertEqual(t, http.StatusOK, resp.StatusCode())
  687. }
  688. func TestOptionsMethod(t *testing.T) {
  689. ts := createGenServer(t)
  690. defer ts.Close()
  691. resp, err := dclr().Options(ts.URL + "/options")
  692. assertError(t, err)
  693. assertEqual(t, http.StatusOK, resp.StatusCode())
  694. assertEqual(t, resp.Header().Get("Access-Control-Expose-Headers"), "x-go-resty-id")
  695. }
  696. func TestPatchMethod(t *testing.T) {
  697. ts := createGenServer(t)
  698. defer ts.Close()
  699. resp, err := dclr().Patch(ts.URL + "/patch")
  700. assertError(t, err)
  701. assertEqual(t, http.StatusOK, resp.StatusCode())
  702. resp.body = nil
  703. assertEqual(t, "", resp.String())
  704. }
  705. func TestRawFileUploadByBody(t *testing.T) {
  706. ts := createFormPostServer(t)
  707. defer ts.Close()
  708. file, err := os.Open(filepath.Join(getTestDataPath(), "test-img.png"))
  709. assertNil(t, err)
  710. fileBytes, err := ioutil.ReadAll(file)
  711. assertNil(t, err)
  712. resp, err := dclr().
  713. SetBody(fileBytes).
  714. SetContentLength(true).
  715. SetAuthToken("004DDB79-6801-4587-B976-F093E6AC44FF").
  716. Put(ts.URL + "/raw-upload")
  717. assertError(t, err)
  718. assertEqual(t, http.StatusOK, resp.StatusCode())
  719. assertEqual(t, "image/png", resp.Request.Header.Get(hdrContentTypeKey))
  720. }
  721. func TestProxySetting(t *testing.T) {
  722. c := dc()
  723. transport, err := c.getTransport()
  724. assertNil(t, err)
  725. assertEqual(t, false, c.IsProxySet())
  726. assertNil(t, transport.Proxy)
  727. c.SetProxy("http://sampleproxy:8888")
  728. assertEqual(t, true, c.IsProxySet())
  729. assertNotNil(t, transport.Proxy)
  730. c.SetProxy("//not.a.user@%66%6f%6f.com:8888")
  731. assertEqual(t, false, c.IsProxySet())
  732. assertNil(t, transport.Proxy)
  733. SetProxy("http://sampleproxy:8888")
  734. assertEqual(t, true, IsProxySet())
  735. RemoveProxy()
  736. assertNil(t, DefaultClient.proxyURL)
  737. assertNil(t, transport.Proxy)
  738. }
  739. func TestGetClient(t *testing.T) {
  740. client := GetClient()
  741. custom := New()
  742. customClient := custom.GetClient()
  743. assertNotNil(t, client)
  744. assertNotNil(t, customClient)
  745. assertNotEqual(t, client, http.DefaultClient)
  746. assertNotEqual(t, customClient, http.DefaultClient)
  747. assertNotEqual(t, client, customClient)
  748. assertEqual(t, DefaultClient.httpClient, client)
  749. }
  750. func TestIncorrectURL(t *testing.T) {
  751. _, err := R().Get("//not.a.user@%66%6f%6f.com/just/a/path/also")
  752. assertEqual(t, true, strings.Contains(err.Error(), "parse //not.a.user@%66%6f%6f.com/just/a/path/also"))
  753. c := dc()
  754. c.SetHostURL("//not.a.user@%66%6f%6f.com")
  755. _, err1 := c.R().Get("/just/a/path/also")
  756. assertEqual(t, true, strings.Contains(err1.Error(), "parse //not.a.user@%66%6f%6f.com/just/a/path/also"))
  757. }
  758. func TestDetectContentTypeForPointer(t *testing.T) {
  759. ts := createPostServer(t)
  760. defer ts.Close()
  761. user := &User{Username: "testuser", Password: "testpass"}
  762. resp, err := dclr().
  763. SetBody(user).
  764. SetResult(AuthSuccess{}).
  765. Post(ts.URL + "/login")
  766. assertError(t, err)
  767. assertEqual(t, http.StatusOK, resp.StatusCode())
  768. t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
  769. logResponse(t, resp)
  770. }
  771. type ExampleUser struct {
  772. FirstName string `json:"frist_name"`
  773. LastName string `json:"last_name"`
  774. ZipCode string `json:"zip_code"`
  775. }
  776. func TestDetectContentTypeForPointerWithSlice(t *testing.T) {
  777. ts := createPostServer(t)
  778. defer ts.Close()
  779. users := &[]ExampleUser{
  780. {FirstName: "firstname1", LastName: "lastname1", ZipCode: "10001"},
  781. {FirstName: "firstname2", LastName: "lastname3", ZipCode: "10002"},
  782. {FirstName: "firstname3", LastName: "lastname3", ZipCode: "10003"},
  783. }
  784. resp, err := dclr().
  785. SetBody(users).
  786. Post(ts.URL + "/users")
  787. assertError(t, err)
  788. assertEqual(t, http.StatusAccepted, resp.StatusCode())
  789. t.Logf("Result Success: %q", resp)
  790. logResponse(t, resp)
  791. }
  792. func TestDetectContentTypeForPointerWithSliceMap(t *testing.T) {
  793. ts := createPostServer(t)
  794. defer ts.Close()
  795. usersmap := map[string]interface{}{
  796. "user1": ExampleUser{FirstName: "firstname1", LastName: "lastname1", ZipCode: "10001"},
  797. "user2": &ExampleUser{FirstName: "firstname2", LastName: "lastname3", ZipCode: "10002"},
  798. "user3": ExampleUser{FirstName: "firstname3", LastName: "lastname3", ZipCode: "10003"},
  799. }
  800. var users []map[string]interface{}
  801. users = append(users, usersmap)
  802. resp, err := dclr().
  803. SetBody(&users).
  804. Post(ts.URL + "/usersmap")
  805. assertError(t, err)
  806. assertEqual(t, http.StatusAccepted, resp.StatusCode())
  807. t.Logf("Result Success: %q", resp)
  808. logResponse(t, resp)
  809. }
  810. func TestDetectContentTypeForSlice(t *testing.T) {
  811. ts := createPostServer(t)
  812. defer ts.Close()
  813. users := []ExampleUser{
  814. {FirstName: "firstname1", LastName: "lastname1", ZipCode: "10001"},
  815. {FirstName: "firstname2", LastName: "lastname3", ZipCode: "10002"},
  816. {FirstName: "firstname3", LastName: "lastname3", ZipCode: "10003"},
  817. }
  818. resp, err := dclr().
  819. SetBody(users).
  820. Post(ts.URL + "/users")
  821. assertError(t, err)
  822. assertEqual(t, http.StatusAccepted, resp.StatusCode())
  823. t.Logf("Result Success: %q", resp)
  824. logResponse(t, resp)
  825. }
  826. func TestMultiParamsQueryString(t *testing.T) {
  827. ts1 := createGetServer(t)
  828. defer ts1.Close()
  829. client := dc()
  830. req1 := client.R()
  831. client.SetQueryParam("status", "open")
  832. _, _ = req1.SetQueryParam("status", "pending").
  833. Get(ts1.URL)
  834. assertEqual(t, true, strings.Contains(req1.URL, "status=pending"))
  835. // pending overrides open
  836. assertEqual(t, false, strings.Contains(req1.URL, "status=open"))
  837. _, _ = req1.SetQueryParam("status", "approved").
  838. Get(ts1.URL)
  839. assertEqual(t, true, strings.Contains(req1.URL, "status=approved"))
  840. // approved overrides pending
  841. assertEqual(t, false, strings.Contains(req1.URL, "status=pending"))
  842. ts2 := createGetServer(t)
  843. defer ts2.Close()
  844. req2 := client.R()
  845. v := url.Values{
  846. "status": []string{"pending", "approved", "reject"},
  847. }
  848. _, _ = req2.SetMultiValueQueryParams(v).Get(ts2.URL)
  849. assertEqual(t, true, strings.Contains(req2.URL, "status=pending"))
  850. assertEqual(t, true, strings.Contains(req2.URL, "status=approved"))
  851. assertEqual(t, true, strings.Contains(req2.URL, "status=reject"))
  852. // because it's removed by key
  853. assertEqual(t, false, strings.Contains(req2.URL, "status=open"))
  854. }
  855. func TestSetQueryStringTypical(t *testing.T) {
  856. ts := createGetServer(t)
  857. defer ts.Close()
  858. resp, err := dclr().
  859. SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more").
  860. Get(ts.URL)
  861. assertError(t, err)
  862. assertEqual(t, http.StatusOK, resp.StatusCode())
  863. assertEqual(t, "200 OK", resp.Status())
  864. assertEqual(t, "TestGet: text response", resp.String())
  865. resp, err = dclr().
  866. SetQueryString("&%%amp;").
  867. Get(ts.URL)
  868. assertError(t, err)
  869. assertEqual(t, http.StatusOK, resp.StatusCode())
  870. assertEqual(t, "200 OK", resp.Status())
  871. assertEqual(t, "TestGet: text response", resp.String())
  872. }
  873. func TestOutputFileWithBaseDirAndRelativePath(t *testing.T) {
  874. ts := createGetServer(t)
  875. defer ts.Close()
  876. defer cleanupFiles(".testdata/dir-sample")
  877. DefaultClient = dc()
  878. SetRedirectPolicy(FlexibleRedirectPolicy(10))
  879. SetOutputDirectory(filepath.Join(getTestDataPath(), "dir-sample"))
  880. SetDebug(true)
  881. SetLogger(ioutil.Discard)
  882. resp, err := R().
  883. SetOutput("go-resty/test-img-success.png").
  884. Get(ts.URL + "/my-image.png")
  885. assertError(t, err)
  886. assertEqual(t, true, resp.Size() != 0)
  887. }
  888. func TestOutputFileWithBaseDirError(t *testing.T) {
  889. c := dc().SetRedirectPolicy(FlexibleRedirectPolicy(10)).
  890. SetOutputDirectory(filepath.Join(getTestDataPath(), `go-resty\0`))
  891. _ = c
  892. }
  893. func TestOutputPathDirNotExists(t *testing.T) {
  894. ts := createGetServer(t)
  895. defer ts.Close()
  896. defer cleanupFiles(filepath.Join(".testdata", "not-exists-dir"))
  897. DefaultClient = dc()
  898. SetRedirectPolicy(FlexibleRedirectPolicy(10))
  899. SetOutputDirectory(filepath.Join(getTestDataPath(), "not-exists-dir"))
  900. resp, err := R().
  901. SetOutput("test-img-success.png").
  902. Get(ts.URL + "/my-image.png")
  903. assertError(t, err)
  904. assertEqual(t, true, resp.Size() != 0)
  905. }
  906. func TestOutputFileAbsPath(t *testing.T) {
  907. ts := createGetServer(t)
  908. defer ts.Close()
  909. defer cleanupFiles(filepath.Join(".testdata", "go-resty"))
  910. _, err := dcr().
  911. SetOutput(filepath.Join(getTestDataPath(), "go-resty", "test-img-success-2.png")).
  912. Get(ts.URL + "/my-image.png")
  913. assertError(t, err)
  914. }
  915. func TestContextInternal(t *testing.T) {
  916. ts := createGetServer(t)
  917. defer ts.Close()
  918. r := R().
  919. SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10))
  920. if r.isContextCancelledIfAvailable() {
  921. t.Error("isContextCancelledIfAvailable != false for vanilla R()")
  922. }
  923. r.addContextIfAvailable()
  924. resp, err := r.Get(ts.URL + "/")
  925. assertError(t, err)
  926. assertEqual(t, http.StatusOK, resp.StatusCode())
  927. }
  928. func TestSRV(t *testing.T) {
  929. c := dc().
  930. SetRedirectPolicy(FlexibleRedirectPolicy(20)).
  931. SetScheme("http")
  932. r := c.R().
  933. SetSRV(&SRVRecord{"xmpp-server", "google.com"})
  934. assertEqual(t, "xmpp-server", r.SRV.Service)
  935. assertEqual(t, "google.com", r.SRV.Domain)
  936. resp, err := r.Get("/")
  937. if err == nil {
  938. assertError(t, err)
  939. assertNotNil(t, resp)
  940. assertEqual(t, http.StatusOK, resp.StatusCode())
  941. }
  942. }
  943. func TestSRVInvalidService(t *testing.T) {
  944. _, err := R().
  945. SetSRV(&SRVRecord{"nonexistantservice", "sampledomain"}).
  946. Get("/")
  947. assertNotNil(t, err)
  948. assertType(t, net.DNSError{}, err)
  949. }
  950. func TestDeprecatedCodeCoverage(t *testing.T) {
  951. var user1 User
  952. err := Unmarshal("application/json",
  953. []byte(`{"username":"testuser", "password":"testpass"}`), &user1)
  954. assertError(t, err)
  955. assertEqual(t, "testuser", user1.Username)
  956. assertEqual(t, "testpass", user1.Password)
  957. var user2 User
  958. err = Unmarshal("application/xml",
  959. []byte(`<?xml version="1.0" encoding="UTF-8"?><User><Username>testuser</Username><Password>testpass</Password></User>`),
  960. &user2)
  961. assertError(t, err)
  962. assertEqual(t, "testuser", user1.Username)
  963. assertEqual(t, "testpass", user1.Password)
  964. }
  965. func TestRequestDoNotParseResponse(t *testing.T) {
  966. ts := createGetServer(t)
  967. defer ts.Close()
  968. resp, err := dc().R().
  969. SetDoNotParseResponse(true).
  970. SetQueryParam("request_no", strconv.FormatInt(time.Now().Unix(), 10)).
  971. Get(ts.URL + "/")
  972. assertError(t, err)
  973. buf := acquireBuffer()
  974. defer releaseBuffer(buf)
  975. _, _ = io.Copy(buf, resp.RawBody())
  976. assertEqual(t, "TestGet: text response", buf.String())
  977. _ = resp.RawBody().Close()
  978. // Manually setting RawResponse as nil
  979. resp, err = dc().R().
  980. SetDoNotParseResponse(true).
  981. Get(ts.URL + "/")
  982. assertError(t, err)
  983. resp.RawResponse = nil
  984. assertNil(t, resp.RawBody())
  985. // just set test part
  986. SetDoNotParseResponse(true)
  987. assertEqual(t, true, DefaultClient.notParseResponse)
  988. SetDoNotParseResponse(false)
  989. }
  990. type noCtTest struct {
  991. Response string `json:"response"`
  992. }
  993. func TestRequestExpectContentTypeTest(t *testing.T) {
  994. ts := createGenServer(t)
  995. defer ts.Close()
  996. c := dc()
  997. resp, err := c.R().
  998. SetResult(noCtTest{}).
  999. ExpectContentType("application/json").
  1000. Get(ts.URL + "/json-no-set")
  1001. assertError(t, err)
  1002. assertEqual(t, http.StatusOK, resp.StatusCode())
  1003. assertNotNil(t, resp.Result())
  1004. assertEqual(t, "json response no content type set", resp.Result().(*noCtTest).Response)
  1005. assertEqual(t, "", firstNonEmpty("", ""))
  1006. }
  1007. func TestGetPathParams(t *testing.T) {
  1008. ts := createGetServer(t)
  1009. defer ts.Close()
  1010. c := dc()
  1011. c.SetHostURL(ts.URL).
  1012. SetPathParams(map[string]string{
  1013. "userId": "sample@sample.com",
  1014. })
  1015. resp, err := c.R().SetPathParams(map[string]string{
  1016. "subAccountId": "100002",
  1017. }).
  1018. Get("/v1/users/{userId}/{subAccountId}/details")
  1019. assertError(t, err)
  1020. assertEqual(t, http.StatusOK, resp.StatusCode())
  1021. assertEqual(t, true, strings.Contains(resp.String(), "TestGetPathParams: text response"))
  1022. assertEqual(t, true, strings.Contains(resp.String(), "/v1/users/sample@sample.com/100002/details"))
  1023. logResponse(t, resp)
  1024. SetPathParams(map[string]string{
  1025. "userId": "sample@sample.com",
  1026. })
  1027. }
  1028. func TestReportMethodSupportsPayload(t *testing.T) {
  1029. ts := createGenServer(t)
  1030. defer ts.Close()
  1031. c := dc()
  1032. resp, err := c.R().
  1033. SetBody("body").
  1034. Execute("REPORT", ts.URL+"/report")
  1035. assertError(t, err)
  1036. assertEqual(t, http.StatusOK, resp.StatusCode())
  1037. }
  1038. func TestRequestQueryStringOrder(t *testing.T) {
  1039. ts := createGetServer(t)
  1040. defer ts.Close()
  1041. resp, err := New().R().
  1042. SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more").
  1043. Get(ts.URL + "/?UniqueId=ead1d0ed-XXX-XXX-XXX-abb7612b3146&Translate=false&tempauth=eyJ0eXAiOiJKV1QiLC...HZEhwVnJ1d0NSUGVLaUpSaVNLRG5scz0&ApiVersion=2.0")
  1044. assertError(t, err)
  1045. assertEqual(t, http.StatusOK, resp.StatusCode())
  1046. assertEqual(t, "200 OK", resp.Status())
  1047. assertNotNil(t, resp.Body())
  1048. assertEqual(t, "TestGet: text response", resp.String())
  1049. logResponse(t, resp)
  1050. }
  1051. func TestRequestOverridesClientAuthorizationHeader(t *testing.T) {
  1052. ts := createAuthServer(t)
  1053. defer ts.Close()
  1054. c := dc()
  1055. c.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
  1056. SetHeader("Authorization", "some token")
  1057. SetHostURL(ts.URL + "/")
  1058. resp, err := c.R().
  1059. SetHeader("Authorization", "Bearer 004DDB79-6801-4587-B976-F093E6AC44FF").
  1060. Get("/profile")
  1061. assertError(t, err)
  1062. assertEqual(t, http.StatusOK, resp.StatusCode())
  1063. }
  1064. func TestRequestFileUploadAsReader(t *testing.T) {
  1065. ts := createFilePostServer(t)
  1066. defer ts.Close()
  1067. file, _ := os.Open(filepath.Join(getTestDataPath(), "test-img.png"))
  1068. defer file.Close()
  1069. resp, err := dclr().
  1070. SetBody(file).
  1071. SetHeader("Content-Type", "image/png").
  1072. Post(ts.URL + "/upload")
  1073. assertError(t, err)
  1074. assertEqual(t, http.StatusOK, resp.StatusCode())
  1075. assertEqual(t, true, strings.Contains(resp.String(), "File Uploaded successfully"))
  1076. file, _ = os.Open(filepath.Join(getTestDataPath(), "test-img.png"))
  1077. defer file.Close()
  1078. resp, err = dclr().
  1079. SetBody(file).
  1080. SetHeader("Content-Type", "image/png").
  1081. SetContentLength(true).
  1082. Post(ts.URL + "/upload")
  1083. assertError(t, err)
  1084. assertEqual(t, http.StatusOK, resp.StatusCode())
  1085. assertEqual(t, true, strings.Contains(resp.String(), "File Uploaded successfully"))
  1086. }
  1087. func TestHostHeaderOverride(t *testing.T) {
  1088. ts := createGetServer(t)
  1089. defer ts.Close()
  1090. resp, err := R().
  1091. SetHeader("Host", "myhostname").
  1092. Get(ts.URL + "/host-header")
  1093. assertError(t, err)
  1094. assertEqual(t, http.StatusOK, resp.StatusCode())
  1095. assertEqual(t, "200 OK", resp.Status())
  1096. assertNotNil(t, resp.Body())
  1097. assertEqual(t, "myhostname", resp.String())
  1098. logResponse(t, resp)
  1099. }
  1100. func TestPathParamURLInput(t *testing.T) {
  1101. ts := createGetServer(t)
  1102. defer ts.Close()
  1103. c := dc().SetDebug(true).SetLogger(ioutil.Discard)
  1104. c.SetHostURL(ts.URL).
  1105. SetPathParams(map[string]string{
  1106. "userId": "sample@sample.com",
  1107. })
  1108. resp, err := c.R().
  1109. SetPathParams(map[string]string{
  1110. "subAccountId": "100002",
  1111. "website": "https://example.com",
  1112. }).Get("/v1/users/{userId}/{subAccountId}/{website}")
  1113. assertError(t, err)
  1114. assertEqual(t, http.StatusOK, resp.StatusCode())
  1115. assertEqual(t, true, strings.Contains(resp.String(), "TestPathParamURLInput: text response"))
  1116. assertEqual(t, true, strings.Contains(resp.String(), "/v1/users/sample@sample.com/100002/https:%2F%2Fexample.com"))
  1117. logResponse(t, resp)
  1118. }