Repository navigation
Expand file tree
/
Copy pathassertions_test.go
More file actions
807 lines (748 loc) · 24.8 KB
/
Copy pathassertions_test.go
File metadata and controls
807 lines (748 loc) · 24.8 KB
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
package httpassert
import (
"errors"
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"testing"
)
func Test_AssertStatusOK(t *testing.T) {
t.Parallel()
testCases := []struct {
StatusCode int
Status string
OK bool
}{
{0, "UNKNOWN", false},
{100, "CONTINUE", false},
{200, "OK", true},
{201, "Created", true},
{204, "No Content", true},
{299, "Custom OK Response", true},
{300, "Multiple Choice", true},
{301, "Moved Permanently", true},
{307, "Temporary Redirect", true},
{399, "Custom Redirect", true},
{400, "Bad Request", false},
{401, "Unauthorized", false},
{429, "Too Many Requests", false},
{500, "Internal Server Error", false},
{914, "Custom Response", false},
}
ok := AssertStatusOK()
nok := AssertStatusNOK()
for _, tc := range testCases {
t.Run(strconv.Itoa(tc.StatusCode), func(t *testing.T) {
res := &Response{
Response: &http.Response{
StatusCode: tc.StatusCode,
Status: tc.Status,
},
}
// Exactly one of the two must hold, so each case checks both.
wantOK, wantNOK := "", fmt.Sprintf("nok: expected NOK, got %d (%q)", tc.StatusCode, tc.Status)
if !tc.OK {
wantOK, wantNOK = fmt.Sprintf("ok: expected OK, got %d (%q)", tc.StatusCode, tc.Status), ""
}
checkErr(t, "ok", check(ok, res), wantOK)
checkErr(t, "nok", check(nok, res), wantNOK)
})
}
}
// mustStatusAssertion builds an assertion from a spec the test author asserts
// is valid.
func mustStatusAssertion(t *testing.T, text string) Assertion {
t.Helper()
assertion, err := AssertStatus(text)
if err != nil {
t.Fatalf("AssertStatus(%q): unexpected error: %s", text, err)
}
return assertion
}
func Test_AssertStatus(t *testing.T) {
t.Parallel()
testCases := []struct {
StatusCode int
Status string
OK bool
}{
{0, "UNKNOWN", false},
{100, "CONTINUE", false},
{200, "OK", true},
{201, "Created", true},
{204, "No Content", true},
{299, "Custom OK Response", true},
{300, "Multiple Choice", false},
{301, "Moved Permanently", false},
{307, "Temporary Redirect", false},
{400, "Bad Request", false},
{429, "Too Many Requests", false},
{500, "Internal Server Error", false},
{914, "Custom Response", false},
}
// 599 appears in no case above, so that assertion must always fail; 200 and
// 429 appear in the table and must pass for their own case only. It used to
// be 1, which is no longer expressible: a spec naming a code no response
// can carry is now rejected at the flag rather than failing at runtime.
assertions := map[int]Assertion{
599: mustStatusAssertion(t, "599"),
200: mustStatusAssertion(t, "200"),
429: mustStatusAssertion(t, "429"),
}
for _, tc := range testCases {
t.Run(strconv.Itoa(tc.StatusCode), func(t *testing.T) {
res := &Response{
Response: &http.Response{
StatusCode: tc.StatusCode,
Status: tc.Status,
},
}
for _, expected := range []int{599, 200, 429} {
want := ""
if tc.StatusCode != expected {
want = fmt.Sprintf("status: expected %d, got %d (%q)", expected, tc.StatusCode, tc.Status)
}
checkErr(t, fmt.Sprintf("expected %d", expected), check(assertions[expected], res), want)
}
})
}
}
func Test_AssertHeader(t *testing.T) {
t.Parallel()
testCases := []struct {
CaseName string
Header map[string][]string
ExpMissing bool
ExpEqualError string
ExpMatchError string
}{
{
CaseName: "No headers",
ExpMissing: true,
ExpEqualError: `header[taRgET]: expected "value", missing`,
ExpMatchError: `header[taRget]: expected to match "(?i)^val.*$", missing`,
},
{
CaseName: "Missing",
Header: map[string][]string{
"one": []string{"value"},
"two": []string{"value", "v", "2"},
},
ExpMissing: true,
ExpEqualError: `header[taRgET]: expected "value", missing`,
ExpMatchError: `header[taRget]: expected to match "(?i)^val.*$", missing`,
},
{
CaseName: "Present",
Header: map[string][]string{
"one": []string{"value"},
"Target": []string{""},
"two": []string{"value", "v", "2"},
},
ExpEqualError: `header[taRgET]: expected "value", got ""`,
ExpMatchError: `header[taRget]: expected to match "(?i)^val.*$", got ""`,
},
{
CaseName: "Non-empty but non-matching value",
Header: map[string][]string{
"one": []string{"value"},
"Target": []string{"v"},
"two": []string{"value", "v", "2"},
},
ExpEqualError: `header[taRgET]: expected "value", got "v"`,
ExpMatchError: `header[taRget]: expected to match "(?i)^val.*$", got "v"`,
},
{
CaseName: "Matching value",
Header: map[string][]string{
"one": []string{"value"},
"Target": []string{"vAl"},
"two": []string{"value", "v", "2"},
},
ExpEqualError: `header[taRgET]: expected "value", got "vAl"`,
},
{
CaseName: "Exact value",
Header: map[string][]string{
"one": []string{"value"},
"Target": []string{"value"},
"two": []string{"value", "v", "2"},
},
},
// Multiple values
{
CaseName: "Multiple: no matching value",
Header: map[string][]string{
"one": []string{"value"},
"Target": []string{"one", "two", "three"},
"two": []string{"value", "v", "2"},
},
ExpEqualError: `header[taRgET]: expected "value", got "one", "two", "three"`,
ExpMatchError: `header[taRget]: expected to match "(?i)^val.*$", got "one", "two", "three"`,
},
{
CaseName: "Multple: Matching value",
Header: map[string][]string{
"one": []string{"value"},
"Target": []string{"one", "two", "vAl", "three"},
"two": []string{"value", "v", "2"},
},
ExpEqualError: `header[taRgET]: expected "value", got "one", "two", "vAl", "three"`,
},
{
CaseName: "Multple: Exact value",
Header: map[string][]string{
"one": []string{"value"},
"Target": []string{"one", "vAl", "two", "value"},
"two": []string{"value", "v", "2"},
},
},
}
present := AssertHeaderPresent("taRgEt")
missing := AssertHeaderMissing("taRgEt")
equal := AssertHeaderEqual("taRgET", "value")
match, err := AssertHeaderMatch("taRget", `(?i)^val.*$`)
if err != nil {
t.Fatalf("unexpected error building the assertion: %s", err)
}
for _, tc := range testCases {
t.Run(tc.CaseName, func(t *testing.T) {
res := &Response{
Response: &http.Response{
Header: http.Header(tc.Header),
},
}
if tc.ExpMissing {
checkErr(t, "present", check(present, res), `header[taRgEt]: expected to be present, missing`)
checkErr(t, "missing", check(missing, res), "")
} else {
checkErr(t, "present", check(present, res), "")
// The values are echoed back, so match rather than pin them.
checkErrMatch(t, "missing", check(missing, res),
`header\[taRgEt\]: expected to be missing, got ".*"$`)
}
checkErr(t, "equal", check(equal, res), tc.ExpEqualError)
checkErr(t, "match", check(match, res), tc.ExpMatchError)
})
}
}
func Test_AssertBody(t *testing.T) {
t.Parallel()
testCases := []struct {
CaseName string
Body []byte
ExpEmptyError string
ExpEqualError string
ExpMatchError string
}{
{
CaseName: "Null body",
ExpEqualError: `body: expected "value", missing`,
ExpMatchError: `body: expected to match "(?i)^val.*$", missing`,
},
{
CaseName: "Empty body",
Body: []byte{},
ExpEqualError: `body: expected "value", missing`,
ExpMatchError: `body: expected to match "(?i)^val.*$", missing`,
},
{
CaseName: "Non-matching body",
Body: []byte("v"),
ExpEmptyError: `body: expected to be empty, got "v"`,
ExpEqualError: `body: expected "value", got "v"`,
ExpMatchError: `body: expected to match "(?i)^val.*$", got "v"`,
},
{
CaseName: "Matching body",
Body: []byte("vAl"),
ExpEmptyError: `body: expected to be empty, got "vAl"`,
ExpEqualError: `body: expected "value", got "vAl"`,
},
{
CaseName: "Exact body",
Body: []byte("value"),
ExpEmptyError: `body: expected to be empty, got "value"`,
},
}
empty := AssertBodyEmpty()
equal := AssertBodyEqual("value")
match, err := AssertBodyMatch(`(?i)^val.*$`)
if err != nil {
t.Fatalf("unexpected error building the assertion: %s", err)
}
for _, tc := range testCases {
t.Run(tc.CaseName, func(t *testing.T) {
res := &Response{BodyBytes: tc.Body}
checkErr(t, "empty", check(empty, res), tc.ExpEmptyError)
checkErr(t, "equal", check(equal, res), tc.ExpEqualError)
checkErr(t, "match", check(match, res), tc.ExpMatchError)
})
}
}
// Test_AssertBody_emptyIsAssertable covers the expectations that an empty body
// satisfies. They were unreachable while emptiness was checked before the
// comparison: the guard existed to word the failure nicely and ended up
// deciding it (#22).
func Test_AssertBody_emptyIsAssertable(t *testing.T) {
t.Parallel()
// Patterns an empty body legitimately matches. `.*` is the one a user is
// most likely to reach for, `^$` the one they mean.
patterns := []string{"^$", ".*", `\A\z`, ""}
t.Run("equal to the empty string", func(t *testing.T) {
res := &Response{BodyBytes: []byte{}}
checkErr(t, "equal", check(AssertBodyEqual(""), res), "")
// And a nil body, which is what a 204 produces.
checkErr(t, "equal, nil body", check(AssertBodyEqual(""), &Response{}), "")
})
for _, p := range patterns {
t.Run("matching "+strconv.Quote(p), func(t *testing.T) {
a, err := AssertBodyMatch(p)
if err != nil {
t.Fatalf("cannot build the assertion: %s", err)
}
checkErr(t, "match", check(a, &Response{BodyBytes: []byte{}}), "")
checkErr(t, "match, nil body", check(a, &Response{}), "")
})
}
// The verdict moved; the wording did not. A body that is empty when
// something was expected still reads as "missing" rather than `got ""`.
t.Run("an empty body still reports as missing", func(t *testing.T) {
res := &Response{BodyBytes: []byte{}}
checkErr(t, "equal", check(AssertBodyEqual("value"), res), `body: expected "value", missing`)
a, err := AssertBodyMatch("^value$")
if err != nil {
t.Fatalf("cannot build the assertion: %s", err)
}
checkErr(t, "match", check(a, res), `body: expected to match "^value$", missing`)
})
// The inverse must keep failing: a non-empty body is not the empty string.
t.Run("a non-empty body does not equal the empty string", func(t *testing.T) {
res := &Response{BodyBytes: []byte("x")}
checkErr(t, "equal", check(AssertBodyEqual(""), res), `body: expected "", got "x"`)
})
}
func Test_AssertRedirect(t *testing.T) {
t.Parallel()
testCases := []struct {
CaseName string
StatusCode int
Header map[string][]string
ExpEqualError string
ExpMatchError string
}{
{
CaseName: "No status, no headers",
ExpEqualError: `redirect: wrong HTTP status: got 0 ("0")`,
ExpMatchError: `redirect: wrong HTTP status: got 0 ("0")`,
},
{
CaseName: "OK status, no headers",
StatusCode: 200,
ExpEqualError: `redirect: wrong HTTP status: got 200 ("2_0_0")`,
ExpMatchError: `redirect: wrong HTTP status: got 200 ("2_0_0")`,
},
{
CaseName: "Error status, no headers",
StatusCode: 400,
ExpEqualError: `redirect: wrong HTTP status: got 400 ("4_0_0")`,
ExpMatchError: `redirect: wrong HTTP status: got 400 ("4_0_0")`,
},
{
CaseName: "3xx, no headers",
StatusCode: 300,
ExpEqualError: `redirect: no Location header`,
ExpMatchError: `redirect: no Location header`,
},
{
CaseName: "3xx, Location missing",
StatusCode: 301,
Header: map[string][]string{
"one": []string{"example.com/"},
"two": []string{"https://example.com/", "v", "2"},
},
ExpEqualError: `redirect: no Location header`,
ExpMatchError: `redirect: no Location header`,
},
{
CaseName: "3xx, Location empty",
StatusCode: 302,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{""},
"two": []string{"https://example.com/", "v", "2"},
},
ExpEqualError: `redirect: wrong Location: expected "https://example.com/", got ""`,
ExpMatchError: `redirect: wrong Location: expected to match "(?i)example\\.[a-z]*/$", got ""`,
},
{
CaseName: "3xx, Location mismatch",
StatusCode: 303,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{"exa"},
"two": []string{"https://example.com/", "v", "2"},
},
ExpEqualError: `redirect: wrong Location: expected "https://example.com/", got "exa"`,
ExpMatchError: `redirect: wrong Location: expected to match "(?i)example\\.[a-z]*/$", got "exa"`,
},
{
CaseName: "3xx, Location match",
StatusCode: 304,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{"eXaMpLe.Com/"},
"two": []string{"https://example.com/", "v", "2"},
},
ExpEqualError: `redirect: wrong Location: expected "https://example.com/", got "eXaMpLe.Com/"`,
},
{
CaseName: "3xx, Location equal",
StatusCode: 305,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{"https://example.com/"},
"two": []string{"example.com/", "v", "2"},
},
},
{
CaseName: "Wrong status, Location equal",
StatusCode: 204,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{"https://example.com/"},
"two": []string{"example.com/", "v", "2"},
},
ExpEqualError: `redirect: wrong HTTP status: got 204 ("2_0_4")`,
ExpMatchError: `redirect: wrong HTTP status: got 204 ("2_0_4")`,
},
// Multiple values
{
CaseName: "Multiple: 3xx, Location mismatch",
StatusCode: 306,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{"one", "two", "three"},
"two": []string{"https://example.com/", "v", "2"},
},
ExpEqualError: `redirect: wrong Location: expected "https://example.com/", got "one"`,
ExpMatchError: `redirect: wrong Location: expected to match "(?i)example\\.[a-z]*/$", got "one"`,
},
{
CaseName: "Multiple: 3xx, Location first match",
StatusCode: 307,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{"eXaMpLe.Com/", "two", "vAl", "three"},
"two": []string{"https://example.com/", "v", "2"},
},
ExpEqualError: `redirect: wrong Location: expected "https://example.com/", got "eXaMpLe.Com/"`,
},
{
CaseName: "Multiple: 3xx, Location second match",
StatusCode: 307,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{"one", "eXaMpLe.Com/", "vAl", "three"},
"two": []string{"https://example.com/", "v", "2"},
},
ExpEqualError: `redirect: wrong Location: expected "https://example.com/", got "one"`,
ExpMatchError: `redirect: wrong Location: expected to match "(?i)example\\.[a-z]*/$", got "one"`,
},
{
CaseName: "Multiple: 3xx, Location first equal",
StatusCode: 308,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{"https://example.com/", "vAl", "two", "example.com/"},
"two": []string{"https://example.com/", "v", "2"},
},
},
{
CaseName: "Multiple: 3xx, Location second equal",
StatusCode: 308,
Header: map[string][]string{
"one": []string{"example.com/"},
"Location": []string{"one", "https://example.com/", "two", "example.com/"},
"two": []string{"https://example.com/", "v", "2"},
},
ExpEqualError: `redirect: wrong Location: expected "https://example.com/", got "one"`,
ExpMatchError: `redirect: wrong Location: expected to match "(?i)example\\.[a-z]*/$", got "one"`,
},
}
equal := AssertRedirectEqual(`https://example.com/`)
match, err := AssertRedirectMatch(`(?i)example\.[a-z]*/$`)
if err != nil {
t.Fatalf("unexpected error building the assertion: %s", err)
}
for _, tc := range testCases {
t.Run(tc.CaseName, func(t *testing.T) {
res := &Response{
Response: &http.Response{
StatusCode: tc.StatusCode,
Status: strings.Join(strings.Split(strconv.Itoa(tc.StatusCode), ""), "_"),
Header: http.Header(tc.Header),
},
}
checkErr(t, "equal", check(equal, res), tc.ExpEqualError)
checkErr(t, "match", check(match, res), tc.ExpMatchError)
})
}
}
// Test_AssertBodyNotEmpty is the assertion --assert-body-empty=false selects.
// It had no constructor at all, which is why that flag registered nothing (#32).
func Test_AssertBodyNotEmpty(t *testing.T) {
t.Parallel()
tests := []struct {
Name string
Body []byte
Want string
}{
{Name: "a body satisfies it", Body: []byte("x")},
{
Name: "an empty body does not",
Body: []byte{},
Want: "body: expected to be non-empty, got nothing",
},
{
// What a 204 produces. It must fail the same way an empty slice
// does, not differently.
Name: "a nil body does not",
Want: "body: expected to be non-empty, got nothing",
},
{
// Whitespace is content. The assertion is about presence, not
// meaning, and trimming here would make it about both.
Name: "whitespace counts as a body",
Body: []byte(" "),
},
}
a := AssertBodyNotEmpty()
for _, tc := range tests {
t.Run(tc.Name, func(t *testing.T) {
checkErr(t, "not-empty", check(a, &Response{BodyBytes: tc.Body}), tc.Want)
})
}
// The pair must be exact opposites on every input, or =false means
// something subtly other than "not that".
t.Run("it is the exact inverse of AssertBodyEmpty", func(t *testing.T) {
empty := AssertBodyEmpty()
for _, body := range [][]byte{nil, {}, []byte(" "), []byte("x"), []byte("longer body")} {
res := &Response{BodyBytes: body}
if (check(empty, res) == nil) == (check(a, res) == nil) {
t.Errorf("both agree on %q; they must disagree", string(body))
}
}
})
}
// Test_AssertMatchConstructorsRejectBadPatterns covers the failure path the
// pattern-based constructors gained when they stopped panicking (#17).
func Test_AssertMatchConstructorsRejectBadPatterns(t *testing.T) {
t.Parallel()
constructors := map[string]func(string) (Assertion, error){
"AssertBodyMatch": AssertBodyMatch,
"AssertRedirectMatch": AssertRedirectMatch,
"AssertHeaderMatch": func(p string) (Assertion, error) { return AssertHeaderMatch("X-Any", p) },
}
for name, build := range constructors {
t.Run(name, func(t *testing.T) {
t.Run("unparseable pattern", func(t *testing.T) {
a, err := build("[unclosed")
if err == nil {
t.Fatal("expected an error for an unparseable pattern, got nil")
}
if a != nil {
t.Error("expected a nil Assertion alongside the error")
}
// The parser's own reason is passed through, not swallowed.
if !strings.Contains(err.Error(), "missing closing ]") {
t.Errorf("error = %q, want it to explain the syntax problem", err)
}
})
t.Run("valid pattern", func(t *testing.T) {
a, err := build(`^ok$`)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if a == nil {
t.Fatal("expected an Assertion")
}
})
})
}
}
// Test_AssertionIdentity pins the structure assertions gained when Assertion
// became an interface (#56): every assertion names its kind, and a failure
// carries the parts of its sentence as data rather than only the sentence.
//
// These are the fields #45 serializes, so a change here is a change to the
// machine-readable contract, not an internal detail. The Message is covered by
// the tables above and deliberately not repeated.
func Test_AssertionIdentity(t *testing.T) {
t.Parallel()
statusRes := func(code int, status string) *Response {
return &Response{
Response: &http.Response{StatusCode: code, Status: status},
}
}
headerRes := func(h http.Header) *Response {
return &Response{
Response: &http.Response{StatusCode: 200, Status: "200 OK", Header: h},
}
}
jq, err := AssertJQ(".n == 1")
if err != nil {
t.Fatalf("cannot build the jq assertion: %s", err)
}
tests := []struct {
Name string
Assertion Assertion
Res *Response
Kind AssertionKind
Target string
Expected any
Actual any
}{
{
Name: "ok", Assertion: AssertStatusOK(),
Res: statusRes(500, "500 Internal Server Error"),
Kind: KindStatusOK, Expected: "2xx-3xx", Actual: 500,
},
{
Name: "nok", Assertion: AssertStatusNOK(),
Res: statusRes(200, "200 OK"),
Kind: KindStatusNOK, Expected: "not 2xx-3xx", Actual: 200,
},
{
Name: "status", Assertion: mustStatusAssertion(t, "200"),
Res: statusRes(500, "500 Internal Server Error"),
Kind: KindStatus, Expected: "200", Actual: 500,
},
{
Name: "header present", Assertion: AssertHeaderPresent("X-Absent"),
Res: headerRes(http.Header{}),
Kind: KindHeader, Target: "X-Absent", Expected: "present",
},
{
Name: "header equal", Assertion: AssertHeaderEqual("X-A", "want"),
Res: headerRes(http.Header{"X-A": []string{"got"}}),
Kind: KindHeader, Target: "X-A", Expected: "want", Actual: []string{"got"},
},
{
Name: "body equal", Assertion: AssertBodyEqual("want"),
Res: &Response{BodyBytes: []byte("got")},
Kind: KindBody, Expected: "want", Actual: "got",
},
{
Name: "redirect", Assertion: AssertRedirectEqual("/there"),
Res: headerRes(http.Header{"Location": []string{"/elsewhere"}}),
// A 200 never reaches the Location comparison, so this is the
// precondition failure, which reports the status it wanted.
Kind: KindRedirect, Expected: "3xx", Actual: 200,
},
{
Name: "jq", Assertion: jq, Res: jqResponse(`{"n":2}`),
Kind: KindJQ, Target: ".n == 1", Expected: true, Actual: false,
},
}
for _, tc := range tests {
t.Run(tc.Name, func(t *testing.T) {
if got := tc.Assertion.Kind(); got != tc.Kind {
t.Errorf("Kind() = %q, want %q", got, tc.Kind)
}
f, err := tc.Assertion.Check(tc.Res)
if err != nil {
t.Fatalf("unexpected evaluation error: %s", err)
}
if f == nil {
t.Fatal("expected a Failure, got none")
}
// Kind is stamped by Check rather than written by each
// constructor, so the two can never drift apart.
if f.Kind != tc.Kind {
t.Errorf("Failure.Kind = %q, want %q", f.Kind, tc.Kind)
}
if f.Target != tc.Target {
t.Errorf("Target = %q, want %q", f.Target, tc.Target)
}
if !reflect.DeepEqual(f.Expected, tc.Expected) {
t.Errorf("Expected = %#v, want %#v", f.Expected, tc.Expected)
}
if !reflect.DeepEqual(f.Actual, tc.Actual) {
t.Errorf("Actual = %#v, want %#v", f.Actual, tc.Actual)
}
if f.Code == "" {
t.Error("Code is empty; structured consumers cannot classify the failure")
}
})
}
}
// Test_AssertionCheckSeparatesFailureFromError covers the distinction the
// interface exists to draw: a response that was read and disagreed is a
// Failure, and one that could not be evaluated at all is an error. Both still
// fail the run -- doOnce collects them into one list -- but only one of them
// has an Expected and an Actual to report.
func Test_AssertionCheckSeparatesFailureFromError(t *testing.T) {
t.Parallel()
t.Run("an assertion that holds reports neither", func(t *testing.T) {
f, err := AssertBodyEqual("same").Check(&Response{BodyBytes: []byte("same")})
if f != nil || err != nil {
t.Errorf("got (%v, %v), want (nil, nil)", f, err)
}
})
t.Run("an undecodable body is an error, not a Failure", func(t *testing.T) {
res := &Response{
Encoding: "compress",
DecodeErr: errors.New(`no decoder for "compress"`),
}
for name, a := range map[string]Assertion{
"body equal": AssertBodyEqual("x"),
"body empty": AssertBodyEmpty(),
} {
t.Run(name, func(t *testing.T) {
f, err := a.Check(res)
if f != nil {
t.Errorf("got a Failure %+v; an unevaluable assertion has no Expected/Actual", f)
}
if err == nil {
t.Fatal("expected an evaluation error, got nil")
}
var evaluation *EvaluationError
if !errors.As(err, &evaluation) {
t.Fatalf("error = %T, want *EvaluationError", err)
}
if evaluation.Code != EvaluationBodyDecode || evaluation.Encoding != "compress" {
t.Errorf("evaluation = %+v, want body-decode error for compress", evaluation)
}
})
}
})
t.Run("a status assertion is unaffected by an undecodable body", func(t *testing.T) {
res := &Response{
Response: &http.Response{StatusCode: 200, Status: "200 OK"},
Encoding: "compress",
DecodeErr: errors.New(`no decoder for "compress"`),
}
f, err := AssertStatusOK().Check(res)
if f != nil || err != nil {
t.Errorf("got (%v, %v), want (nil, nil)", f, err)
}
})
}
func Test_AssertionCheckStampsEvaluationErrorKind(t *testing.T) {
t.Parallel()
assertion := Must(AssertJQ(".healthy"))
failure, err := assertion.Check(jqResponse("not JSON"))
if failure != nil {
t.Fatalf("Failure = %+v, want nil for an evaluation error", failure)
}
var evaluation *EvaluationError
if !errors.As(err, &evaluation) {
t.Fatalf("error = %T %v, want *EvaluationError", err, err)
}
if evaluation.Code != EvaluationJSON || evaluation.Kind != assertion.Kind() {
t.Errorf("EvaluationError = %+v, want JSON error for %q assertion", evaluation, assertion.Kind())
}
}