response.go 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. package httpexpect
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "mime"
  9. "net/http"
  10. "reflect"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/ajg/form"
  16. "github.com/gorilla/websocket"
  17. )
  18. // Response provides methods to inspect attached http.Response object.
  19. type Response struct {
  20. noCopy noCopy
  21. config Config
  22. chain *chain
  23. httpResp *http.Response
  24. websocket *websocket.Conn
  25. rtt *time.Duration
  26. content []byte
  27. contentState contentState
  28. cookies []*http.Cookie
  29. }
  30. type contentState int
  31. const (
  32. contentPending contentState = iota
  33. contentRetreived
  34. contentFailed
  35. )
  36. // NewResponse returns a new Response instance.
  37. //
  38. // If reporter is nil, the function panics.
  39. // If response is nil, failure is reported.
  40. //
  41. // If rtt is given, it defines response round-trip time to be reported
  42. // by response.RoundTripTime().
  43. func NewResponse(
  44. reporter Reporter, response *http.Response, rtt ...time.Duration,
  45. ) *Response {
  46. config := Config{Reporter: reporter}
  47. config = config.withDefaults()
  48. return newResponse(responseOpts{
  49. config: config,
  50. chain: newChainWithConfig("Response()", config),
  51. httpResp: response,
  52. rtt: rtt,
  53. })
  54. }
  55. // NewResponse returns a new Response instance with config.
  56. //
  57. // Requirements for config are same as for WithConfig function.
  58. // If response is nil, failure is reported.
  59. //
  60. // If rtt is given, it defines response round-trip time to be reported
  61. // by response.RoundTripTime().
  62. func NewResponseC(
  63. config Config, response *http.Response, rtt ...time.Duration,
  64. ) *Response {
  65. config = config.withDefaults()
  66. return newResponse(responseOpts{
  67. config: config,
  68. chain: newChainWithConfig("Response()", config),
  69. httpResp: response,
  70. rtt: rtt,
  71. })
  72. }
  73. type responseOpts struct {
  74. config Config
  75. chain *chain
  76. httpResp *http.Response
  77. websocket *websocket.Conn
  78. rtt []time.Duration
  79. }
  80. func newResponse(opts responseOpts) *Response {
  81. opts.config.validate()
  82. r := &Response{
  83. config: opts.config,
  84. chain: opts.chain.clone(),
  85. contentState: contentPending,
  86. }
  87. opChain := r.chain.enter("")
  88. defer opChain.leave()
  89. if len(opts.rtt) > 1 {
  90. opChain.fail(AssertionFailure{
  91. Type: AssertUsage,
  92. Errors: []error{
  93. errors.New("unexpected multiple rtt arguments"),
  94. },
  95. })
  96. return r
  97. }
  98. if len(opts.rtt) > 0 {
  99. rttCopy := opts.rtt[0]
  100. r.rtt = &rttCopy
  101. }
  102. if opts.httpResp == nil {
  103. opChain.fail(AssertionFailure{
  104. Type: AssertNotNil,
  105. Actual: &AssertionValue{opts.httpResp},
  106. Errors: []error{
  107. errors.New("expected: non-nil response"),
  108. },
  109. })
  110. return r
  111. }
  112. r.httpResp = opts.httpResp
  113. if r.httpResp.Body != nil && r.httpResp.Body != http.NoBody {
  114. if _, ok := r.httpResp.Body.(*bodyWrapper); !ok {
  115. respCopy := *r.httpResp
  116. r.httpResp = &respCopy
  117. r.httpResp.Body = newBodyWrapper(r.httpResp.Body, nil)
  118. }
  119. }
  120. r.websocket = opts.websocket
  121. r.cookies = r.httpResp.Cookies()
  122. r.chain.setResponse(r)
  123. return r
  124. }
  125. func (r *Response) getContent(opChain *chain) ([]byte, bool) {
  126. switch r.contentState {
  127. case contentRetreived:
  128. return r.content, true
  129. case contentFailed:
  130. return nil, false
  131. case contentPending:
  132. break
  133. }
  134. resp := r.httpResp
  135. if resp.Body == nil || resp.Body == http.NoBody {
  136. return []byte{}, true
  137. }
  138. if bw, ok := resp.Body.(*bodyWrapper); ok {
  139. bw.Rewind()
  140. }
  141. content, err := ioutil.ReadAll(resp.Body)
  142. closeErr := resp.Body.Close()
  143. if err == nil {
  144. err = closeErr
  145. }
  146. if err != nil {
  147. opChain.fail(AssertionFailure{
  148. Type: AssertOperation,
  149. Errors: []error{
  150. errors.New("failed to read response body"),
  151. err,
  152. },
  153. })
  154. r.content = nil
  155. r.contentState = contentFailed
  156. return nil, false
  157. }
  158. r.content = content
  159. r.contentState = contentRetreived
  160. return r.content, true
  161. }
  162. // Raw returns underlying http.Response object.
  163. // This is the value originally passed to NewResponse.
  164. func (r *Response) Raw() *http.Response {
  165. return r.httpResp
  166. }
  167. // Alias is similar to Value.Alias.
  168. func (r *Response) Alias(name string) *Response {
  169. opChain := r.chain.enter("Alias(%q)", name)
  170. defer opChain.leave()
  171. r.chain.setAlias(name)
  172. return r
  173. }
  174. // RoundTripTime returns a new Duration instance with response round-trip time.
  175. //
  176. // The returned duration is the time interval starting just before request is
  177. // sent and ending right after response is received (handshake finished for
  178. // WebSocket request), retrieved from a monotonic clock source.
  179. //
  180. // Example:
  181. //
  182. // resp := NewResponse(t, response, time.Duration(10000000))
  183. // resp.RoundTripTime().Lt(10 * time.Millisecond)
  184. func (r *Response) RoundTripTime() *Duration {
  185. opChain := r.chain.enter("RoundTripTime()")
  186. defer opChain.leave()
  187. if opChain.failed() {
  188. return newDuration(opChain, nil)
  189. }
  190. return newDuration(opChain, r.rtt)
  191. }
  192. // Deprecated: use RoundTripTime instead.
  193. func (r *Response) Duration() *Number {
  194. opChain := r.chain.enter("Duration()")
  195. defer opChain.leave()
  196. if opChain.failed() {
  197. return newNumber(opChain, 0)
  198. }
  199. if r.rtt == nil {
  200. return newNumber(opChain, 0)
  201. }
  202. return newNumber(opChain, float64(*r.rtt))
  203. }
  204. // Status succeeds if response contains given status code.
  205. //
  206. // Example:
  207. //
  208. // resp := NewResponse(t, response)
  209. // resp.Status(http.StatusOK)
  210. func (r *Response) Status(status int) *Response {
  211. opChain := r.chain.enter("Status()")
  212. defer opChain.leave()
  213. if opChain.failed() {
  214. return r
  215. }
  216. r.checkEqual(opChain, "http status",
  217. statusCodeText(status), statusCodeText(r.httpResp.StatusCode))
  218. return r
  219. }
  220. // StatusRange is enum for response status ranges.
  221. type StatusRange int
  222. const (
  223. // Status1xx defines "Informational" status codes.
  224. Status1xx StatusRange = 100
  225. // Status2xx defines "Success" status codes.
  226. Status2xx StatusRange = 200
  227. // Status3xx defines "Redirection" status codes.
  228. Status3xx StatusRange = 300
  229. // Status4xx defines "Client Error" status codes.
  230. Status4xx StatusRange = 400
  231. // Status5xx defines "Server Error" status codes.
  232. Status5xx StatusRange = 500
  233. )
  234. // StatusRange succeeds if response status belongs to given range.
  235. //
  236. // Supported ranges:
  237. // - Status1xx - Informational
  238. // - Status2xx - Success
  239. // - Status3xx - Redirection
  240. // - Status4xx - Client Error
  241. // - Status5xx - Server Error
  242. //
  243. // See https://en.wikipedia.org/wiki/List_of_HTTP_status_codes.
  244. //
  245. // Example:
  246. //
  247. // resp := NewResponse(t, response)
  248. // resp.StatusRange(Status2xx)
  249. func (r *Response) StatusRange(rn StatusRange) *Response {
  250. opChain := r.chain.enter("StatusRange()")
  251. defer opChain.leave()
  252. if opChain.failed() {
  253. return r
  254. }
  255. status := statusCodeText(r.httpResp.StatusCode)
  256. actual := statusRangeText(r.httpResp.StatusCode)
  257. expected := statusRangeText(int(rn))
  258. if actual == "" || actual != expected {
  259. opChain.fail(AssertionFailure{
  260. Type: AssertBelongs,
  261. Actual: &AssertionValue{status},
  262. Expected: &AssertionValue{AssertionList{
  263. statusRangeText(int(rn)),
  264. }},
  265. Errors: []error{
  266. errors.New("expected: http status belongs to given range"),
  267. },
  268. })
  269. }
  270. return r
  271. }
  272. // StatusList succeeds if response matches with any given status code list
  273. //
  274. // Example:
  275. //
  276. // resp := NewResponse(t, response)
  277. // resp.StatusList(http.StatusForbidden, http.StatusUnauthorized)
  278. func (r *Response) StatusList(values ...int) *Response {
  279. opChain := r.chain.enter("StatusList()")
  280. defer opChain.leave()
  281. if opChain.failed() {
  282. return r
  283. }
  284. if len(values) == 0 {
  285. opChain.fail(AssertionFailure{
  286. Type: AssertUsage,
  287. Errors: []error{
  288. errors.New("unexpected empty status list"),
  289. },
  290. })
  291. return r
  292. }
  293. var found bool
  294. for _, v := range values {
  295. if v == r.httpResp.StatusCode {
  296. found = true
  297. break
  298. }
  299. }
  300. if !found {
  301. opChain.fail(AssertionFailure{
  302. Type: AssertBelongs,
  303. Actual: &AssertionValue{statusCodeText(r.httpResp.StatusCode)},
  304. Expected: &AssertionValue{AssertionList(statusListText(values))},
  305. Errors: []error{
  306. errors.New("expected: http status belongs to given list"),
  307. },
  308. })
  309. }
  310. return r
  311. }
  312. func statusCodeText(code int) string {
  313. if s := http.StatusText(code); s != "" {
  314. return strconv.Itoa(code) + " " + s
  315. }
  316. return strconv.Itoa(code)
  317. }
  318. func statusRangeText(code int) string {
  319. switch {
  320. case code >= 100 && code < 200:
  321. return "1xx Informational"
  322. case code >= 200 && code < 300:
  323. return "2xx Success"
  324. case code >= 300 && code < 400:
  325. return "3xx Redirection"
  326. case code >= 400 && code < 500:
  327. return "4xx Client Error"
  328. case code >= 500 && code < 600:
  329. return "5xx Server Error"
  330. default:
  331. return ""
  332. }
  333. }
  334. func statusListText(values []int) []interface{} {
  335. var statusText []interface{}
  336. for _, v := range values {
  337. statusText = append(statusText, statusCodeText(v))
  338. }
  339. return statusText
  340. }
  341. // Headers returns a new Object instance with response header map.
  342. //
  343. // Example:
  344. //
  345. // resp := NewResponse(t, response)
  346. // resp.Headers().Value("Content-Type").String().IsEqual("application-json")
  347. func (r *Response) Headers() *Object {
  348. opChain := r.chain.enter("Headers()")
  349. defer opChain.leave()
  350. if opChain.failed() {
  351. return newObject(opChain, nil)
  352. }
  353. var value map[string]interface{}
  354. value, _ = canonMap(opChain, r.httpResp.Header)
  355. return newObject(opChain, value)
  356. }
  357. // Header returns a new String instance with given header field.
  358. //
  359. // Example:
  360. //
  361. // resp := NewResponse(t, response)
  362. // resp.Header("Content-Type").IsEqual("application-json")
  363. // resp.Header("Date").AsDateTime().Le(time.Now())
  364. func (r *Response) Header(header string) *String {
  365. opChain := r.chain.enter("Header(%q)", header)
  366. defer opChain.leave()
  367. if opChain.failed() {
  368. return newString(opChain, "")
  369. }
  370. value := r.httpResp.Header.Get(header)
  371. return newString(opChain, value)
  372. }
  373. // Cookies returns a new Array instance with all cookie names set by this response.
  374. // Returned Array contains a String value for every cookie name.
  375. //
  376. // Note that this returns only cookies set by Set-Cookie headers of this response.
  377. // It doesn't return session cookies from previous responses, which may be stored
  378. // in a cookie jar.
  379. //
  380. // Example:
  381. //
  382. // resp := NewResponse(t, response)
  383. // resp.Cookies().Contains("session")
  384. func (r *Response) Cookies() *Array {
  385. opChain := r.chain.enter("Cookies()")
  386. defer opChain.leave()
  387. if opChain.failed() {
  388. return newArray(opChain, nil)
  389. }
  390. names := []interface{}{}
  391. for _, c := range r.cookies {
  392. names = append(names, c.Name)
  393. }
  394. return newArray(opChain, names)
  395. }
  396. // Cookie returns a new Cookie instance with specified cookie from response.
  397. //
  398. // Note that this returns only cookies set by Set-Cookie headers of this response.
  399. // It doesn't return session cookies from previous responses, which may be stored
  400. // in a cookie jar.
  401. //
  402. // Example:
  403. //
  404. // resp := NewResponse(t, response)
  405. // resp.Cookie("session").Domain().IsEqual("example.com")
  406. func (r *Response) Cookie(name string) *Cookie {
  407. opChain := r.chain.enter("Cookie(%q)", name)
  408. defer opChain.leave()
  409. if opChain.failed() {
  410. return newCookie(opChain, nil)
  411. }
  412. var cookie *Cookie
  413. names := []string{}
  414. for _, c := range r.cookies {
  415. if c.Name == name {
  416. cookie = newCookie(opChain, c)
  417. break
  418. }
  419. names = append(names, c.Name)
  420. }
  421. if cookie == nil {
  422. opChain.fail(AssertionFailure{
  423. Type: AssertContainsElement,
  424. Actual: &AssertionValue{names},
  425. Expected: &AssertionValue{name},
  426. Errors: []error{
  427. errors.New("expected: response contains cookie with given name"),
  428. },
  429. })
  430. return newCookie(opChain, nil)
  431. }
  432. return cookie
  433. }
  434. // Websocket returns Websocket instance for interaction with WebSocket server.
  435. //
  436. // May be called only if the WithWebsocketUpgrade was called on the request.
  437. // That is responsibility of the caller to explicitly disconnect websocket after use.
  438. //
  439. // Example:
  440. //
  441. // req := NewRequestC(config, "GET", "/path")
  442. // req.WithWebsocketUpgrade()
  443. // ws := req.Expect().Websocket()
  444. // defer ws.Disconnect()
  445. func (r *Response) Websocket() *Websocket {
  446. opChain := r.chain.enter("Websocket()")
  447. defer opChain.leave()
  448. if opChain.failed() {
  449. return newWebsocket(opChain, r.config, nil)
  450. }
  451. if r.websocket == nil {
  452. opChain.fail(AssertionFailure{
  453. Type: AssertUsage,
  454. Errors: []error{
  455. errors.New(
  456. "Websocket() requires WithWebsocketUpgrade() to be called on request"),
  457. },
  458. })
  459. return newWebsocket(opChain, r.config, nil)
  460. }
  461. return newWebsocket(opChain, r.config, r.websocket)
  462. }
  463. // Body returns a new String instance with response body.
  464. //
  465. // Example:
  466. //
  467. // resp := NewResponse(t, response)
  468. // resp.Body().NotEmpty()
  469. // resp.Body().Length().IsEqual(100)
  470. func (r *Response) Body() *String {
  471. opChain := r.chain.enter("Body()")
  472. defer opChain.leave()
  473. if opChain.failed() {
  474. return newString(opChain, "")
  475. }
  476. content, ok := r.getContent(opChain)
  477. if !ok {
  478. return newString(opChain, "")
  479. }
  480. return newString(opChain, string(content))
  481. }
  482. // NoContent succeeds if response contains empty Content-Type header and
  483. // empty body.
  484. func (r *Response) NoContent() *Response {
  485. opChain := r.chain.enter("NoContent()")
  486. defer opChain.leave()
  487. if opChain.failed() {
  488. return r
  489. }
  490. contentType := r.httpResp.Header.Get("Content-Type")
  491. if !r.checkEqual(opChain, `"Content-Type" header`, "", contentType) {
  492. return r
  493. }
  494. content, ok := r.getContent(opChain)
  495. if !ok {
  496. return r
  497. }
  498. if !r.checkEqual(opChain, "body", "", string(content)) {
  499. return r
  500. }
  501. return r
  502. }
  503. // HasContentType succeeds if response contains Content-Type header with given
  504. // media type and charset.
  505. //
  506. // If charset is omitted, and mediaType is non-empty, Content-Type header
  507. // should contain empty or utf-8 charset.
  508. //
  509. // If charset is omitted, and mediaType is also empty, Content-Type header
  510. // should contain no charset.
  511. func (r *Response) HasContentType(mediaType string, charset ...string) *Response {
  512. opChain := r.chain.enter("HasContentType()")
  513. defer opChain.leave()
  514. if opChain.failed() {
  515. return r
  516. }
  517. if len(charset) > 1 {
  518. opChain.fail(AssertionFailure{
  519. Type: AssertUsage,
  520. Errors: []error{
  521. errors.New("unexpected multiple charset arguments"),
  522. },
  523. })
  524. return r
  525. }
  526. r.checkContentType(opChain, mediaType, charset...)
  527. return r
  528. }
  529. // HasContentEncoding succeeds if response has exactly given Content-Encoding list.
  530. // Common values are empty, "gzip", "compress", "deflate", "identity" and "br".
  531. func (r *Response) HasContentEncoding(encoding ...string) *Response {
  532. opChain := r.chain.enter("HasContentEncoding()")
  533. defer opChain.leave()
  534. if opChain.failed() {
  535. return r
  536. }
  537. r.checkEqual(opChain, `"Content-Encoding" header`,
  538. encoding,
  539. r.httpResp.Header["Content-Encoding"])
  540. return r
  541. }
  542. // HasTransferEncoding succeeds if response contains given Transfer-Encoding list.
  543. // Common values are empty, "chunked" and "identity".
  544. func (r *Response) HasTransferEncoding(encoding ...string) *Response {
  545. opChain := r.chain.enter("HasTransferEncoding()")
  546. defer opChain.leave()
  547. if opChain.failed() {
  548. return r
  549. }
  550. r.checkEqual(opChain, `"Transfer-Encoding" header`,
  551. encoding,
  552. r.httpResp.TransferEncoding)
  553. return r
  554. }
  555. // Deprecated: use HasContentType instead.
  556. func (r *Response) ContentType(mediaType string, charset ...string) *Response {
  557. return r.HasContentType(mediaType, charset...)
  558. }
  559. // Deprecated: use HasContentEncoding instead.
  560. func (r *Response) ContentEncoding(encoding ...string) *Response {
  561. return r.HasContentEncoding(encoding...)
  562. }
  563. // Deprecated: use HasTransferEncoding instead.
  564. func (r *Response) TransferEncoding(encoding ...string) *Response {
  565. return r.HasTransferEncoding(encoding...)
  566. }
  567. // ContentOpts define parameters for matching the response content parameters.
  568. type ContentOpts struct {
  569. // The media type Content-Type part, e.g. "application/json"
  570. MediaType string
  571. // The character set Content-Type part, e.g. "utf-8"
  572. Charset string
  573. }
  574. // Text returns a new String instance with response body.
  575. //
  576. // Text succeeds if response contains "text/plain" Content-Type header
  577. // with empty or "utf-8" charset.
  578. //
  579. // Example:
  580. //
  581. // resp := NewResponse(t, response)
  582. // resp.Text().IsEqual("hello, world!")
  583. // resp.Text(ContentOpts{
  584. // MediaType: "text/plain",
  585. // }).IsEqual("hello, world!")
  586. func (r *Response) Text(options ...ContentOpts) *String {
  587. opChain := r.chain.enter("Text()")
  588. defer opChain.leave()
  589. if opChain.failed() {
  590. return newString(opChain, "")
  591. }
  592. if len(options) > 1 {
  593. opChain.fail(AssertionFailure{
  594. Type: AssertUsage,
  595. Errors: []error{
  596. errors.New("unexpected multiple options arguments"),
  597. },
  598. })
  599. return newString(opChain, "")
  600. }
  601. if !r.checkContentOptions(opChain, options, "text/plain") {
  602. return newString(opChain, "")
  603. }
  604. content, ok := r.getContent(opChain)
  605. if !ok {
  606. return newString(opChain, "")
  607. }
  608. return newString(opChain, string(content))
  609. }
  610. // Form returns a new Object instance with form decoded from response body.
  611. //
  612. // Form succeeds if response contains "application/x-www-form-urlencoded"
  613. // Content-Type header and if form may be decoded from response body.
  614. // Decoding is performed using https://github.com/ajg/form.
  615. //
  616. // Example:
  617. //
  618. // resp := NewResponse(t, response)
  619. // resp.Form().Value("foo").IsEqual("bar")
  620. // resp.Form(ContentOpts{
  621. // MediaType: "application/x-www-form-urlencoded",
  622. // }).Value("foo").IsEqual("bar")
  623. func (r *Response) Form(options ...ContentOpts) *Object {
  624. opChain := r.chain.enter("Form()")
  625. defer opChain.leave()
  626. if opChain.failed() {
  627. return newObject(opChain, nil)
  628. }
  629. if len(options) > 1 {
  630. opChain.fail(AssertionFailure{
  631. Type: AssertUsage,
  632. Errors: []error{
  633. errors.New("unexpected multiple options arguments"),
  634. },
  635. })
  636. return newObject(opChain, nil)
  637. }
  638. object := r.getForm(opChain, options...)
  639. return newObject(opChain, object)
  640. }
  641. func (r *Response) getForm(
  642. opChain *chain, options ...ContentOpts,
  643. ) map[string]interface{} {
  644. if !r.checkContentOptions(opChain, options, "application/x-www-form-urlencoded", "") {
  645. return nil
  646. }
  647. content, ok := r.getContent(opChain)
  648. if !ok {
  649. return nil
  650. }
  651. decoder := form.NewDecoder(bytes.NewReader(content))
  652. var object map[string]interface{}
  653. if err := decoder.Decode(&object); err != nil {
  654. opChain.fail(AssertionFailure{
  655. Type: AssertValid,
  656. Actual: &AssertionValue{
  657. string(content),
  658. },
  659. Errors: []error{
  660. errors.New("failed to decode form"),
  661. err,
  662. },
  663. })
  664. return nil
  665. }
  666. return object
  667. }
  668. // JSON returns a new Value instance with JSON decoded from response body.
  669. //
  670. // JSON succeeds if response contains "application/json" Content-Type header
  671. // with empty or "utf-8" charset and if JSON may be decoded from response body.
  672. //
  673. // Example:
  674. //
  675. // resp := NewResponse(t, response)
  676. // resp.JSON().Array().ConsistsOf("foo", "bar")
  677. // resp.JSON(ContentOpts{
  678. // MediaType: "application/json",
  679. // }).Array.ConsistsOf("foo", "bar")
  680. func (r *Response) JSON(options ...ContentOpts) *Value {
  681. opChain := r.chain.enter("JSON()")
  682. defer opChain.leave()
  683. if opChain.failed() {
  684. return newValue(opChain, nil)
  685. }
  686. if len(options) > 1 {
  687. opChain.fail(AssertionFailure{
  688. Type: AssertUsage,
  689. Errors: []error{
  690. errors.New("unexpected multiple options arguments"),
  691. },
  692. })
  693. return newValue(opChain, nil)
  694. }
  695. value := r.getJSON(opChain, options...)
  696. return newValue(opChain, value)
  697. }
  698. func (r *Response) getJSON(opChain *chain, options ...ContentOpts) interface{} {
  699. if !r.checkContentOptions(opChain, options, "application/json") {
  700. return nil
  701. }
  702. content, ok := r.getContent(opChain)
  703. if !ok {
  704. return nil
  705. }
  706. var value interface{}
  707. if err := json.Unmarshal(content, &value); err != nil {
  708. opChain.fail(AssertionFailure{
  709. Type: AssertValid,
  710. Actual: &AssertionValue{
  711. string(content),
  712. },
  713. Errors: []error{
  714. errors.New("failed to decode json"),
  715. err,
  716. },
  717. })
  718. return nil
  719. }
  720. return value
  721. }
  722. // JSONP returns a new Value instance with JSONP decoded from response body.
  723. //
  724. // JSONP succeeds if response contains "application/javascript" Content-Type
  725. // header with empty or "utf-8" charset and response body of the following form:
  726. //
  727. // callback(<valid json>);
  728. //
  729. // or:
  730. //
  731. // callback(<valid json>)
  732. //
  733. // Whitespaces are allowed.
  734. //
  735. // Example:
  736. //
  737. // resp := NewResponse(t, response)
  738. // resp.JSONP("myCallback").Array().ConsistsOf("foo", "bar")
  739. // resp.JSONP("myCallback", ContentOpts{
  740. // MediaType: "application/javascript",
  741. // }).Array.ConsistsOf("foo", "bar")
  742. func (r *Response) JSONP(callback string, options ...ContentOpts) *Value {
  743. opChain := r.chain.enter("JSONP()")
  744. defer opChain.leave()
  745. if opChain.failed() {
  746. return newValue(opChain, nil)
  747. }
  748. if len(options) > 1 {
  749. opChain.fail(AssertionFailure{
  750. Type: AssertUsage,
  751. Errors: []error{
  752. errors.New("unexpected multiple options arguments"),
  753. },
  754. })
  755. return newValue(opChain, nil)
  756. }
  757. value := r.getJSONP(opChain, callback, options...)
  758. return newValue(opChain, value)
  759. }
  760. var (
  761. jsonp = regexp.MustCompile(`^\s*([^\s(]+)\s*\((.*)\)\s*;*\s*$`)
  762. )
  763. func (r *Response) getJSONP(
  764. opChain *chain, callback string, options ...ContentOpts,
  765. ) interface{} {
  766. if !r.checkContentOptions(opChain, options, "application/javascript") {
  767. return nil
  768. }
  769. content, ok := r.getContent(opChain)
  770. if !ok {
  771. return nil
  772. }
  773. m := jsonp.FindSubmatch(content)
  774. if len(m) != 3 || string(m[1]) != callback {
  775. opChain.fail(AssertionFailure{
  776. Type: AssertValid,
  777. Actual: &AssertionValue{
  778. string(content),
  779. },
  780. Errors: []error{
  781. fmt.Errorf(`expected: JSONP body in form of "%s(<valid json>)"`,
  782. callback),
  783. },
  784. })
  785. return nil
  786. }
  787. var value interface{}
  788. if err := json.Unmarshal(m[2], &value); err != nil {
  789. opChain.fail(AssertionFailure{
  790. Type: AssertValid,
  791. Actual: &AssertionValue{
  792. string(content),
  793. },
  794. Errors: []error{
  795. errors.New("failed to decode json"),
  796. err,
  797. },
  798. })
  799. return nil
  800. }
  801. return value
  802. }
  803. func (r *Response) checkContentOptions(
  804. opChain *chain, options []ContentOpts, expectedType string, expectedCharset ...string,
  805. ) bool {
  806. if len(options) != 0 {
  807. if options[0].MediaType != "" {
  808. expectedType = options[0].MediaType
  809. }
  810. if options[0].Charset != "" {
  811. expectedCharset = []string{options[0].Charset}
  812. }
  813. }
  814. return r.checkContentType(opChain, expectedType, expectedCharset...)
  815. }
  816. func (r *Response) checkContentType(
  817. opChain *chain, expectedType string, expectedCharset ...string,
  818. ) bool {
  819. contentType := r.httpResp.Header.Get("Content-Type")
  820. if expectedType == "" && len(expectedCharset) == 0 {
  821. if contentType == "" {
  822. return true
  823. }
  824. }
  825. mediaType, params, err := mime.ParseMediaType(contentType)
  826. if err != nil {
  827. opChain.fail(AssertionFailure{
  828. Type: AssertValid,
  829. Actual: &AssertionValue{contentType},
  830. Errors: []error{
  831. errors.New(`invalid "Content-Type" response header`),
  832. err,
  833. },
  834. })
  835. return false
  836. }
  837. if mediaType != expectedType {
  838. opChain.fail(AssertionFailure{
  839. Type: AssertEqual,
  840. Actual: &AssertionValue{mediaType},
  841. Expected: &AssertionValue{expectedType},
  842. Errors: []error{
  843. errors.New(`unexpected media type in "Content-Type" response header`),
  844. },
  845. })
  846. return false
  847. }
  848. charset := params["charset"]
  849. if len(expectedCharset) == 0 {
  850. if charset != "" && !strings.EqualFold(charset, "utf-8") {
  851. opChain.fail(AssertionFailure{
  852. Type: AssertBelongs,
  853. Actual: &AssertionValue{charset},
  854. Expected: &AssertionValue{AssertionList{"", "utf-8"}},
  855. Errors: []error{
  856. errors.New(`unexpected charset in "Content-Type" response header`),
  857. },
  858. })
  859. return false
  860. }
  861. } else {
  862. if !strings.EqualFold(charset, expectedCharset[0]) {
  863. opChain.fail(AssertionFailure{
  864. Type: AssertEqual,
  865. Actual: &AssertionValue{charset},
  866. Expected: &AssertionValue{expectedCharset[0]},
  867. Errors: []error{
  868. errors.New(`unexpected charset in "Content-Type" response header`),
  869. },
  870. })
  871. return false
  872. }
  873. }
  874. return true
  875. }
  876. func (r *Response) checkEqual(
  877. opChain *chain, what string, expected, actual interface{},
  878. ) bool {
  879. if !reflect.DeepEqual(expected, actual) {
  880. opChain.fail(AssertionFailure{
  881. Type: AssertEqual,
  882. Actual: &AssertionValue{actual},
  883. Expected: &AssertionValue{expected},
  884. Errors: []error{
  885. fmt.Errorf("unexpected %s value", what),
  886. },
  887. })
  888. return false
  889. }
  890. return true
  891. }