-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsteps.go
1915 lines (1550 loc) · 61.9 KB
/
steps.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 gdutils
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/goccy/go-yaml"
ch "github.com/pawelWritesCode/charset"
"github.com/pawelWritesCode/df"
"moul.io/http2curl/v2"
"github.com/pawelWritesCode/gdutils/pkg/httpcache"
"github.com/pawelWritesCode/gdutils/pkg/mathutils"
"github.com/pawelWritesCode/gdutils/pkg/osutils"
"github.com/pawelWritesCode/gdutils/pkg/timeutils"
"github.com/pawelWritesCode/gdutils/pkg/types"
"github.com/pawelWritesCode/gdutils/pkg/validator"
)
// BodyHeaders is entity that holds information about request body and request headers.
type BodyHeaders struct {
// Body should contain HTTP(s) request body
Body any
// Headers should contain HTTP(s) request headers
Headers map[string]string
}
/*
RequestSendWithBodyAndHeaders sends HTTP(s) requests with provided body and headers.
Argument "method" indices HTTP request method for example: "POST", "GET" etc.
Argument "urlTemplate" should be full valid URL. May include template values.
Argument "bodyTemplate" should contain data (may include template values)
in JSON or YAML format with keys "body" and "headers".
*/
func (apiCtx *APIContext) RequestSendWithBodyAndHeaders(method, urlTemplate string, bodyAndHeaderTemplate string) error {
input, err := apiCtx.TemplateEngine.Replace(bodyAndHeaderTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'headers and body' template, err: %w", err)
}
url, err := apiCtx.TemplateEngine.Replace(urlTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'url' template, err: %w", err)
}
var bodyAndHeaders BodyHeaders
var dataFormat df.DataFormat
if df.IsJSON([]byte(input)) {
dataFormat = df.JSON
} else if df.IsYAML([]byte(input)) {
dataFormat = df.YAML
} else if df.IsXML([]byte(input)) {
return fmt.Errorf("this method does not support data in format: %s", df.XML)
} else {
return fmt.Errorf("could not recognize data format. Check your data, maybe you have typo somewhere or syntax error. Supported formats are: %s, %s", df.JSON, df.YAML)
}
switch dataFormat {
case df.JSON:
err = apiCtx.Serializers.JSON.Deserialize([]byte(input), &bodyAndHeaders)
case df.YAML:
err = apiCtx.Serializers.YAML.Deserialize([]byte(input), &bodyAndHeaders)
default:
err = fmt.Errorf("could not recognize data format. Check your data, maybe you have typo somewhere or syntax error. Supported formats are: %s, %s", df.JSON, df.YAML)
}
if err != nil {
return fmt.Errorf("can't deserialize 'headers and body' data, err: %w", err)
}
var reqBody []byte
switch dataFormat {
case df.JSON:
reqBody, err = apiCtx.Serializers.JSON.Serialize(bodyAndHeaders.Body)
case df.YAML:
reqBody, err = apiCtx.Serializers.YAML.Serialize(bodyAndHeaders.Body)
default:
err = fmt.Errorf("could not recognize data format. Check your data, maybe you have typo somewhere or syntax error. Supported formats are: %s, %s", df.JSON, df.YAML)
}
if err != nil {
return fmt.Errorf("can't serialize data to send it with HTTP(s) request, err: %w", err)
}
req, err := http.NewRequest(method, url, bytes.NewBuffer(reqBody))
if err != nil {
return fmt.Errorf("can't create request due to err: %w", err)
}
for headerName, headerValue := range bodyAndHeaders.Headers {
req.Header.Set(headerName, headerValue)
}
if apiCtx.Debugger.IsOn() {
command, _ := http2curl.GetCurlCommand(req)
apiCtx.Debugger.Print(command.String())
}
apiCtx.Cache.Save(httpcache.LastHTTPRequestTimestamp, time.Now())
resp, err := apiCtx.RequestDoer.Do(req)
if err != nil {
return fmt.Errorf("failed to send request %s %s, reason: %w", req.Method, req.URL.String(), err)
}
apiCtx.Cache.Save(httpcache.LastHTTPResponseTimestamp, time.Now())
apiCtx.Cache.Save(httpcache.LastHTTPResponseCacheKey, resp)
if apiCtx.Debugger.IsOn() {
respBody, _ := apiCtx.GetLastResponseBody()
apiCtx.Debugger.Print(fmt.Sprintf("%s %s (%d)", req.Method, req.URL.String(), resp.StatusCode))
apiCtx.Debugger.Print(string(respBody))
}
return nil
}
// RequestPrepare prepares new request and saves it in cache under cacheKey
func (apiCtx *APIContext) RequestPrepare(method, urlTemplate, cacheKey string) error {
url, err := apiCtx.TemplateEngine.Replace(urlTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'url' template, err: %w", err)
}
req, err := http.NewRequest(method, url, nil)
if err != nil {
return fmt.Errorf("can't create request due to err: %w", err)
}
apiCtx.Cache.Save(cacheKey, req)
return nil
}
// RequestSetHeaders sets provided headers for previously prepared request.
// incoming data should be in JSON or YAML format
func (apiCtx *APIContext) RequestSetHeaders(cacheKey, headersTemplate string) error {
headers, err := apiCtx.TemplateEngine.Replace(headersTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'headers' template, err: %w", err)
}
var headersMap map[string]string
headersBytes := []byte(headers)
if df.IsJSON(headersBytes) {
if err = apiCtx.Serializers.JSON.Deserialize(headersBytes, &headersMap); err != nil {
return fmt.Errorf("could not deserialize provided headers, err: %w", err)
}
} else if df.IsYAML(headersBytes) {
if err = apiCtx.Serializers.YAML.Deserialize(headersBytes, &headersMap); err != nil {
return fmt.Errorf("could not deserialize provided headers, err: %w", err)
}
} else if df.IsXML(headersBytes) {
return fmt.Errorf("this method does not support data in format: %s", df.XML)
} else {
return fmt.Errorf("could not recognize data format. Check your data, maybe you have typo somewhere or syntax error. Supported formats are: %s, %s", df.JSON, df.YAML)
}
req, err := apiCtx.GetPreparedRequest(cacheKey)
if err != nil {
return fmt.Errorf("could not obtain prepared request, err: %w", err)
}
for hName, hValue := range headersMap {
req.Header.Set(hName, hValue)
}
apiCtx.Cache.Save(cacheKey, req)
return nil
}
// RequestSetBody sets body for previously prepared request
// bodyTemplate may be in any format and accepts template values
func (apiCtx *APIContext) RequestSetBody(cacheKey, bodyTemplate string) error {
body, err := apiCtx.TemplateEngine.Replace(bodyTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'body' template, err: %w", err)
}
req, err := apiCtx.GetPreparedRequest(cacheKey)
if err != nil {
return fmt.Errorf("could not obtain prepared request, err: %w", err)
}
req.Body = ioutil.NopCloser(bytes.NewReader([]byte(body)))
apiCtx.Cache.Save(cacheKey, req)
return nil
}
// RequestSetCookies sets cookies for previously prepared request.
// cookiesTemplate should be YAML or JSON deserializable on []http.Cookie.
func (apiCtx *APIContext) RequestSetCookies(cacheKey, cookiesTemplate string) error {
var cookies []http.Cookie
userCookies, err := apiCtx.TemplateEngine.Replace(cookiesTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'cookies' template, err: %w", err)
}
req, err := apiCtx.GetPreparedRequest(cacheKey)
if err != nil {
return fmt.Errorf("could not obtain prepared request, err: %w", err)
}
userCookiesBytes := []byte(userCookies)
if df.IsJSON(userCookiesBytes) {
if err = apiCtx.Serializers.JSON.Deserialize(userCookiesBytes, &cookies); err != nil {
return fmt.Errorf("could not deserialize provided cookies, err: %w", err)
}
} else if df.IsYAML(userCookiesBytes) {
if err = apiCtx.Serializers.YAML.Deserialize(userCookiesBytes, &cookies); err != nil {
return fmt.Errorf("could not deserialize provided cookies, err: %w", err)
}
} else if df.IsXML(userCookiesBytes) {
return fmt.Errorf("this method does not support data in format: %s", df.XML)
} else {
return fmt.Errorf("could not recognize data format. Check your data, maybe you have typo somewhere or syntax error. Supported formats are: %s, %s", df.JSON, df.YAML)
}
for _, cookie := range cookies {
req.AddCookie(&cookie)
}
apiCtx.Cache.Save(cacheKey, req)
return nil
}
/*
RequestSetForm sets form for previously prepared request.
Internally method sets proper Content-Type: multipart/form-data header.
formTemplate should be YAML or JSON deserializable on map[string]string.
*/
func (apiCtx *APIContext) RequestSetForm(cacheKey, formTemplate string) error {
form, err := apiCtx.TemplateEngine.Replace(formTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'form' template, err: %w", err)
}
req, err := apiCtx.GetPreparedRequest(cacheKey)
if err != nil {
return fmt.Errorf("could not obtain prepared request, err: %w", err)
}
var formKeyVal map[string]string
formBytes := []byte(form)
if df.IsJSON(formBytes) {
err = apiCtx.Serializers.JSON.Deserialize(formBytes, &formKeyVal)
} else if df.IsYAML(formBytes) {
err = apiCtx.Serializers.YAML.Deserialize(formBytes, &formKeyVal)
} else if df.IsXML(formBytes) {
return fmt.Errorf("this method does not support data in format: %s", df.XML)
} else {
return fmt.Errorf("could not recognize data format. Check your data, maybe you have typo somewhere or syntax error. Supported formats are: %s, %s", df.JSON, df.YAML)
}
if err != nil {
return err
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for key, value := range formKeyVal {
reference, foundValidReference := apiCtx.fileRecognizer.Recognize(value)
if foundValidReference {
if reference.Reference.Type == osutils.ReferenceTypeOSPath {
file, err := os.Open(reference.Reference.Value)
if err != nil {
return fmt.Errorf("could not open file with reference %s, err: %w", reference.Reference.Value, err)
}
part, err := writer.CreateFormFile(key, filepath.Base(file.Name()))
if err != nil {
return fmt.Errorf("writer could not create form file, err: %w", err)
}
_, err = io.Copy(part, file)
if err != nil {
return fmt.Errorf("internal problem with copying, err: %w", err)
}
}
continue
}
if reference.IsFoundReference() && !foundValidReference {
return fmt.Errorf("form field '%s' holds invalid reference to file", key)
}
fw, err := writer.CreateFormField(key)
if err != nil {
return fmt.Errorf("writer could not create form field, err: %w", err)
}
_, err = io.Copy(fw, strings.NewReader(value))
if err != nil {
return fmt.Errorf("internal problem with copying, err: %w", err)
}
}
err = writer.Close()
if err != nil {
return fmt.Errorf("problem with closing writer, err: %w", err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))
apiCtx.Cache.Save(cacheKey, req)
return nil
}
// RequestSend sends previously prepared HTTP(s) request.
func (apiCtx *APIContext) RequestSend(cacheKey string) error {
req, err := apiCtx.GetPreparedRequest(cacheKey)
if err != nil {
return fmt.Errorf("could not obtain prepared request, err: %w", err)
}
if apiCtx.Debugger.IsOn() {
command, _ := http2curl.GetCurlCommand(req)
apiCtx.Debugger.Print(command.String())
}
apiCtx.Cache.Save(httpcache.LastHTTPRequestTimestamp, time.Now())
resp, err := apiCtx.RequestDoer.Do(req)
if err != nil {
return fmt.Errorf("failed to send request %s %s, reason: %w", req.Method, req.URL.String(), err)
}
apiCtx.Cache.Save(httpcache.LastHTTPResponseTimestamp, time.Now())
apiCtx.Cache.Save(httpcache.LastHTTPResponseCacheKey, resp)
if apiCtx.Debugger.IsOn() {
respBody, _ := apiCtx.GetLastResponseBody()
apiCtx.Debugger.Print(fmt.Sprintf("%s %s (%d)", req.Method, req.URL.String(), resp.StatusCode))
apiCtx.Debugger.Print(string(respBody))
}
return nil
}
// GenerateRandomInt generates random integer from provided range
// and preserve it under given cacheKey key.
func (apiCtx *APIContext) GenerateRandomInt(from, to int, cacheKey string) error {
randomInteger, err := mathutils.RandomInt(from, to)
if err != nil {
return fmt.Errorf("problem during generating pseudo random integer, err: %w", err)
}
apiCtx.Cache.Save(cacheKey, randomInteger)
return nil
}
// GenerateFloat64 generates random float from provided range
// and preserve it under given cacheKey key.
func (apiCtx *APIContext) GenerateFloat64(from, to float64, cacheKey string) error {
randFloat, err := mathutils.RandomFloat64(from, to)
if err != nil {
return fmt.Errorf("problem during generating pseudo random float, randomFloat err: %w", err)
}
apiCtx.Cache.Save(cacheKey, randFloat)
return nil
}
// GeneratorRandomRunes creates random runes generator func using provided charset
// return func creates runes from provided range and preserve it under given cacheKey
func (apiCtx *APIContext) GeneratorRandomRunes(charset string) func(from, to int, cacheKey string) error {
return func(from, to int, cacheKey string) error {
randInt, err := mathutils.RandomInt(from, to)
if err != nil {
return fmt.Errorf("problem during generating random runes, randomInt err: %w", err)
}
apiCtx.Cache.Save(cacheKey, string(ch.RandomRunes(randInt, []rune(charset))))
return nil
}
}
/*
GeneratorRandomSentence creates generator func for creating random sentences
each sentence has length from - to as provided in params and is saved in provided cacheKey
*/
func (apiCtx *APIContext) GeneratorRandomSentence(charset string, wordMinLength, wordMaxLength int) func(from, to int, cacheKey string) error {
return func(from, to int, cacheKey string) error {
if from > to {
return fmt.Errorf("could not generate sentence because of invalid range provided, from '%d' should not be greater than to: '%d'", from, to)
}
if wordMinLength > wordMaxLength {
return fmt.Errorf("could not generate sentence because of invalid range provided, wordMinLength '%d' should not be greater than wordMaxLength '%d'", wordMinLength, wordMaxLength)
}
numberOfWords, err := mathutils.RandomInt(from, to)
if err != nil {
return fmt.Errorf("problem during generating random sentence, randomInt err: %w", err)
}
sentence := ""
for i := 0; i < numberOfWords; i++ {
lengthOfWord, err := mathutils.RandomInt(wordMinLength, wordMaxLength)
if err != nil {
return fmt.Errorf("problem during generating random sentence, word randomInt err: %w", err)
}
word := ch.RandomRunes(lengthOfWord, []rune(charset))
if i == numberOfWords-1 {
sentence += string(word)
} else {
sentence += string(word) + " "
}
}
apiCtx.Cache.Save(cacheKey, sentence)
return nil
}
}
// GetTimeAndTravel accepts time object, move timeDuration in time and
// save it in cache under given cacheKey.
func (apiCtx *APIContext) GetTimeAndTravel(t time.Time, timeDirection timeutils.TimeDirection, timeDuration time.Duration, cacheKey string) error {
var newTime time.Time
switch timeDirection {
case timeutils.TimeDirectionBackward:
newTime = t.Add(-timeDuration)
case timeutils.TimeDirectionForward:
newTime = t.Add(timeDuration)
default:
return fmt.Errorf("unknown time direction: %s, allowed: %s, %s", timeDirection, timeutils.TimeDirectionForward, timeutils.TimeDirectionBackward)
}
apiCtx.Cache.Save(cacheKey, newTime)
return nil
}
// GenerateTimeAndTravel creates current time object, move timeDuration in time and
// save it in cache under given cacheKey.
func (apiCtx *APIContext) GenerateTimeAndTravel(timeDirection timeutils.TimeDirection, timeDuration time.Duration, cacheKey string) error {
return apiCtx.GetTimeAndTravel(time.Now(), timeDirection, timeDuration, cacheKey)
}
// AssertStatusCodeIs compare last response status code with given in argument.
func (apiCtx *APIContext) AssertStatusCodeIs(code int) error {
lastResponse, err := apiCtx.GetLastResponse()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response, err: %w", err)
}
if lastResponse.StatusCode != code {
return fmt.Errorf("expected status code %d, but got %d", code, lastResponse.StatusCode)
}
return nil
}
// AssertStatusCodeIsNot asserts that last response status code is not provided.
func (apiCtx *APIContext) AssertStatusCodeIsNot(code int) error {
lastResponse, err := apiCtx.GetLastResponse()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response, err: %w", err)
}
if lastResponse.StatusCode != code {
return nil
}
return fmt.Errorf("expected status code different than %d, but got %d", code, lastResponse.StatusCode)
}
// AssertResponseFormatIs checks whether last response body has given data format.
// Available data formats are listed in format package.
func (apiCtx *APIContext) AssertResponseFormatIs(dataFormat df.DataFormat) error {
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
switch dataFormat {
case df.JSON:
if df.IsJSON(body) {
return nil
}
return fmt.Errorf("response body doesn't have format %s", df.JSON)
case df.YAML:
if df.IsYAML(body) {
return nil
}
return fmt.Errorf("response body doesn't have format %s", df.YAML)
case df.XML:
if df.IsXML(body) {
return nil
}
return fmt.Errorf("response body doesn't have format %s", df.XML)
case df.HTML:
if df.IsHTML(body) {
return nil
}
return fmt.Errorf("response body doesn't have format %s", df.HTML)
case df.PlainText:
if df.IsPlainText(body) {
return nil
}
return fmt.Errorf("response body doesn't have format %s", df.PlainText)
default:
return fmt.Errorf("unknown last response body data format, available formats: %s, %s, %s, %s, %s",
df.JSON, df.YAML, df.XML, df.HTML, df.PlainText)
}
}
// AssertResponseFormatIsNot checks whether last response body has not given data format.
// Available data formats are listed in format package.
func (apiCtx *APIContext) AssertResponseFormatIsNot(dataFormat df.DataFormat) error {
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
switch dataFormat {
case df.JSON:
if df.IsJSON(body) {
return fmt.Errorf("response body has format %s", df.JSON)
}
return nil
case df.YAML:
if df.IsYAML(body) {
return fmt.Errorf("response body has format %s", df.YAML)
}
return nil
case df.XML:
if df.IsXML(body) {
return fmt.Errorf("response body has format %s", df.XML)
}
return nil
case df.HTML:
if df.IsHTML(body) {
return fmt.Errorf("response body has format %s", df.HTML)
}
return nil
case df.PlainText:
if df.IsPlainText(body) {
return fmt.Errorf("response body has format %s", df.PlainText)
}
return nil
default:
return fmt.Errorf("unknown last response body data format, available formats: %s, %s, %s, %s, %s",
df.JSON, df.YAML, df.XML, df.HTML, df.PlainText)
}
}
// AssertNodeExists checks whether last response body contains given node.
// expr should be valid according to injected PathFinder for given data format
func (apiCtx *APIContext) AssertNodeExists(dataFormat df.DataFormat, exprTemplate string) error {
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'form' template, err: %w", err)
}
_, err = apiCtx.getNode(body, expr, dataFormat, types.Any)
if err != nil {
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("last response body:\n\n%s", body))
}
return fmt.Errorf("node '%s' could not be found within last response body, reason: %w", expr, err)
}
return nil
}
// AssertNodeNotExists checks whether last response body does not contain given node.
// expr should be valid according to injected PathFinder for given data format
func (apiCtx *APIContext) AssertNodeNotExists(dataFormat df.DataFormat, exprTemplate string) error {
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'form' template, err: %w", err)
}
if body == nil || len(body) == 0 {
return fmt.Errorf("provided nil body")
}
_, err = apiCtx.getNode(body, expr, dataFormat, types.Any)
if err != nil {
return nil
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("last response body:\n\n%s", body))
}
return fmt.Errorf("%s node '%s' exists", dataFormat, expr)
}
// AssertNodesExist checks whether last request body has keys defined in string separated by comma
// nodeExprs should be valid according to injected PathFinder expressions separated by comma (,)
func (apiCtx *APIContext) AssertNodesExist(dataFormat df.DataFormat, expressionsTemplate string) error {
expressions, err := apiCtx.TemplateEngine.Replace(expressionsTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'form' template, err: %w", err)
}
keysSlice := strings.Split(expressions, ",")
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
errs := make([]error, 0, len(keysSlice))
for _, key := range keysSlice {
trimmedKey := strings.TrimSpace(key)
_, err := apiCtx.getNode(body, trimmedKey, dataFormat, types.Any)
if err != nil {
errs = append(errs, fmt.Errorf("node '%s', err: %s", trimmedKey, err.Error()))
}
}
if len(errs) > 0 {
var errString string
for _, err := range errs {
errString += fmt.Sprintf("%s\n", err)
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("last response body:\n\n%s", body))
}
return errors.New(errString)
}
return nil
}
// AssertNodeIsType checks whether node from last response body is of provided type.
// available types are listed in types subpackage.
// expr should be valid according to injected PathResolver.
func (apiCtx *APIContext) AssertNodeIsType(dataFormat df.DataFormat, exprTemplate string, inType types.DataType) error {
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'form' template, err: %w", err)
}
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
_, err = apiCtx.getNode(body, expr, dataFormat, inType)
return err
}
// AssertNodeIsNotType checks whether node from last response body is of provided type.
// available types are listed in types subpackage.
// expr should be valid according to injected PathResolver.
func (apiCtx *APIContext) AssertNodeIsNotType(dataFormat df.DataFormat, exprTemplate string, inType types.DataType) error {
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'form' template, err: %w", err)
}
var iNodeVal any
switch dataFormat {
case df.JSON:
iNodeVal, err = apiCtx.PathFinders.JSON.Find(expr, body)
if err != nil {
return fmt.Errorf("could not find node using provided expression: '%s', err: %w", expr, err)
}
if !(inType.IsValidJSONDataType() || inType.IsValidGoDataType()) {
return fmt.Errorf("%s is not any of JSON data types and is not any of Go Data types", inType)
}
if inType.IsValidJSONDataType() {
recognizedDataType := apiCtx.TypeMappers.JSON.Map(iNodeVal)
if recognizedDataType != inType {
return nil
}
return fmt.Errorf("node '%s' has type '%s', but expected not to be", expr, inType)
}
recognizedDataType := apiCtx.TypeMappers.GO.Map(iNodeVal)
if recognizedDataType != inType {
return nil
}
return fmt.Errorf("node '%s' has type '%s', but expected not to be", expr, inType)
case df.YAML:
iNodeVal, err = apiCtx.PathFinders.YAML.Find(expr, body)
if err != nil {
return fmt.Errorf("could not find node using provided expression: '%s', err: %w", expr, err)
}
if !(inType.IsValidYAMLDataType() || inType.IsValidGoDataType()) {
return fmt.Errorf("%s is not any of YAML data types and is not any of Go Data types", inType)
}
if inType.IsValidJSONDataType() {
recognizedDataType := apiCtx.TypeMappers.YAML.Map(iNodeVal)
if recognizedDataType != inType {
return nil
}
return fmt.Errorf("node '%s' has type '%s', but expected not to be", expr, inType)
}
recognizedDataType := apiCtx.TypeMappers.GO.Map(iNodeVal)
if recognizedDataType != inType {
return nil
}
return fmt.Errorf("node '%s' has type '%s', but expected not to be", expr, inType)
case df.XML:
return fmt.Errorf("this method does not support data in format: %s", df.XML)
default:
return fmt.Errorf("provided unknown format: %s, format should be one of : %s, %s",
dataFormat, df.JSON, df.YAML)
}
}
// AssertNodeIsTypeAndValue compares node value from expression to expected by user dataValue of given by user dataType
// Available data types are listed in switch section in each case directive.
// expr should be valid according to injected PathFinder for provided dataFormat.
func (apiCtx *APIContext) AssertNodeIsTypeAndValue(dataFormat df.DataFormat, exprTemplate string, dataType types.DataType, dataValue string) error {
nodeValueReplaced, err := apiCtx.TemplateEngine.Replace(dataValue, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'value' template, err: %w", err)
}
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'expression' template, err: %w", err)
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("provided expression template '%s' was replace to '%s'", exprTemplate, expr))
}
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
iValue, err := apiCtx.getNode(body, expr, dataFormat, dataType)
if err != nil {
return err
}
return assertNodeTypeAndValue(expr, dataType, iValue, nodeValueReplaced)
}
// AssertNodeIsTypeAndHasOneOfValues checks whether node value obtained using exprTemplate matches one of values held by
// valuesTemplates argument. Values should be separated by comma (,) and may contain template values.
func (apiCtx *APIContext) AssertNodeIsTypeAndHasOneOfValues(dataFormat df.DataFormat, exprTemplate string, dataType types.DataType, valuesTemplates string) error {
values, err := apiCtx.TemplateEngine.Replace(valuesTemplates, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'valuesTemplates' template, err: %w", err)
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("provided values template: '%s' was replace to: '%s'", valuesTemplates, values))
}
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'expression' template, err: %w", err)
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("provided expression template: '%s' was replace to: '%s'", exprTemplate, expr))
}
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
iValue, err := apiCtx.getNode(body, expr, dataFormat, dataType)
if err != nil {
return err
}
valuesSlice := strings.Split(values, ",")
valuesSliceTrimmed := make([]string, 0, len(valuesSlice))
for _, v := range valuesSlice {
valuesSliceTrimmed = append(valuesSliceTrimmed, strings.TrimSpace(v))
}
for _, value := range valuesSliceTrimmed {
if err = assertNodeTypeAndValue(expr, dataType, iValue, value); err == nil {
return nil
}
}
return fmt.Errorf("node '%s' doesn't contain any of: %#v", expr, valuesSliceTrimmed)
}
// AssertNodeContainsSubString AsserNodeContainsSubString checks whether value of last HTTP response node, obtained using exprTemplate
// is string type and contains given substring
func (apiCtx *APIContext) AssertNodeContainsSubString(dataFormat df.DataFormat, exprTemplate string, subTemplate string) error {
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'expr' template, err: %w", err)
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("provided expression template: '%s' was replace to: '%s'", exprTemplate, expr))
}
sub, err := apiCtx.TemplateEngine.Replace(subTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'sub' template, err: %w", err)
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("provided substring template: '%s' was replace to: '%s'", subTemplate, sub))
}
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
iValue, err := apiCtx.getNode(body, expr, dataFormat, types.String)
if err != nil {
return err
}
valueString, ok := iValue.(string)
if !ok {
return fmt.Errorf("node '%s' value detected as string, but can't be converted to string, err: %w", expr, err)
}
if !strings.Contains(valueString, sub) {
return fmt.Errorf("node '%s' string value doesn't contain any occurrence of '%s'", expr, sub)
}
return nil
}
// AssertNodeNotContainsSubString AsserNodeNotContainsSubString checks whether value of last HTTP response node, obtained using exprTemplate
// is string type and doesn't contain given substring
func (apiCtx *APIContext) AssertNodeNotContainsSubString(dataFormat df.DataFormat, exprTemplate string, subTemplate string) error {
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'expr' template, err: %w", err)
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("provided expression template: '%s' was replace to: '%s'", exprTemplate, expr))
}
sub, err := apiCtx.TemplateEngine.Replace(subTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'sub' template, err: %w", err)
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("provided substring template: '%s' was replace to: '%s'", subTemplate, sub))
}
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
iValue, err := apiCtx.getNode(body, expr, dataFormat, types.String)
if err != nil {
return err
}
valueString, ok := iValue.(string)
if !ok {
return fmt.Errorf("node '%s' value detected as string, but can't be converted to string, err: %w", expr, err)
}
if strings.Contains(valueString, sub) {
return fmt.Errorf("node '%s' string value contain some '%s', but expected not to", expr, sub)
}
return nil
}
// AssertNodeSliceLengthIs checks whether given key is slice and has given length
// expr should be valid according to injected PathFinder for provided dataFormat
func (apiCtx *APIContext) AssertNodeSliceLengthIs(dataFormat df.DataFormat, exprTemplate string, length int) error {
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'expression' template, err: %w", err)
}
iValue, err := apiCtx.getNode(body, expr, dataFormat, types.Any)
if err != nil {
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("last response body:\n\n%s", body))
}
return fmt.Errorf("node '%s', err: %s", expr, err.Error())
}
v := reflect.ValueOf(iValue)
if v.Kind() == reflect.Slice {
if v.Len() != length {
return fmt.Errorf("node '%s' contains slice(array) which has length: %d, but expected: %d", expr, v.Len(), length)
}
return nil
}
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("last response body:\n\n%s", body))
}
return fmt.Errorf("%s does not point at slice(array) in last HTTP(s) response body", expr)
}
// AssertNodeSliceLengthIsNot checks whether given key is slice and has not given length
// expr should be valid according to injected PathFinder for provided dataFormat
func (apiCtx *APIContext) AssertNodeSliceLengthIsNot(dataFormat df.DataFormat, exprTemplate string, length int) error {
body, err := apiCtx.GetLastResponseBody()
if err != nil {
return fmt.Errorf("could not obtain last HTTP(s) response body, err: %w", err)
}
expr, err := apiCtx.TemplateEngine.Replace(exprTemplate, apiCtx.Cache.All())
if err != nil {
return fmt.Errorf("template engine has problem with 'expression' template, err: %w", err)
}
iValue, err := apiCtx.getNode(body, expr, dataFormat, types.Any)
if err != nil {
if apiCtx.Debugger.IsOn() {
apiCtx.Debugger.Print(fmt.Sprintf("last response body:\n\n%s", body))
}
return fmt.Errorf("node '%s', err: %s", expr, err.Error())
}
v := reflect.ValueOf(iValue)
if v.Kind() == reflect.Slice {
if v.Len() != length {
return nil
}