/
step_request.go
1103 lines (983 loc) · 28.4 KB
/
step_request.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 hrp
import (
"bytes"
"compress/gzip"
"compress/zlib"
"crypto/tls"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/andybalholm/brotli"
"github.com/fatih/color"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/hrp/internal/builtin"
"github.com/httprunner/httprunner/hrp/internal/httpstat"
"github.com/httprunner/httprunner/hrp/internal/json"
)
type HTTPMethod string
const (
httpGET HTTPMethod = "GET"
httpHEAD HTTPMethod = "HEAD"
httpPOST HTTPMethod = "POST"
httpPUT HTTPMethod = "PUT"
httpDELETE HTTPMethod = "DELETE"
httpOPTIONS HTTPMethod = "OPTIONS"
httpPATCH HTTPMethod = "PATCH"
)
// Request represents HTTP request data structure.
// This is used for teststep.
type Request struct {
Method HTTPMethod `json:"method" yaml:"method"` // required
URL string `json:"url" yaml:"url"` // required
HTTP2 bool `json:"http2,omitempty" yaml:"http2,omitempty"`
Params map[string]interface{} `json:"params,omitempty" yaml:"params,omitempty"`
Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
Cookies map[string]string `json:"cookies,omitempty" yaml:"cookies,omitempty"`
Body interface{} `json:"body,omitempty" yaml:"body,omitempty"`
Json interface{} `json:"json,omitempty" yaml:"json,omitempty"`
Data interface{} `json:"data,omitempty" yaml:"data,omitempty"`
Timeout float32 `json:"timeout,omitempty" yaml:"timeout,omitempty"`
AllowRedirects bool `json:"allow_redirects,omitempty" yaml:"allow_redirects,omitempty"`
Verify bool `json:"verify,omitempty" yaml:"verify,omitempty"`
}
func newRequestBuilder(parser *Parser, config *TConfig, stepRequest *Request) *requestBuilder {
// convert request struct to map
jsonRequest, _ := json.Marshal(stepRequest)
var requestMap map[string]interface{}
_ = json.Unmarshal(jsonRequest, &requestMap)
request := &http.Request{
Header: make(http.Header),
}
if stepRequest.HTTP2 {
request.ProtoMajor = 2
request.ProtoMinor = 0
} else {
request.ProtoMajor = 1
request.ProtoMinor = 1
}
return &requestBuilder{
stepRequest: stepRequest,
req: request,
config: config,
parser: parser,
requestMap: requestMap,
}
}
type requestBuilder struct {
stepRequest *Request
req *http.Request
parser *Parser
config *TConfig
requestMap map[string]interface{}
}
func (r *requestBuilder) prepareHeaders(stepVariables map[string]interface{}) error {
// prepare request headers
stepHeaders := r.stepRequest.Headers
if r.config.Headers != nil {
// override headers
stepHeaders = mergeMap(stepHeaders, r.config.Headers)
}
if len(stepHeaders) > 0 {
headers, err := r.parser.ParseHeaders(stepHeaders, stepVariables)
if err != nil {
return errors.Wrap(err, "parse headers failed")
}
for key, value := range headers {
// omit pseudo header names for HTTP/1, e.g. :authority, :method, :path, :scheme
if strings.HasPrefix(key, ":") {
continue
}
r.req.Header.Add(key, value)
// prepare content length
if strings.EqualFold(key, "Content-Length") && value != "" {
if l, err := strconv.ParseInt(value, 10, 64); err == nil {
r.req.ContentLength = l
}
}
}
}
// prepare request cookies
for cookieName, cookieValue := range r.stepRequest.Cookies {
value, err := r.parser.Parse(cookieValue, stepVariables)
if err != nil {
return errors.Wrap(err, "parse cookie value failed")
}
r.req.AddCookie(&http.Cookie{
Name: cookieName,
Value: fmt.Sprintf("%v", value),
})
}
// update header
headers := make(map[string]string)
for key, value := range r.req.Header {
headers[key] = value[0]
}
r.requestMap["headers"] = headers
return nil
}
func (r *requestBuilder) prepareUrlParams(stepVariables map[string]interface{}) error {
// parse step request url
requestUrl, err := r.parser.ParseString(r.stepRequest.URL, stepVariables)
if err != nil {
log.Error().Err(err).Msg("parse request url failed")
return err
}
rawUrl := buildURL(r.config.BaseURL, convertString(requestUrl))
// prepare request params
var queryParams url.Values
if len(r.stepRequest.Params) > 0 {
params, err := r.parser.Parse(r.stepRequest.Params, stepVariables)
if err != nil {
return errors.Wrap(err, "parse request params failed")
}
parsedParams := params.(map[string]interface{})
r.requestMap["params"] = parsedParams
if len(parsedParams) > 0 {
queryParams = make(url.Values)
for k, v := range parsedParams {
queryParams.Add(k, fmt.Sprint(v))
}
}
}
if queryParams != nil {
// append params to url
paramStr := queryParams.Encode()
if strings.IndexByte(rawUrl, '?') == -1 {
rawUrl = rawUrl + "?" + paramStr
} else {
rawUrl = rawUrl + "&" + paramStr
}
}
// prepare url
u, err := url.Parse(rawUrl)
if err != nil {
return errors.Wrap(err, "parse url failed")
}
r.req.URL = u
r.req.Host = u.Host
return nil
}
func (r *requestBuilder) prepareBody(stepVariables map[string]interface{}) error {
// prepare request body
if r.stepRequest.Body == nil {
return nil
}
data, err := r.parser.Parse(r.stepRequest.Body, stepVariables)
if err != nil {
return err
}
// check request body format if Content-Type specified as application/json
if strings.HasPrefix(r.req.Header.Get("Content-Type"), "application/json") {
switch data.(type) {
case bool, float64, string, map[string]interface{}, []interface{}, nil:
break
default:
return errors.Errorf("request body type inconsistent with Content-Type: %v",
r.req.Header.Get("Content-Type"))
}
}
r.requestMap["body"] = data
var dataBytes []byte
switch vv := data.(type) {
case map[string]interface{}:
contentType := r.req.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/x-www-form-urlencoded") {
// post form data
formData := make(url.Values)
for k, v := range vv {
formData.Add(k, fmt.Sprint(v))
}
dataBytes = []byte(formData.Encode())
} else {
// post json
dataBytes, err = json.Marshal(vv)
if err != nil {
return err
}
if contentType == "" {
r.req.Header.Set("Content-Type", "application/json; charset=utf-8")
}
}
case []interface{}:
contentType := r.req.Header.Get("Content-Type")
// post json
dataBytes, err = json.Marshal(vv)
if err != nil {
return err
}
if contentType == "" {
r.req.Header.Set("Content-Type", "application/json; charset=utf-8")
}
case string:
dataBytes = []byte(vv)
case []byte:
dataBytes = vv
case bytes.Buffer:
dataBytes = vv.Bytes()
default: // unexpected body type
return errors.New("unexpected request body type")
}
r.req.Body = io.NopCloser(bytes.NewReader(dataBytes))
r.req.ContentLength = int64(len(dataBytes))
return nil
}
func runStepRequest(r *SessionRunner, step *TStep) (stepResult *StepResult, err error) {
stepResult = &StepResult{
Name: step.Name,
StepType: stepTypeRequest,
Success: false,
ContentSize: 0,
}
defer func() {
// update testcase summary
if err != nil {
stepResult.Attachment = err.Error()
}
}()
// override step variables
stepVariables, err := r.MergeStepVariables(step.Variables)
if err != nil {
return
}
sessionData := newSessionData()
parser := r.GetParser()
config := r.GetConfig()
rb := newRequestBuilder(parser, config, step.Request)
rb.req.Method = string(step.Request.Method)
err = rb.prepareUrlParams(stepVariables)
if err != nil {
return
}
err = rb.prepareHeaders(stepVariables)
if err != nil {
return
}
err = rb.prepareBody(stepVariables)
if err != nil {
return
}
// add request object to step variables, could be used in setup hooks
stepVariables["hrp_step_name"] = step.Name
stepVariables["hrp_step_request"] = rb.requestMap
// deal with setup hooks
for _, setupHook := range step.SetupHooks {
_, err = parser.Parse(setupHook, stepVariables)
if err != nil {
return stepResult, errors.Wrap(err, "run setup hooks failed")
}
}
// log & print request
if r.LogOn() {
if err := printRequest(rb.req); err != nil {
return stepResult, err
}
}
// stat HTTP request
var httpStat httpstat.Stat
if r.HTTPStatOn() {
ctx := httpstat.WithHTTPStat(rb.req, &httpStat)
rb.req = rb.req.WithContext(ctx)
}
// do request action
start := time.Now()
var resp *http.Response
if step.Request.HTTP2 {
resp, err = r.hrpRunner.http2Client.Do(rb.req)
} else {
resp, err = r.hrpRunner.httpClient.Do(rb.req)
}
if err != nil {
return stepResult, errors.Wrap(err, "do request failed")
}
defer resp.Body.Close()
// decode response body in br/gzip/deflate formats
err = decodeResponseBody(resp)
if err != nil {
return stepResult, errors.Wrap(err, "decode response body failed")
}
// log & print response
if r.LogOn() {
if err := printResponse(resp); err != nil {
return stepResult, err
}
}
// new response object
respObj, err := newHttpResponseObject(r.hrpRunner.t, parser, resp)
if err != nil {
err = errors.Wrap(err, "init ResponseObject error")
return
}
stepResult.Elapsed = time.Since(start).Milliseconds()
if r.HTTPStatOn() {
// resp.Body has been ReadAll
httpStat.Finish()
stepResult.HttpStat = httpStat.Durations()
httpStat.Print()
}
// add response object to step variables, could be used in teardown hooks
stepVariables["hrp_step_response"] = respObj.respObjMeta
// deal with teardown hooks
for _, teardownHook := range step.TeardownHooks {
_, err = parser.Parse(teardownHook, stepVariables)
if err != nil {
return stepResult, errors.Wrap(err, "run teardown hooks failed")
}
}
sessionData.ReqResps.Request = rb.requestMap
sessionData.ReqResps.Response = builtin.FormatResponse(respObj.respObjMeta)
// extract variables from response
extractors := step.Extract
extractMapping := respObj.Extract(extractors)
stepResult.ExportVars = extractMapping
// override step variables with extracted variables
stepVariables = mergeVariables(stepVariables, extractMapping)
// validate response
err = respObj.Validate(step.Validators, stepVariables)
sessionData.Validators = respObj.validationResults
if err == nil {
sessionData.Success = true
stepResult.Success = true
}
stepResult.ContentSize = resp.ContentLength
stepResult.Data = sessionData
// update summary
r.summary.Records = append(r.summary.Records, stepResult)
r.summary.Stat.Total += 1
if stepResult.Success {
r.summary.Stat.Successes += 1
} else {
r.summary.Stat.Failures += 1
// update summary result to failed
r.summary.Success = false
}
return stepResult, err
}
func printRequest(req *http.Request) error {
reqContentType := req.Header.Get("Content-Type")
printBody := shouldPrintBody(reqContentType)
reqDump, err := httputil.DumpRequest(req, printBody)
if err != nil {
return errors.Wrap(err, "dump request failed")
}
fmt.Println("-------------------- request --------------------")
reqContent := string(reqDump)
if reqContentType != "" && !printBody {
reqContent += fmt.Sprintf("(request body omitted for Content-Type: %v)", reqContentType)
}
fmt.Println(reqContent)
return nil
}
func printf(format string, a ...interface{}) (n int, err error) {
return fmt.Fprintf(color.Output, format, a...)
}
func printResponse(resp *http.Response) error {
fmt.Println("==================== response ====================")
connectedVia := "plaintext"
if resp.TLS != nil {
switch resp.TLS.Version {
case tls.VersionTLS12:
connectedVia = "TLSv1.2"
case tls.VersionTLS13:
connectedVia = "TLSv1.3"
}
}
printf("%s %s\n", color.CyanString("Connected via"), color.BlueString("%s", connectedVia))
respContentType := resp.Header.Get("Content-Type")
printBody := shouldPrintBody(respContentType)
respDump, err := httputil.DumpResponse(resp, printBody)
if err != nil {
return errors.Wrap(err, "dump response failed")
}
respContent := string(respDump)
if respContentType != "" && !printBody {
respContent += fmt.Sprintf("(response body omitted for Content-Type: %v)", respContentType)
}
fmt.Println(respContent)
fmt.Println("--------------------------------------------------")
return nil
}
func decodeResponseBody(resp *http.Response) (err error) {
switch resp.Header.Get("Content-Encoding") {
case "br":
resp.Body = io.NopCloser(brotli.NewReader(resp.Body))
case "gzip":
resp.Body, err = gzip.NewReader(resp.Body)
if err != nil {
return err
}
resp.ContentLength = -1 // set to unknown to avoid Content-Length mismatched
case "deflate":
resp.Body, err = zlib.NewReader(resp.Body)
if err != nil {
return err
}
resp.ContentLength = -1 // set to unknown to avoid Content-Length mismatched
}
return nil
}
// shouldPrintBody return true if the Content-Type is printable
// including text/*, application/json, application/xml, application/www-form-urlencoded
func shouldPrintBody(contentType string) bool {
if strings.HasPrefix(contentType, "text/") {
return true
}
if strings.HasPrefix(contentType, "application/json") {
return true
}
if strings.HasPrefix(contentType, "application/xml") {
return true
}
if strings.HasPrefix(contentType, "application/x-www-form-urlencoded") {
return true
}
return false
}
// NewStep returns a new constructed teststep with specified step name.
func NewStep(name string) *StepRequest {
return &StepRequest{
step: &TStep{
Name: name,
Variables: make(map[string]interface{}),
},
}
}
type StepRequest struct {
step *TStep
}
// WithVariables sets variables for current teststep.
func (s *StepRequest) WithVariables(variables map[string]interface{}) *StepRequest {
s.step.Variables = variables
return s
}
// SetupHook adds a setup hook for current teststep.
func (s *StepRequest) SetupHook(hook string) *StepRequest {
s.step.SetupHooks = append(s.step.SetupHooks, hook)
return s
}
// HTTP2 enables HTTP/2 protocol
func (s *StepRequest) HTTP2() *StepRequest {
s.step.Request = &Request{
HTTP2: true,
}
return s
}
// GET makes a HTTP GET request.
func (s *StepRequest) GET(url string) *StepRequestWithOptionalArgs {
if s.step.Request != nil {
s.step.Request.Method = httpGET
s.step.Request.URL = url
} else {
s.step.Request = &Request{
Method: httpGET,
URL: url,
}
}
return &StepRequestWithOptionalArgs{
step: s.step,
}
}
// HEAD makes a HTTP HEAD request.
func (s *StepRequest) HEAD(url string) *StepRequestWithOptionalArgs {
if s.step.Request != nil {
s.step.Request.Method = httpHEAD
s.step.Request.URL = url
} else {
s.step.Request = &Request{
Method: httpHEAD,
URL: url,
}
}
return &StepRequestWithOptionalArgs{
step: s.step,
}
}
// POST makes a HTTP POST request.
func (s *StepRequest) POST(url string) *StepRequestWithOptionalArgs {
if s.step.Request != nil {
s.step.Request.Method = httpPOST
s.step.Request.URL = url
} else {
s.step.Request = &Request{
Method: httpPOST,
URL: url,
}
}
return &StepRequestWithOptionalArgs{
step: s.step,
}
}
// PUT makes a HTTP PUT request.
func (s *StepRequest) PUT(url string) *StepRequestWithOptionalArgs {
if s.step.Request != nil {
s.step.Request.Method = httpPUT
s.step.Request.URL = url
} else {
s.step.Request = &Request{
Method: httpPUT,
URL: url,
}
}
return &StepRequestWithOptionalArgs{
step: s.step,
}
}
// DELETE makes a HTTP DELETE request.
func (s *StepRequest) DELETE(url string) *StepRequestWithOptionalArgs {
if s.step.Request != nil {
s.step.Request.Method = httpDELETE
s.step.Request.URL = url
} else {
s.step.Request = &Request{
Method: httpDELETE,
URL: url,
}
}
return &StepRequestWithOptionalArgs{
step: s.step,
}
}
// OPTIONS makes a HTTP OPTIONS request.
func (s *StepRequest) OPTIONS(url string) *StepRequestWithOptionalArgs {
if s.step.Request != nil {
s.step.Request.Method = httpOPTIONS
s.step.Request.URL = url
} else {
s.step.Request = &Request{
Method: httpOPTIONS,
URL: url,
}
}
return &StepRequestWithOptionalArgs{
step: s.step,
}
}
// PATCH makes a HTTP PATCH request.
func (s *StepRequest) PATCH(url string) *StepRequestWithOptionalArgs {
if s.step.Request != nil {
s.step.Request.Method = httpPATCH
s.step.Request.URL = url
} else {
s.step.Request = &Request{
Method: httpPATCH,
URL: url,
}
}
return &StepRequestWithOptionalArgs{
step: s.step,
}
}
// CallRefCase calls a referenced testcase.
func (s *StepRequest) CallRefCase(tc ITestCase) *StepTestCaseWithOptionalArgs {
var err error
s.step.TestCase, err = tc.ToTestCase()
if err != nil {
log.Error().Err(err).Msg("failed to load testcase")
os.Exit(1)
}
return &StepTestCaseWithOptionalArgs{
step: s.step,
}
}
// CallRefAPI calls a referenced api.
func (s *StepRequest) CallRefAPI(api IAPI) *StepAPIWithOptionalArgs {
var err error
s.step.API, err = api.ToAPI()
if err != nil {
log.Error().Err(err).Msg("failed to load api")
os.Exit(1)
}
return &StepAPIWithOptionalArgs{
step: s.step,
}
}
// StartTransaction starts a transaction.
func (s *StepRequest) StartTransaction(name string) *StepTransaction {
s.step.Transaction = &Transaction{
Name: name,
Type: transactionStart,
}
return &StepTransaction{
step: s.step,
}
}
// EndTransaction ends a transaction.
func (s *StepRequest) EndTransaction(name string) *StepTransaction {
s.step.Transaction = &Transaction{
Name: name,
Type: transactionEnd,
}
return &StepTransaction{
step: s.step,
}
}
// SetThinkTime sets think time.
func (s *StepRequest) SetThinkTime(time float64) *StepThinkTime {
s.step.ThinkTime = &ThinkTime{
Time: time,
}
return &StepThinkTime{
step: s.step,
}
}
// SetRendezvous creates a new rendezvous
func (s *StepRequest) SetRendezvous(name string) *StepRendezvous {
s.step.Rendezvous = &Rendezvous{
Name: name,
}
return &StepRendezvous{
step: s.step,
}
}
// WebSocket creates a new websocket action
func (s *StepRequest) WebSocket() *StepWebSocket {
s.step.WebSocket = &WebSocketAction{}
return &StepWebSocket{
step: s.step,
}
}
// StepRequestWithOptionalArgs implements IStep interface.
type StepRequestWithOptionalArgs struct {
step *TStep
}
// SetVerify sets whether to verify SSL for current HTTP request.
func (s *StepRequestWithOptionalArgs) SetVerify(verify bool) *StepRequestWithOptionalArgs {
s.step.Request.Verify = verify
return s
}
// SetTimeout sets timeout for current HTTP request.
func (s *StepRequestWithOptionalArgs) SetTimeout(timeout float32) *StepRequestWithOptionalArgs {
s.step.Request.Timeout = timeout
return s
}
// SetProxies sets proxies for current HTTP request.
func (s *StepRequestWithOptionalArgs) SetProxies(proxies map[string]string) *StepRequestWithOptionalArgs {
// TODO
return s
}
// SetAllowRedirects sets whether to allow redirects for current HTTP request.
func (s *StepRequestWithOptionalArgs) SetAllowRedirects(allowRedirects bool) *StepRequestWithOptionalArgs {
s.step.Request.AllowRedirects = allowRedirects
return s
}
// SetAuth sets auth for current HTTP request.
func (s *StepRequestWithOptionalArgs) SetAuth(auth map[string]string) *StepRequestWithOptionalArgs {
// TODO
return s
}
// WithParams sets HTTP request params for current step.
func (s *StepRequestWithOptionalArgs) WithParams(params map[string]interface{}) *StepRequestWithOptionalArgs {
s.step.Request.Params = params
return s
}
// WithHeaders sets HTTP request headers for current step.
func (s *StepRequestWithOptionalArgs) WithHeaders(headers map[string]string) *StepRequestWithOptionalArgs {
s.step.Request.Headers = headers
return s
}
// WithCookies sets HTTP request cookies for current step.
func (s *StepRequestWithOptionalArgs) WithCookies(cookies map[string]string) *StepRequestWithOptionalArgs {
s.step.Request.Cookies = cookies
return s
}
// WithBody sets HTTP request body for current step.
func (s *StepRequestWithOptionalArgs) WithBody(body interface{}) *StepRequestWithOptionalArgs {
s.step.Request.Body = body
return s
}
// TeardownHook adds a teardown hook for current teststep.
func (s *StepRequestWithOptionalArgs) TeardownHook(hook string) *StepRequestWithOptionalArgs {
s.step.TeardownHooks = append(s.step.TeardownHooks, hook)
return s
}
// Validate switches to step validation.
func (s *StepRequestWithOptionalArgs) Validate() *StepRequestValidation {
return &StepRequestValidation{
step: s.step,
}
}
// Extract switches to step extraction.
func (s *StepRequestWithOptionalArgs) Extract() *StepRequestExtraction {
s.step.Extract = make(map[string]string)
return &StepRequestExtraction{
step: s.step,
}
}
func (s *StepRequestWithOptionalArgs) Name() string {
if s.step.Name != "" {
return s.step.Name
}
return fmt.Sprintf("%v %s", s.step.Request.Method, s.step.Request.URL)
}
func (s *StepRequestWithOptionalArgs) Type() StepType {
return StepType(fmt.Sprintf("request-%v", s.step.Request.Method))
}
func (s *StepRequestWithOptionalArgs) Struct() *TStep {
return s.step
}
func (s *StepRequestWithOptionalArgs) Run(r *SessionRunner) (*StepResult, error) {
return runStepRequest(r, s.step)
}
// StepRequestExtraction implements IStep interface.
type StepRequestExtraction struct {
step *TStep
}
// WithJmesPath sets the JMESPath expression to extract from the response.
func (s *StepRequestExtraction) WithJmesPath(jmesPath string, varName string) *StepRequestExtraction {
s.step.Extract[varName] = jmesPath
return s
}
// Validate switches to step validation.
func (s *StepRequestExtraction) Validate() *StepRequestValidation {
return &StepRequestValidation{
step: s.step,
}
}
func (s *StepRequestExtraction) Name() string {
return s.step.Name
}
func (s *StepRequestExtraction) Type() StepType {
if s.step.Request != nil {
return StepType(fmt.Sprintf("request-%v", s.step.Request.Method))
}
if s.step.WebSocket != nil {
return StepType(fmt.Sprintf("websocket-%v", s.step.WebSocket.Type))
}
return "extraction"
}
func (s *StepRequestExtraction) Struct() *TStep {
return s.step
}
func (s *StepRequestExtraction) Run(r *SessionRunner) (*StepResult, error) {
if s.step.Request != nil {
return runStepRequest(r, s.step)
}
if s.step.WebSocket != nil {
return runStepWebSocket(r, s.step)
}
return nil, errors.New("unexpected protocol type")
}
// StepRequestValidation implements IStep interface.
type StepRequestValidation struct {
step *TStep
}
func (s *StepRequestValidation) Name() string {
if s.step.Name != "" {
return s.step.Name
}
return fmt.Sprintf("%s %s", s.step.Request.Method, s.step.Request.URL)
}
func (s *StepRequestValidation) Type() StepType {
if s.step.Request != nil {
return StepType(fmt.Sprintf("request-%v", s.step.Request.Method))
}
if s.step.WebSocket != nil {
return StepType(fmt.Sprintf("websocket-%v", s.step.WebSocket.Type))
}
return "validation"
}
func (s *StepRequestValidation) Struct() *TStep {
return s.step
}
func (s *StepRequestValidation) Run(r *SessionRunner) (*StepResult, error) {
if s.step.Request != nil {
return runStepRequest(r, s.step)
}
if s.step.WebSocket != nil {
return runStepWebSocket(r, s.step)
}
return nil, errors.New("unexpected protocol type")
}
func (s *StepRequestValidation) AssertEqual(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,
Assert: "equals",
Expect: expected,
Message: msg,
}
s.step.Validators = append(s.step.Validators, v)
return s
}
func (s *StepRequestValidation) AssertGreater(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,
Assert: "greater_than",
Expect: expected,
Message: msg,
}
s.step.Validators = append(s.step.Validators, v)
return s
}
func (s *StepRequestValidation) AssertLess(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,
Assert: "less_than",
Expect: expected,
Message: msg,
}
s.step.Validators = append(s.step.Validators, v)
return s
}
func (s *StepRequestValidation) AssertGreaterOrEqual(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,
Assert: "greater_or_equals",
Expect: expected,
Message: msg,
}
s.step.Validators = append(s.step.Validators, v)
return s
}
func (s *StepRequestValidation) AssertLessOrEqual(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,
Assert: "less_or_equals",
Expect: expected,
Message: msg,
}
s.step.Validators = append(s.step.Validators, v)
return s
}
func (s *StepRequestValidation) AssertNotEqual(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,
Assert: "not_equal",
Expect: expected,
Message: msg,
}
s.step.Validators = append(s.step.Validators, v)
return s
}
func (s *StepRequestValidation) AssertContains(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,
Assert: "contains",
Expect: expected,
Message: msg,
}
s.step.Validators = append(s.step.Validators, v)
return s
}
func (s *StepRequestValidation) AssertTypeMatch(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,
Assert: "type_match",
Expect: expected,
Message: msg,
}
s.step.Validators = append(s.step.Validators, v)
return s
}
func (s *StepRequestValidation) AssertRegexp(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,
Assert: "regex_match",
Expect: expected,
Message: msg,
}
s.step.Validators = append(s.step.Validators, v)
return s
}
func (s *StepRequestValidation) AssertStartsWith(jmesPath string, expected interface{}, msg string) *StepRequestValidation {
v := Validator{
Check: jmesPath,