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