-
Notifications
You must be signed in to change notification settings - Fork 56
/
apitest.go
1221 lines (1039 loc) · 32.8 KB
/
apitest.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 apitest
import (
"bytes"
"context"
"encoding/json"
"fmt"
"hash/fnv"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/textproto"
"net/url"
"os"
"path/filepath"
"runtime/debug"
"sort"
"strings"
"time"
)
// SystemUnderTestDefaultName default name for system under test
const SystemUnderTestDefaultName = "sut"
// ConsumerDefaultName default consumer name
const ConsumerDefaultName = "cli"
var divider = strings.Repeat("-", 10)
var requestDebugPrefix = fmt.Sprintf("%s>", divider)
var responseDebugPrefix = fmt.Sprintf("<%s", divider)
// APITest is the top level struct holding the test spec
type APITest struct {
debugEnabled bool
mockResponseDelayEnabled bool
networkingEnabled bool
networkingHTTPClient *http.Client
reporter ReportFormatter
verifier Verifier
recorder *Recorder
handler http.Handler
name string
request *Request
response *Response
observers []Observe
mocksObservers []Observe
recorderHook RecorderHook
mocks []*Mock
t TestingT
httpClient *http.Client
httpRequest *http.Request
transport *Transport
meta map[string]interface{}
started time.Time
finished time.Time
}
// InboundRequest used to wrap the incoming request with a timestamp
type InboundRequest struct {
request *http.Request
timestamp time.Time
}
// FinalResponse used to wrap the final response with a timestamp
type FinalResponse struct {
response *http.Response
timestamp time.Time
}
// Observe will be called by with the request and response on completion
type Observe func(*http.Response, *http.Request, *APITest)
// RecorderHook used to implement a custom interaction recorder
type RecorderHook func(*Recorder)
// New creates a new api test. The name is optional and will appear in test reports
func New(name ...string) *APITest {
apiTest := &APITest{
meta: map[string]interface{}{},
}
request := &Request{
apiTest: apiTest,
headers: map[string][]string{},
query: map[string][]string{},
formData: map[string][]string{},
}
response := &Response{
apiTest: apiTest,
headers: map[string][]string{},
}
apiTest.request = request
apiTest.response = response
if len(name) > 0 {
apiTest.name = name[0]
}
return apiTest
}
// Handler is a convenience method for creating a new apitest with a handler
func Handler(handler http.Handler) *APITest {
return New().Handler(handler)
}
// HandlerFunc is a convenience method for creating a new apitest with a handler func
func HandlerFunc(handlerFunc http.HandlerFunc) *APITest {
return New().HandlerFunc(handlerFunc)
}
// EnableNetworking will enable networking for provided clients
func (a *APITest) EnableNetworking(cli ...*http.Client) *APITest {
a.networkingEnabled = true
if len(cli) == 1 {
a.networkingHTTPClient = cli[0]
return a
}
a.networkingHTTPClient = http.DefaultClient
return a
}
// EnableMockResponseDelay turns on mock response delays (defaults to OFF)
func (a *APITest) EnableMockResponseDelay() *APITest {
a.mockResponseDelayEnabled = true
return a
}
// Debug logs to the console the http wire representation of all http interactions that are intercepted by apitest. This includes the inbound request to the application under test, the response returned by the application and any interactions that are intercepted by the mock server.
func (a *APITest) Debug() *APITest {
a.debugEnabled = true
return a
}
// Report provides a hook to add custom formatting to the output of the test
func (a *APITest) Report(reporter ReportFormatter) *APITest {
a.reporter = reporter
return a
}
// Recorder provides a hook to add a recorder to the test
func (a *APITest) Recorder(recorder *Recorder) *APITest {
a.recorder = recorder
return a
}
// Meta provides a hook to add custom meta data to the test which can be picked up when defining a custom reporter
func (a *APITest) Meta(meta map[string]interface{}) *APITest {
a.meta = meta
return a
}
// Handler defines the http handler that is invoked when the test is run
func (a *APITest) Handler(handler http.Handler) *APITest {
a.handler = handler
return a
}
// HandlerFunc defines the http handler that is invoked when the test is run
func (a *APITest) HandlerFunc(handlerFunc http.HandlerFunc) *APITest {
a.handler = handlerFunc
return a
}
// Mocks is a builder method for setting the mocks
func (a *APITest) Mocks(mocks ...*Mock) *APITest {
var m []*Mock
for i := range mocks {
if mocks[i].anyTimesSet {
m = append(m, mocks[i])
continue
}
times := mocks[i].response.mock.times
for j := 1; j <= times; j++ {
mockCpy := mocks[i].copy()
mockCpy.times = 1
m = append(m, mockCpy)
}
}
a.mocks = m
return a
}
// HttpClient allows the developer to provide a custom http client when using mocks
func (a *APITest) HttpClient(cli *http.Client) *APITest {
a.httpClient = cli
return a
}
// Observe is a builder method for setting the observers
func (a *APITest) Observe(observers ...Observe) *APITest {
a.observers = observers
return a
}
// ObserveMocks is a builder method for setting the mocks observers
func (a *APITest) ObserveMocks(observer Observe) *APITest {
a.mocksObservers = append(a.mocksObservers, observer)
return a
}
// RecorderHook allows the consumer to provider a function that will receive the recorder instance before the
// test runs. This can be used to inject custom events which can then be rendered in diagrams
// Deprecated: use Recorder() instead
func (a *APITest) RecorderHook(hook RecorderHook) *APITest {
a.recorderHook = hook
return a
}
// Request returns the request spec
func (a *APITest) Request() *Request {
return a.request
}
// Response returns the expected response
func (a *APITest) Response() *Response {
return a.response
}
// Request is the user defined request that will be invoked on the handler under test
type Request struct {
interceptor Intercept
method string
url string
body string
query map[string][]string
queryCollection map[string][]string
headers map[string][]string
formData map[string][]string
multipartBody *bytes.Buffer
multipart *multipart.Writer
cookies []*Cookie
basicAuth string
context context.Context
apiTest *APITest
}
// Intercept will be called before the request is made. Updates to the request will be reflected in the test
type Intercept func(*http.Request)
type pair struct {
l string
r string
}
// Intercept is a builder method for setting the request interceptor
func (a *APITest) Intercept(interceptor Intercept) *APITest {
a.request.interceptor = interceptor
return a
}
// Verifier allows consumers to override the verification implementation.
func (a *APITest) Verifier(v Verifier) *APITest {
a.verifier = v
return a
}
// Method is a builder method for setting the http method of the request
func (a *APITest) Method(method string) *Request {
a.request.method = method
return a.request
}
// HttpRequest defines the native `http.Request`
func (a *APITest) HttpRequest(req *http.Request) *Request {
a.httpRequest = req
return a.request
}
// Get is a convenience method for setting the request as http.MethodGet
func (a *APITest) Get(url string) *Request {
a.request.method = http.MethodGet
a.request.url = url
return a.request
}
// Getf is a convenience method that adds formatting support to Get
func (a *APITest) Getf(format string, args ...interface{}) *Request {
return a.Get(fmt.Sprintf(format, args...))
}
// Post is a convenience method for setting the request as http.MethodPost
func (a *APITest) Post(url string) *Request {
r := a.request
r.method = http.MethodPost
r.url = url
return r
}
// Postf is a convenience method that adds formatting support to Post
func (a *APITest) Postf(format string, args ...interface{}) *Request {
return a.Post(fmt.Sprintf(format, args...))
}
// Put is a convenience method for setting the request as http.MethodPut
func (a *APITest) Put(url string) *Request {
r := a.request
r.method = http.MethodPut
r.url = url
return r
}
// Putf is a convenience method that adds formatting support to Put
func (a *APITest) Putf(format string, args ...interface{}) *Request {
return a.Put(fmt.Sprintf(format, args...))
}
// Delete is a convenience method for setting the request as http.MethodDelete
func (a *APITest) Delete(url string) *Request {
a.request.method = http.MethodDelete
a.request.url = url
return a.request
}
// Deletef is a convenience method that adds formatting support to Delete
func (a *APITest) Deletef(format string, args ...interface{}) *Request {
return a.Delete(fmt.Sprintf(format, args...))
}
// Patch is a convenience method for setting the request as http.MethodPatch
func (a *APITest) Patch(url string) *Request {
a.request.method = http.MethodPatch
a.request.url = url
return a.request
}
// Patchf is a convenience method that adds formatting support to Patch
func (a *APITest) Patchf(format string, args ...interface{}) *Request {
return a.Patch(fmt.Sprintf(format, args...))
}
// URL is a builder method for setting the url of the request
func (r *Request) URL(url string) *Request {
r.url = url
return r
}
// URLf is a builder method for setting the url of the request and supports a formatter
func (r *Request) URLf(format string, args ...interface{}) *Request {
r.url = fmt.Sprintf(format, args...)
return r
}
// Body is a builder method to set the request body
func (r *Request) Body(b string) *Request {
r.body = b
return r
}
// Bodyf sets the request body and supports a formatter
func (r *Request) Bodyf(format string, args ...interface{}) *Request {
r.body = fmt.Sprintf(format, args...)
return r
}
// BodyFromFile is a builder method to set the request body
func (r *Request) BodyFromFile(f string) *Request {
b, err := ioutil.ReadFile(f)
if err != nil {
r.apiTest.t.Fatal(err)
}
r.body = string(b)
return r
}
// JSON is a convenience method for setting the request body and content type header as "application/json".
// If v is not a string or []byte it will marshall the provided variable as json
func (r *Request) JSON(v interface{}) *Request {
switch x := v.(type) {
case string:
r.body = x
case []byte:
r.body = string(x)
default:
asJSON, err := json.Marshal(x)
if err != nil {
r.apiTest.t.Fatal(err)
return nil
}
r.body = string(asJSON)
}
r.ContentType("application/json")
return r
}
// JSONFromFile is a convenience method for setting the request body and content type header as "application/json"
func (r *Request) JSONFromFile(f string) *Request {
r.BodyFromFile(f)
r.ContentType("application/json")
return r
}
// GraphQLQuery is a convenience method for building a graphql POST request
func (r *Request) GraphQLQuery(query string, variables ...map[string]interface{}) *Request {
q := GraphQLRequestBody{
Query: query,
}
if len(variables) > 0 {
q.Variables = variables[0]
}
return r.GraphQLRequest(q)
}
// GraphQLRequest builds a graphql POST request
func (r *Request) GraphQLRequest(body GraphQLRequestBody) *Request {
r.ContentType("application/json")
data, err := json.Marshal(body)
if err != nil {
r.apiTest.t.Fatal(err)
}
r.body = string(data)
return r
}
// GraphQLRequestBody represents the POST request body as per the GraphQL spec
type GraphQLRequestBody struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
OperationName string `json:"operationName,omitempty"`
}
// Query is a convenience method to add a query parameter to the request.
func (r *Request) Query(key, value string) *Request {
r.query[key] = append(r.query[key], value)
return r
}
// QueryParams is a builder method to set the request query parameters.
// This can be used in combination with request.QueryCollection
func (r *Request) QueryParams(params map[string]string) *Request {
for k, v := range params {
r.query[k] = append(r.query[k], v)
}
return r
}
// QueryCollection is a builder method to set the request query parameters
// This can be used in combination with request.Query
func (r *Request) QueryCollection(q map[string][]string) *Request {
r.queryCollection = q
return r
}
// Header is a builder method to set the request headers
func (r *Request) Header(key, value string) *Request {
normalizedKey := textproto.CanonicalMIMEHeaderKey(key)
r.headers[normalizedKey] = append(r.headers[normalizedKey], value)
return r
}
// Headers is a builder method to set the request headers
func (r *Request) Headers(headers map[string]string) *Request {
for k, v := range headers {
normalizedKey := textproto.CanonicalMIMEHeaderKey(k)
r.headers[normalizedKey] = append(r.headers[normalizedKey], v)
}
return r
}
// ContentType is a builder method to set the Content-Type header of the request
func (r *Request) ContentType(contentType string) *Request {
normalizedKey := textproto.CanonicalMIMEHeaderKey("Content-Type")
r.headers[normalizedKey] = []string{contentType}
return r
}
// Cookie is a convenience method for setting a single request cookies by name and value
func (r *Request) Cookie(name, value string) *Request {
r.cookies = append(r.cookies, &Cookie{name: &name, value: &value})
return r
}
// Cookies is a builder method to set the request cookies
func (r *Request) Cookies(c ...*Cookie) *Request {
r.cookies = append(r.cookies, c...)
return r
}
// BasicAuth is a builder method to sets basic auth on the request.
func (r *Request) BasicAuth(username, password string) *Request {
r.basicAuth = fmt.Sprintf("%s:%s", username, password)
return r
}
// WithContext is a builder method to set a context on the request
func (r *Request) WithContext(ctx context.Context) *Request {
r.context = ctx
return r
}
// FormData is a builder method to set the body form data
// Also sets the content type of the request to application/x-www-form-urlencoded
func (r *Request) FormData(name string, values ...string) *Request {
defer r.checkCombineFormDataWithMultipart()
r.ContentType("application/x-www-form-urlencoded")
r.formData[name] = append(r.formData[name], values...)
return r
}
// MultipartFormData is a builder method to set the field in multipart form data
// Also sets the content type of the request to multipart/form-data
func (r *Request) MultipartFormData(name string, values ...string) *Request {
defer r.checkCombineFormDataWithMultipart()
r.setMultipartWriter()
for _, value := range values {
if err := r.multipart.WriteField(name, value); err != nil {
r.apiTest.t.Fatal(err)
}
}
return r
}
// MultipartFile is a builder method to set the file in multipart form data
// Also sets the content type of the request to multipart/form-data
func (r *Request) MultipartFile(name string, ff ...string) *Request {
defer r.checkCombineFormDataWithMultipart()
r.setMultipartWriter()
for _, f := range ff {
func() {
file, err := os.Open(f)
if err != nil {
r.apiTest.t.Fatal(err)
}
defer file.Close()
part, err := r.multipart.CreateFormFile(name, filepath.Base(file.Name()))
if err != nil {
r.apiTest.t.Fatal(err)
}
if _, err = io.Copy(part, file); err != nil {
r.apiTest.t.Fatal(err)
}
}()
}
return r
}
func (r *Request) setMultipartWriter() {
if r.multipart == nil {
r.multipartBody = &bytes.Buffer{}
r.multipart = multipart.NewWriter(r.multipartBody)
}
}
func (r *Request) checkCombineFormDataWithMultipart() {
if r.multipart != nil && len(r.formData) > 0 {
r.apiTest.t.Fatal("FormData (application/x-www-form-urlencoded) and MultiPartFormData(multipart/form-data) cannot be combined")
}
}
// Expect marks the request spec as complete and following code will define the expected response
func (r *Request) Expect(t TestingT) *Response {
r.apiTest.t = t
return r.apiTest.response
}
// Response is the user defined expected response from the application under test
type Response struct {
status int
body string
headers map[string][]string
headersPresent []string
headersNotPresent []string
cookies []*Cookie
cookiesPresent []string
cookiesNotPresent []string
apiTest *APITest
assert []Assert
}
// Assert is a user defined custom assertion function
type Assert func(*http.Response, *http.Request) error
// Body is the expected response body
func (r *Response) Body(b string) *Response {
r.body = b
return r
}
// Bodyf is the expected response body that supports a formatter
func (r *Response) Bodyf(format string, args ...interface{}) *Response {
r.body = fmt.Sprintf(format, args...)
return r
}
// BodyFromFile reads the given file and uses the content as the expected response body
func (r *Response) BodyFromFile(f string) *Response {
b, err := ioutil.ReadFile(f)
if err != nil {
r.apiTest.t.Fatal(err)
}
r.body = string(b)
return r
}
// Cookies is the expected response cookies
func (r *Response) Cookies(cookies ...*Cookie) *Response {
r.cookies = append(r.cookies, cookies...)
return r
}
// Cookie is used to match on an individual cookie name/value pair in the expected response cookies
func (r *Response) Cookie(name, value string) *Response {
r.cookies = append(r.cookies, NewCookie(name).Value(value))
return r
}
// CookiePresent is used to assert that a cookie is present in the response,
// regardless of its value
func (r *Response) CookiePresent(cookieName string) *Response {
r.cookiesPresent = append(r.cookiesPresent, cookieName)
return r
}
// CookieNotPresent is used to assert that a cookie is not present in the response
func (r *Response) CookieNotPresent(cookieName string) *Response {
r.cookiesNotPresent = append(r.cookiesNotPresent, cookieName)
return r
}
// Header is a builder method to set the request headers
func (r *Response) Header(key, value string) *Response {
normalizedName := textproto.CanonicalMIMEHeaderKey(key)
r.headers[normalizedName] = append(r.headers[normalizedName], value)
return r
}
// HeaderPresent is a builder method to set the request headers that should be present in the response
func (r *Response) HeaderPresent(name string) *Response {
normalizedName := textproto.CanonicalMIMEHeaderKey(name)
r.headersPresent = append(r.headersPresent, normalizedName)
return r
}
// HeaderNotPresent is a builder method to set the request headers that should not be present in the response
func (r *Response) HeaderNotPresent(name string) *Response {
normalizedName := textproto.CanonicalMIMEHeaderKey(name)
r.headersNotPresent = append(r.headersNotPresent, normalizedName)
return r
}
// Headers is a builder method to set the request headers
func (r *Response) Headers(headers map[string]string) *Response {
for name, value := range headers {
normalizedName := textproto.CanonicalMIMEHeaderKey(name)
r.headers[normalizedName] = append(r.headers[textproto.CanonicalMIMEHeaderKey(normalizedName)], value)
}
return r
}
// Status is the expected response http status code
func (r *Response) Status(s int) *Response {
r.status = s
return r
}
// Assert allows the consumer to provide a user defined function containing their own
// custom assertions
func (r *Response) Assert(fn func(*http.Response, *http.Request) error) *Response {
r.assert = append(r.assert, fn)
return r.apiTest.response
}
// End runs the test returning the result to the caller
func (r *Response) End() Result {
apiTest := r.apiTest
defer func() {
if apiTest.debugEnabled {
apiTest.finished = time.Now()
fmt.Println(fmt.Sprintf("Duration: %s\n", apiTest.finished.Sub(apiTest.started)))
}
}()
if apiTest.handler == nil && !apiTest.networkingEnabled {
apiTest.t.Fatal("either define a http.Handler or enable networking")
}
apiTest.started = time.Now()
var res *http.Response
if apiTest.reporter != nil {
res = apiTest.report()
} else {
res = r.runTest()
}
var unmatchedMocks []UnmatchedMock
for _, m := range r.apiTest.mocks {
if m.isUsed == false {
unmatchedMocks = append(unmatchedMocks, UnmatchedMock{
URL: *m.request.url,
})
break
}
}
return Result{
Response: res,
unmatchedMocks: unmatchedMocks,
}
}
// Result provides the final result
type Result struct {
Response *http.Response
unmatchedMocks []UnmatchedMock
}
// UnmatchedMocks returns any mocks that were not used, e.g. there was not a matching http Request for the mock
func (r Result) UnmatchedMocks() []UnmatchedMock {
return r.unmatchedMocks
}
// JSON unmarshal the result response body to a valid struct
func (r Result) JSON(t interface{}) {
data, err := ioutil.ReadAll(r.Response.Body)
if err != nil {
panic(err)
}
err = json.Unmarshal(data, t)
if err != nil {
panic(err)
}
}
type mockInteraction struct {
request *http.Request
response *http.Response
timestamp time.Time
}
func (r *mockInteraction) GetRequestHost() string {
host := r.request.Host
if host == "" {
host = r.request.URL.Host
}
return host
}
func (a *APITest) report() *http.Response {
var capturedInboundReq *http.Request
var capturedFinalRes *http.Response
var capturedMockInteractions []*mockInteraction
a.observers = append(a.observers, func(finalRes *http.Response, inboundReq *http.Request, a *APITest) {
capturedFinalRes = copyHttpResponse(finalRes)
capturedInboundReq = copyHttpRequest(inboundReq)
})
a.mocksObservers = append(a.mocksObservers, func(mockRes *http.Response, mockReq *http.Request, a *APITest) {
capturedMockInteractions = append(capturedMockInteractions, &mockInteraction{
request: copyHttpRequest(mockReq),
response: copyHttpResponse(mockRes),
timestamp: time.Now().UTC(),
})
})
if a.recorder == nil {
a.recorder = NewTestRecorder()
}
defer a.recorder.Reset()
if a.recorderHook != nil {
a.recorderHook(a.recorder)
}
a.started = time.Now()
res := a.response.runTest()
a.finished = time.Now()
a.recorder.
AddTitle(fmt.Sprintf("%s %s", capturedInboundReq.Method, capturedInboundReq.URL.String())).
AddSubTitle(a.name).
AddHttpRequest(HttpRequest{
Source: ConsumerDefaultName,
Target: SystemUnderTestDefaultName,
Value: capturedInboundReq,
Timestamp: a.started,
})
for _, interaction := range capturedMockInteractions {
a.recorder.AddHttpRequest(HttpRequest{
Source: SystemUnderTestDefaultName,
Target: interaction.GetRequestHost(),
Value: interaction.request,
Timestamp: interaction.timestamp,
})
if interaction.response != nil {
a.recorder.AddHttpResponse(HttpResponse{
Source: interaction.GetRequestHost(),
Target: SystemUnderTestDefaultName,
Value: interaction.response,
Timestamp: interaction.timestamp,
})
}
}
a.recorder.AddHttpResponse(HttpResponse{
Source: SystemUnderTestDefaultName,
Target: ConsumerDefaultName,
Value: capturedFinalRes,
Timestamp: a.finished,
})
sort.Slice(a.recorder.Events, func(i, j int) bool {
return a.recorder.Events[i].GetTime().Before(a.recorder.Events[j].GetTime())
})
meta := map[string]interface{}{}
for k, v := range a.meta {
meta[k] = v
}
meta["status_code"] = capturedFinalRes.StatusCode
meta["path"] = capturedInboundReq.URL.String()
meta["method"] = capturedInboundReq.Method
meta["name"] = a.name
meta["hash"] = createHash(meta)
meta["duration"] = a.finished.Sub(a.started).Nanoseconds()
a.recorder.AddMeta(meta)
a.reporter.Format(a.recorder)
return res
}
func createHash(meta map[string]interface{}) string {
path := meta["path"]
method := meta["method"]
name := meta["name"]
app := meta["app"]
prefix := fnv.New32a()
_, err := prefix.Write([]byte(fmt.Sprintf("%s%s%s", app, strings.ToUpper(method.(string)), path)))
if err != nil {
panic(err)
}
suffix := fnv.New32a()
_, err = suffix.Write([]byte(name.(string)))
if err != nil {
panic(err)
}
return fmt.Sprintf("%d_%d", prefix.Sum32(), suffix.Sum32())
}
func (r *Response) runTest() *http.Response {
a := r.apiTest
if len(a.mocks) > 0 {
a.transport = newTransport(
a.mocks,
a.httpClient,
a.debugEnabled,
a.mockResponseDelayEnabled,
a.mocksObservers,
r.apiTest,
)
defer a.transport.Reset()
a.transport.Hijack()
}
res, req := a.doRequest()
defer func() {
if len(a.observers) > 0 {
for _, observe := range a.observers {
observe(res, req, a)
}
}
}()
if a.verifier == nil {
a.verifier = DefaultVerifier{}
}
a.assertMocks()
a.assertResponse(res)
a.assertHeaders(res)
a.assertCookies(res)
a.assertFunc(res, req)
return copyHttpResponse(res)
}
func (a *APITest) assertMocks() {
for _, mock := range a.mocks {
if mock.anyTimesSet == false && mock.isUsed == false && mock.timesSet {
a.verifier.Fail(a.t, "mock was not invoked expected times", failureMessageArgs{Name: a.name})
}
}
}
func (a *APITest) assertFunc(res *http.Response, req *http.Request) {
if len(a.response.assert) > 0 {
for _, assertFn := range a.response.assert {
err := assertFn(copyHttpResponse(res), copyHttpRequest(req))
if err != nil {
a.verifier.NoError(a.t, err, failureMessageArgs{Name: a.name})
}
}
}
}
func (a *APITest) doRequest() (*http.Response, *http.Request) {
req := a.buildRequest()
if a.request.interceptor != nil {
a.request.interceptor(req)
}
resRecorder := httptest.NewRecorder()
if a.debugEnabled {
requestDump, err := httputil.DumpRequest(req, true)
if err == nil {
debugLog(requestDebugPrefix, "inbound http request", string(requestDump))
}
}
var res *http.Response
var err error
if !a.networkingEnabled {
a.serveHttp(resRecorder, copyHttpRequest(req))
res = resRecorder.Result()
} else {
res, err = a.networkingHTTPClient.Do(copyHttpRequest(req))
if err != nil {
a.t.Fatal(err)
}
}
if a.debugEnabled {
responseDump, err := httputil.DumpResponse(res, true)
if err == nil {
debugLog(responseDebugPrefix, "final response", string(responseDump))
}
}
return res, req
}
func (a *APITest) serveHttp(res *httptest.ResponseRecorder, req *http.Request) {
defer func() {
if err := recover(); err != nil {
a.t.Fatalf("%s: %s", err, debug.Stack())
}
}()
a.handler.ServeHTTP(res, req)
}
func (a *APITest) buildRequest() *http.Request {
if a.httpRequest != nil {
return a.httpRequest
}
if len(a.request.formData) > 0 {
form := url.Values{}
for k := range a.request.formData {
for _, value := range a.request.formData[k] {
form.Add(k, value)
}
}
a.request.Body(form.Encode())
}
if a.request.multipart != nil {
err := a.request.multipart.Close()
if err != nil {
a.request.apiTest.t.Fatal(err)
}
a.request.Header("Content-Type", a.request.multipart.FormDataContentType())
a.request.Body(a.request.multipartBody.String())
}
req, _ := http.NewRequest(a.request.method, a.request.url, bytes.NewBufferString(a.request.body))
if a.request.context != nil {
req = req.WithContext(a.request.context)
}
req.URL.RawQuery = formatQuery(a.request)
req.Host = SystemUnderTestDefaultName
if a.networkingEnabled {
req.Host = req.URL.Host
}