Debian Codegraph @

td/example_test.go

raw
1 // Copyright (c) 2018-2025, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package td_test
8
9 import (
10 "bytes"
11 "encoding/json"
12 "errors"
13 "fmt"
14 "math"
15 "os"
16 "regexp"
17 "strconv"
18 "strings"
19 "testing"
20 "time"
21
22 "github.com/maxatome/go-testdeep/td"
23 )
24
25 func Example() {
26 t := &testing.T{}
27
28 dateToTime := func(str string) time.Time {
29 t, err := time.Parse(time.RFC3339, str)
30 if err != nil {
31 panic(err)
32 }
33 return t
34 }
35
36 type PetFamily uint8
37
38 const (
39 Canidae PetFamily = 1
40 Felidae PetFamily = 2
41 )
42
43 type Pet struct {
44 Name string
45 Birthday time.Time
46 Family PetFamily
47 }
48
49 type Master struct {
50 Name string
51 AnnualIncome int
52 Pets []*Pet
53 }
54
55 // Imagine a function returning a Master slice...
56 masters := []Master{
57 {
58 Name: "Bob Smith",
59 AnnualIncome: 25000,
60 Pets: []*Pet{
61 {
62 Name: "Quizz",
63 Birthday: dateToTime("2010-11-05T10:00:00Z"),
64 Family: Canidae,
65 },
66 {
67 Name: "Charlie",
68 Birthday: dateToTime("2013-05-11T08:00:00Z"),
69 Family: Canidae,
70 },
71 },
72 },
73 {
74 Name: "John Doe",
75 AnnualIncome: 38000,
76 Pets: []*Pet{
77 {
78 Name: "Coco",
79 Birthday: dateToTime("2015-08-05T18:00:00Z"),
80 Family: Felidae,
81 },
82 {
83 Name: "Lucky",
84 Birthday: dateToTime("2014-04-17T07:00:00Z"),
85 Family: Canidae,
86 },
87 },
88 },
89 }
90
91 // Let's check masters slice contents
92 ok := td.Cmp(t, masters, td.All(
93 td.Len(td.Gt(0)), // len(masters) should be > 0
94 td.ArrayEach(
95 // For each Master
96 td.Struct(Master{}, td.StructFields{
97 // Master Name should be composed of 2 words, with 1st letter uppercased
98 "Name": td.Re(`^[A-Z][a-z]+ [A-Z][a-z]+\z`),
99 // Annual income should be greater than $10000
100 "AnnualIncome": td.Gt(10000),
101 "Pets": td.ArrayEach(
102 // For each Pet
103 td.Struct(&Pet{}, td.StructFields{
104 // Pet Name should be composed of 1 word, with 1st letter uppercased
105 "Name": td.Re(`^[A-Z][a-z]+\z`),
106 "Birthday": td.All(
107 // Pet should be born after 2010, January 1st, but before now!
108 td.Between(dateToTime("2010-01-01T00:00:00Z"), time.Now()),
109 // AND minutes, seconds and nanoseconds should be 0
110 td.Code(func(t time.Time) bool {
111 return t.Minute() == 0 && t.Second() == 0 && t.Nanosecond() == 0
112 }),
113 ),
114 // Only dogs and cats allowed
115 "Family": td.Any(Canidae, Felidae),
116 }),
117 ),
118 }),
119 ),
120 ))
121 fmt.Println(ok)
122
123 // Output:
124 // true
125 }
126
127 func ExampleIgnore() {
128 t := &testing.T{}
129
130 ok := td.Cmp(t, []int{1, 2, 3},
131 td.Slice([]int{}, td.ArrayEntries{
132 0: 1,
133 1: td.Ignore(), // do not care about this entry
134 2: 3,
135 }))
136 fmt.Println(ok)
137
138 // Output:
139 // true
140 }
141
142 func ExampleAll() {
143 t := &testing.T{}
144
145 got := "foo/bar"
146
147 // Checks got string against:
148 // "o/b" regexp *AND* "bar" suffix *AND* exact "foo/bar" string
149 ok := td.Cmp(t,
150 got,
151 td.All(td.Re("o/b"), td.HasSuffix("bar"), "foo/bar"),
152 "checks value %s", got)
153 fmt.Println(ok)
154
155 // Checks got string against:
156 // "o/b" regexp *AND* "bar" suffix *AND* exact "fooX/Ybar" string
157 ok = td.Cmp(t,
158 got,
159 td.All(td.Re("o/b"), td.HasSuffix("bar"), "fooX/Ybar"),
160 "checks value %s", got)
161 fmt.Println(ok)
162
163 // When some operators or values have to be reused and mixed between
164 // several calls, Flatten can be used to avoid boring and
165 // inefficient []any copies:
166 regOps := td.Flatten([]td.TestDeep{td.Re("o/b"), td.Re(`^fo`), td.Re(`ar$`)})
167 ok = td.Cmp(t,
168 got,
169 td.All(td.HasPrefix("foo"), regOps, td.HasSuffix("bar")),
170 "checks all operators against value %s", got)
171 fmt.Println(ok)
172
173 // Output:
174 // true
175 // false
176 // true
177 }
178
179 func ExampleAny() {
180 t := &testing.T{}
181
182 got := "foo/bar"
183
184 // Checks got string against:
185 // "zip" regexp *OR* "bar" suffix
186 ok := td.Cmp(t, got, td.Any(td.Re("zip"), td.HasSuffix("bar")),
187 "checks value %s", got)
188 fmt.Println(ok)
189
190 // Checks got string against:
191 // "zip" regexp *OR* "foo" suffix
192 ok = td.Cmp(t, got, td.Any(td.Re("zip"), td.HasSuffix("foo")),
193 "checks value %s", got)
194 fmt.Println(ok)
195
196 // When some operators or values have to be reused and mixed between
197 // several calls, Flatten can be used to avoid boring and
198 // inefficient []any copies:
199 regOps := td.Flatten([]td.TestDeep{td.Re("a/c"), td.Re(`^xx`), td.Re(`ar$`)})
200 ok = td.Cmp(t,
201 got,
202 td.Any(td.HasPrefix("xxx"), regOps, td.HasSuffix("zip")),
203 "check at least one operator matches value %s", got)
204 fmt.Println(ok)
205
206 // Output:
207 // true
208 // false
209 // true
210 }
211
212 func ExampleArray_array() {
213 t := &testing.T{}
214
215 got := [3]int{42, 58, 26}
216
217 ok := td.Cmp(t, got,
218 td.Array([3]int{42}, td.ArrayEntries{1: 58, 2: td.Ignore()}),
219 "checks array %v", got)
220 fmt.Println("Simple array:", ok)
221
222 ok = td.Cmp(t, &got,
223 td.Array(&[3]int{42}, td.ArrayEntries{1: 58, 2: td.Ignore()}),
224 "checks array %v", got)
225 fmt.Println("Array pointer:", ok)
226
227 ok = td.Cmp(t, &got,
228 td.Array((*[3]int)(nil), td.ArrayEntries{0: 42, 1: 58, 2: td.Ignore()}),
229 "checks array %v", got)
230 fmt.Println("Array pointer, nil model:", ok)
231
232 // Output:
233 // Simple array: true
234 // Array pointer: true
235 // Array pointer, nil model: true
236 }
237
238 func ExampleArray_typedArray() {
239 t := &testing.T{}
240
241 type MyArray [3]int
242
243 got := MyArray{42, 58, 26}
244
245 ok := td.Cmp(t, got,
246 td.Array(MyArray{42}, td.ArrayEntries{1: 58, 2: td.Ignore()}),
247 "checks typed array %v", got)
248 fmt.Println("Typed array:", ok)
249
250 ok = td.Cmp(t, &got,
251 td.Array(&MyArray{42}, td.ArrayEntries{1: 58, 2: td.Ignore()}),
252 "checks pointer on typed array %v", got)
253 fmt.Println("Pointer on a typed array:", ok)
254
255 ok = td.Cmp(t, &got,
256 td.Array(&MyArray{}, td.ArrayEntries{0: 42, 1: 58, 2: td.Ignore()}),
257 "checks pointer on typed array %v", got)
258 fmt.Println("Pointer on a typed array, empty model:", ok)
259
260 ok = td.Cmp(t, &got,
261 td.Array((*MyArray)(nil), td.ArrayEntries{0: 42, 1: 58, 2: td.Ignore()}),
262 "checks pointer on typed array %v", got)
263 fmt.Println("Pointer on a typed array, nil model:", ok)
264
265 // Output:
266 // Typed array: true
267 // Pointer on a typed array: true
268 // Pointer on a typed array, empty model: true
269 // Pointer on a typed array, nil model: true
270 }
271
272 func ExampleArrayEach_array() {
273 t := &testing.T{}
274
275 got := [3]int{42, 58, 26}
276
277 ok := td.Cmp(t, got, td.ArrayEach(td.Between(25, 60)),
278 "checks each item of array %v is in [25 .. 60]", got)
279 fmt.Println(ok)
280
281 // Output:
282 // true
283 }
284
285 func ExampleArrayEach_typedArray() {
286 t := &testing.T{}
287
288 type MyArray [3]int
289
290 got := MyArray{42, 58, 26}
291
292 ok := td.Cmp(t, got, td.ArrayEach(td.Between(25, 60)),
293 "checks each item of typed array %v is in [25 .. 60]", got)
294 fmt.Println(ok)
295
296 ok = td.Cmp(t, &got, td.ArrayEach(td.Between(25, 60)),
297 "checks each item of typed array pointer %v is in [25 .. 60]", got)
298 fmt.Println(ok)
299
300 // Output:
301 // true
302 // true
303 }
304
305 func ExampleArrayEach_slice() {
306 t := &testing.T{}
307
308 got := []int{42, 58, 26}
309
310 ok := td.Cmp(t, got, td.ArrayEach(td.Between(25, 60)),
311 "checks each item of slice %v is in [25 .. 60]", got)
312 fmt.Println(ok)
313
314 // Output:
315 // true
316 }
317
318 func ExampleArrayEach_typedSlice() {
319 t := &testing.T{}
320
321 type MySlice []int
322
323 got := MySlice{42, 58, 26}
324
325 ok := td.Cmp(t, got, td.ArrayEach(td.Between(25, 60)),
326 "checks each item of typed slice %v is in [25 .. 60]", got)
327 fmt.Println(ok)
328
329 ok = td.Cmp(t, &got, td.ArrayEach(td.Between(25, 60)),
330 "checks each item of typed slice pointer %v is in [25 .. 60]", got)
331 fmt.Println(ok)
332
333 // Output:
334 // true
335 // true
336 }
337
338 func ExampleBag() {
339 t := &testing.T{}
340
341 got := []int{1, 3, 5, 8, 8, 1, 2}
342
343 // Matches as all items are present
344 ok := td.Cmp(t, got, td.Bag(1, 1, 2, 3, 5, 8, 8),
345 "checks all items are present, in any order")
346 fmt.Println(ok)
347
348 // Does not match as got contains 2 times 1 and 8, and these
349 // duplicates are not expected
350 ok = td.Cmp(t, got, td.Bag(1, 2, 3, 5, 8),
351 "checks all items are present, in any order")
352 fmt.Println(ok)
353
354 got = []int{1, 3, 5, 8, 2}
355
356 // Duplicates of 1 and 8 are expected but not present in got
357 ok = td.Cmp(t, got, td.Bag(1, 1, 2, 3, 5, 8, 8),
358 "checks all items are present, in any order")
359 fmt.Println(ok)
360
361 // Matches as all items are present
362 ok = td.Cmp(t, got, td.Bag(1, 2, 3, 5, td.Gt(7)),
363 "checks all items are present, in any order")
364 fmt.Println(ok)
365
366 // When expected is already a non-[]any slice, it cannot be
367 // flattened directly using expected... without copying it to a new
368 // []any slice, then use td.Flatten!
369 expected := []int{1, 2, 3, 5}
370 ok = td.Cmp(t, got, td.Bag(td.Flatten(expected), td.Gt(7)),
371 "checks all expected items are present, in any order")
372 fmt.Println(ok)
373
374 // Output:
375 // true
376 // false
377 // false
378 // true
379 // true
380 }
381
382 func ExampleBetween_int() {
383 t := &testing.T{}
384
385 got := 156
386
387 ok := td.Cmp(t, got, td.Between(154, 156),
388 "checks %v is in [154 .. 156]", got)
389 fmt.Println(ok)
390
391 // BoundsInIn is implicit
392 ok = td.Cmp(t, got, td.Between(154, 156, td.BoundsInIn),
393 "checks %v is in [154 .. 156]", got)
394 fmt.Println(ok)
395
396 ok = td.Cmp(t, got, td.Between(154, 156, td.BoundsInOut),
397 "checks %v is in [154 .. 156[", got)
398 fmt.Println(ok)
399
400 ok = td.Cmp(t, got, td.Between(154, 156, td.BoundsOutIn),
401 "checks %v is in ]154 .. 156]", got)
402 fmt.Println(ok)
403
404 ok = td.Cmp(t, got, td.Between(154, 156, td.BoundsOutOut),
405 "checks %v is in ]154 .. 156[", got)
406 fmt.Println(ok)
407
408 // Output:
409 // true
410 // true
411 // false
412 // true
413 // false
414 }
415
416 func ExampleBetween_string() {
417 t := &testing.T{}
418
419 got := "abc"
420
421 ok := td.Cmp(t, got, td.Between("aaa", "abc"),
422 `checks "%v" is in ["aaa" .. "abc"]`, got)
423 fmt.Println(ok)
424
425 // BoundsInIn is implicit
426 ok = td.Cmp(t, got, td.Between("aaa", "abc", td.BoundsInIn),
427 `checks "%v" is in ["aaa" .. "abc"]`, got)
428 fmt.Println(ok)
429
430 ok = td.Cmp(t, got, td.Between("aaa", "abc", td.BoundsInOut),
431 `checks "%v" is in ["aaa" .. "abc"[`, got)
432 fmt.Println(ok)
433
434 ok = td.Cmp(t, got, td.Between("aaa", "abc", td.BoundsOutIn),
435 `checks "%v" is in ]"aaa" .. "abc"]`, got)
436 fmt.Println(ok)
437
438 ok = td.Cmp(t, got, td.Between("aaa", "abc", td.BoundsOutOut),
439 `checks "%v" is in ]"aaa" .. "abc"[`, got)
440 fmt.Println(ok)
441
442 // Output:
443 // true
444 // true
445 // false
446 // true
447 // false
448 }
449
450 func ExampleBetween_time() {
451 t := &testing.T{}
452
453 before := time.Now()
454 occurredAt := time.Now()
455 after := time.Now()
456
457 ok := td.Cmp(t, occurredAt, td.Between(before, after))
458 fmt.Println("It occurred between before and after:", ok)
459
460 type MyTime time.Time
461 ok = td.Cmp(t, MyTime(occurredAt), td.Between(MyTime(before), MyTime(after)))
462 fmt.Println("Same for convertible MyTime type:", ok)
463
464 ok = td.Cmp(t, MyTime(occurredAt), td.Between(before, after))
465 fmt.Println("MyTime vs time.Time:", ok)
466
467 ok = td.Cmp(t, occurredAt, td.Between(before, 10*time.Second))
468 fmt.Println("Using a time.Duration as TO:", ok)
469
470 ok = td.Cmp(t, MyTime(occurredAt), td.Between(MyTime(before), 10*time.Second))
471 fmt.Println("Using MyTime as FROM and time.Duration as TO:", ok)
472
473 // Output:
474 // It occurred between before and after: true
475 // Same for convertible MyTime type: true
476 // MyTime vs time.Time: false
477 // Using a time.Duration as TO: true
478 // Using MyTime as FROM and time.Duration as TO: true
479 }
480
481 func ExampleCap() {
482 t := &testing.T{}
483
484 got := make([]int, 0, 12)
485
486 ok := td.Cmp(t, got, td.Cap(12), "checks %v capacity is 12", got)
487 fmt.Println(ok)
488
489 ok = td.Cmp(t, got, td.Cap(0), "checks %v capacity is 0", got)
490 fmt.Println(ok)
491
492 got = nil
493
494 ok = td.Cmp(t, got, td.Cap(0), "checks %v capacity is 0", got)
495 fmt.Println(ok)
496
497 // Output:
498 // true
499 // false
500 // true
501 }
502
503 func ExampleCap_operator() {
504 t := &testing.T{}
505
506 got := make([]int, 0, 12)
507
508 ok := td.Cmp(t, got, td.Cap(td.Between(10, 12)),
509 "checks %v capacity is in [10 .. 12]", got)
510 fmt.Println(ok)
511
512 ok = td.Cmp(t, got, td.Cap(td.Gt(10)),
513 "checks %v capacity is in [10 .. 12]", got)
514 fmt.Println(ok)
515
516 // Output:
517 // true
518 // true
519 }
520
521 func ExampleCatch() {
522 t := &testing.T{}
523
524 got := &struct {
525 Fullname string `json:"fullname"`
526 Age int `json:"age"`
527 }{
528 Fullname: "Bob",
529 Age: 42,
530 }
531
532 var age int
533 ok := td.Cmp(t, got,
534 td.JSON(`{"age":$1,"fullname":"Bob"}`,
535 td.Catch(&age, td.Between(40, 45))))
536 fmt.Println("check got age+fullname:", ok)
537 fmt.Println("caught age:", age)
538
539 // Output:
540 // check got age+fullname: true
541 // caught age: 42
542 }
543
544 func ExampleCode() {
545 t := &testing.T{}
546
547 got := "12"
548
549 ok := td.Cmp(t, got,
550 td.Code(func(num string) bool {
551 n, err := strconv.Atoi(num)
552 return err == nil && n > 10 && n < 100
553 }),
554 "checks string `%s` contains a number and this number is in ]10 .. 100[",
555 got)
556 fmt.Println(ok)
557
558 // Same with failure reason
559 ok = td.Cmp(t, got,
560 td.Code(func(num string) (bool, string) {
561 n, err := strconv.Atoi(num)
562 if err != nil {
563 return false, "not a number"
564 }
565 if n > 10 && n < 100 {
566 return true, ""
567 }
568 return false, "not in ]10 .. 100["
569 }),
570 "checks string `%s` contains a number and this number is in ]10 .. 100[",
571 got)
572 fmt.Println(ok)
573
574 // Same with failure reason thanks to error
575 ok = td.Cmp(t, got,
576 td.Code(func(num string) error {
577 n, err := strconv.Atoi(num)
578 if err != nil {
579 return err
580 }
581 if n > 10 && n < 100 {
582 return nil
583 }
584 return fmt.Errorf("%d not in ]10 .. 100[", n)
585 }),
586 "checks string `%s` contains a number and this number is in ]10 .. 100[",
587 got)
588 fmt.Println(ok)
589
590 // Output:
591 // true
592 // true
593 // true
594 }
595
596 func ExampleCode_custom() {
597 t := &testing.T{}
598
599 got := 123
600
601 ok := td.Cmp(t, got, td.Code(func(t *td.T, num int) {
602 t.Cmp(num, 123)
603 }))
604 fmt.Println("with one *td.T:", ok)
605
606 ok = td.Cmp(t, got, td.Code(func(assert, require *td.T, num int) {
607 assert.Cmp(num, 123)
608 require.Cmp(num, 123)
609 }))
610 fmt.Println("with assert & require *td.T:", ok)
611
612 // Output:
613 // with one *td.T: true
614 // with assert & require *td.T: true
615 }
616
617 func ExampleContains_arraySlice() {
618 t := &testing.T{}
619
620 ok := td.Cmp(t, [...]int{11, 22, 33, 44}, td.Contains(22))
621 fmt.Println("array contains 22:", ok)
622
623 ok = td.Cmp(t, [...]int{11, 22, 33, 44}, td.Contains(td.Between(20, 25)))
624 fmt.Println("array contains at least one item in [20 .. 25]:", ok)
625
626 ok = td.Cmp(t, []int{11, 22, 33, 44}, td.Contains(22))
627 fmt.Println("slice contains 22:", ok)
628
629 ok = td.Cmp(t, []int{11, 22, 33, 44}, td.Contains(td.Between(20, 25)))
630 fmt.Println("slice contains at least one item in [20 .. 25]:", ok)
631
632 ok = td.Cmp(t, []int{11, 22, 33, 44}, td.Contains([]int{22, 33}))
633 fmt.Println("slice contains the sub-slice [22, 33]:", ok)
634
635 // Output:
636 // array contains 22: true
637 // array contains at least one item in [20 .. 25]: true
638 // slice contains 22: true
639 // slice contains at least one item in [20 .. 25]: true
640 // slice contains the sub-slice [22, 33]: true
641 }
642
643 func ExampleContains_nil() {
644 t := &testing.T{}
645
646 num := 123
647 got := [...]*int{&num, nil}
648
649 ok := td.Cmp(t, got, td.Contains(nil))
650 fmt.Println("array contains untyped nil:", ok)
651
652 ok = td.Cmp(t, got, td.Contains((*int)(nil)))
653 fmt.Println("array contains *int nil:", ok)
654
655 ok = td.Cmp(t, got, td.Contains(td.Nil()))
656 fmt.Println("array contains Nil():", ok)
657
658 ok = td.Cmp(t, got, td.Contains((*byte)(nil)))
659 fmt.Println("array contains *byte nil:", ok) // types differ: *byte ≠ *int
660
661 // Output:
662 // array contains untyped nil: true
663 // array contains *int nil: true
664 // array contains Nil(): true
665 // array contains *byte nil: false
666 }
667
668 func ExampleContains_map() {
669 t := &testing.T{}
670
671 ok := td.Cmp(t,
672 map[string]int{"foo": 11, "bar": 22, "zip": 33}, td.Contains(22))
673 fmt.Println("map contains value 22:", ok)
674
675 ok = td.Cmp(t,
676 map[string]int{"foo": 11, "bar": 22, "zip": 33},
677 td.Contains(td.Between(20, 25)))
678 fmt.Println("map contains at least one value in [20 .. 25]:", ok)
679
680 // Output:
681 // map contains value 22: true
682 // map contains at least one value in [20 .. 25]: true
683 }
684
685 func ExampleContains_string() {
686 t := &testing.T{}
687
688 got := "foobar"
689
690 ok := td.Cmp(t, got, td.Contains("oob"), "checks %s", got)
691 fmt.Println("contains `oob` string:", ok)
692
693 ok = td.Cmp(t, got, td.Contains([]byte("oob")), "checks %s", got)
694 fmt.Println("contains `oob` []byte:", ok)
695
696 ok = td.Cmp(t, got, td.Contains('b'), "checks %s", got)
697 fmt.Println("contains 'b' rune:", ok)
698
699 ok = td.Cmp(t, got, td.Contains(byte('a')), "checks %s", got)
700 fmt.Println("contains 'a' byte:", ok)
701
702 ok = td.Cmp(t, got, td.Contains(td.Between('n', 'p')), "checks %s", got)
703 fmt.Println("contains at least one character ['n' .. 'p']:", ok)
704
705 // Output:
706 // contains `oob` string: true
707 // contains `oob` []byte: true
708 // contains 'b' rune: true
709 // contains 'a' byte: true
710 // contains at least one character ['n' .. 'p']: true
711 }
712
713 func ExampleContains_stringer() {
714 t := &testing.T{}
715
716 // bytes.Buffer implements fmt.Stringer
717 got := bytes.NewBufferString("foobar")
718
719 ok := td.Cmp(t, got, td.Contains("oob"), "checks %s", got)
720 fmt.Println("contains `oob` string:", ok)
721
722 ok = td.Cmp(t, got, td.Contains('b'), "checks %s", got)
723 fmt.Println("contains 'b' rune:", ok)
724
725 ok = td.Cmp(t, got, td.Contains(byte('a')), "checks %s", got)
726 fmt.Println("contains 'a' byte:", ok)
727
728 ok = td.Cmp(t, got, td.Contains(td.Between('n', 'p')), "checks %s", got)
729 fmt.Println("contains at least one character ['n' .. 'p']:", ok)
730
731 // Output:
732 // contains `oob` string: true
733 // contains 'b' rune: true
734 // contains 'a' byte: true
735 // contains at least one character ['n' .. 'p']: true
736 }
737
738 func ExampleContains_error() {
739 t := &testing.T{}
740
741 got := errors.New("foobar")
742
743 ok := td.Cmp(t, got, td.Contains("oob"), "checks %s", got)
744 fmt.Println("contains `oob` string:", ok)
745
746 ok = td.Cmp(t, got, td.Contains('b'), "checks %s", got)
747 fmt.Println("contains 'b' rune:", ok)
748
749 ok = td.Cmp(t, got, td.Contains(byte('a')), "checks %s", got)
750 fmt.Println("contains 'a' byte:", ok)
751
752 ok = td.Cmp(t, got, td.Contains(td.Between('n', 'p')), "checks %s", got)
753 fmt.Println("contains at least one character ['n' .. 'p']:", ok)
754
755 // Output:
756 // contains `oob` string: true
757 // contains 'b' rune: true
758 // contains 'a' byte: true
759 // contains at least one character ['n' .. 'p']: true
760 }
761
762 func ExampleContainsKey() {
763 t := &testing.T{}
764
765 ok := td.Cmp(t,
766 map[string]int{"foo": 11, "bar": 22, "zip": 33}, td.ContainsKey("foo"))
767 fmt.Println(`map contains key "foo":`, ok)
768
769 ok = td.Cmp(t,
770 map[int]bool{12: true, 24: false, 42: true, 51: false},
771 td.ContainsKey(td.Between(40, 50)))
772 fmt.Println("map contains at least a key in [40 .. 50]:", ok)
773
774 ok = td.Cmp(t,
775 map[string]int{"FOO": 11, "bar": 22, "zip": 33},
776 td.ContainsKey(td.Smuggle(strings.ToLower, "foo")))
777 fmt.Println(`map contains key "foo" without taking case into account:`, ok)
778
779 // Output:
780 // map contains key "foo": true
781 // map contains at least a key in [40 .. 50]: true
782 // map contains key "foo" without taking case into account: true
783 }
784
785 func ExampleContainsKey_nil() {
786 t := &testing.T{}
787
788 num := 1234
789 got := map[*int]bool{&num: false, nil: true}
790
791 ok := td.Cmp(t, got, td.ContainsKey(nil))
792 fmt.Println("map contains untyped nil key:", ok)
793
794 ok = td.Cmp(t, got, td.ContainsKey((*int)(nil)))
795 fmt.Println("map contains *int nil key:", ok)
796
797 ok = td.Cmp(t, got, td.ContainsKey(td.Nil()))
798 fmt.Println("map contains Nil() key:", ok)
799
800 ok = td.Cmp(t, got, td.ContainsKey((*byte)(nil)))
801 fmt.Println("map contains *byte nil key:", ok) // types differ: *byte ≠ *int
802
803 // Output:
804 // map contains untyped nil key: true
805 // map contains *int nil key: true
806 // map contains Nil() key: true
807 // map contains *byte nil key: false
808 }
809
810 func ExampleDelay() {
811 t := &testing.T{}
812
813 cmpNow := func(expected td.TestDeep) bool {
814 time.Sleep(time.Microsecond) // imagine a DB insert returning a CreatedAt
815 return td.Cmp(t, time.Now(), expected)
816 }
817
818 before := time.Now()
819
820 ok := cmpNow(td.Between(before, time.Now()))
821 fmt.Println("Between called before compare:", ok)
822
823 ok = cmpNow(td.Delay(func() td.TestDeep {
824 return td.Between(before, time.Now())
825 }))
826 fmt.Println("Between delayed until compare:", ok)
827
828 // Output:
829 // Between called before compare: false
830 // Between delayed until compare: true
831 }
832
833 func ExampleEmpty() {
834 t := &testing.T{}
835
836 ok := td.Cmp(t, nil, td.Empty()) // special case: nil is considered empty
837 fmt.Println(ok)
838
839 // fails, typed nil is not empty (expect for channel, map, slice or
840 // pointers on array, channel, map slice and strings)
841 ok = td.Cmp(t, (*int)(nil), td.Empty())
842 fmt.Println(ok)
843
844 ok = td.Cmp(t, "", td.Empty())
845 fmt.Println(ok)
846
847 // Fails as 0 is a number, so not empty. Use Zero() instead
848 ok = td.Cmp(t, 0, td.Empty())
849 fmt.Println(ok)
850
851 ok = td.Cmp(t, (map[string]int)(nil), td.Empty())
852 fmt.Println(ok)
853
854 ok = td.Cmp(t, map[string]int{}, td.Empty())
855 fmt.Println(ok)
856
857 ok = td.Cmp(t, ([]int)(nil), td.Empty())
858 fmt.Println(ok)
859
860 ok = td.Cmp(t, []int{}, td.Empty())
861 fmt.Println(ok)
862
863 ok = td.Cmp(t, []int{3}, td.Empty()) // fails, as not empty
864 fmt.Println(ok)
865
866 ok = td.Cmp(t, [3]int{}, td.Empty()) // fails, Empty() is not Zero()!
867 fmt.Println(ok)
868
869 // Output:
870 // true
871 // false
872 // true
873 // false
874 // true
875 // true
876 // true
877 // true
878 // false
879 // false
880 }
881
882 func ExampleEmpty_pointers() {
883 t := &testing.T{}
884
885 type MySlice []int
886
887 ok := td.Cmp(t, MySlice{}, td.Empty()) // Ptr() not needed
888 fmt.Println(ok)
889
890 ok = td.Cmp(t, &MySlice{}, td.Empty())
891 fmt.Println(ok)
892
893 l1 := &MySlice{}
894 l2 := &l1
895 l3 := &l2
896 ok = td.Cmp(t, &l3, td.Empty())
897 fmt.Println(ok)
898
899 // Works the same for array, map, channel and string
900
901 // But not for others types as:
902 type MyStruct struct {
903 Value int
904 }
905
906 ok = td.Cmp(t, &MyStruct{}, td.Empty()) // fails, use Zero() instead
907 fmt.Println(ok)
908
909 // Output:
910 // true
911 // true
912 // true
913 // false
914 }
915
916 func ExampleErrorIs() {
917 t := &testing.T{}
918
919 err1 := fmt.Errorf("failure1")
920 err2 := fmt.Errorf("failure2: %w", err1)
921 err3 := fmt.Errorf("failure3: %w", err2)
922 err := fmt.Errorf("failure4: %w", err3)
923
924 ok := td.Cmp(t, err, td.ErrorIs(err))
925 fmt.Println("error is itself:", ok)
926
927 ok = td.Cmp(t, err, td.ErrorIs(err1))
928 fmt.Println("error is also err1:", ok)
929
930 ok = td.Cmp(t, err1, td.ErrorIs(err))
931 fmt.Println("err1 is err:", ok)
932
933 // Output:
934 // error is itself: true
935 // error is also err1: true
936 // err1 is err: false
937 }
938
939 func ExampleFirst_classic() {
940 t := &testing.T{}
941
942 got := []int{-3, -2, -1, 0, 1, 2, 3}
943
944 ok := td.Cmp(t, got, td.First(td.Gt(0), 1))
945 fmt.Println("first positive number is 1:", ok)
946
947 isEven := func(x int) bool { return x%2 == 0 }
948
949 ok = td.Cmp(t, got, td.First(isEven, -2))
950 fmt.Println("first even number is -2:", ok)
951
952 ok = td.Cmp(t, got, td.First(isEven, td.Lt(0)))
953 fmt.Println("first even number is < 0:", ok)
954
955 ok = td.Cmp(t, got, td.First(isEven, td.Code(isEven)))
956 fmt.Println("first even number is well even:", ok)
957
958 // Output:
959 // first positive number is 1: true
960 // first even number is -2: true
961 // first even number is < 0: true
962 // first even number is well even: true
963 }
964
965 func ExampleFirst_empty() {
966 t := &testing.T{}
967
968 ok := td.Cmp(t, ([]int)(nil), td.First(td.Gt(0), td.Gt(0)))
969 fmt.Println("first in nil slice:", ok)
970
971 ok = td.Cmp(t, []int{}, td.First(td.Gt(0), td.Gt(0)))
972 fmt.Println("first in empty slice:", ok)
973
974 ok = td.Cmp(t, &[]int{}, td.First(td.Gt(0), td.Gt(0)))
975 fmt.Println("first in empty pointed slice:", ok)
976
977 ok = td.Cmp(t, [0]int{}, td.First(td.Gt(0), td.Gt(0)))
978 fmt.Println("first in empty array:", ok)
979
980 // Output:
981 // first in nil slice: false
982 // first in empty slice: false
983 // first in empty pointed slice: false
984 // first in empty array: false
985 }
986
987 func ExampleFirst_struct() {
988 t := &testing.T{}
989
990 type Person struct {
991 Fullname string `json:"fullname"`
992 Age int `json:"age"`
993 }
994
995 got := []*Person{
996 {
997 Fullname: "Bob Foobar",
998 Age: 42,
999 },
1000 {
1001 Fullname: "Alice Bingo",
1002 Age: 37,
1003 },
1004 }
1005
1006 ok := td.Cmp(t, got, td.First(
1007 td.Smuggle("Age", td.Gt(30)),
1008 td.Smuggle("Fullname", "Bob Foobar")))
1009 fmt.Println("first person.Age > 30 → Bob:", ok)
1010
1011 ok = td.Cmp(t, got, td.First(
1012 td.JSONPointer("/age", td.Gt(30)),
1013 td.SuperJSONOf(`{"fullname":"Bob Foobar"}`)))
1014 fmt.Println("first person.Age > 30 → Bob, using JSON:", ok)
1015
1016 ok = td.Cmp(t, got, td.First(
1017 td.JSONPointer("/age", td.Gt(30)),
1018 td.JSONPointer("/fullname", td.HasPrefix("Bob"))))
1019 fmt.Println("first person.Age > 30 → Bob, using JSONPointer:", ok)
1020
1021 // Output:
1022 // first person.Age > 30 → Bob: true
1023 // first person.Age > 30 → Bob, using JSON: true
1024 // first person.Age > 30 → Bob, using JSONPointer: true
1025 }
1026
1027 func ExampleFirst_json() {
1028 t := &testing.T{}
1029
1030 got := map[string]any{
1031 "values": []int{1, 2, 3, 4},
1032 }
1033 ok := td.Cmp(t, got, td.JSON(`{"values": First(Gt(2), 3)}`))
1034 fmt.Println("first number > 2:", ok)
1035
1036 got = map[string]any{
1037 "persons": []map[string]any{
1038 {"id": 1, "name": "Joe"},
1039 {"id": 2, "name": "Bob"},
1040 {"id": 3, "name": "Alice"},
1041 {"id": 4, "name": "Brian"},
1042 {"id": 5, "name": "Britt"},
1043 },
1044 }
1045 ok = td.Cmp(t, got, td.JSON(`
1046 {
1047 "persons": First(JSONPointer("/name", "Brian"), {"id": 4, "name": "Brian"})
1048 }`))
1049 fmt.Println(`is "Brian" content OK:`, ok)
1050
1051 ok = td.Cmp(t, got, td.JSON(`
1052 {
1053 "persons": First(JSONPointer("/name", "Brian"), JSONPointer("/id", 4))
1054 }`))
1055 fmt.Println(`ID of "Brian" is 4:`, ok)
1056
1057 // Output:
1058 // first number > 2: true
1059 // is "Brian" content OK: true
1060 // ID of "Brian" is 4: true
1061 }
1062
1063 func ExampleGrep_classic() {
1064 t := &testing.T{}
1065
1066 got := []int{-3, -2, -1, 0, 1, 2, 3}
1067
1068 ok := td.Cmp(t, got, td.Grep(td.Gt(0), []int{1, 2, 3}))
1069 fmt.Println("check positive numbers:", ok)
1070
1071 isEven := func(x int) bool { return x%2 == 0 }
1072
1073 ok = td.Cmp(t, got, td.Grep(isEven, []int{-2, 0, 2}))
1074 fmt.Println("even numbers are -2, 0 and 2:", ok)
1075
1076 ok = td.Cmp(t, got, td.Grep(isEven, td.Set(0, 2, -2)))
1077 fmt.Println("even numbers are also 0, 2 and -2:", ok)
1078
1079 ok = td.Cmp(t, got, td.Grep(isEven, td.ArrayEach(td.Code(isEven))))
1080 fmt.Println("even numbers are each even:", ok)
1081
1082 // Output:
1083 // check positive numbers: true
1084 // even numbers are -2, 0 and 2: true
1085 // even numbers are also 0, 2 and -2: true
1086 // even numbers are each even: true
1087 }
1088
1089 func ExampleGrep_nil() {
1090 t := &testing.T{}
1091
1092 var got []int
1093 ok := td.Cmp(t, got, td.Grep(td.Gt(0), ([]int)(nil)))
1094 fmt.Println("typed []int nil:", ok)
1095
1096 ok = td.Cmp(t, got, td.Grep(td.Gt(0), ([]string)(nil)))
1097 fmt.Println("typed []string nil:", ok)
1098
1099 ok = td.Cmp(t, got, td.Grep(td.Gt(0), td.Nil()))
1100 fmt.Println("td.Nil:", ok)
1101
1102 ok = td.Cmp(t, got, td.Grep(td.Gt(0), []int{}))
1103 fmt.Println("empty non-nil slice:", ok)
1104
1105 // Output:
1106 // typed []int nil: true
1107 // typed []string nil: false
1108 // td.Nil: true
1109 // empty non-nil slice: false
1110 }
1111
1112 func ExampleGrep_struct() {
1113 t := &testing.T{}
1114
1115 type Person struct {
1116 Fullname string `json:"fullname"`
1117 Age int `json:"age"`
1118 }
1119
1120 got := []*Person{
1121 {
1122 Fullname: "Bob Foobar",
1123 Age: 42,
1124 },
1125 {
1126 Fullname: "Alice Bingo",
1127 Age: 27,
1128 },
1129 }
1130
1131 ok := td.Cmp(t, got, td.Grep(
1132 td.Smuggle("Age", td.Gt(30)),
1133 td.All(
1134 td.Len(1),
1135 td.ArrayEach(td.Smuggle("Fullname", "Bob Foobar")),
1136 )))
1137 fmt.Println("person.Age > 30 → only Bob:", ok)
1138
1139 ok = td.Cmp(t, got, td.Grep(
1140 td.JSONPointer("/age", td.Gt(30)),
1141 td.JSON(`[ SuperMapOf({"fullname":"Bob Foobar"}) ]`)))
1142 fmt.Println("person.Age > 30 → only Bob, using JSON:", ok)
1143
1144 // Output:
1145 // person.Age > 30 → only Bob: true
1146 // person.Age > 30 → only Bob, using JSON: true
1147 }
1148
1149 func ExampleGrep_json() {
1150 t := &testing.T{}
1151
1152 got := map[string]any{
1153 "values": []int{1, 2, 3, 4},
1154 }
1155 ok := td.Cmp(t, got, td.JSON(`{"values": Grep(Gt(2), [3, 4])}`))
1156 fmt.Println("grep a number > 2:", ok)
1157
1158 got = map[string]any{
1159 "persons": []map[string]any{
1160 {"id": 1, "name": "Joe"},
1161 {"id": 2, "name": "Bob"},
1162 {"id": 3, "name": "Alice"},
1163 {"id": 4, "name": "Brian"},
1164 {"id": 5, "name": "Britt"},
1165 },
1166 }
1167 ok = td.Cmp(t, got, td.JSON(`
1168 {
1169 "persons": Grep(JSONPointer("/name", HasPrefix("Br")), [
1170 {"id": 4, "name": "Brian"},
1171 {"id": 5, "name": "Britt"},
1172 ])
1173 }`))
1174 fmt.Println(`grep "Br" prefix:`, ok)
1175
1176 // Output:
1177 // grep a number > 2: true
1178 // grep "Br" prefix: true
1179 }
1180
1181 func ExampleGt_int() {
1182 t := &testing.T{}
1183
1184 got := 156
1185
1186 ok := td.Cmp(t, got, td.Gt(155), "checks %v is > 155", got)
1187 fmt.Println(ok)
1188
1189 ok = td.Cmp(t, got, td.Gt(156), "checks %v is > 156", got)
1190 fmt.Println(ok)
1191
1192 // Output:
1193 // true
1194 // false
1195 }
1196
1197 func ExampleGt_string() {
1198 t := &testing.T{}
1199
1200 got := "abc"
1201
1202 ok := td.Cmp(t, got, td.Gt("abb"), `checks "%v" is > "abb"`, got)
1203 fmt.Println(ok)
1204
1205 ok = td.Cmp(t, got, td.Gt("abc"), `checks "%v" is > "abc"`, got)
1206 fmt.Println(ok)
1207
1208 // Output:
1209 // true
1210 // false
1211 }
1212
1213 func ExampleGte_int() {
1214 t := &testing.T{}
1215
1216 got := 156
1217
1218 ok := td.Cmp(t, got, td.Gte(156), "checks %v is ≥ 156", got)
1219 fmt.Println(ok)
1220
1221 ok = td.Cmp(t, got, td.Gte(155), "checks %v is ≥ 155", got)
1222 fmt.Println(ok)
1223
1224 ok = td.Cmp(t, got, td.Gte(157), "checks %v is ≥ 157", got)
1225 fmt.Println(ok)
1226
1227 // Output:
1228 // true
1229 // true
1230 // false
1231 }
1232
1233 func ExampleGte_string() {
1234 t := &testing.T{}
1235
1236 got := "abc"
1237
1238 ok := td.Cmp(t, got, td.Gte("abc"), `checks "%v" is ≥ "abc"`, got)
1239 fmt.Println(ok)
1240
1241 ok = td.Cmp(t, got, td.Gte("abb"), `checks "%v" is ≥ "abb"`, got)
1242 fmt.Println(ok)
1243
1244 ok = td.Cmp(t, got, td.Gte("abd"), `checks "%v" is ≥ "abd"`, got)
1245 fmt.Println(ok)
1246
1247 // Output:
1248 // true
1249 // true
1250 // false
1251 }
1252
1253 func ExampleIsa() {
1254 t := &testing.T{}
1255
1256 type TstStruct struct {
1257 Field int
1258 }
1259
1260 got := TstStruct{Field: 1}
1261
1262 ok := td.Cmp(t, got, td.Isa(TstStruct{}), "checks got is a TstStruct")
1263 fmt.Println(ok)
1264
1265 ok = td.Cmp(t, got, td.Isa(&TstStruct{}),
1266 "checks got is a pointer on a TstStruct")
1267 fmt.Println(ok)
1268
1269 ok = td.Cmp(t, &got, td.Isa(&TstStruct{}),
1270 "checks &got is a pointer on a TstStruct")
1271 fmt.Println(ok)
1272
1273 // Output:
1274 // true
1275 // false
1276 // true
1277 }
1278
1279 func ExampleIsa_interface() {
1280 t := &testing.T{}
1281
1282 got := bytes.NewBufferString("foobar")
1283
1284 ok := td.Cmp(t, got, td.Isa((*fmt.Stringer)(nil)),
1285 "checks got implements fmt.Stringer interface")
1286 fmt.Println(ok)
1287
1288 errGot := fmt.Errorf("An error #%d occurred", 123)
1289
1290 ok = td.Cmp(t, errGot, td.Isa((*error)(nil)),
1291 "checks errGot is a *error or implements error interface")
1292 fmt.Println(ok)
1293
1294 // As nil, is passed below, it is not an interface but nil… So it
1295 // does not match
1296 errGot = nil
1297
1298 ok = td.Cmp(t, errGot, td.Isa((*error)(nil)),
1299 "checks errGot is a *error or implements error interface")
1300 fmt.Println(ok)
1301
1302 // BUT if its address is passed, now it is OK as the types match
1303 ok = td.Cmp(t, &errGot, td.Isa((*error)(nil)),
1304 "checks &errGot is a *error or implements error interface")
1305 fmt.Println(ok)
1306
1307 // Output:
1308 // true
1309 // true
1310 // false
1311 // true
1312 }
1313
1314 func ExampleJSON_basic() {
1315 t := &testing.T{}
1316
1317 got := &struct {
1318 Fullname string `json:"fullname"`
1319 Age int `json:"age"`
1320 }{
1321 Fullname: "Bob",
1322 Age: 42,
1323 }
1324
1325 ok := td.Cmp(t, got, td.JSON(`{"age":42,"fullname":"Bob"}`))
1326 fmt.Println("check got with age then fullname:", ok)
1327
1328 ok = td.Cmp(t, got, td.JSON(`{"fullname":"Bob","age":42}`))
1329 fmt.Println("check got with fullname then age:", ok)
1330
1331 ok = td.Cmp(t, got, td.JSON(`
1332 // This should be the JSON representation of a struct
1333 {
1334 // A person:
1335 "fullname": "Bob", // The name of this person
1336 "age": 42 /* The age of this person:
1337 - 42 of course
1338 - to demonstrate a multi-lines comment */
1339 }`))
1340 fmt.Println("check got with nicely formatted and commented JSON:", ok)
1341
1342 ok = td.Cmp(t, got, td.JSON(`{"fullname":"Bob","age":42,"gender":"male"}`))
1343 fmt.Println("check got with gender field:", ok)
1344
1345 ok = td.Cmp(t, got, td.JSON(`{"fullname":"Bob"}`))
1346 fmt.Println("check got with fullname only:", ok)
1347
1348 ok = td.Cmp(t, true, td.JSON(`true`))
1349 fmt.Println("check boolean got is true:", ok)
1350
1351 ok = td.Cmp(t, 42, td.JSON(`42`))
1352 fmt.Println("check numeric got is 42:", ok)
1353
1354 got = nil
1355 ok = td.Cmp(t, got, td.JSON(`null`))
1356 fmt.Println("check nil got is null:", ok)
1357
1358 // Output:
1359 // check got with age then fullname: true
1360 // check got with fullname then age: true
1361 // check got with nicely formatted and commented JSON: true
1362 // check got with gender field: false
1363 // check got with fullname only: false
1364 // check boolean got is true: true
1365 // check numeric got is 42: true
1366 // check nil got is null: true
1367 }
1368
1369 func ExampleJSON_placeholders() {
1370 t := &testing.T{}
1371
1372 type Person struct {
1373 Fullname string `json:"fullname"`
1374 Age int `json:"age"`
1375 Children []*Person `json:"children,omitempty"`
1376 }
1377
1378 got := &Person{
1379 Fullname: "Bob Foobar",
1380 Age: 42,
1381 }
1382
1383 ok := td.Cmp(t, got, td.JSON(`{"age": $1, "fullname": $2}`, 42, "Bob Foobar"))
1384 fmt.Println("check got with numeric placeholders without operators:", ok)
1385
1386 ok = td.Cmp(t, got,
1387 td.JSON(`{"age": $1, "fullname": $2}`,
1388 td.Between(40, 45),
1389 td.HasSuffix("Foobar")))
1390 fmt.Println("check got with numeric placeholders:", ok)
1391
1392 ok = td.Cmp(t, got,
1393 td.JSON(`{"age": "$1", "fullname": "$2"}`,
1394 td.Between(40, 45),
1395 td.HasSuffix("Foobar")))
1396 fmt.Println("check got with double-quoted numeric placeholders:", ok)
1397
1398 ok = td.Cmp(t, got,
1399 td.JSON(`{"age": $age, "fullname": $name}`,
1400 td.Tag("age", td.Between(40, 45)),
1401 td.Tag("name", td.HasSuffix("Foobar"))))
1402 fmt.Println("check got with named placeholders:", ok)
1403
1404 got.Children = []*Person{
1405 {Fullname: "Alice", Age: 28},
1406 {Fullname: "Brian", Age: 22},
1407 }
1408 ok = td.Cmp(t, got,
1409 td.JSON(`{"age": $age, "fullname": $name, "children": $children}`,
1410 td.Tag("age", td.Between(40, 45)),
1411 td.Tag("name", td.HasSuffix("Foobar")),
1412 td.Tag("children", td.Bag(
1413 &Person{Fullname: "Brian", Age: 22},
1414 &Person{Fullname: "Alice", Age: 28},
1415 ))))
1416 fmt.Println("check got w/named placeholders, and children w/go structs:", ok)
1417
1418 ok = td.Cmp(t, got,
1419 td.JSON(`{"age": Between($1, $2), "fullname": HasSuffix($suffix), "children": Len(2)}`,
1420 40, 45,
1421 td.Tag("suffix", "Foobar")))
1422 fmt.Println("check got w/num & named placeholders:", ok)
1423
1424 // Output:
1425 // check got with numeric placeholders without operators: true
1426 // check got with numeric placeholders: true
1427 // check got with double-quoted numeric placeholders: true
1428 // check got with named placeholders: true
1429 // check got w/named placeholders, and children w/go structs: true
1430 // check got w/num & named placeholders: true
1431 }
1432
1433 func ExampleJSON_embedding() {
1434 t := &testing.T{}
1435
1436 got := &struct {
1437 Fullname string `json:"fullname"`
1438 Age int `json:"age"`
1439 }{
1440 Fullname: "Bob Foobar",
1441 Age: 42,
1442 }
1443
1444 ok := td.Cmp(t, got, td.JSON(`{"age": NotZero(), "fullname": NotEmpty()}`))
1445 fmt.Println("check got with simple operators:", ok)
1446
1447 ok = td.Cmp(t, got, td.JSON(`{"age": $^NotZero, "fullname": $^NotEmpty}`))
1448 fmt.Println("check got with operator shortcuts:", ok)
1449
1450 ok = td.Cmp(t, got, td.JSON(`
1451 {
1452 "age": Between(40, 42, "]]"), // in ]40; 42]
1453 "fullname": All(
1454 HasPrefix("Bob"),
1455 HasSuffix("bar") // ← comma is optional here
1456 )
1457 }`))
1458 fmt.Println("check got with complex operators:", ok)
1459
1460 ok = td.Cmp(t, got, td.JSON(`
1461 {
1462 "age": Between(40, 42, "]["), // in ]40; 42[ → 42 excluded
1463 "fullname": All(
1464 HasPrefix("Bob"),
1465 HasSuffix("bar"),
1466 )
1467 }`))
1468 fmt.Println("check got with complex operators:", ok)
1469
1470 ok = td.Cmp(t, got, td.JSON(`
1471 {
1472 "age": Between($1, $2, $3), // in ]40; 42]
1473 "fullname": All(
1474 HasPrefix($4),
1475 HasSuffix("bar") // ← comma is optional here
1476 )
1477 }`,
1478 40, 42, td.BoundsOutIn,
1479 "Bob"))
1480 fmt.Println("check got with complex operators, w/placeholder args:", ok)
1481
1482 // Output:
1483 // check got with simple operators: true
1484 // check got with operator shortcuts: true
1485 // check got with complex operators: true
1486 // check got with complex operators: false
1487 // check got with complex operators, w/placeholder args: true
1488 }
1489
1490 func ExampleJSON_rawStrings() {
1491 t := &testing.T{}
1492
1493 type details struct {
1494 Address string `json:"address"`
1495 Car string `json:"car"`
1496 }
1497
1498 got := &struct {
1499 Fullname string `json:"fullname"`
1500 Age int `json:"age"`
1501 Details details `json:"details"`
1502 }{
1503 Fullname: "Foo Bar",
1504 Age: 42,
1505 Details: details{
1506 Address: "something",
1507 Car: "Peugeot",
1508 },
1509 }
1510
1511 ok := td.Cmp(t, got,
1512 td.JSON(`
1513 {
1514 "fullname": HasPrefix("Foo"),
1515 "age": Between(41, 43),
1516 "details": SuperMapOf({
1517 "address": NotEmpty, // () are optional when no parameters
1518 "car": Any("Peugeot", "Tesla", "Jeep") // any of these
1519 })
1520 }`))
1521 fmt.Println("Original:", ok)
1522
1523 ok = td.Cmp(t, got,
1524 td.JSON(`
1525 {
1526 "fullname": "$^HasPrefix(\"Foo\")",
1527 "age": "$^Between(41, 43)",
1528 "details": "$^SuperMapOf({\n\"address\": NotEmpty,\n\"car\": Any(\"Peugeot\", \"Tesla\", \"Jeep\")\n})"
1529 }`))
1530 fmt.Println("JSON compliant:", ok)
1531
1532 ok = td.Cmp(t, got,
1533 td.JSON(`
1534 {
1535 "fullname": "$^HasPrefix(\"Foo\")",
1536 "age": "$^Between(41, 43)",
1537 "details": "$^SuperMapOf({
1538 \"address\": NotEmpty, // () are optional when no parameters
1539 \"car\": Any(\"Peugeot\", \"Tesla\", \"Jeep\") // any of these
1540 })"
1541 }`))
1542 fmt.Println("JSON multilines strings:", ok)
1543
1544 ok = td.Cmp(t, got,
1545 td.JSON(`
1546 {
1547 "fullname": "$^HasPrefix(r<Foo>)",
1548 "age": "$^Between(41, 43)",
1549 "details": "$^SuperMapOf({
1550 r<address>: NotEmpty, // () are optional when no parameters
1551 r<car>: Any(r<Peugeot>, r<Tesla>, r<Jeep>) // any of these
1552 })"
1553 }`))
1554 fmt.Println("Raw strings:", ok)
1555
1556 // Output:
1557 // Original: true
1558 // JSON compliant: true
1559 // JSON multilines strings: true
1560 // Raw strings: true
1561 }
1562
1563 func ExampleJSON_file() {
1564 t := &testing.T{}
1565
1566 got := &struct {
1567 Fullname string `json:"fullname"`
1568 Age int `json:"age"`
1569 Gender string `json:"gender"`
1570 }{
1571 Fullname: "Bob Foobar",
1572 Age: 42,
1573 Gender: "male",
1574 }
1575
1576 tmpDir, err := os.MkdirTemp("", "")
1577 if err != nil {
1578 t.Fatal(err)
1579 }
1580 defer os.RemoveAll(tmpDir) //nolint: errcheck // clean up
1581
1582 filename := tmpDir + "/test.json"
1583 if err = os.WriteFile(filename, []byte(`
1584 {
1585 "fullname": "$name",
1586 "age": "$age",
1587 "gender": "$gender"
1588 }`), 0644); err != nil {
1589 t.Fatal(err)
1590 }
1591
1592 // OK let's test with this file
1593 ok := td.Cmp(t, got,
1594 td.JSON(filename,
1595 td.Tag("name", td.HasPrefix("Bob")),
1596 td.Tag("age", td.Between(40, 45)),
1597 td.Tag("gender", td.Re(`^(male|female)\z`))))
1598 fmt.Println("Full match from file name:", ok)
1599
1600 // When the file is already open
1601 file, err := os.Open(filename)
1602 if err != nil {
1603 t.Fatal(err)
1604 }
1605 ok = td.Cmp(t, got,
1606 td.JSON(file,
1607 td.Tag("name", td.HasPrefix("Bob")),
1608 td.Tag("age", td.Between(40, 45)),
1609 td.Tag("gender", td.Re(`^(male|female)\z`))))
1610 fmt.Println("Full match from io.Reader:", ok)
1611
1612 // Output:
1613 // Full match from file name: true
1614 // Full match from io.Reader: true
1615 }
1616
1617 func ExampleJSONPointer_rfc6901() {
1618 t := &testing.T{}
1619
1620 got := json.RawMessage(`
1621 {
1622 "foo": ["bar", "baz"],
1623 "": 0,
1624 "a/b": 1,
1625 "c%d": 2,
1626 "e^f": 3,
1627 "g|h": 4,
1628 "i\\j": 5,
1629 "k\"l": 6,
1630 " ": 7,
1631 "m~n": 8
1632 }`)
1633
1634 expected := map[string]any{
1635 "foo": []any{"bar", "baz"},
1636 "": 0,
1637 "a/b": 1,
1638 "c%d": 2,
1639 "e^f": 3,
1640 "g|h": 4,
1641 `i\j`: 5,
1642 `k"l`: 6,
1643 " ": 7,
1644 "m~n": 8,
1645 }
1646 ok := td.Cmp(t, got, td.JSONPointer("", expected))
1647 fmt.Println("Empty JSON pointer means all:", ok)
1648
1649 ok = td.Cmp(t, got, td.JSONPointer(`/foo`, []any{"bar", "baz"}))
1650 fmt.Println("Extract `foo` key:", ok)
1651
1652 ok = td.Cmp(t, got, td.JSONPointer(`/foo/0`, "bar"))
1653 fmt.Println("First item of `foo` key slice:", ok)
1654
1655 ok = td.Cmp(t, got, td.JSONPointer(`/`, 0))
1656 fmt.Println("Empty key:", ok)
1657
1658 ok = td.Cmp(t, got, td.JSONPointer(`/a~1b`, 1))
1659 fmt.Println("Slash has to be escaped using `~1`:", ok)
1660
1661 ok = td.Cmp(t, got, td.JSONPointer(`/c%d`, 2))
1662 fmt.Println("% in key:", ok)
1663
1664 ok = td.Cmp(t, got, td.JSONPointer(`/e^f`, 3))
1665 fmt.Println("^ in key:", ok)
1666
1667 ok = td.Cmp(t, got, td.JSONPointer(`/g|h`, 4))
1668 fmt.Println("| in key:", ok)
1669
1670 ok = td.Cmp(t, got, td.JSONPointer(`/i\j`, 5))
1671 fmt.Println("Backslash in key:", ok)
1672
1673 ok = td.Cmp(t, got, td.JSONPointer(`/k"l`, 6))
1674 fmt.Println("Double-quote in key:", ok)
1675
1676 ok = td.Cmp(t, got, td.JSONPointer(`/ `, 7))
1677 fmt.Println("Space key:", ok)
1678
1679 ok = td.Cmp(t, got, td.JSONPointer(`/m~0n`, 8))
1680 fmt.Println("Tilde has to be escaped using `~0`:", ok)
1681
1682 // Output:
1683 // Empty JSON pointer means all: true
1684 // Extract `foo` key: true
1685 // First item of `foo` key slice: true
1686 // Empty key: true
1687 // Slash has to be escaped using `~1`: true
1688 // % in key: true
1689 // ^ in key: true
1690 // | in key: true
1691 // Backslash in key: true
1692 // Double-quote in key: true
1693 // Space key: true
1694 // Tilde has to be escaped using `~0`: true
1695 }
1696
1697 func ExampleJSONPointer_struct() {
1698 t := &testing.T{}
1699
1700 // Without json tags, encoding/json uses public fields name
1701 type Item struct {
1702 Name string
1703 Value int64
1704 Next *Item
1705 }
1706
1707 got := Item{
1708 Name: "first",
1709 Value: 1,
1710 Next: &Item{
1711 Name: "second",
1712 Value: 2,
1713 Next: &Item{
1714 Name: "third",
1715 Value: 3,
1716 },
1717 },
1718 }
1719
1720 ok := td.Cmp(t, got, td.JSONPointer("/Next/Next/Name", "third"))
1721 fmt.Println("3rd item name is `third`:", ok)
1722
1723 ok = td.Cmp(t, got, td.JSONPointer("/Next/Next/Value", td.Gte(int64(3))))
1724 fmt.Println("3rd item value is greater or equal than 3:", ok)
1725
1726 ok = td.Cmp(t, got,
1727 td.JSONPointer("/Next",
1728 td.JSONPointer("/Next",
1729 td.JSONPointer("/Value", td.Gte(int64(3))))))
1730 fmt.Println("3rd item value is still greater or equal than 3:", ok)
1731
1732 ok = td.Cmp(t, got, td.JSONPointer("/Next/Next/Next/Name", td.Ignore()))
1733 fmt.Println("4th item exists and has a name:", ok)
1734
1735 // Struct comparison work with or without pointer: &Item{…} works too
1736 ok = td.Cmp(t, got, td.JSONPointer("/Next/Next", Item{
1737 Name: "third",
1738 Value: 3,
1739 }))
1740 fmt.Println("3rd item full comparison:", ok)
1741
1742 // Output:
1743 // 3rd item name is `third`: true
1744 // 3rd item value is greater or equal than 3: true
1745 // 3rd item value is still greater or equal than 3: true
1746 // 4th item exists and has a name: false
1747 // 3rd item full comparison: true
1748 }
1749
1750 func ExampleJSONPointer_has_hasnt() {
1751 t := &testing.T{}
1752
1753 got := json.RawMessage(`
1754 {
1755 "name": "Bob",
1756 "age": 42,
1757 "children": [
1758 {
1759 "name": "Alice",
1760 "age": 16
1761 },
1762 {
1763 "name": "Britt",
1764 "age": 21,
1765 "children": [
1766 {
1767 "name": "John",
1768 "age": 1
1769 }
1770 ]
1771 }
1772 ]
1773 }`)
1774
1775 // Has Bob some children?
1776 ok := td.Cmp(t, got, td.JSONPointer("/children", td.Len(td.Gt(0))))
1777 fmt.Println("Bob has at least one child:", ok)
1778
1779 // But checking "children" exists is enough here
1780 ok = td.Cmp(t, got, td.JSONPointer("/children/0/children", td.Ignore()))
1781 fmt.Println("Alice has children:", ok)
1782
1783 ok = td.Cmp(t, got, td.JSONPointer("/children/1/children", td.Ignore()))
1784 fmt.Println("Britt has children:", ok)
1785
1786 // The reverse can be checked too
1787 ok = td.Cmp(t, got, td.Not(td.JSONPointer("/children/0/children", td.Ignore())))
1788 fmt.Println("Alice hasn't children:", ok)
1789
1790 ok = td.Cmp(t, got, td.Not(td.JSONPointer("/children/1/children", td.Ignore())))
1791 fmt.Println("Britt hasn't children:", ok)
1792
1793 // Output:
1794 // Bob has at least one child: true
1795 // Alice has children: false
1796 // Britt has children: true
1797 // Alice hasn't children: true
1798 // Britt hasn't children: false
1799 }
1800
1801 func ExampleList() {
1802 t := &testing.T{}
1803
1804 got := []int{1, 33, 8, 2}
1805
1806 // Matches as all items are present
1807 ok := td.Cmp(t, got, td.List(1, td.Between(32, 34), td.Gt(7), 2))
1808 fmt.Println("checks all items match, in this order:", ok)
1809
1810 // Does not match as got does not use the same order as expected
1811 ok = td.Cmp(t, got, td.List(1, td.Gt(7), 2, td.Between(32, 34)))
1812 fmt.Println("checks all items match, in wrong order:", ok)
1813
1814 // When expected is already a non-[]any slice, it cannot be
1815 // flattened directly using expected... without copying it to a new
1816 // []any slice, then use td.Flatten!
1817 expected := []int{1, 33, 8}
1818 ok = td.Cmp(t, got, td.List(td.Flatten(expected), td.Lte(2)))
1819 fmt.Println("checks all expected items are present + last one ≤ 2:", ok)
1820
1821 // Output:
1822 // checks all items match, in this order: true
1823 // checks all items match, in wrong order: false
1824 // checks all expected items are present + last one ≤ 2: true
1825 }
1826
1827 func ExampleKeys() {
1828 t := &testing.T{}
1829
1830 got := map[string]int{"foo": 1, "bar": 2, "zip": 3}
1831
1832 // Keys tests keys in an ordered manner
1833 ok := td.Cmp(t, got, td.Keys([]string{"bar", "foo", "zip"}))
1834 fmt.Println("All sorted keys are found:", ok)
1835
1836 // If the expected keys are not ordered, it fails
1837 ok = td.Cmp(t, got, td.Keys([]string{"zip", "bar", "foo"}))
1838 fmt.Println("All unsorted keys are found:", ok)
1839
1840 // To circumvent that, one can use Bag operator
1841 ok = td.Cmp(t, got, td.Keys(td.Bag("zip", "bar", "foo")))
1842 fmt.Println("All unsorted keys are found, with the help of Bag operator:", ok)
1843
1844 // Check that each key is 3 bytes long
1845 ok = td.Cmp(t, got, td.Keys(td.ArrayEach(td.Len(3))))
1846 fmt.Println("Each key is 3 bytes long:", ok)
1847
1848 // Output:
1849 // All sorted keys are found: true
1850 // All unsorted keys are found: false
1851 // All unsorted keys are found, with the help of Bag operator: true
1852 // Each key is 3 bytes long: true
1853 }
1854
1855 func ExampleLast_classic() {
1856 t := &testing.T{}
1857
1858 got := []int{-3, -2, -1, 0, 1, 2, 3}
1859
1860 ok := td.Cmp(t, got, td.Last(td.Lt(0), -1))
1861 fmt.Println("last negative number is -1:", ok)
1862
1863 isEven := func(x int) bool { return x%2 == 0 }
1864
1865 ok = td.Cmp(t, got, td.Last(isEven, 2))
1866 fmt.Println("last even number is 2:", ok)
1867
1868 ok = td.Cmp(t, got, td.Last(isEven, td.Gt(0)))
1869 fmt.Println("last even number is > 0:", ok)
1870
1871 ok = td.Cmp(t, got, td.Last(isEven, td.Code(isEven)))
1872 fmt.Println("last even number is well even:", ok)
1873
1874 // Output:
1875 // last negative number is -1: true
1876 // last even number is 2: true
1877 // last even number is > 0: true
1878 // last even number is well even: true
1879 }
1880
1881 func ExampleLast_empty() {
1882 t := &testing.T{}
1883
1884 ok := td.Cmp(t, ([]int)(nil), td.Last(td.Gt(0), td.Gt(0)))
1885 fmt.Println("last in nil slice:", ok)
1886
1887 ok = td.Cmp(t, []int{}, td.Last(td.Gt(0), td.Gt(0)))
1888 fmt.Println("last in empty slice:", ok)
1889
1890 ok = td.Cmp(t, &[]int{}, td.Last(td.Gt(0), td.Gt(0)))
1891 fmt.Println("last in empty pointed slice:", ok)
1892
1893 ok = td.Cmp(t, [0]int{}, td.Last(td.Gt(0), td.Gt(0)))
1894 fmt.Println("last in empty array:", ok)
1895
1896 // Output:
1897 // last in nil slice: false
1898 // last in empty slice: false
1899 // last in empty pointed slice: false
1900 // last in empty array: false
1901 }
1902
1903 func ExampleLast_struct() {
1904 t := &testing.T{}
1905
1906 type Person struct {
1907 Fullname string `json:"fullname"`
1908 Age int `json:"age"`
1909 }
1910
1911 got := []*Person{
1912 {
1913 Fullname: "Bob Foobar",
1914 Age: 42,
1915 },
1916 {
1917 Fullname: "Alice Bingo",
1918 Age: 37,
1919 },
1920 }
1921
1922 ok := td.Cmp(t, got, td.Last(
1923 td.Smuggle("Age", td.Gt(30)),
1924 td.Smuggle("Fullname", "Alice Bingo")))
1925 fmt.Println("last person.Age > 30 → Alice:", ok)
1926
1927 ok = td.Cmp(t, got, td.Last(
1928 td.JSONPointer("/age", td.Gt(30)),
1929 td.SuperJSONOf(`{"fullname":"Alice Bingo"}`)))
1930 fmt.Println("last person.Age > 30 → Alice, using JSON:", ok)
1931
1932 ok = td.Cmp(t, got, td.Last(
1933 td.JSONPointer("/age", td.Gt(30)),
1934 td.JSONPointer("/fullname", td.HasPrefix("Alice"))))
1935 fmt.Println("first person.Age > 30 → Alice, using JSONPointer:", ok)
1936
1937 // Output:
1938 // last person.Age > 30 → Alice: true
1939 // last person.Age > 30 → Alice, using JSON: true
1940 // first person.Age > 30 → Alice, using JSONPointer: true
1941 }
1942
1943 func ExampleLast_json() {
1944 t := &testing.T{}
1945
1946 got := map[string]any{
1947 "values": []int{1, 2, 3, 4},
1948 }
1949 ok := td.Cmp(t, got, td.JSON(`{"values": Last(Lt(3), 2)}`))
1950 fmt.Println("last number < 3:", ok)
1951
1952 got = map[string]any{
1953 "persons": []map[string]any{
1954 {"id": 1, "name": "Joe"},
1955 {"id": 2, "name": "Bob"},
1956 {"id": 3, "name": "Alice"},
1957 {"id": 4, "name": "Brian"},
1958 {"id": 5, "name": "Britt"},
1959 },
1960 }
1961 ok = td.Cmp(t, got, td.JSON(`
1962 {
1963 "persons": Last(JSONPointer("/name", "Brian"), {"id": 4, "name": "Brian"})
1964 }`))
1965 fmt.Println(`is "Brian" content OK:`, ok)
1966
1967 ok = td.Cmp(t, got, td.JSON(`
1968 {
1969 "persons": Last(JSONPointer("/name", "Brian"), JSONPointer("/id", 4))
1970 }`))
1971 fmt.Println(`ID of "Brian" is 4:`, ok)
1972
1973 // Output:
1974 // last number < 3: true
1975 // is "Brian" content OK: true
1976 // ID of "Brian" is 4: true
1977 }
1978
1979 func ExampleLax() {
1980 t := &testing.T{}
1981
1982 gotInt64 := int64(1234)
1983 gotInt32 := int32(1235)
1984
1985 type myInt uint16
1986 gotMyInt := myInt(1236)
1987
1988 expected := td.Between(1230, 1240) // int type here
1989
1990 ok := td.Cmp(t, gotInt64, td.Lax(expected))
1991 fmt.Println("int64 got between ints [1230 .. 1240]:", ok)
1992
1993 ok = td.Cmp(t, gotInt32, td.Lax(expected))
1994 fmt.Println("int32 got between ints [1230 .. 1240]:", ok)
1995
1996 ok = td.Cmp(t, gotMyInt, td.Lax(expected))
1997 fmt.Println("myInt got between ints [1230 .. 1240]:", ok)
1998
1999 // Output:
2000 // int64 got between ints [1230 .. 1240]: true
2001 // int32 got between ints [1230 .. 1240]: true
2002 // myInt got between ints [1230 .. 1240]: true
2003 }
2004
2005 func ExampleLen_slice() {
2006 t := &testing.T{}
2007
2008 got := []int{11, 22, 33}
2009
2010 ok := td.Cmp(t, got, td.Len(3), "checks %v len is 3", got)
2011 fmt.Println(ok)
2012
2013 ok = td.Cmp(t, got, td.Len(0), "checks %v len is 0", got)
2014 fmt.Println(ok)
2015
2016 got = nil
2017
2018 ok = td.Cmp(t, got, td.Len(0), "checks %v len is 0", got)
2019 fmt.Println(ok)
2020
2021 // Output:
2022 // true
2023 // false
2024 // true
2025 }
2026
2027 func ExampleLen_map() {
2028 t := &testing.T{}
2029
2030 got := map[int]bool{11: true, 22: false, 33: false}
2031
2032 ok := td.Cmp(t, got, td.Len(3), "checks %v len is 3", got)
2033 fmt.Println(ok)
2034
2035 ok = td.Cmp(t, got, td.Len(0), "checks %v len is 0", got)
2036 fmt.Println(ok)
2037
2038 got = nil
2039
2040 ok = td.Cmp(t, got, td.Len(0), "checks %v len is 0", got)
2041 fmt.Println(ok)
2042
2043 // Output:
2044 // true
2045 // false
2046 // true
2047 }
2048
2049 func ExampleLen_operatorSlice() {
2050 t := &testing.T{}
2051
2052 got := []int{11, 22, 33}
2053
2054 ok := td.Cmp(t, got, td.Len(td.Between(3, 8)),
2055 "checks %v len is in [3 .. 8]", got)
2056 fmt.Println(ok)
2057
2058 ok = td.Cmp(t, got, td.Len(td.Lt(5)), "checks %v len is < 5", got)
2059 fmt.Println(ok)
2060
2061 // Output:
2062 // true
2063 // true
2064 }
2065
2066 func ExampleLen_operatorMap() {
2067 t := &testing.T{}
2068
2069 got := map[int]bool{11: true, 22: false, 33: false}
2070
2071 ok := td.Cmp(t, got, td.Len(td.Between(3, 8)),
2072 "checks %v len is in [3 .. 8]", got)
2073 fmt.Println(ok)
2074
2075 ok = td.Cmp(t, got, td.Len(td.Gte(3)), "checks %v len is ≥ 3", got)
2076 fmt.Println(ok)
2077
2078 // Output:
2079 // true
2080 // true
2081 }
2082
2083 func ExampleLt_int() {
2084 t := &testing.T{}
2085
2086 got := 156
2087
2088 ok := td.Cmp(t, got, td.Lt(157), "checks %v is < 157", got)
2089 fmt.Println(ok)
2090
2091 ok = td.Cmp(t, got, td.Lt(156), "checks %v is < 156", got)
2092 fmt.Println(ok)
2093
2094 // Output:
2095 // true
2096 // false
2097 }
2098
2099 func ExampleLt_string() {
2100 t := &testing.T{}
2101
2102 got := "abc"
2103
2104 ok := td.Cmp(t, got, td.Lt("abd"), `checks "%v" is < "abd"`, got)
2105 fmt.Println(ok)
2106
2107 ok = td.Cmp(t, got, td.Lt("abc"), `checks "%v" is < "abc"`, got)
2108 fmt.Println(ok)
2109
2110 // Output:
2111 // true
2112 // false
2113 }
2114
2115 func ExampleLte_int() {
2116 t := &testing.T{}
2117
2118 got := 156
2119
2120 ok := td.Cmp(t, got, td.Lte(156), "checks %v is ≤ 156", got)
2121 fmt.Println(ok)
2122
2123 ok = td.Cmp(t, got, td.Lte(157), "checks %v is ≤ 157", got)
2124 fmt.Println(ok)
2125
2126 ok = td.Cmp(t, got, td.Lte(155), "checks %v is ≤ 155", got)
2127 fmt.Println(ok)
2128
2129 // Output:
2130 // true
2131 // true
2132 // false
2133 }
2134
2135 func ExampleLte_string() {
2136 t := &testing.T{}
2137
2138 got := "abc"
2139
2140 ok := td.Cmp(t, got, td.Lte("abc"), `checks "%v" is ≤ "abc"`, got)
2141 fmt.Println(ok)
2142
2143 ok = td.Cmp(t, got, td.Lte("abd"), `checks "%v" is ≤ "abd"`, got)
2144 fmt.Println(ok)
2145
2146 ok = td.Cmp(t, got, td.Lte("abb"), `checks "%v" is ≤ "abb"`, got)
2147 fmt.Println(ok)
2148
2149 // Output:
2150 // true
2151 // true
2152 // false
2153 }
2154
2155 func ExampleMap_map() {
2156 t := &testing.T{}
2157
2158 got := map[string]int{"foo": 12, "bar": 42, "zip": 89}
2159
2160 ok := td.Cmp(t, got,
2161 td.Map(map[string]int{"bar": 42},
2162 td.MapEntries{"foo": td.Lt(15), "zip": td.Ignore()}),
2163 "checks map %v", got)
2164 fmt.Println(ok)
2165
2166 ok = td.Cmp(t, got,
2167 td.Map(map[string]int{},
2168 td.MapEntries{"bar": 42, "foo": td.Lt(15), "zip": td.Ignore()}),
2169 "checks map %v", got)
2170 fmt.Println(ok)
2171
2172 ok = td.Cmp(t, got,
2173 td.Map((map[string]int)(nil),
2174 td.MapEntries{"bar": 42, "foo": td.Lt(15), "zip": td.Ignore()}),
2175 "checks map %v", got)
2176 fmt.Println(ok)
2177
2178 // Output:
2179 // true
2180 // true
2181 // true
2182 }
2183
2184 func ExampleMap_typedMap() {
2185 t := &testing.T{}
2186
2187 type MyMap map[string]int
2188
2189 got := MyMap{"foo": 12, "bar": 42, "zip": 89}
2190
2191 ok := td.Cmp(t, got,
2192 td.Map(MyMap{"bar": 42}, td.MapEntries{"foo": td.Lt(15), "zip": td.Ignore()}),
2193 "checks typed map %v", got)
2194 fmt.Println(ok)
2195
2196 ok = td.Cmp(t, &got,
2197 td.Map(&MyMap{"bar": 42}, td.MapEntries{"foo": td.Lt(15), "zip": td.Ignore()}),
2198 "checks pointer on typed map %v", got)
2199 fmt.Println(ok)
2200
2201 ok = td.Cmp(t, &got,
2202 td.Map(&MyMap{}, td.MapEntries{"bar": 42, "foo": td.Lt(15), "zip": td.Ignore()}),
2203 "checks pointer on typed map %v", got)
2204 fmt.Println(ok)
2205
2206 ok = td.Cmp(t, &got,
2207 td.Map((*MyMap)(nil), td.MapEntries{"bar": 42, "foo": td.Lt(15), "zip": td.Ignore()}),
2208 "checks pointer on typed map %v", got)
2209 fmt.Println(ok)
2210
2211 // Output:
2212 // true
2213 // true
2214 // true
2215 // true
2216 }
2217
2218 func ExampleMapEach_map() {
2219 t := &testing.T{}
2220
2221 got := map[string]int{"foo": 12, "bar": 42, "zip": 89}
2222
2223 ok := td.Cmp(t, got, td.MapEach(td.Between(10, 90)),
2224 "checks each value of map %v is in [10 .. 90]", got)
2225 fmt.Println(ok)
2226
2227 // Output:
2228 // true
2229 }
2230
2231 func ExampleMapEach_typedMap() {
2232 t := &testing.T{}
2233
2234 type MyMap map[string]int
2235
2236 got := MyMap{"foo": 12, "bar": 42, "zip": 89}
2237
2238 ok := td.Cmp(t, got, td.MapEach(td.Between(10, 90)),
2239 "checks each value of typed map %v is in [10 .. 90]", got)
2240 fmt.Println(ok)
2241
2242 ok = td.Cmp(t, &got, td.MapEach(td.Between(10, 90)),
2243 "checks each value of typed map pointer %v is in [10 .. 90]", got)
2244 fmt.Println(ok)
2245
2246 // Output:
2247 // true
2248 // true
2249 }
2250
2251 func ExampleN() {
2252 t := &testing.T{}
2253
2254 got := 1.12345
2255
2256 ok := td.Cmp(t, got, td.N(1.1234, 0.00006),
2257 "checks %v = 1.1234 ± 0.00006", got)
2258 fmt.Println(ok)
2259
2260 // Output:
2261 // true
2262 }
2263
2264 func ExampleNaN_float32() {
2265 t := &testing.T{}
2266
2267 got := float32(math.NaN())
2268
2269 ok := td.Cmp(t, got, td.NaN(),
2270 "checks %v is not-a-number", got)
2271
2272 fmt.Println("float32(math.NaN()) is float32 not-a-number:", ok)
2273
2274 got = 12
2275
2276 ok = td.Cmp(t, got, td.NaN(),
2277 "checks %v is not-a-number", got)
2278
2279 fmt.Println("float32(12) is float32 not-a-number:", ok)
2280
2281 // Output:
2282 // float32(math.NaN()) is float32 not-a-number: true
2283 // float32(12) is float32 not-a-number: false
2284 }
2285
2286 func ExampleNaN_float64() {
2287 t := &testing.T{}
2288
2289 got := math.NaN()
2290
2291 ok := td.Cmp(t, got, td.NaN(),
2292 "checks %v is not-a-number", got)
2293
2294 fmt.Println("math.NaN() is not-a-number:", ok)
2295
2296 got = 12
2297
2298 ok = td.Cmp(t, got, td.NaN(),
2299 "checks %v is not-a-number", got)
2300
2301 fmt.Println("float64(12) is not-a-number:", ok)
2302
2303 // Output:
2304 // math.NaN() is not-a-number: true
2305 // float64(12) is not-a-number: false
2306 }
2307
2308 func ExampleNil() {
2309 t := &testing.T{}
2310
2311 var got fmt.Stringer // interface
2312
2313 // nil value can be compared directly with nil, no need of Nil() here
2314 ok := td.Cmp(t, got, nil)
2315 fmt.Println(ok)
2316
2317 // But it works with Nil() anyway
2318 ok = td.Cmp(t, got, td.Nil())
2319 fmt.Println(ok)
2320
2321 got = (*bytes.Buffer)(nil)
2322
2323 // In the case of an interface containing a nil pointer, comparing
2324 // with nil fails, as the interface is not nil
2325 ok = td.Cmp(t, got, nil)
2326 fmt.Println(ok)
2327
2328 // In this case Nil() succeed
2329 ok = td.Cmp(t, got, td.Nil())
2330 fmt.Println(ok)
2331
2332 // Output:
2333 // true
2334 // true
2335 // false
2336 // true
2337 }
2338
2339 func ExampleNone() {
2340 t := &testing.T{}
2341
2342 got := 18
2343
2344 ok := td.Cmp(t, got, td.None(0, 10, 20, 30, td.Between(100, 199)),
2345 "checks %v is non-null, and ≠ 10, 20 & 30, and not in [100-199]", got)
2346 fmt.Println(ok)
2347
2348 got = 20
2349
2350 ok = td.Cmp(t, got, td.None(0, 10, 20, 30, td.Between(100, 199)),
2351 "checks %v is non-null, and ≠ 10, 20 & 30, and not in [100-199]", got)
2352 fmt.Println(ok)
2353
2354 got = 142
2355
2356 ok = td.Cmp(t, got, td.None(0, 10, 20, 30, td.Between(100, 199)),
2357 "checks %v is non-null, and ≠ 10, 20 & 30, and not in [100-199]", got)
2358 fmt.Println(ok)
2359
2360 prime := td.Flatten([]int{1, 2, 3, 5, 7, 11, 13})
2361 even := td.Flatten([]int{2, 4, 6, 8, 10, 12, 14})
2362 for _, got := range [...]int{9, 3, 8, 15} {
2363 ok = td.Cmp(t, got, td.None(prime, even, td.Gt(14)),
2364 "checks %v is not prime number, nor an even number and not > 14")
2365 fmt.Printf("%d → %t\n", got, ok)
2366 }
2367
2368 // Output:
2369 // true
2370 // false
2371 // false
2372 // 9 → true
2373 // 3 → false
2374 // 8 → false
2375 // 15 → false
2376 }
2377
2378 func ExampleNotAny() {
2379 t := &testing.T{}
2380
2381 got := []int{4, 5, 9, 42}
2382
2383 ok := td.Cmp(t, got, td.NotAny(3, 6, 8, 41, 43),
2384 "checks %v contains no item listed in NotAny()", got)
2385 fmt.Println(ok)
2386
2387 ok = td.Cmp(t, got, td.NotAny(3, 6, 8, 42, 43),
2388 "checks %v contains no item listed in NotAny()", got)
2389 fmt.Println(ok)
2390
2391 // When expected is already a non-[]any slice, it cannot be
2392 // flattened directly using notExpected... without copying it to a new
2393 // []any slice, then use td.Flatten!
2394 notExpected := []int{3, 6, 8, 41, 43}
2395 ok = td.Cmp(t, got, td.NotAny(td.Flatten(notExpected)),
2396 "checks %v contains no item listed in notExpected", got)
2397 fmt.Println(ok)
2398
2399 // Output:
2400 // true
2401 // false
2402 // true
2403 }
2404
2405 func ExampleNot() {
2406 t := &testing.T{}
2407
2408 got := 42
2409
2410 ok := td.Cmp(t, got, td.Not(0), "checks %v is non-null", got)
2411 fmt.Println(ok)
2412
2413 ok = td.Cmp(t, got, td.Not(td.Between(10, 30)),
2414 "checks %v is not in [10 .. 30]", got)
2415 fmt.Println(ok)
2416
2417 got = 0
2418
2419 ok = td.Cmp(t, got, td.Not(0), "checks %v is non-null", got)
2420 fmt.Println(ok)
2421
2422 // Output:
2423 // true
2424 // true
2425 // false
2426 }
2427
2428 func ExampleNotEmpty() {
2429 t := &testing.T{}
2430
2431 ok := td.Cmp(t, nil, td.NotEmpty()) // fails, as nil is considered empty
2432 fmt.Println(ok)
2433
2434 ok = td.Cmp(t, "foobar", td.NotEmpty())
2435 fmt.Println(ok)
2436
2437 // Fails as 0 is a number, so not empty. Use NotZero() instead
2438 ok = td.Cmp(t, 0, td.NotEmpty())
2439 fmt.Println(ok)
2440
2441 ok = td.Cmp(t, map[string]int{"foobar": 42}, td.NotEmpty())
2442 fmt.Println(ok)
2443
2444 ok = td.Cmp(t, []int{1}, td.NotEmpty())
2445 fmt.Println(ok)
2446
2447 ok = td.Cmp(t, [3]int{}, td.NotEmpty()) // succeeds, NotEmpty() is not NotZero()!
2448 fmt.Println(ok)
2449
2450 // Output:
2451 // false
2452 // true
2453 // false
2454 // true
2455 // true
2456 // true
2457 }
2458
2459 func ExampleNotEmpty_pointers() {
2460 t := &testing.T{}
2461
2462 type MySlice []int
2463
2464 ok := td.Cmp(t, MySlice{12}, td.NotEmpty())
2465 fmt.Println(ok)
2466
2467 ok = td.Cmp(t, &MySlice{12}, td.NotEmpty()) // Ptr() not needed
2468 fmt.Println(ok)
2469
2470 l1 := &MySlice{12}
2471 l2 := &l1
2472 l3 := &l2
2473 ok = td.Cmp(t, &l3, td.NotEmpty())
2474 fmt.Println(ok)
2475
2476 // Works the same for array, map, channel and string
2477
2478 // But not for others types as:
2479 type MyStruct struct {
2480 Value int
2481 }
2482
2483 ok = td.Cmp(t, &MyStruct{}, td.NotEmpty()) // fails, use NotZero() instead
2484 fmt.Println(ok)
2485
2486 // Output:
2487 // true
2488 // true
2489 // true
2490 // false
2491 }
2492
2493 func ExampleNotNaN_float32() {
2494 t := &testing.T{}
2495
2496 got := float32(math.NaN())
2497
2498 ok := td.Cmp(t, got, td.NotNaN(),
2499 "checks %v is not-a-number", got)
2500
2501 fmt.Println("float32(math.NaN()) is NOT float32 not-a-number:", ok)
2502
2503 got = 12
2504
2505 ok = td.Cmp(t, got, td.NotNaN(),
2506 "checks %v is not-a-number", got)
2507
2508 fmt.Println("float32(12) is NOT float32 not-a-number:", ok)
2509
2510 // Output:
2511 // float32(math.NaN()) is NOT float32 not-a-number: false
2512 // float32(12) is NOT float32 not-a-number: true
2513 }
2514
2515 func ExampleNotNaN_float64() {
2516 t := &testing.T{}
2517
2518 got := math.NaN()
2519
2520 ok := td.Cmp(t, got, td.NotNaN(),
2521 "checks %v is NOT not-a-number", got)
2522
2523 fmt.Println("math.NaN() is NOT not-a-number:", ok)
2524
2525 got = 12
2526
2527 ok = td.Cmp(t, got, td.NotNaN(),
2528 "checks %v is NOT not-a-number", got)
2529
2530 fmt.Println("float64(12) is NOT not-a-number:", ok)
2531
2532 // Output:
2533 // math.NaN() is NOT not-a-number: false
2534 // float64(12) is NOT not-a-number: true
2535 }
2536
2537 func ExampleNotNil() {
2538 t := &testing.T{}
2539
2540 var got fmt.Stringer = &bytes.Buffer{}
2541
2542 // nil value can be compared directly with Not(nil), no need of NotNil() here
2543 ok := td.Cmp(t, got, td.Not(nil))
2544 fmt.Println(ok)
2545
2546 // But it works with NotNil() anyway
2547 ok = td.Cmp(t, got, td.NotNil())
2548 fmt.Println(ok)
2549
2550 got = (*bytes.Buffer)(nil)
2551
2552 // In the case of an interface containing a nil pointer, comparing
2553 // with Not(nil) succeeds, as the interface is not nil
2554 ok = td.Cmp(t, got, td.Not(nil))
2555 fmt.Println(ok)
2556
2557 // In this case NotNil() fails
2558 ok = td.Cmp(t, got, td.NotNil())
2559 fmt.Println(ok)
2560
2561 // Output:
2562 // true
2563 // true
2564 // true
2565 // false
2566 }
2567
2568 func ExampleNotZero() {
2569 t := &testing.T{}
2570
2571 ok := td.Cmp(t, 0, td.NotZero()) // fails
2572 fmt.Println(ok)
2573
2574 ok = td.Cmp(t, float64(0), td.NotZero()) // fails
2575 fmt.Println(ok)
2576
2577 ok = td.Cmp(t, 12, td.NotZero())
2578 fmt.Println(ok)
2579
2580 ok = td.Cmp(t, (map[string]int)(nil), td.NotZero()) // fails, as nil
2581 fmt.Println(ok)
2582
2583 ok = td.Cmp(t, map[string]int{}, td.NotZero()) // succeeds, as not nil
2584 fmt.Println(ok)
2585
2586 ok = td.Cmp(t, ([]int)(nil), td.NotZero()) // fails, as nil
2587 fmt.Println(ok)
2588
2589 ok = td.Cmp(t, []int{}, td.NotZero()) // succeeds, as not nil
2590 fmt.Println(ok)
2591
2592 ok = td.Cmp(t, [3]int{}, td.NotZero()) // fails
2593 fmt.Println(ok)
2594
2595 ok = td.Cmp(t, [3]int{0, 1}, td.NotZero()) // succeeds, DATA[1] is not 0
2596 fmt.Println(ok)
2597
2598 ok = td.Cmp(t, bytes.Buffer{}, td.NotZero()) // fails
2599 fmt.Println(ok)
2600
2601 ok = td.Cmp(t, &bytes.Buffer{}, td.NotZero()) // succeeds, as pointer not nil
2602 fmt.Println(ok)
2603
2604 ok = td.Cmp(t, &bytes.Buffer{}, td.Ptr(td.NotZero())) // fails as deref by Ptr()
2605 fmt.Println(ok)
2606
2607 // Output:
2608 // false
2609 // false
2610 // true
2611 // false
2612 // true
2613 // false
2614 // true
2615 // false
2616 // true
2617 // false
2618 // true
2619 // false
2620 }
2621
2622 func ExamplePPtr() {
2623 t := &testing.T{}
2624
2625 num := 12
2626 got := &num
2627
2628 ok := td.Cmp(t, &got, td.PPtr(12))
2629 fmt.Println(ok)
2630
2631 ok = td.Cmp(t, &got, td.PPtr(td.Between(4, 15)))
2632 fmt.Println(ok)
2633
2634 // Output:
2635 // true
2636 // true
2637 }
2638
2639 func ExamplePtr() {
2640 t := &testing.T{}
2641
2642 got := 12
2643
2644 ok := td.Cmp(t, &got, td.Ptr(12))
2645 fmt.Println(ok)
2646
2647 ok = td.Cmp(t, &got, td.Ptr(td.Between(4, 15)))
2648 fmt.Println(ok)
2649
2650 // Output:
2651 // true
2652 // true
2653 }
2654
2655 func ExampleRe() {
2656 t := &testing.T{}
2657
2658 got := "foo bar"
2659 ok := td.Cmp(t, got, td.Re("(zip|bar)$"), "checks value %s", got)
2660 fmt.Println(ok)
2661
2662 got = "bar foo"
2663 ok = td.Cmp(t, got, td.Re("(zip|bar)$"), "checks value %s", got)
2664 fmt.Println(ok)
2665
2666 // Output:
2667 // true
2668 // false
2669 }
2670
2671 func ExampleRe_stringer() {
2672 t := &testing.T{}
2673
2674 // bytes.Buffer implements fmt.Stringer
2675 got := bytes.NewBufferString("foo bar")
2676 ok := td.Cmp(t, got, td.Re("(zip|bar)$"), "checks value %s", got)
2677 fmt.Println(ok)
2678
2679 // Output:
2680 // true
2681 }
2682
2683 func ExampleRe_error() {
2684 t := &testing.T{}
2685
2686 got := errors.New("foo bar")
2687 ok := td.Cmp(t, got, td.Re("(zip|bar)$"), "checks value %s", got)
2688 fmt.Println(ok)
2689
2690 // Output:
2691 // true
2692 }
2693
2694 func ExampleRe_capture() {
2695 t := &testing.T{}
2696
2697 got := "foo bar biz"
2698 ok := td.Cmp(t, got, td.Re(`^(\w+) (\w+) (\w+)$`, td.Set("biz", "foo", "bar")),
2699 "checks value %s", got)
2700 fmt.Println(ok)
2701
2702 got = "foo bar! biz"
2703 ok = td.Cmp(t, got, td.Re(`^(\w+) (\w+) (\w+)$`, td.Set("biz", "foo", "bar")),
2704 "checks value %s", got)
2705 fmt.Println(ok)
2706
2707 // Output:
2708 // true
2709 // false
2710 }
2711
2712 func ExampleRe_multilines() {
2713 t := &testing.T{}
2714
2715 got := `multi
2716 lines
2717 probably
2718 more
2719 than 4
2720 `
2721 expectedRe := `^multi
2722 lines?
2723 (probably|possibly)
2724 more
2725 than \d+
2726 \z`
2727
2728 ok := td.Cmp(t, got, td.Re(expectedRe))
2729 fmt.Println("Raw multi-lines string matches:", ok)
2730
2731 // But for strings with many, many, many lines, when the regexp
2732 // doesn't match, it is sometimes difficult to see where the regexp
2733 // failed in the string. Here td.List & td.Flatten can help to apply
2734 // regexp line per line (note expectedRe is not anchored anymore):
2735 expectedRe = `multi
2736 lines?
2737 (probably|possibly)
2738 more
2739 than \d+
2740 `
2741 ok = td.Cmp(t,
2742 strings.Split(got, "\n"),
2743 td.List(td.Flatten(strings.Split(expectedRe, "\n"),
2744 func(line string) any {
2745 return td.Re(`^` + line + `\z`)
2746 })))
2747 fmt.Println("All string lines match:", ok)
2748
2749 // Output:
2750 // Raw multi-lines string matches: true
2751 // All string lines match: true
2752 }
2753
2754 func ExampleReAll_capture() {
2755 t := &testing.T{}
2756
2757 got := "foo bar biz"
2758 ok := td.Cmp(t, got, td.ReAll(`(\w+)`, td.Set("biz", "foo", "bar")),
2759 "checks value %s", got)
2760 fmt.Println(ok)
2761
2762 // Matches, but all catured groups do not match Set
2763 got = "foo BAR biz"
2764 ok = td.Cmp(t, got, td.ReAll(`(\w+)`, td.Set("biz", "foo", "bar")),
2765 "checks value %s", got)
2766 fmt.Println(ok)
2767
2768 // Output:
2769 // true
2770 // false
2771 }
2772
2773 func ExampleReAll_captureComplex() {
2774 t := &testing.T{}
2775
2776 got := "11 45 23 56 85 96"
2777 ok := td.Cmp(t, got,
2778 td.ReAll(`(\d+)`, td.ArrayEach(td.Code(func(num string) bool {
2779 n, err := strconv.Atoi(num)
2780 return err == nil && n > 10 && n < 100
2781 }))),
2782 "checks value %s", got)
2783 fmt.Println(ok)
2784
2785 // Matches, but 11 is not greater than 20
2786 ok = td.Cmp(t, got,
2787 td.ReAll(`(\d+)`, td.ArrayEach(td.Code(func(num string) bool {
2788 n, err := strconv.Atoi(num)
2789 return err == nil && n > 20 && n < 100
2790 }))),
2791 "checks value %s", got)
2792 fmt.Println(ok)
2793
2794 // Output:
2795 // true
2796 // false
2797 }
2798
2799 func ExampleRe_compiled() {
2800 t := &testing.T{}
2801
2802 expected := regexp.MustCompile("(zip|bar)$")
2803
2804 got := "foo bar"
2805 ok := td.Cmp(t, got, td.Re(expected), "checks value %s", got)
2806 fmt.Println(ok)
2807
2808 got = "bar foo"
2809 ok = td.Cmp(t, got, td.Re(expected), "checks value %s", got)
2810 fmt.Println(ok)
2811
2812 // Output:
2813 // true
2814 // false
2815 }
2816
2817 func ExampleRe_compiledStringer() {
2818 t := &testing.T{}
2819
2820 expected := regexp.MustCompile("(zip|bar)$")
2821
2822 // bytes.Buffer implements fmt.Stringer
2823 got := bytes.NewBufferString("foo bar")
2824 ok := td.Cmp(t, got, td.Re(expected), "checks value %s", got)
2825 fmt.Println(ok)
2826
2827 // Output:
2828 // true
2829 }
2830
2831 func ExampleRe_compiledError() {
2832 t := &testing.T{}
2833
2834 expected := regexp.MustCompile("(zip|bar)$")
2835
2836 got := errors.New("foo bar")
2837 ok := td.Cmp(t, got, td.Re(expected), "checks value %s", got)
2838 fmt.Println(ok)
2839
2840 // Output:
2841 // true
2842 }
2843
2844 func ExampleRe_compiledCapture() {
2845 t := &testing.T{}
2846
2847 expected := regexp.MustCompile(`^(\w+) (\w+) (\w+)$`)
2848
2849 got := "foo bar biz"
2850 ok := td.Cmp(t, got, td.Re(expected, td.Set("biz", "foo", "bar")),
2851 "checks value %s", got)
2852 fmt.Println(ok)
2853
2854 got = "foo bar! biz"
2855 ok = td.Cmp(t, got, td.Re(expected, td.Set("biz", "foo", "bar")),
2856 "checks value %s", got)
2857 fmt.Println(ok)
2858
2859 // Output:
2860 // true
2861 // false
2862 }
2863
2864 func ExampleReAll_compiledCapture() {
2865 t := &testing.T{}
2866
2867 expected := regexp.MustCompile(`(\w+)`)
2868
2869 got := "foo bar biz"
2870 ok := td.Cmp(t, got, td.ReAll(expected, td.Set("biz", "foo", "bar")),
2871 "checks value %s", got)
2872 fmt.Println(ok)
2873
2874 // Matches, but all catured groups do not match Set
2875 got = "foo BAR biz"
2876 ok = td.Cmp(t, got, td.ReAll(expected, td.Set("biz", "foo", "bar")),
2877 "checks value %s", got)
2878 fmt.Println(ok)
2879
2880 // Output:
2881 // true
2882 // false
2883 }
2884
2885 func ExampleReAll_compiledCaptureComplex() {
2886 t := &testing.T{}
2887
2888 expected := regexp.MustCompile(`(\d+)`)
2889
2890 got := "11 45 23 56 85 96"
2891 ok := td.Cmp(t, got,
2892 td.ReAll(expected, td.ArrayEach(td.Code(func(num string) bool {
2893 n, err := strconv.Atoi(num)
2894 return err == nil && n > 10 && n < 100
2895 }))),
2896 "checks value %s", got)
2897 fmt.Println(ok)
2898
2899 // Matches, but 11 is not greater than 20
2900 ok = td.Cmp(t, got,
2901 td.ReAll(expected, td.ArrayEach(td.Code(func(num string) bool {
2902 n, err := strconv.Atoi(num)
2903 return err == nil && n > 20 && n < 100
2904 }))),
2905 "checks value %s", got)
2906 fmt.Println(ok)
2907
2908 // Output:
2909 // true
2910 // false
2911 }
2912
2913 func ExampleRecv_basic() {
2914 t := &testing.T{}
2915
2916 got := make(chan int, 3)
2917
2918 ok := td.Cmp(t, got, td.Recv(td.RecvNothing))
2919 fmt.Println("nothing to receive:", ok)
2920
2921 got <- 1
2922 got <- 2
2923 got <- 3
2924 close(got)
2925
2926 ok = td.Cmp(t, got, td.Recv(1))
2927 fmt.Println("1st receive is 1:", ok)
2928
2929 ok = td.Cmp(t, got, td.All(
2930 td.Recv(2),
2931 td.Recv(td.Between(3, 4)),
2932 td.Recv(td.RecvClosed),
2933 ))
2934 fmt.Println("next receives are 2, 3 then closed:", ok)
2935
2936 ok = td.Cmp(t, got, td.Recv(td.RecvNothing))
2937 fmt.Println("nothing to receive:", ok)
2938
2939 // Output:
2940 // nothing to receive: true
2941 // 1st receive is 1: true
2942 // next receives are 2, 3 then closed: true
2943 // nothing to receive: false
2944 }
2945
2946 func ExampleRecv_channelPointer() {
2947 t := &testing.T{}
2948
2949 got := make(chan int, 3)
2950
2951 ok := td.Cmp(t, got, td.Recv(td.RecvNothing))
2952 fmt.Println("nothing to receive:", ok)
2953
2954 got <- 1
2955 got <- 2
2956 got <- 3
2957 close(got)
2958
2959 ok = td.Cmp(t, &got, td.Recv(1))
2960 fmt.Println("1st receive is 1:", ok)
2961
2962 ok = td.Cmp(t, &got, td.All(
2963 td.Recv(2),
2964 td.Recv(td.Between(3, 4)),
2965 td.Recv(td.RecvClosed),
2966 ))
2967 fmt.Println("next receives are 2, 3 then closed:", ok)
2968
2969 ok = td.Cmp(t, got, td.Recv(td.RecvNothing))
2970 fmt.Println("nothing to receive:", ok)
2971
2972 // Output:
2973 // nothing to receive: true
2974 // 1st receive is 1: true
2975 // next receives are 2, 3 then closed: true
2976 // nothing to receive: false
2977 }
2978
2979 func ExampleRecv_withTimeout() {
2980 t := &testing.T{}
2981
2982 got := make(chan int, 1)
2983 tick := make(chan struct{})
2984
2985 go func() {
2986 // ①
2987 <-tick
2988 time.Sleep(100 * time.Millisecond)
2989 got <- 0
2990
2991 // ②
2992 <-tick
2993 time.Sleep(100 * time.Millisecond)
2994 got <- 1
2995
2996 // ③
2997 <-tick
2998 time.Sleep(100 * time.Millisecond)
2999 close(got)
3000 }()
3001
3002 td.Cmp(t, got, td.Recv(td.RecvNothing))
3003
3004 // ①
3005 tick <- struct{}{}
3006 ok := td.Cmp(t, got, td.Recv(td.RecvNothing))
3007 fmt.Println("① RecvNothing:", ok)
3008 ok = td.Cmp(t, got, td.Recv(0, 150*time.Millisecond))
3009 fmt.Println("① receive 0 w/150ms timeout:", ok)
3010 ok = td.Cmp(t, got, td.Recv(td.RecvNothing))
3011 fmt.Println("① RecvNothing:", ok)
3012
3013 // ②
3014 tick <- struct{}{}
3015 ok = td.Cmp(t, got, td.Recv(td.RecvNothing))
3016 fmt.Println("② RecvNothing:", ok)
3017 ok = td.Cmp(t, got, td.Recv(1, 150*time.Millisecond))
3018 fmt.Println("② receive 1 w/150ms timeout:", ok)
3019 ok = td.Cmp(t, got, td.Recv(td.RecvNothing))
3020 fmt.Println("② RecvNothing:", ok)
3021
3022 // ③
3023 tick <- struct{}{}
3024 ok = td.Cmp(t, got, td.Recv(td.RecvNothing))
3025 fmt.Println("③ RecvNothing:", ok)
3026 ok = td.Cmp(t, got, td.Recv(td.RecvClosed, 150*time.Millisecond))
3027 fmt.Println("③ check closed w/150ms timeout:", ok)
3028
3029 // Output:
3030 // ① RecvNothing: true
3031 // ① receive 0 w/150ms timeout: true
3032 // ① RecvNothing: true
3033 // ② RecvNothing: true
3034 // ② receive 1 w/150ms timeout: true
3035 // ② RecvNothing: true
3036 // ③ RecvNothing: true
3037 // ③ check closed w/150ms timeout: true
3038 }
3039
3040 func ExampleRecv_nilChannel() {
3041 t := &testing.T{}
3042
3043 var ch chan int
3044
3045 ok := td.Cmp(t, ch, td.Recv(td.RecvNothing))
3046 fmt.Println("nothing to receive from nil channel:", ok)
3047
3048 ok = td.Cmp(t, ch, td.Recv(42))
3049 fmt.Println("something to receive from nil channel:", ok)
3050
3051 ok = td.Cmp(t, ch, td.Recv(td.RecvClosed))
3052 fmt.Println("is a nil channel closed:", ok)
3053
3054 // Output:
3055 // nothing to receive from nil channel: true
3056 // something to receive from nil channel: false
3057 // is a nil channel closed: false
3058 }
3059
3060 func ExampleSet() {
3061 t := &testing.T{}
3062
3063 got := []int{1, 3, 5, 8, 8, 1, 2}
3064
3065 // Matches as all items are present, ignoring duplicates
3066 ok := td.Cmp(t, got, td.Set(1, 2, 3, 5, 8),
3067 "checks all items are present, in any order")
3068 fmt.Println(ok)
3069
3070 // Duplicates are ignored in a Set
3071 ok = td.Cmp(t, got, td.Set(1, 2, 2, 2, 2, 2, 3, 5, 8),
3072 "checks all items are present, in any order")
3073 fmt.Println(ok)
3074
3075 // Tries its best not to raise an error when a value can be matched
3076 // by several Set entries
3077 ok = td.Cmp(t, got, td.Set(td.Between(1, 4), 3, td.Between(2, 10)),
3078 "checks all items are present, in any order")
3079 fmt.Println(ok)
3080
3081 // When expected is already a non-[]any slice, it cannot be
3082 // flattened directly using expected... without copying it to a new
3083 // []any slice, then use td.Flatten!
3084 expected := []int{1, 2, 3, 5, 8}
3085 ok = td.Cmp(t, got, td.Set(td.Flatten(expected)),
3086 "checks all expected items are present, in any order")
3087 fmt.Println(ok)
3088
3089 // Output:
3090 // true
3091 // true
3092 // true
3093 // true
3094 }
3095
3096 func ExampleShallow() {
3097 t := &testing.T{}
3098
3099 type MyStruct struct {
3100 Value int
3101 }
3102 data := MyStruct{Value: 12}
3103 got := &data
3104
3105 ok := td.Cmp(t, got, td.Shallow(&data),
3106 "checks pointers only, not contents")
3107 fmt.Println(ok)
3108
3109 // Same contents, but not same pointer
3110 ok = td.Cmp(t, got, td.Shallow(&MyStruct{Value: 12}),
3111 "checks pointers only, not contents")
3112 fmt.Println(ok)
3113
3114 // Output:
3115 // true
3116 // false
3117 }
3118
3119 func ExampleShallow_slice() {
3120 t := &testing.T{}
3121
3122 back := []int{1, 2, 3, 1, 2, 3}
3123 a := back[:3]
3124 b := back[3:]
3125
3126 ok := td.Cmp(t, a, td.Shallow(back))
3127 fmt.Println("are ≠ but share the same area:", ok)
3128
3129 ok = td.Cmp(t, b, td.Shallow(back))
3130 fmt.Println("are = but do not point to same area:", ok)
3131
3132 // Output:
3133 // are ≠ but share the same area: true
3134 // are = but do not point to same area: false
3135 }
3136
3137 func ExampleShallow_string() {
3138 t := &testing.T{}
3139
3140 back := "foobarfoobar"
3141 a := back[:6]
3142 b := back[6:]
3143
3144 ok := td.Cmp(t, a, td.Shallow(back))
3145 fmt.Println("are ≠ but share the same area:", ok)
3146
3147 ok = td.Cmp(t, b, td.Shallow(a))
3148 fmt.Println("are = but do not point to same area:", ok)
3149
3150 // Output:
3151 // are ≠ but share the same area: true
3152 // are = but do not point to same area: false
3153 }
3154
3155 func ExampleSlice_slice() {
3156 t := &testing.T{}
3157
3158 got := []int{42, 58, 26}
3159
3160 ok := td.Cmp(t, got, td.Slice([]int{42}, td.ArrayEntries{1: 58, 2: td.Ignore()}),
3161 "checks slice %v", got)
3162 fmt.Println(ok)
3163
3164 ok = td.Cmp(t, got,
3165 td.Slice([]int{}, td.ArrayEntries{0: 42, 1: 58, 2: td.Ignore()}),
3166 "checks slice %v", got)
3167 fmt.Println(ok)
3168
3169 ok = td.Cmp(t, got,
3170 td.Slice(([]int)(nil), td.ArrayEntries{0: 42, 1: 58, 2: td.Ignore()}),
3171 "checks slice %v", got)
3172 fmt.Println(ok)
3173
3174 // Output:
3175 // true
3176 // true
3177 // true
3178 }
3179
3180 func ExampleSlice_typedSlice() {
3181 t := &testing.T{}
3182
3183 type MySlice []int
3184
3185 got := MySlice{42, 58, 26}
3186
3187 ok := td.Cmp(t, got, td.Slice(MySlice{42}, td.ArrayEntries{1: 58, 2: td.Ignore()}),
3188 "checks typed slice %v", got)
3189 fmt.Println(ok)
3190
3191 ok = td.Cmp(t, &got, td.Slice(&MySlice{42}, td.ArrayEntries{1: 58, 2: td.Ignore()}),
3192 "checks pointer on typed slice %v", got)
3193 fmt.Println(ok)
3194
3195 ok = td.Cmp(t, &got,
3196 td.Slice(&MySlice{}, td.ArrayEntries{0: 42, 1: 58, 2: td.Ignore()}),
3197 "checks pointer on typed slice %v", got)
3198 fmt.Println(ok)
3199
3200 ok = td.Cmp(t, &got,
3201 td.Slice((*MySlice)(nil), td.ArrayEntries{0: 42, 1: 58, 2: td.Ignore()}),
3202 "checks pointer on typed slice %v", got)
3203 fmt.Println(ok)
3204
3205 // Output:
3206 // true
3207 // true
3208 // true
3209 // true
3210 }
3211
3212 func ExampleSort_basic() {
3213 t := &testing.T{}
3214
3215 got := []int{-1, 1, 2, -3, 3, -2, 0}
3216
3217 // Generic ascending order (≥0 or nil)
3218 ok := td.Cmp(t, got, td.Sort(1, []int{-3, -2, -1, 0, 1, 2, 3}))
3219 fmt.Println("asc order:", ok)
3220
3221 ok = td.Cmp(t, got, td.Sort(0, []int{-3, -2, -1, 0, 1, 2, 3}))
3222 fmt.Println("asc order:", ok)
3223
3224 ok = td.Cmp(t, got, td.Sort(nil, []int{-3, -2, -1, 0, 1, 2, 3}))
3225 fmt.Println("asc order:", ok)
3226
3227 // Generic descending order (< 0)
3228 ok = td.Cmp(t, got, td.Sort(-1, []int{3, 2, 1, 0, -1, -2, -3}))
3229 fmt.Println("desc order:", ok)
3230
3231 evenHigher := func(a, b int) bool {
3232 if (a%2 == 0) != (b%2 == 0) {
3233 return a%2 != 0
3234 }
3235 return a < b
3236 }
3237 ok = td.Cmp(t, got, td.Sort(evenHigher, []int{-3, -1, 1, 3, -2, 0, 2}))
3238 fmt.Println("even higher order:", ok)
3239
3240 // Output:
3241 // asc order: true
3242 // asc order: true
3243 // asc order: true
3244 // desc order: true
3245 // even higher order: true
3246 }
3247
3248 func ExampleSort_fields_path() {
3249 t := &testing.T{}
3250
3251 type Person struct {
3252 Name string
3253 Age int
3254 }
3255
3256 brian := Person{Name: "Brian", Age: 22}
3257 bob := Person{Name: "Bob", Age: 19}
3258 stephen := Person{Name: "Stephen", Age: 19}
3259 alice := Person{Name: "Alice", Age: 20}
3260 marcel := Person{Name: "Marcel", Age: 25}
3261 got := []Person{brian, bob, stephen, alice, marcel}
3262
3263 ok := td.Cmp(t, got,
3264 td.Sort("Name", []Person{alice, bob, brian, marcel, stephen}))
3265 fmt.Println("by name asc:", ok)
3266
3267 ok = td.Cmp(t, got,
3268 td.Sort("-Name", []Person{stephen, marcel, brian, bob, alice}))
3269 fmt.Println("by name desc:", ok)
3270
3271 ok = td.Cmp(t, got,
3272 td.Sort([]string{"-Age", "Name"}, []Person{marcel, brian, alice, bob, stephen}))
3273 fmt.Println("by age desc, then by name asc:", ok)
3274
3275 type A struct{ props map[string]int }
3276 p12 := A{props: map[string]int{"priority": 12}}
3277 p23 := A{props: map[string]int{"priority": 23}}
3278 p34 := A{props: map[string]int{"priority": 34}}
3279 got2 := []A{p23, p12, p34}
3280 ok = td.Cmp(t, got2, td.Sort(`-props[priority]`, []A{p34, p23, p12}))
3281 fmt.Println("by priority desc:", ok)
3282
3283 ok = td.Cmp(t, got2, td.Sort(`props.priority`, []A{p12, p23, p34}))
3284 fmt.Println("by priority asc:", ok)
3285
3286 // Output:
3287 // by name asc: true
3288 // by name desc: true
3289 // by age desc, then by name asc: true
3290 // by priority desc: true
3291 // by priority asc: true
3292 }
3293
3294 func ExampleSorted_basic() {
3295 t := &testing.T{}
3296
3297 got := []int{-3, -2, -1, 0, 1, 2, 3}
3298
3299 ok := td.Cmp(t, got, td.Sorted())
3300 fmt.Println("is asc order (default):", ok)
3301
3302 ok = td.Cmp(t, got, td.Sorted(1))
3303 fmt.Println("is asc order (1):", ok)
3304
3305 ok = td.Cmp(t, got, td.Sorted(0))
3306 fmt.Println("is asc order (0):", ok)
3307
3308 ok = td.Cmp(t, got, td.Sorted(nil))
3309 fmt.Println("is asc order (nil):", ok)
3310
3311 ok = td.Cmp(t, got, td.Sorted(-1))
3312 fmt.Println("is desc order:", ok)
3313
3314 got = []int{-3, -1, 1, 3, -2, 0, 2}
3315 evenHigher := func(a, b int) bool {
3316 if (a%2 == 0) != (b%2 == 0) {
3317 return a%2 != 0
3318 }
3319 return a < b
3320 }
3321 ok = td.Cmp(t, got, td.Sorted(evenHigher))
3322 fmt.Println("is even higher order:", ok)
3323
3324 // Output:
3325 // is asc order (default): true
3326 // is asc order (1): true
3327 // is asc order (0): true
3328 // is asc order (nil): true
3329 // is desc order: false
3330 // is even higher order: true
3331 }
3332
3333 func ExampleSorted_fields_path() {
3334 t := &testing.T{}
3335
3336 type Person struct {
3337 Name string
3338 Age int
3339 }
3340
3341 alice := Person{Name: "Alice", Age: 20}
3342 bob := Person{Name: "Bob", Age: 19}
3343 brian := Person{Name: "Brian", Age: 22}
3344 marcel := Person{Name: "Marcel", Age: 25}
3345 stephen := Person{Name: "Stephen", Age: 19}
3346
3347 got := []Person{alice, bob, brian, marcel, stephen}
3348 ok := td.Cmp(t, got, td.Sorted("Name"))
3349 fmt.Println("is sorted by name asc:", ok)
3350
3351 got = []Person{stephen, marcel, brian, bob, alice}
3352 ok = td.Cmp(t, got, td.Sorted("-Name"))
3353 fmt.Println("is sorted by name desc:", ok)
3354
3355 got = []Person{marcel, brian, alice, bob, stephen}
3356 ok = td.Cmp(t, got, td.Sorted("-Age", "Name"))
3357 fmt.Println("is sorted by age desc, then by name asc 1:", ok)
3358
3359 got = []Person{marcel, brian, alice, stephen, bob}
3360 ok = td.Cmp(t, got, td.Sorted("-Age", "Name"))
3361 fmt.Println("is sorted by age desc, then by name asc 2:", ok)
3362
3363 type A struct{ props map[string]int }
3364 p12 := A{props: map[string]int{"priority": 12}}
3365 p23 := A{props: map[string]int{"priority": 23}}
3366 p34 := A{props: map[string]int{"priority": 34}}
3367 got2 := []A{p34, p23, p12}
3368 ok = td.Cmp(t, got2, td.Sorted(`-props[priority]`))
3369 fmt.Println("is sorted by priority desc:", ok)
3370
3371 ok = td.Cmp(t, got2, td.Sorted(`props.priority`))
3372 fmt.Println("is sorted by priority asc:", ok)
3373
3374 // Output:
3375 // is sorted by name asc: true
3376 // is sorted by name desc: true
3377 // is sorted by age desc, then by name asc 1: true
3378 // is sorted by age desc, then by name asc 2: false
3379 // is sorted by priority desc: true
3380 // is sorted by priority asc: false
3381 }
3382
3383 func ExampleSuperSliceOf_array() {
3384 t := &testing.T{}
3385
3386 got := [4]int{42, 58, 26, 666}
3387
3388 ok := td.Cmp(t, got,
3389 td.SuperSliceOf([4]int{1: 58}, td.ArrayEntries{3: td.Gt(660)}),
3390 "checks array %v", got)
3391 fmt.Println("Only check items #1 & #3:", ok)
3392
3393 ok = td.Cmp(t, got,
3394 td.SuperSliceOf([4]int{}, td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3395 "checks array %v", got)
3396 fmt.Println("Only check items #0 & #3:", ok)
3397
3398 ok = td.Cmp(t, &got,
3399 td.SuperSliceOf(&[4]int{}, td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3400 "checks array %v", got)
3401 fmt.Println("Only check items #0 & #3 of an array pointer:", ok)
3402
3403 ok = td.Cmp(t, &got,
3404 td.SuperSliceOf((*[4]int)(nil), td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3405 "checks array %v", got)
3406 fmt.Println("Only check items #0 & #3 of an array pointer, using nil model:", ok)
3407
3408 // Output:
3409 // Only check items #1 & #3: true
3410 // Only check items #0 & #3: true
3411 // Only check items #0 & #3 of an array pointer: true
3412 // Only check items #0 & #3 of an array pointer, using nil model: true
3413 }
3414
3415 func ExampleSuperSliceOf_typedArray() {
3416 t := &testing.T{}
3417
3418 type MyArray [4]int
3419
3420 got := MyArray{42, 58, 26, 666}
3421
3422 ok := td.Cmp(t, got,
3423 td.SuperSliceOf(MyArray{1: 58}, td.ArrayEntries{3: td.Gt(660)}),
3424 "checks typed array %v", got)
3425 fmt.Println("Only check items #1 & #3:", ok)
3426
3427 ok = td.Cmp(t, got,
3428 td.SuperSliceOf(MyArray{}, td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3429 "checks array %v", got)
3430 fmt.Println("Only check items #0 & #3:", ok)
3431
3432 ok = td.Cmp(t, &got,
3433 td.SuperSliceOf(&MyArray{}, td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3434 "checks array %v", got)
3435 fmt.Println("Only check items #0 & #3 of an array pointer:", ok)
3436
3437 ok = td.Cmp(t, &got,
3438 td.SuperSliceOf((*MyArray)(nil), td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3439 "checks array %v", got)
3440 fmt.Println("Only check items #0 & #3 of an array pointer, using nil model:", ok)
3441
3442 // Output:
3443 // Only check items #1 & #3: true
3444 // Only check items #0 & #3: true
3445 // Only check items #0 & #3 of an array pointer: true
3446 // Only check items #0 & #3 of an array pointer, using nil model: true
3447 }
3448
3449 func ExampleSuperSliceOf_slice() {
3450 t := &testing.T{}
3451
3452 got := []int{42, 58, 26, 666}
3453
3454 ok := td.Cmp(t, got,
3455 td.SuperSliceOf([]int{1: 58}, td.ArrayEntries{3: td.Gt(660)}),
3456 "checks array %v", got)
3457 fmt.Println("Only check items #1 & #3:", ok)
3458
3459 ok = td.Cmp(t, got,
3460 td.SuperSliceOf([]int{}, td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3461 "checks array %v", got)
3462 fmt.Println("Only check items #0 & #3:", ok)
3463
3464 ok = td.Cmp(t, &got,
3465 td.SuperSliceOf(&[]int{}, td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3466 "checks array %v", got)
3467 fmt.Println("Only check items #0 & #3 of a slice pointer:", ok)
3468
3469 ok = td.Cmp(t, &got,
3470 td.SuperSliceOf((*[]int)(nil), td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3471 "checks array %v", got)
3472 fmt.Println("Only check items #0 & #3 of a slice pointer, using nil model:", ok)
3473
3474 // Output:
3475 // Only check items #1 & #3: true
3476 // Only check items #0 & #3: true
3477 // Only check items #0 & #3 of a slice pointer: true
3478 // Only check items #0 & #3 of a slice pointer, using nil model: true
3479 }
3480
3481 func ExampleSuperSliceOf_typedSlice() {
3482 t := &testing.T{}
3483
3484 type MySlice []int
3485
3486 got := MySlice{42, 58, 26, 666}
3487
3488 ok := td.Cmp(t, got,
3489 td.SuperSliceOf(MySlice{1: 58}, td.ArrayEntries{3: td.Gt(660)}),
3490 "checks typed array %v", got)
3491 fmt.Println("Only check items #1 & #3:", ok)
3492
3493 ok = td.Cmp(t, got,
3494 td.SuperSliceOf(MySlice{}, td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3495 "checks array %v", got)
3496 fmt.Println("Only check items #0 & #3:", ok)
3497
3498 ok = td.Cmp(t, &got,
3499 td.SuperSliceOf(&MySlice{}, td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3500 "checks array %v", got)
3501 fmt.Println("Only check items #0 & #3 of a slice pointer:", ok)
3502
3503 ok = td.Cmp(t, &got,
3504 td.SuperSliceOf((*MySlice)(nil), td.ArrayEntries{0: 42, 3: td.Between(660, 670)}),
3505 "checks array %v", got)
3506 fmt.Println("Only check items #0 & #3 of a slice pointer, using nil model:", ok)
3507
3508 // Output:
3509 // Only check items #1 & #3: true
3510 // Only check items #0 & #3: true
3511 // Only check items #0 & #3 of a slice pointer: true
3512 // Only check items #0 & #3 of a slice pointer, using nil model: true
3513 }
3514
3515 func ExampleSmuggle_convert() {
3516 t := &testing.T{}
3517
3518 got := int64(123)
3519
3520 ok := td.Cmp(t, got,
3521 td.Smuggle(func(n int64) int { return int(n) }, 123),
3522 "checks int64 got against an int value")
3523 fmt.Println(ok)
3524
3525 ok = td.Cmp(t, "123",
3526 td.Smuggle(
3527 func(numStr string) (int, bool) {
3528 n, err := strconv.Atoi(numStr)
3529 return n, err == nil
3530 },
3531 td.Between(120, 130)),
3532 "checks that number in %#v is in [120 .. 130]")
3533 fmt.Println(ok)
3534
3535 ok = td.Cmp(t, "123",
3536 td.Smuggle(
3537 func(numStr string) (int, bool, string) {
3538 n, err := strconv.Atoi(numStr)
3539 if err != nil {
3540 return 0, false, "string must contain a number"
3541 }
3542 return n, true, ""
3543 },
3544 td.Between(120, 130)),
3545 "checks that number in %#v is in [120 .. 130]")
3546 fmt.Println(ok)
3547
3548 ok = td.Cmp(t, "123",
3549 td.Smuggle(
3550 func(numStr string) (int, error) { //nolint: gocritic
3551 return strconv.Atoi(numStr)
3552 },
3553 td.Between(120, 130)),
3554 "checks that number in %#v is in [120 .. 130]")
3555 fmt.Println(ok)
3556
3557 // Short version :)
3558 ok = td.Cmp(t, "123",
3559 td.Smuggle(strconv.Atoi, td.Between(120, 130)),
3560 "checks that number in %#v is in [120 .. 130]")
3561 fmt.Println(ok)
3562
3563 // Output:
3564 // true
3565 // true
3566 // true
3567 // true
3568 // true
3569 }
3570
3571 func ExampleSmuggle_lax() {
3572 t := &testing.T{}
3573
3574 // got is an int16 and Smuggle func input is an int64: it is OK
3575 got := int(123)
3576
3577 ok := td.Cmp(t, got,
3578 td.Smuggle(func(n int64) uint32 { return uint32(n) }, uint32(123)))
3579 fmt.Println("got int16(123) → smuggle via int64 → uint32(123):", ok)
3580
3581 // Output:
3582 // got int16(123) → smuggle via int64 → uint32(123): true
3583 }
3584
3585 func ExampleSmuggle_auto_unmarshal() {
3586 t := &testing.T{}
3587
3588 // Automatically json.Unmarshal to compare
3589 got := []byte(`{"a":1,"b":2}`)
3590
3591 ok := td.Cmp(t, got,
3592 td.Smuggle(
3593 func(b json.RawMessage) (r map[string]int, err error) {
3594 err = json.Unmarshal(b, &r)
3595 return
3596 },
3597 map[string]int{
3598 "a": 1,
3599 "b": 2,
3600 }))
3601 fmt.Println("JSON contents is OK:", ok)
3602
3603 // Output:
3604 // JSON contents is OK: true
3605 }
3606
3607 func ExampleSmuggle_cast() {
3608 t := &testing.T{}
3609
3610 // A string containing JSON
3611 got := `{ "foo": 123 }`
3612
3613 // Automatically cast a string to a json.RawMessage so td.JSON can operate
3614 ok := td.Cmp(t, got,
3615 td.Smuggle(json.RawMessage{}, td.JSON(`{"foo":123}`)))
3616 fmt.Println("JSON contents in string is OK:", ok)
3617
3618 // Automatically read from io.Reader to a json.RawMessage
3619 ok = td.Cmp(t, bytes.NewReader([]byte(got)),
3620 td.Smuggle(json.RawMessage{}, td.JSON(`{"foo":123}`)))
3621 fmt.Println("JSON contents just read is OK:", ok)
3622
3623 // Output:
3624 // JSON contents in string is OK: true
3625 // JSON contents just read is OK: true
3626 }
3627
3628 func ExampleSmuggle_complex() {
3629 t := &testing.T{}
3630
3631 // No end date but a start date and a duration
3632 type StartDuration struct {
3633 StartDate time.Time
3634 Duration time.Duration
3635 }
3636
3637 // Checks that end date is between 17th and 19th February both at 0h
3638 // for each of these durations in hours
3639
3640 for _, duration := range []time.Duration{48 * time.Hour, 72 * time.Hour, 96 * time.Hour} {
3641 got := StartDuration{
3642 StartDate: time.Date(2018, time.February, 14, 12, 13, 14, 0, time.UTC),
3643 Duration: duration,
3644 }
3645
3646 // Simplest way, but in case of Between() failure, error will be bound
3647 // to DATA<smuggled>, not very clear...
3648 ok := td.Cmp(t, got,
3649 td.Smuggle(
3650 func(sd StartDuration) time.Time {
3651 return sd.StartDate.Add(sd.Duration)
3652 },
3653 td.Between(
3654 time.Date(2018, time.February, 17, 0, 0, 0, 0, time.UTC),
3655 time.Date(2018, time.February, 19, 0, 0, 0, 0, time.UTC))))
3656 fmt.Println(ok)
3657
3658 // Name the computed value "ComputedEndDate" to render a Between() failure
3659 // more understandable, so error will be bound to DATA.ComputedEndDate
3660 ok = td.Cmp(t, got,
3661 td.Smuggle(
3662 func(sd StartDuration) td.SmuggledGot {
3663 return td.SmuggledGot{
3664 Name: "ComputedEndDate",
3665 Got: sd.StartDate.Add(sd.Duration),
3666 }
3667 },
3668 td.Between(
3669 time.Date(2018, time.February, 17, 0, 0, 0, 0, time.UTC),
3670 time.Date(2018, time.February, 19, 0, 0, 0, 0, time.UTC))))
3671 fmt.Println(ok)
3672 }
3673
3674 // Output:
3675 // false
3676 // false
3677 // true
3678 // true
3679 // true
3680 // true
3681 }
3682
3683 func ExampleSmuggle_interface() {
3684 t := &testing.T{}
3685
3686 gotTime, err := time.Parse(time.RFC3339, "2018-05-23T12:13:14Z")
3687 if err != nil {
3688 t.Fatal(err)
3689 }
3690
3691 // Do not check the struct itself, but its stringified form
3692 ok := td.Cmp(t, gotTime,
3693 td.Smuggle(func(s fmt.Stringer) string {
3694 return s.String()
3695 },
3696 "2018-05-23 12:13:14 +0000 UTC"))
3697 fmt.Println("stringified time.Time OK:", ok)
3698
3699 // If got does not implement the fmt.Stringer interface, it fails
3700 // without calling the Smuggle func
3701 type MyTime time.Time
3702 ok = td.Cmp(t, MyTime(gotTime),
3703 td.Smuggle(func(s fmt.Stringer) string {
3704 fmt.Println("Smuggle func called!")
3705 return s.String()
3706 },
3707 "2018-05-23 12:13:14 +0000 UTC"))
3708 fmt.Println("stringified MyTime OK:", ok)
3709
3710 // Output:
3711 // stringified time.Time OK: true
3712 // stringified MyTime OK: false
3713 }
3714
3715 func ExampleSmuggle_field_path() {
3716 t := &testing.T{}
3717
3718 type Body struct {
3719 Name string
3720 Value any
3721 }
3722 type Request struct {
3723 Body *Body
3724 }
3725 type Transaction struct {
3726 Request
3727 }
3728 type ValueNum struct {
3729 Num int
3730 }
3731
3732 got := &Transaction{
3733 Request: Request{
3734 Body: &Body{
3735 Name: "test",
3736 Value: &ValueNum{Num: 123},
3737 },
3738 },
3739 }
3740
3741 // Want to check whether Num is between 100 and 200?
3742 ok := td.Cmp(t, got,
3743 td.Smuggle(
3744 func(tr *Transaction) (int, error) {
3745 if tr.Body == nil ||
3746 tr.Body.Value == nil {
3747 return 0, errors.New("Request.Body or Request.Body.Value is nil")
3748 }
3749 if v, ok := tr.Body.Value.(*ValueNum); ok && v != nil {
3750 return v.Num, nil
3751 }
3752 return 0, errors.New("Request.Body.Value isn't *ValueNum or nil")
3753 },
3754 td.Between(100, 200)))
3755 fmt.Println("check Num by hand:", ok)
3756
3757 // Same, but automagically generated...
3758 ok = td.Cmp(t, got, td.Smuggle("Request.Body.Value.Num", td.Between(100, 200)))
3759 fmt.Println("check Num using a fields-path:", ok)
3760
3761 // And as Request is an anonymous field, can be simplified further
3762 // as it can be omitted
3763 ok = td.Cmp(t, got, td.Smuggle("Body.Value.Num", td.Between(100, 200)))
3764 fmt.Println("check Num using an other fields-path:", ok)
3765
3766 // Note that maps and array/slices are supported
3767 got.Body.Value = map[string]any{
3768 "foo": []any{
3769 3: map[int]string{666: "bar"},
3770 },
3771 }
3772 ok = td.Cmp(t, got, td.Smuggle("Body.Value[foo][3][666]", "bar"))
3773 fmt.Println("check fields-path including maps/slices:", ok)
3774
3775 // Output:
3776 // check Num by hand: true
3777 // check Num using a fields-path: true
3778 // check Num using an other fields-path: true
3779 // check fields-path including maps/slices: true
3780 }
3781
3782 func ExampleString() {
3783 t := &testing.T{}
3784
3785 got := "foobar"
3786
3787 ok := td.Cmp(t, got, td.String("foobar"), "checks %s", got)
3788 fmt.Println("using string:", ok)
3789
3790 ok = td.Cmp(t, []byte(got), td.String("foobar"), "checks %s", got)
3791 fmt.Println("using []byte:", ok)
3792
3793 // Output:
3794 // using string: true
3795 // using []byte: true
3796 }
3797
3798 func ExampleString_stringer() {
3799 t := &testing.T{}
3800
3801 // bytes.Buffer implements fmt.Stringer
3802 got := bytes.NewBufferString("foobar")
3803
3804 ok := td.Cmp(t, got, td.String("foobar"), "checks %s", got)
3805 fmt.Println(ok)
3806
3807 // Output:
3808 // true
3809 }
3810
3811 func ExampleString_error() {
3812 t := &testing.T{}
3813
3814 got := errors.New("foobar")
3815
3816 ok := td.Cmp(t, got, td.String("foobar"), "checks %s", got)
3817 fmt.Println(ok)
3818
3819 // Output:
3820 // true
3821 }
3822
3823 func ExampleHasPrefix() {
3824 t := &testing.T{}
3825
3826 got := "foobar"
3827
3828 ok := td.Cmp(t, got, td.HasPrefix("foo"), "checks %s", got)
3829 fmt.Println("using string:", ok)
3830
3831 ok = td.Cmp(t, []byte(got), td.HasPrefix("foo"), "checks %s", got)
3832 fmt.Println("using []byte:", ok)
3833
3834 // Output:
3835 // using string: true
3836 // using []byte: true
3837 }
3838
3839 func ExampleHasPrefix_stringer() {
3840 t := &testing.T{}
3841
3842 // bytes.Buffer implements fmt.Stringer
3843 got := bytes.NewBufferString("foobar")
3844
3845 ok := td.Cmp(t, got, td.HasPrefix("foo"), "checks %s", got)
3846 fmt.Println(ok)
3847
3848 // Output:
3849 // true
3850 }
3851
3852 func ExampleHasPrefix_error() {
3853 t := &testing.T{}
3854
3855 got := errors.New("foobar")
3856
3857 ok := td.Cmp(t, got, td.HasPrefix("foo"), "checks %s", got)
3858 fmt.Println(ok)
3859
3860 // Output:
3861 // true
3862 }
3863
3864 func ExampleHasSuffix() {
3865 t := &testing.T{}
3866
3867 got := "foobar"
3868
3869 ok := td.Cmp(t, got, td.HasSuffix("bar"), "checks %s", got)
3870 fmt.Println("using string:", ok)
3871
3872 ok = td.Cmp(t, []byte(got), td.HasSuffix("bar"), "checks %s", got)
3873 fmt.Println("using []byte:", ok)
3874
3875 // Output:
3876 // using string: true
3877 // using []byte: true
3878 }
3879
3880 func ExampleHasSuffix_stringer() {
3881 t := &testing.T{}
3882
3883 // bytes.Buffer implements fmt.Stringer
3884 got := bytes.NewBufferString("foobar")
3885
3886 ok := td.Cmp(t, got, td.HasSuffix("bar"), "checks %s", got)
3887 fmt.Println(ok)
3888
3889 // Output:
3890 // true
3891 }
3892
3893 func ExampleHasSuffix_error() {
3894 t := &testing.T{}
3895
3896 got := errors.New("foobar")
3897
3898 ok := td.Cmp(t, got, td.HasSuffix("bar"), "checks %s", got)
3899 fmt.Println(ok)
3900
3901 // Output:
3902 // true
3903 }
3904
3905 func ExampleStruct() {
3906 t := &testing.T{}
3907
3908 type Person struct {
3909 Name string
3910 Age int
3911 NumChildren int
3912 }
3913
3914 got := Person{
3915 Name: "Foobar",
3916 Age: 42,
3917 NumChildren: 3,
3918 }
3919
3920 // As NumChildren is zero in Struct() call, it is not checked
3921 ok := td.Cmp(t, got,
3922 td.Struct(Person{Name: "Foobar"}, td.StructFields{
3923 "Age": td.Between(40, 50),
3924 }),
3925 "checks %v is the right Person")
3926 fmt.Println("Foobar is between 40 & 50:", ok)
3927
3928 // Model can be empty
3929 ok = td.Cmp(t, got,
3930 td.Struct(Person{}, td.StructFields{
3931 "Name": "Foobar",
3932 "Age": td.Between(40, 50),
3933 "NumChildren": td.Not(0),
3934 }),
3935 "checks %v is the right Person")
3936 fmt.Println("Foobar has some children:", ok)
3937
3938 // Works with pointers too
3939 ok = td.Cmp(t, &got,
3940 td.Struct(&Person{}, td.StructFields{
3941 "Name": "Foobar",
3942 "Age": td.Between(40, 50),
3943 "NumChildren": td.Not(0),
3944 }),
3945 "checks %v is the right Person")
3946 fmt.Println("Foobar has some children (using pointer):", ok)
3947
3948 // Model does not need to be instanciated
3949 ok = td.Cmp(t, &got,
3950 td.Struct((*Person)(nil), td.StructFields{
3951 "Name": "Foobar",
3952 "Age": td.Between(40, 50),
3953 "NumChildren": td.Not(0),
3954 }),
3955 "checks %v is the right Person")
3956 fmt.Println("Foobar has some children (using nil model):", ok)
3957
3958 // Output:
3959 // Foobar is between 40 & 50: true
3960 // Foobar has some children: true
3961 // Foobar has some children (using pointer): true
3962 // Foobar has some children (using nil model): true
3963 }
3964
3965 func ExampleStruct_overwrite_model() {
3966 t := &testing.T{}
3967
3968 type Person struct {
3969 Name string
3970 Age int
3971 NumChildren int
3972 }
3973
3974 got := Person{
3975 Name: "Foobar",
3976 Age: 42,
3977 NumChildren: 3,
3978 }
3979
3980 ok := td.Cmp(t, got,
3981 td.Struct(
3982 Person{
3983 Name: "Foobar",
3984 Age: 53,
3985 },
3986 td.StructFields{
3987 ">Age": td.Between(40, 50), // ">" to overwrite Age:53 in model
3988 "NumChildren": td.Gt(2),
3989 }),
3990 "checks %v is the right Person")
3991 fmt.Println("Foobar is between 40 & 50:", ok)
3992
3993 ok = td.Cmp(t, got,
3994 td.Struct(
3995 Person{
3996 Name: "Foobar",
3997 Age: 53,
3998 },
3999 td.StructFields{
4000 "> Age": td.Between(40, 50), // same, ">" can be followed by spaces
4001 "NumChildren": td.Gt(2),
4002 }),
4003 "checks %v is the right Person")
4004 fmt.Println("Foobar is between 40 & 50:", ok)
4005
4006 // Output:
4007 // Foobar is between 40 & 50: true
4008 // Foobar is between 40 & 50: true
4009 }
4010
4011 func ExampleStruct_patterns() {
4012 t := &testing.T{}
4013
4014 type Person struct {
4015 Firstname string
4016 Lastname string
4017 Surname string
4018 Nickname string
4019 CreatedAt time.Time
4020 UpdatedAt time.Time
4021 DeletedAt *time.Time
4022 }
4023
4024 now := time.Now()
4025 got := Person{
4026 Firstname: "Maxime",
4027 Lastname: "Foo",
4028 Surname: "Max",
4029 Nickname: "max",
4030 CreatedAt: now,
4031 UpdatedAt: now,
4032 DeletedAt: nil, // not deleted yet
4033 }
4034
4035 ok := td.Cmp(t, got,
4036 td.Struct(Person{Lastname: "Foo"}, td.StructFields{
4037 `DeletedAt`: nil,
4038 `= *name`: td.Re(`^(?i)max`), // shell pattern, matches all names except Lastname as in model
4039 `=~ At\z`: td.Lte(time.Now()), // regexp, matches CreatedAt & UpdatedAt
4040 }),
4041 "mix shell & regexp patterns")
4042 fmt.Println("Patterns match only remaining fields:", ok)
4043
4044 ok = td.Cmp(t, got,
4045 td.Struct(Person{Lastname: "Foo"}, td.StructFields{
4046 `DeletedAt`: nil,
4047 `1 = *name`: td.Re(`^(?i)max`), // shell pattern, matches all names except Lastname as in model
4048 `2 =~ At\z`: td.Lte(time.Now()), // regexp, matches CreatedAt & UpdatedAt
4049 }),
4050 "ordered patterns")
4051 fmt.Println("Ordered patterns match only remaining fields:", ok)
4052
4053 // Output:
4054 // Patterns match only remaining fields: true
4055 // Ordered patterns match only remaining fields: true
4056 }
4057
4058 func ExampleStruct_struct_fields() { // only operator
4059 t := &testing.T{}
4060
4061 type Person struct {
4062 Name string
4063 Age int
4064 NumChildren int
4065 }
4066
4067 got := Person{
4068 Name: "Foobar",
4069 Age: 42,
4070 NumChildren: 3,
4071 }
4072
4073 ok := td.Cmp(t, got, td.Struct(Person{Name: "Foobar"}), "no StructFields")
4074 fmt.Println("Without any StructFields:", ok)
4075
4076 ok = td.Cmp(t, got,
4077 td.Struct(Person{Name: "Bingo"},
4078 td.StructFields{
4079 "> Name": "pipo",
4080 "Age": 42,
4081 },
4082 td.StructFields{
4083 "> Name": "bingo",
4084 "NumChildren": 10,
4085 },
4086 td.StructFields{
4087 ">Name": "Foobar",
4088 "NumChildren": 3,
4089 }),
4090 "merge several StructFields")
4091 fmt.Println("Merge several StructFields:", ok)
4092
4093 // Output:
4094 // Without any StructFields: true
4095 // Merge several StructFields: true
4096 }
4097
4098 func ExampleStruct_lazy_model() {
4099 t := &testing.T{}
4100
4101 got := struct {
4102 name string
4103 age int
4104 }{
4105 name: "Foobar",
4106 age: 42,
4107 }
4108
4109 ok := td.Cmp(t, got, td.Struct(nil, td.StructFields{
4110 "name": "Foobar",
4111 "age": td.Between(40, 45),
4112 }))
4113 fmt.Println("Lazy model:", ok)
4114
4115 ok = td.Cmp(t, got, td.Struct(nil, td.StructFields{
4116 "name": "Foobar",
4117 "zip": 666,
4118 }))
4119 fmt.Println("Lazy model with unknown field:", ok)
4120
4121 // Output:
4122 // Lazy model: true
4123 // Lazy model with unknown field: false
4124 }
4125
4126 func ExampleSStruct() {
4127 t := &testing.T{}
4128
4129 type Person struct {
4130 Name string
4131 Age int
4132 NumChildren int
4133 }
4134
4135 got := Person{
4136 Name: "Foobar",
4137 Age: 42,
4138 NumChildren: 0,
4139 }
4140
4141 // NumChildren is not listed in expected fields so it must be zero
4142 ok := td.Cmp(t, got,
4143 td.SStruct(Person{Name: "Foobar"}, td.StructFields{
4144 "Age": td.Between(40, 50),
4145 }),
4146 "checks %v is the right Person")
4147 fmt.Println("Foobar is between 40 & 50:", ok)
4148
4149 // Model can be empty
4150 got.NumChildren = 3
4151 ok = td.Cmp(t, got,
4152 td.SStruct(Person{}, td.StructFields{
4153 "Name": "Foobar",
4154 "Age": td.Between(40, 50),
4155 "NumChildren": td.Not(0),
4156 }),
4157 "checks %v is the right Person")
4158 fmt.Println("Foobar has some children:", ok)
4159
4160 // Works with pointers too
4161 ok = td.Cmp(t, &got,
4162 td.SStruct(&Person{}, td.StructFields{
4163 "Name": "Foobar",
4164 "Age": td.Between(40, 50),
4165 "NumChildren": td.Not(0),
4166 }),
4167 "checks %v is the right Person")
4168 fmt.Println("Foobar has some children (using pointer):", ok)
4169
4170 // Model does not need to be instanciated
4171 ok = td.Cmp(t, &got,
4172 td.SStruct((*Person)(nil), td.StructFields{
4173 "Name": "Foobar",
4174 "Age": td.Between(40, 50),
4175 "NumChildren": td.Not(0),
4176 }),
4177 "checks %v is the right Person")
4178 fmt.Println("Foobar has some children (using nil model):", ok)
4179
4180 // Output:
4181 // Foobar is between 40 & 50: true
4182 // Foobar has some children: true
4183 // Foobar has some children (using pointer): true
4184 // Foobar has some children (using nil model): true
4185 }
4186
4187 func ExampleSStruct_overwrite_model() {
4188 t := &testing.T{}
4189
4190 type Person struct {
4191 Name string
4192 Age int
4193 NumChildren int
4194 }
4195
4196 got := Person{
4197 Name: "Foobar",
4198 Age: 42,
4199 NumChildren: 3,
4200 }
4201
4202 ok := td.Cmp(t, got,
4203 td.SStruct(
4204 Person{
4205 Name: "Foobar",
4206 Age: 53,
4207 },
4208 td.StructFields{
4209 ">Age": td.Between(40, 50), // ">" to overwrite Age:53 in model
4210 "NumChildren": td.Gt(2),
4211 }),
4212 "checks %v is the right Person")
4213 fmt.Println("Foobar is between 40 & 50:", ok)
4214
4215 ok = td.Cmp(t, got,
4216 td.SStruct(
4217 Person{
4218 Name: "Foobar",
4219 Age: 53,
4220 },
4221 td.StructFields{
4222 "> Age": td.Between(40, 50), // same, ">" can be followed by spaces
4223 "NumChildren": td.Gt(2),
4224 }),
4225 "checks %v is the right Person")
4226 fmt.Println("Foobar is between 40 & 50:", ok)
4227
4228 // Output:
4229 // Foobar is between 40 & 50: true
4230 // Foobar is between 40 & 50: true
4231 }
4232
4233 func ExampleSStruct_patterns() {
4234 t := &testing.T{}
4235
4236 type Person struct {
4237 Firstname string
4238 Lastname string
4239 Surname string
4240 Nickname string
4241 CreatedAt time.Time
4242 UpdatedAt time.Time
4243 DeletedAt *time.Time
4244 id int64
4245 secret string
4246 }
4247
4248 now := time.Now()
4249 got := Person{
4250 Firstname: "Maxime",
4251 Lastname: "Foo",
4252 Surname: "Max",
4253 Nickname: "max",
4254 CreatedAt: now,
4255 UpdatedAt: now,
4256 DeletedAt: nil, // not deleted yet
4257 id: 2345,
4258 secret: "5ecr3T",
4259 }
4260
4261 ok := td.Cmp(t, got,
4262 td.SStruct(Person{Lastname: "Foo"}, td.StructFields{
4263 `DeletedAt`: nil,
4264 `= *name`: td.Re(`^(?i)max`), // shell pattern, matches all names except Lastname as in model
4265 `=~ At\z`: td.Lte(time.Now()), // regexp, matches CreatedAt & UpdatedAt
4266 `! [A-Z]*`: td.Ignore(), // private fields
4267 }),
4268 "mix shell & regexp patterns")
4269 fmt.Println("Patterns match only remaining fields:", ok)
4270
4271 ok = td.Cmp(t, got,
4272 td.SStruct(Person{Lastname: "Foo"}, td.StructFields{
4273 `DeletedAt`: nil,
4274 `1 = *name`: td.Re(`^(?i)max`), // shell pattern, matches all names except Lastname as in model
4275 `2 =~ At\z`: td.Lte(time.Now()), // regexp, matches CreatedAt & UpdatedAt
4276 `3 !~ ^[A-Z]`: td.Ignore(), // private fields
4277 }),
4278 "ordered patterns")
4279 fmt.Println("Ordered patterns match only remaining fields:", ok)
4280
4281 // Output:
4282 // Patterns match only remaining fields: true
4283 // Ordered patterns match only remaining fields: true
4284 }
4285
4286 func ExampleSStruct_struct_fields() { // only operator
4287 t := &testing.T{}
4288
4289 type Person struct {
4290 Name string
4291 Age int
4292 NumChildren int
4293 }
4294
4295 got := Person{
4296 Name: "Foobar",
4297 Age: 42,
4298 NumChildren: 3,
4299 }
4300
4301 // No added value here, but it works
4302 ok := td.Cmp(t, got,
4303 td.SStruct(Person{
4304 Name: "Foobar",
4305 Age: 42,
4306 NumChildren: 3,
4307 }),
4308 "no StructFields")
4309 fmt.Println("Without any StructFields:", ok)
4310
4311 ok = td.Cmp(t, got,
4312 td.SStruct(Person{Name: "Bingo"},
4313 td.StructFields{
4314 "> Name": "pipo",
4315 "Age": 42,
4316 },
4317 td.StructFields{
4318 "> Name": "bingo",
4319 "NumChildren": 10,
4320 },
4321 td.StructFields{
4322 ">Name": "Foobar",
4323 "NumChildren": 3,
4324 }),
4325 "merge several StructFields")
4326 fmt.Println("Merge several StructFields:", ok)
4327
4328 // Output:
4329 // Without any StructFields: true
4330 // Merge several StructFields: true
4331 }
4332
4333 func ExampleSStruct_lazy_model() {
4334 t := &testing.T{}
4335
4336 got := struct {
4337 name string
4338 age int
4339 }{
4340 name: "Foobar",
4341 age: 42,
4342 }
4343
4344 ok := td.Cmp(t, got, td.SStruct(nil, td.StructFields{
4345 "name": "Foobar",
4346 "age": td.Between(40, 45),
4347 }))
4348 fmt.Println("Lazy model:", ok)
4349
4350 ok = td.Cmp(t, got, td.SStruct(nil, td.StructFields{
4351 "name": "Foobar",
4352 "zip": 666,
4353 }))
4354 fmt.Println("Lazy model with unknown field:", ok)
4355
4356 // Output:
4357 // Lazy model: true
4358 // Lazy model with unknown field: false
4359 }
4360
4361 func ExampleSubBagOf() {
4362 t := &testing.T{}
4363
4364 got := []int{1, 3, 5, 8, 8, 1, 2}
4365
4366 ok := td.Cmp(t, got, td.SubBagOf(0, 0, 1, 1, 2, 2, 3, 3, 5, 5, 8, 8, 9, 9),
4367 "checks at least all items are present, in any order")
4368 fmt.Println(ok)
4369
4370 // got contains one 8 too many
4371 ok = td.Cmp(t, got, td.SubBagOf(0, 0, 1, 1, 2, 2, 3, 3, 5, 5, 8, 9, 9),
4372 "checks at least all items are present, in any order")
4373 fmt.Println(ok)
4374
4375 got = []int{1, 3, 5, 2}
4376
4377 ok = td.Cmp(t, got, td.SubBagOf(
4378 td.Between(0, 3),
4379 td.Between(0, 3),
4380 td.Between(0, 3),
4381 td.Between(0, 3),
4382 td.Gt(4),
4383 td.Gt(4)),
4384 "checks at least all items match, in any order with TestDeep operators")
4385 fmt.Println(ok)
4386
4387 // When expected is already a non-[]any slice, it cannot be
4388 // flattened directly using expected... without copying it to a new
4389 // []any slice, then use td.Flatten!
4390 expected := []int{1, 2, 3, 5, 9, 8}
4391 ok = td.Cmp(t, got, td.SubBagOf(td.Flatten(expected)),
4392 "checks at least all expected items are present, in any order")
4393 fmt.Println(ok)
4394
4395 // Output:
4396 // true
4397 // false
4398 // true
4399 // true
4400 }
4401
4402 func ExampleSubJSONOf_basic() {
4403 t := &testing.T{}
4404
4405 got := &struct {
4406 Fullname string `json:"fullname"`
4407 Age int `json:"age"`
4408 }{
4409 Fullname: "Bob",
4410 Age: 42,
4411 }
4412
4413 ok := td.Cmp(t, got, td.SubJSONOf(`{"age":42,"fullname":"Bob","gender":"male"}`))
4414 fmt.Println("check got with age then fullname:", ok)
4415
4416 ok = td.Cmp(t, got, td.SubJSONOf(`{"fullname":"Bob","age":42,"gender":"male"}`))
4417 fmt.Println("check got with fullname then age:", ok)
4418
4419 ok = td.Cmp(t, got, td.SubJSONOf(`
4420 // This should be the JSON representation of a struct
4421 {
4422 // A person:
4423 "fullname": "Bob", // The name of this person
4424 "age": 42, /* The age of this person:
4425 - 42 of course
4426 - to demonstrate a multi-lines comment */
4427 "gender": "male" // This field is ignored as SubJSONOf
4428 }`))
4429 fmt.Println("check got with nicely formatted and commented JSON:", ok)
4430
4431 ok = td.Cmp(t, got, td.SubJSONOf(`{"fullname":"Bob","gender":"male"}`))
4432 fmt.Println("check got without age field:", ok)
4433
4434 // Output:
4435 // check got with age then fullname: true
4436 // check got with fullname then age: true
4437 // check got with nicely formatted and commented JSON: true
4438 // check got without age field: false
4439 }
4440
4441 func ExampleSubJSONOf_placeholders() {
4442 t := &testing.T{}
4443
4444 got := &struct {
4445 Fullname string `json:"fullname"`
4446 Age int `json:"age"`
4447 }{
4448 Fullname: "Bob Foobar",
4449 Age: 42,
4450 }
4451
4452 ok := td.Cmp(t, got,
4453 td.SubJSONOf(`{"age": $1, "fullname": $2, "gender": $3}`,
4454 42, "Bob Foobar", "male"))
4455 fmt.Println("check got with numeric placeholders without operators:", ok)
4456
4457 ok = td.Cmp(t, got,
4458 td.SubJSONOf(`{"age": $1, "fullname": $2, "gender": $3}`,
4459 td.Between(40, 45),
4460 td.HasSuffix("Foobar"),
4461 td.NotEmpty()))
4462 fmt.Println("check got with numeric placeholders:", ok)
4463
4464 ok = td.Cmp(t, got,
4465 td.SubJSONOf(`{"age": "$1", "fullname": "$2", "gender": "$3"}`,
4466 td.Between(40, 45),
4467 td.HasSuffix("Foobar"),
4468 td.NotEmpty()))
4469 fmt.Println("check got with double-quoted numeric placeholders:", ok)
4470
4471 ok = td.Cmp(t, got,
4472 td.SubJSONOf(`{"age": $age, "fullname": $name, "gender": $gender}`,
4473 td.Tag("age", td.Between(40, 45)),
4474 td.Tag("name", td.HasSuffix("Foobar")),
4475 td.Tag("gender", td.NotEmpty())))
4476 fmt.Println("check got with named placeholders:", ok)
4477
4478 ok = td.Cmp(t, got,
4479 td.SubJSONOf(`{"age": $^NotZero, "fullname": $^NotEmpty, "gender": $^NotEmpty}`))
4480 fmt.Println("check got with operator shortcuts:", ok)
4481
4482 // Output:
4483 // check got with numeric placeholders without operators: true
4484 // check got with numeric placeholders: true
4485 // check got with double-quoted numeric placeholders: true
4486 // check got with named placeholders: true
4487 // check got with operator shortcuts: true
4488 }
4489
4490 func ExampleSubJSONOf_file() {
4491 t := &testing.T{}
4492
4493 got := &struct {
4494 Fullname string `json:"fullname"`
4495 Age int `json:"age"`
4496 Gender string `json:"gender"`
4497 }{
4498 Fullname: "Bob Foobar",
4499 Age: 42,
4500 Gender: "male",
4501 }
4502
4503 tmpDir, err := os.MkdirTemp("", "")
4504 if err != nil {
4505 t.Fatal(err)
4506 }
4507 defer os.RemoveAll(tmpDir) //nolint: errcheck // clean up
4508
4509 filename := tmpDir + "/test.json"
4510 if err = os.WriteFile(filename, []byte(`
4511 {
4512 "fullname": "$name",
4513 "age": "$age",
4514 "gender": "$gender",
4515 "details": {
4516 "city": "TestCity",
4517 "zip": 666
4518 }
4519 }`), 0644); err != nil {
4520 t.Fatal(err)
4521 }
4522
4523 // OK let's test with this file
4524 ok := td.Cmp(t, got,
4525 td.SubJSONOf(filename,
4526 td.Tag("name", td.HasPrefix("Bob")),
4527 td.Tag("age", td.Between(40, 45)),
4528 td.Tag("gender", td.Re(`^(male|female)\z`))))
4529 fmt.Println("Full match from file name:", ok)
4530
4531 // When the file is already open
4532 file, err := os.Open(filename)
4533 if err != nil {
4534 t.Fatal(err)
4535 }
4536 ok = td.Cmp(t, got,
4537 td.SubJSONOf(file,
4538 td.Tag("name", td.HasPrefix("Bob")),
4539 td.Tag("age", td.Between(40, 45)),
4540 td.Tag("gender", td.Re(`^(male|female)\z`))))
4541 fmt.Println("Full match from io.Reader:", ok)
4542
4543 // Output:
4544 // Full match from file name: true
4545 // Full match from io.Reader: true
4546 }
4547
4548 func ExampleSubMapOf_map() {
4549 t := &testing.T{}
4550
4551 got := map[string]int{"foo": 12, "bar": 42}
4552
4553 ok := td.Cmp(t, got,
4554 td.SubMapOf(map[string]int{"bar": 42}, td.MapEntries{"foo": td.Lt(15), "zip": 666}),
4555 "checks map %v is included in expected keys/values", got)
4556 fmt.Println(ok)
4557
4558 // Output:
4559 // true
4560 }
4561
4562 func ExampleSubMapOf_typedMap() {
4563 t := &testing.T{}
4564
4565 type MyMap map[string]int
4566
4567 got := MyMap{"foo": 12, "bar": 42}
4568
4569 ok := td.Cmp(t, got,
4570 td.SubMapOf(MyMap{"bar": 42}, td.MapEntries{"foo": td.Lt(15), "zip": 666}),
4571 "checks typed map %v is included in expected keys/values", got)
4572 fmt.Println(ok)
4573
4574 ok = td.Cmp(t, &got,
4575 td.SubMapOf(&MyMap{"bar": 42}, td.MapEntries{"foo": td.Lt(15), "zip": 666}),
4576 "checks pointed typed map %v is included in expected keys/values", got)
4577 fmt.Println(ok)
4578
4579 // Output:
4580 // true
4581 // true
4582 }
4583
4584 func ExampleSubSetOf() {
4585 t := &testing.T{}
4586
4587 got := []int{1, 3, 5, 8, 8, 1, 2}
4588
4589 // Matches as all items are expected, ignoring duplicates
4590 ok := td.Cmp(t, got, td.SubSetOf(1, 2, 3, 4, 5, 6, 7, 8),
4591 "checks at least all items are present, in any order, ignoring duplicates")
4592 fmt.Println(ok)
4593
4594 // Tries its best not to raise an error when a value can be matched
4595 // by several SubSetOf entries
4596 ok = td.Cmp(t, got, td.SubSetOf(td.Between(1, 4), 3, td.Between(2, 10), td.Gt(100)),
4597 "checks at least all items are present, in any order, ignoring duplicates")
4598 fmt.Println(ok)
4599
4600 // When expected is already a non-[]any slice, it cannot be
4601 // flattened directly using expected... without copying it to a new
4602 // []any slice, then use td.Flatten!
4603 expected := []int{1, 2, 3, 4, 5, 6, 7, 8}
4604 ok = td.Cmp(t, got, td.SubSetOf(td.Flatten(expected)),
4605 "checks at least all expected items are present, in any order, ignoring duplicates")
4606 fmt.Println(ok)
4607
4608 // Output:
4609 // true
4610 // true
4611 // true
4612 }
4613
4614 func ExampleSuperBagOf() {
4615 t := &testing.T{}
4616
4617 got := []int{1, 3, 5, 8, 8, 1, 2}
4618
4619 ok := td.Cmp(t, got, td.SuperBagOf(8, 5, 8),
4620 "checks the items are present, in any order")
4621 fmt.Println(ok)
4622
4623 ok = td.Cmp(t, got, td.SuperBagOf(td.Gt(5), td.Lte(2)),
4624 "checks at least 2 items of %v match", got)
4625 fmt.Println(ok)
4626
4627 // When expected is already a non-[]any slice, it cannot be
4628 // flattened directly using expected... without copying it to a new
4629 // []any slice, then use td.Flatten!
4630 expected := []int{8, 5, 8}
4631 ok = td.Cmp(t, got, td.SuperBagOf(td.Flatten(expected)),
4632 "checks the expected items are present, in any order")
4633 fmt.Println(ok)
4634
4635 // Output:
4636 // true
4637 // true
4638 // true
4639 }
4640
4641 func ExampleSuperJSONOf_basic() {
4642 t := &testing.T{}
4643
4644 got := &struct {
4645 Fullname string `json:"fullname"`
4646 Age int `json:"age"`
4647 Gender string `json:"gender"`
4648 City string `json:"city"`
4649 Zip int `json:"zip"`
4650 }{
4651 Fullname: "Bob",
4652 Age: 42,
4653 Gender: "male",
4654 City: "TestCity",
4655 Zip: 666,
4656 }
4657
4658 ok := td.Cmp(t, got, td.SuperJSONOf(`{"age":42,"fullname":"Bob","gender":"male"}`))
4659 fmt.Println("check got with age then fullname:", ok)
4660
4661 ok = td.Cmp(t, got, td.SuperJSONOf(`{"fullname":"Bob","age":42,"gender":"male"}`))
4662 fmt.Println("check got with fullname then age:", ok)
4663
4664 ok = td.Cmp(t, got, td.SuperJSONOf(`
4665 // This should be the JSON representation of a struct
4666 {
4667 // A person:
4668 "fullname": "Bob", // The name of this person
4669 "age": 42, /* The age of this person:
4670 - 42 of course
4671 - to demonstrate a multi-lines comment */
4672 "gender": "male" // The gender!
4673 }`))
4674 fmt.Println("check got with nicely formatted and commented JSON:", ok)
4675
4676 ok = td.Cmp(t, got,
4677 td.SuperJSONOf(`{"fullname":"Bob","gender":"male","details":{}}`))
4678 fmt.Println("check got with details field:", ok)
4679
4680 // Output:
4681 // check got with age then fullname: true
4682 // check got with fullname then age: true
4683 // check got with nicely formatted and commented JSON: true
4684 // check got with details field: false
4685 }
4686
4687 func ExampleSuperJSONOf_placeholders() {
4688 t := &testing.T{}
4689
4690 got := &struct {
4691 Fullname string `json:"fullname"`
4692 Age int `json:"age"`
4693 Gender string `json:"gender"`
4694 City string `json:"city"`
4695 Zip int `json:"zip"`
4696 }{
4697 Fullname: "Bob Foobar",
4698 Age: 42,
4699 Gender: "male",
4700 City: "TestCity",
4701 Zip: 666,
4702 }
4703
4704 ok := td.Cmp(t, got,
4705 td.SuperJSONOf(`{"age": $1, "fullname": $2, "gender": $3}`,
4706 42, "Bob Foobar", "male"))
4707 fmt.Println("check got with numeric placeholders without operators:", ok)
4708
4709 ok = td.Cmp(t, got,
4710 td.SuperJSONOf(`{"age": $1, "fullname": $2, "gender": $3}`,
4711 td.Between(40, 45),
4712 td.HasSuffix("Foobar"),
4713 td.NotEmpty()))
4714 fmt.Println("check got with numeric placeholders:", ok)
4715
4716 ok = td.Cmp(t, got,
4717 td.SuperJSONOf(`{"age": "$1", "fullname": "$2", "gender": "$3"}`,
4718 td.Between(40, 45),
4719 td.HasSuffix("Foobar"),
4720 td.NotEmpty()))
4721 fmt.Println("check got with double-quoted numeric placeholders:", ok)
4722
4723 ok = td.Cmp(t, got,
4724 td.SuperJSONOf(`{"age": $age, "fullname": $name, "gender": $gender}`,
4725 td.Tag("age", td.Between(40, 45)),
4726 td.Tag("name", td.HasSuffix("Foobar")),
4727 td.Tag("gender", td.NotEmpty())))
4728 fmt.Println("check got with named placeholders:", ok)
4729
4730 ok = td.Cmp(t, got,
4731 td.SuperJSONOf(`{"age": $^NotZero, "fullname": $^NotEmpty, "gender": $^NotEmpty}`))
4732 fmt.Println("check got with operator shortcuts:", ok)
4733
4734 // Output:
4735 // check got with numeric placeholders without operators: true
4736 // check got with numeric placeholders: true
4737 // check got with double-quoted numeric placeholders: true
4738 // check got with named placeholders: true
4739 // check got with operator shortcuts: true
4740 }
4741
4742 func ExampleSuperJSONOf_file() {
4743 t := &testing.T{}
4744
4745 got := &struct {
4746 Fullname string `json:"fullname"`
4747 Age int `json:"age"`
4748 Gender string `json:"gender"`
4749 City string `json:"city"`
4750 Zip int `json:"zip"`
4751 }{
4752 Fullname: "Bob Foobar",
4753 Age: 42,
4754 Gender: "male",
4755 City: "TestCity",
4756 Zip: 666,
4757 }
4758
4759 tmpDir, err := os.MkdirTemp("", "")
4760 if err != nil {
4761 t.Fatal(err)
4762 }
4763 defer os.RemoveAll(tmpDir) //nolint: errcheck // clean up
4764
4765 filename := tmpDir + "/test.json"
4766 if err = os.WriteFile(filename, []byte(`
4767 {
4768 "fullname": "$name",
4769 "age": "$age",
4770 "gender": "$gender"
4771 }`), 0644); err != nil {
4772 t.Fatal(err)
4773 }
4774
4775 // OK let's test with this file
4776 ok := td.Cmp(t, got,
4777 td.SuperJSONOf(filename,
4778 td.Tag("name", td.HasPrefix("Bob")),
4779 td.Tag("age", td.Between(40, 45)),
4780 td.Tag("gender", td.Re(`^(male|female)\z`))))
4781 fmt.Println("Full match from file name:", ok)
4782
4783 // When the file is already open
4784 file, err := os.Open(filename)
4785 if err != nil {
4786 t.Fatal(err)
4787 }
4788 ok = td.Cmp(t, got,
4789 td.SuperJSONOf(file,
4790 td.Tag("name", td.HasPrefix("Bob")),
4791 td.Tag("age", td.Between(40, 45)),
4792 td.Tag("gender", td.Re(`^(male|female)\z`))))
4793 fmt.Println("Full match from io.Reader:", ok)
4794
4795 // Output:
4796 // Full match from file name: true
4797 // Full match from io.Reader: true
4798 }
4799
4800 func ExampleSuperMapOf_map() {
4801 t := &testing.T{}
4802
4803 got := map[string]int{"foo": 12, "bar": 42, "zip": 89}
4804
4805 ok := td.Cmp(t, got,
4806 td.SuperMapOf(map[string]int{"bar": 42}, td.MapEntries{"foo": td.Lt(15)}),
4807 "checks map %v contains at least all expected keys/values", got)
4808 fmt.Println(ok)
4809
4810 // Output:
4811 // true
4812 }
4813
4814 func ExampleSuperMapOf_typedMap() {
4815 t := &testing.T{}
4816
4817 type MyMap map[string]int
4818
4819 got := MyMap{"foo": 12, "bar": 42, "zip": 89}
4820
4821 ok := td.Cmp(t, got,
4822 td.SuperMapOf(MyMap{"bar": 42}, td.MapEntries{"foo": td.Lt(15)}),
4823 "checks typed map %v contains at least all expected keys/values", got)
4824 fmt.Println(ok)
4825
4826 ok = td.Cmp(t, &got,
4827 td.SuperMapOf(&MyMap{"bar": 42}, td.MapEntries{"foo": td.Lt(15)}),
4828 "checks pointed typed map %v contains at least all expected keys/values",
4829 got)
4830 fmt.Println(ok)
4831
4832 // Output:
4833 // true
4834 // true
4835 }
4836
4837 func ExampleSuperSetOf() {
4838 t := &testing.T{}
4839
4840 got := []int{1, 3, 5, 8, 8, 1, 2}
4841
4842 ok := td.Cmp(t, got, td.SuperSetOf(1, 2, 3),
4843 "checks the items are present, in any order and ignoring duplicates")
4844 fmt.Println(ok)
4845
4846 ok = td.Cmp(t, got, td.SuperSetOf(td.Gt(5), td.Lte(2)),
4847 "checks at least 2 items of %v match ignoring duplicates", got)
4848 fmt.Println(ok)
4849
4850 // When expected is already a non-[]any slice, it cannot be
4851 // flattened directly using expected... without copying it to a new
4852 // []any slice, then use td.Flatten!
4853 expected := []int{1, 2, 3}
4854 ok = td.Cmp(t, got, td.SuperSetOf(td.Flatten(expected)),
4855 "checks the expected items are present, in any order and ignoring duplicates")
4856 fmt.Println(ok)
4857
4858 // Output:
4859 // true
4860 // true
4861 // true
4862 }
4863
4864 func ExampleTruncTime() {
4865 t := &testing.T{}
4866
4867 dateToTime := func(str string) time.Time {
4868 t, err := time.Parse(time.RFC3339Nano, str)
4869 if err != nil {
4870 panic(err)
4871 }
4872 return t
4873 }
4874
4875 got := dateToTime("2018-05-01T12:45:53.123456789Z")
4876
4877 // Compare dates ignoring nanoseconds and monotonic parts
4878 expected := dateToTime("2018-05-01T12:45:53Z")
4879 ok := td.Cmp(t, got, td.TruncTime(expected, time.Second),
4880 "checks date %v, truncated to the second", got)
4881 fmt.Println(ok)
4882
4883 // Compare dates ignoring time and so monotonic parts
4884 expected = dateToTime("2018-05-01T11:22:33.444444444Z")
4885 ok = td.Cmp(t, got, td.TruncTime(expected, 24*time.Hour),
4886 "checks date %v, truncated to the day", got)
4887 fmt.Println(ok)
4888
4889 // Compare dates exactly but ignoring monotonic part
4890 expected = dateToTime("2018-05-01T12:45:53.123456789Z")
4891 ok = td.Cmp(t, got, td.TruncTime(expected),
4892 "checks date %v ignoring monotonic part", got)
4893 fmt.Println(ok)
4894
4895 // Output:
4896 // true
4897 // true
4898 // true
4899 }
4900
4901 func ExampleValues() {
4902 t := &testing.T{}
4903
4904 got := map[string]int{"foo": 1, "bar": 2, "zip": 3}
4905
4906 // Values tests values in an ordered manner
4907 ok := td.Cmp(t, got, td.Values([]int{1, 2, 3}))
4908 fmt.Println("All sorted values are found:", ok)
4909
4910 // If the expected values are not ordered, it fails
4911 ok = td.Cmp(t, got, td.Values([]int{3, 1, 2}))
4912 fmt.Println("All unsorted values are found:", ok)
4913
4914 // To circumvent that, one can use Bag operator
4915 ok = td.Cmp(t, got, td.Values(td.Bag(3, 1, 2)))
4916 fmt.Println("All unsorted values are found, with the help of Bag operator:", ok)
4917
4918 // Check that each value is between 1 and 3
4919 ok = td.Cmp(t, got, td.Values(td.ArrayEach(td.Between(1, 3))))
4920 fmt.Println("Each value is between 1 and 3:", ok)
4921
4922 // Output:
4923 // All sorted values are found: true
4924 // All unsorted values are found: false
4925 // All unsorted values are found, with the help of Bag operator: true
4926 // Each value is between 1 and 3: true
4927 }
4928
4929 func ExampleZero() {
4930 t := &testing.T{}
4931
4932 ok := td.Cmp(t, 0, td.Zero())
4933 fmt.Println(ok)
4934
4935 ok = td.Cmp(t, float64(0), td.Zero())
4936 fmt.Println(ok)
4937
4938 ok = td.Cmp(t, 12, td.Zero()) // fails, as 12 is not 0 :)
4939 fmt.Println(ok)
4940
4941 ok = td.Cmp(t, (map[string]int)(nil), td.Zero())
4942 fmt.Println(ok)
4943
4944 ok = td.Cmp(t, map[string]int{}, td.Zero()) // fails, as not nil
4945 fmt.Println(ok)
4946
4947 ok = td.Cmp(t, ([]int)(nil), td.Zero())
4948 fmt.Println(ok)
4949
4950 ok = td.Cmp(t, []int{}, td.Zero()) // fails, as not nil
4951 fmt.Println(ok)
4952
4953 ok = td.Cmp(t, [3]int{}, td.Zero())
4954 fmt.Println(ok)
4955
4956 ok = td.Cmp(t, [3]int{0, 1}, td.Zero()) // fails, DATA[1] is not 0
4957 fmt.Println(ok)
4958
4959 ok = td.Cmp(t, bytes.Buffer{}, td.Zero())
4960 fmt.Println(ok)
4961
4962 ok = td.Cmp(t, &bytes.Buffer{}, td.Zero()) // fails, as pointer not nil
4963 fmt.Println(ok)
4964
4965 ok = td.Cmp(t, &bytes.Buffer{}, td.Ptr(td.Zero())) // OK with the help of Ptr()
4966 fmt.Println(ok)
4967
4968 // Output:
4969 // true
4970 // true
4971 // false
4972 // true
4973 // false
4974 // true
4975 // false
4976 // true
4977 // false
4978 // true
4979 // false
4980 // true
4981 }