Debian Codegraph @

td/td_smuggle_test.go

raw
1 // Copyright (c) 2018-2024, 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 "compress/gzip"
12 "encoding/hex"
13 "encoding/json"
14 "errors"
15 "fmt"
16 "io"
17 "reflect"
18 "strconv"
19 "strings"
20 "testing"
21 "time"
22
23 "github.com/maxatome/go-testdeep/internal/ctxerr"
24 "github.com/maxatome/go-testdeep/internal/test"
25 "github.com/maxatome/go-testdeep/td"
26 )
27
28 // reArmReader is a bytes.Reader that re-arms when an error occurs,
29 // typically on EOF.
30 type reArmReader bytes.Reader
31
32 var _ io.Reader = (*reArmReader)(nil)
33
34 func newReArmReader(b []byte) *reArmReader {
35 return (*reArmReader)(bytes.NewReader(b))
36 }
37
38 func (r *reArmReader) Read(b []byte) (n int, err error) {
39 n, err = (*bytes.Reader)(r).Read(b)
40 if err != nil {
41 (*bytes.Reader)(r).Seek(0, io.SeekStart) //nolint: errcheck
42 }
43 return
44 }
45
46 func (r *reArmReader) String() string { return "<no string here>" }
47
48 func TestSmuggle(t *testing.T) {
49 num := 42
50 gotStruct := MyStruct{
51 MyStructMid: MyStructMid{
52 MyStructBase: MyStructBase{
53 ValBool: true,
54 },
55 ValStr: "foobar",
56 },
57 ValInt: 123,
58 Ptr: &num,
59 }
60
61 gotTime, err := time.Parse(time.RFC3339, "2018-05-23T12:13:14Z")
62 if err != nil {
63 t.Fatal(err)
64 }
65
66 //
67 // One returned value
68 checkOK(t,
69 gotTime,
70 td.Smuggle(
71 func(date time.Time) int {
72 return date.Year()
73 },
74 td.Between(2010, 2020)))
75
76 checkOK(t,
77 gotStruct,
78 td.Smuggle(
79 func(s MyStruct) td.SmuggledGot {
80 return td.SmuggledGot{
81 Name: "ValStr",
82 Got: s.ValStr,
83 }
84 },
85 td.Contains("oob")))
86
87 checkOK(t,
88 gotStruct,
89 td.Smuggle(
90 func(s MyStruct) *td.SmuggledGot {
91 return &td.SmuggledGot{
92 Name: "ValStr",
93 Got: s.ValStr,
94 }
95 },
96 td.Contains("oob")))
97
98 //
99 // 2 returned values
100 checkOK(t,
101 gotStruct,
102 td.Smuggle(
103 func(s MyStruct) (string, bool) {
104 if s.ValStr == "" {
105 return "", false
106 }
107 return s.ValStr, true
108 },
109 td.Contains("oob")))
110
111 checkOK(t,
112 gotStruct,
113 td.Smuggle(
114 func(s MyStruct) (td.SmuggledGot, bool) {
115 if s.ValStr == "" {
116 return td.SmuggledGot{}, false
117 }
118 return td.SmuggledGot{
119 Name: "ValStr",
120 Got: s.ValStr,
121 }, true
122 },
123 td.Contains("oob")))
124
125 checkOK(t,
126 gotStruct,
127 td.Smuggle(
128 func(s MyStruct) (*td.SmuggledGot, bool) {
129 if s.ValStr == "" {
130 return nil, false
131 }
132 return &td.SmuggledGot{
133 Name: "ValStr",
134 Got: s.ValStr,
135 }, true
136 },
137 td.Contains("oob")))
138
139 //
140 // 3 returned values
141 checkOK(t,
142 gotStruct,
143 td.Smuggle(
144 func(s MyStruct) (string, bool, string) {
145 if s.ValStr == "" {
146 return "", false, "ValStr must not be empty"
147 }
148 return s.ValStr, true, ""
149 },
150 td.Contains("oob")))
151
152 checkOK(t,
153 gotStruct,
154 td.Smuggle(
155 func(s MyStruct) (td.SmuggledGot, bool, string) {
156 if s.ValStr == "" {
157 return td.SmuggledGot{}, false, "ValStr must not be empty"
158 }
159 return td.SmuggledGot{
160 Name: "ValStr",
161 Got: s.ValStr,
162 }, true, ""
163 },
164 td.Contains("oob")))
165
166 checkOK(t,
167 gotStruct,
168 td.Smuggle(
169 func(s MyStruct) (*td.SmuggledGot, bool, string) {
170 if s.ValStr == "" {
171 return nil, false, "ValStr must not be empty"
172 }
173 return &td.SmuggledGot{
174 Name: "ValStr",
175 Got: s.ValStr,
176 }, true, ""
177 },
178 td.Contains("oob")))
179
180 //
181 // Convertible types
182 checkOK(t, 123,
183 td.Smuggle(func(n float64) int { return int(n) }, 123))
184
185 type xInt int
186 checkOK(t, xInt(123),
187 td.Smuggle(func(n int) int64 { return int64(n) }, int64(123)))
188 checkOK(t, xInt(123),
189 td.Smuggle(func(n uint32) int64 { return int64(n) }, int64(123)))
190
191 checkOK(t, int32(123),
192 td.Smuggle(func(n int64) int { return int(n) }, 123))
193
194 checkOK(t, gotTime,
195 td.Smuggle(func(t fmt.Stringer) string { return t.String() },
196 "2018-05-23 12:13:14 +0000 UTC"))
197
198 checkOK(t, []byte("{}"),
199 td.Smuggle(
200 func(x json.RawMessage) json.RawMessage { return x },
201 td.JSON(`{}`)))
202
203 //
204 // bytes slice caster variations
205 checkOK(t, []byte(`{"foo":1}`),
206 td.Smuggle(json.RawMessage{}, td.JSON(`{"foo":1}`)))
207
208 checkOK(t, []byte(`{"foo":1}`),
209 td.Smuggle(json.RawMessage(nil), td.JSON(`{"foo":1}`)))
210
211 checkOK(t, []byte(`{"foo":1}`),
212 td.Smuggle(reflect.TypeOf(json.RawMessage(nil)), td.JSON(`{"foo":1}`)))
213
214 checkOK(t, `{"foo":1}`,
215 td.Smuggle(json.RawMessage{}, td.JSON(`{"foo":1}`)))
216
217 checkOK(t, newReArmReader([]byte(`{"foo":1}`)), // io.Reader first
218 td.Smuggle(json.RawMessage{}, td.JSON(`{"foo":1}`)))
219
220 // Use %T as starting go1.27, json.RawMessage is now an alias to
221 // jsontext.Value
222 jsonRawMessageType := fmt.Sprintf("%T", json.RawMessage{})
223
224 checkError(t, nil,
225 td.Smuggle(json.RawMessage{}, td.JSON(`{}`)),
226 expectedError{
227 Message: mustBe("incompatible parameter type"),
228 Path: mustBe("DATA"),
229 Got: mustBe("nil"),
230 Expected: mustBe(jsonRawMessageType + " or convertible or io.Reader"),
231 })
232
233 checkError(t, MyStruct{},
234 td.Smuggle(json.RawMessage{}, td.JSON(`{}`)),
235 expectedError{
236 Message: mustBe("incompatible parameter type"),
237 Path: mustBe("DATA"),
238 Got: mustBe("td_test.MyStruct"),
239 Expected: mustBe(jsonRawMessageType + " or convertible or io.Reader"),
240 })
241
242 checkError(t, errReader{}, // erroneous io.Reader
243 td.Smuggle(json.RawMessage{}, td.JSON(`{}`)),
244 expectedError{
245 Message: mustBe("an error occurred while reading from io.Reader"),
246 Path: mustBe("DATA"),
247 Summary: mustBe("an error occurred"),
248 })
249
250 //
251 // strings caster variations
252 type myString string
253 checkOK(t, `pipo bingo`,
254 td.Smuggle("", td.HasSuffix("bingo")))
255
256 checkOK(t, []byte(`pipo bingo`),
257 td.Smuggle(myString(""), td.HasSuffix("bingo")))
258
259 checkOK(t, []byte(`pipo bingo`),
260 td.Smuggle(reflect.TypeOf(myString("")), td.HasSuffix("bingo")))
261
262 checkOK(t, newReArmReader([]byte(`pipo bingo`)), // io.Reader first
263 td.Smuggle(myString(""), td.HasSuffix("bingo")))
264
265 checkError(t, nil,
266 td.Smuggle("", "bingo"),
267 expectedError{
268 Message: mustBe("incompatible parameter type"),
269 Path: mustBe("DATA"),
270 Got: mustBe("nil"),
271 Expected: mustBe("string or convertible or io.Reader"),
272 })
273
274 checkError(t, MyStruct{},
275 td.Smuggle(myString(""), "bingo"),
276 expectedError{
277 Message: mustBe("incompatible parameter type"),
278 Path: mustBe("DATA"),
279 Got: mustBe("td_test.MyStruct"),
280 Expected: mustBe("td_test.myString or convertible or io.Reader"),
281 })
282
283 checkError(t, errReader{}, // erroneous io.Reader
284 td.Smuggle("", "bingo"),
285 expectedError{
286 Message: mustBe("an error occurred while reading from io.Reader"),
287 Path: mustBe("DATA"),
288 Summary: mustBe("an error occurred"),
289 })
290
291 //
292 // Any other caster variations
293 checkOK(t, `pipo bingo`,
294 td.Smuggle([]rune{}, td.Contains([]rune(`bing`))))
295 checkOK(t, `pipo bingo`,
296 td.Smuggle(([]rune)(nil), td.Contains([]rune(`bing`))))
297 checkOK(t, `pipo bingo`,
298 td.Smuggle(reflect.TypeOf([]rune{}), td.Contains([]rune(`bing`))))
299
300 checkOK(t, 123.456, td.Smuggle(int64(0), int64(123)))
301 checkOK(t, 123.456, td.Smuggle(reflect.TypeOf(int64(0)), int64(123)))
302
303 //
304 // Chained Smuggle
305 checkOK(t, `123456789`,
306 td.Smuggle(
307 strconv.Atoi,
308 strconv.Itoa,
309 strconv.Atoi,
310 strconv.Itoa,
311 strconv.Atoi,
312 123456789))
313
314 //
315 // Errors
316 checkError(t, "123",
317 td.Smuggle(func(n float64) int { return int(n) }, 123),
318 expectedError{
319 Message: mustBe("incompatible parameter type"),
320 Path: mustBe("DATA"),
321 Got: mustBe("string"),
322 Expected: mustBe("float64"),
323 })
324
325 checkError(t, nil,
326 td.Smuggle(func(n int64) int { return int(n) }, 123),
327 expectedError{
328 Message: mustBe("incompatible parameter type"),
329 Path: mustBe("DATA"),
330 Got: mustBe("nil"),
331 Expected: mustBe("int64"),
332 })
333
334 checkError(t, 12,
335 td.Smuggle(func(n int) (int, bool) { return n, false }, 12),
336 expectedError{
337 Message: mustBe("ran smuggle code with %% as argument"),
338 Path: mustBe("DATA"),
339 Summary: mustBe(" value: 12\nit failed but didn't say why"),
340 })
341
342 type MyBool bool
343 type MyString string
344 checkError(t, 12,
345 td.Smuggle(func(n int) (int, MyBool, MyString) {
346 return n, false, "very custom error"
347 }, 12),
348 expectedError{
349 Message: mustBe("ran smuggle code with %% as argument"),
350 Path: mustBe("DATA"),
351 Summary: mustBe(" value: 12\nit failed coz: very custom error"),
352 })
353
354 checkError(t, 12,
355 td.Smuggle(func(n int) (int, error) {
356 return n, errors.New("very custom error")
357 }, 12),
358 expectedError{
359 Message: mustBe("ran smuggle code with %% as argument"),
360 Path: mustBe("DATA"),
361 Summary: mustBe(" value: 12\nit failed coz: very custom error"),
362 })
363
364 checkError(t, 12,
365 td.Smuggle(func(n int) *td.SmuggledGot { return nil }, int64(13)),
366 expectedError{
367 Message: mustBe("values differ"),
368 Path: mustBe("DATA"),
369 Got: mustBe("nil"),
370 Expected: mustBe("(int64) 13"),
371 })
372
373 // Internal use
374 checkError(t, 12,
375 td.Smuggle(func(n int) (int, error) {
376 return n, &ctxerr.Error{
377 Message: "my message",
378 Summary: ctxerr.NewSummary("my summary"),
379 }
380 }, 13),
381 expectedError{
382 Message: mustBe("my message"),
383 Path: mustBe("DATA"),
384 Summary: mustBe("my summary"),
385 })
386
387 //
388 // Errors behind Smuggle()
389 checkError(t, 12,
390 td.Smuggle(func(n int) int64 { return int64(n) }, int64(13)),
391 expectedError{
392 Message: mustBe("values differ"),
393 Path: mustBe("DATA<smuggled>"),
394 Got: mustBe("(int64) 12"),
395 Expected: mustBe("(int64) 13"),
396 })
397
398 checkError(t, gotStruct,
399 td.Smuggle("MyStructMid.MyStructBase.ValBool", false),
400 expectedError{
401 Message: mustBe("values differ"),
402 Path: mustBe("DATA.MyStructMid.MyStructBase.ValBool"),
403 Got: mustBe("true"),
404 Expected: mustBe("false"),
405 })
406
407 checkError(t, 12,
408 td.Smuggle(func(n int) td.SmuggledGot {
409 return td.SmuggledGot{
410 // With Name = ""
411 Got: int64(n),
412 }
413 }, int64(13)),
414 expectedError{
415 Message: mustBe("values differ"),
416 Path: mustBe("DATA<smuggled>"),
417 Got: mustBe("(int64) 12"),
418 Expected: mustBe("(int64) 13"),
419 })
420
421 checkError(t, 12,
422 td.Smuggle(func(n int) *td.SmuggledGot {
423 return &td.SmuggledGot{
424 Name: "<int64>",
425 Got: int64(n),
426 }
427 }, int64(13)),
428 expectedError{
429 Message: mustBe("values differ"),
430 Path: mustBe("DATA<int64>"), // no dot added between DATA and <int64>
431 Got: mustBe("(int64) 12"),
432 Expected: mustBe("(int64) 13"),
433 })
434
435 checkError(t, 12,
436 td.Smuggle(func(n int) *td.SmuggledGot {
437 return &td.SmuggledGot{
438 Name: "Int64",
439 Got: int64(n),
440 }
441 }, int64(13)),
442 expectedError{
443 Message: mustBe("values differ"),
444 Path: mustBe("DATA.Int64"), // dot added between DATA and Int64
445 Got: mustBe("(int64) 12"),
446 Expected: mustBe("(int64) 13"),
447 })
448
449 //
450 // Bad usage
451 const usage = "Smuggle(FUNC|FIELDS_PATH|ANY_TYPE[, FUNC|FIELDS_PATH|ANY_TYPE, ...], TESTDEEP_OPERATOR|EXPECTED_VALUE): "
452
453 checkError(t, "never tested",
454 td.Smuggle("only one param"),
455 expectedError{
456 Message: mustBe("bad usage of Smuggle operator"),
457 Path: mustBe("DATA"),
458 Summary: mustBe("usage: " + usage[:len(usage)-2] + ", too few parameters"),
459 })
460
461 checkError(t, "never tested",
462 td.Smuggle(nil, 12),
463 expectedError{
464 Message: mustBe("bad usage of Smuggle operator"),
465 Path: mustBe("DATA"),
466 Summary: mustBe("usage: " + usage[:len(usage)-2] + ", ANY_TYPE cannot be nil nor interface"),
467 })
468
469 checkError(t, nil,
470 td.Smuggle(reflect.TypeOf((*fmt.Stringer)(nil)).Elem(), 1234),
471 expectedError{
472 Message: mustBe("bad usage of Smuggle operator"),
473 Path: mustBe("DATA"),
474 Summary: mustBe("usage: " + usage[:len(usage)-2] + ", ANY_TYPE reflect.Type cannot be interface"),
475 })
476
477 checkError(t, nil, // error in a chained Smuggle
478 td.Smuggle(reflect.TypeOf((*fmt.Stringer)(nil)).Elem(), "", 1234),
479 expectedError{
480 Message: mustBe("bad usage of Smuggle operator"),
481 Path: mustBe("DATA"),
482 Summary: mustBe("usage: " + usage[:len(usage)-2] + ", ANY_TYPE reflect.Type cannot be interface as 1st parameter"),
483 })
484
485 checkError(t, nil,
486 td.Smuggle(reflect.TypeOf(func() {}), 1234),
487 expectedError{
488 Message: mustBe("bad usage of Smuggle operator"),
489 Path: mustBe("DATA"),
490 Summary: mustBe("usage: " + usage[:len(usage)-2] + ", ANY_TYPE reflect.Type cannot be func"),
491 })
492
493 checkError(t, "never tested",
494 td.Smuggle((func(string) int)(nil), 12),
495 expectedError{
496 Message: mustBe("bad usage of Smuggle operator"),
497 Path: mustBe("DATA"),
498 Summary: mustBe("Smuggle(FUNC): FUNC cannot be a nil function"),
499 })
500
501 checkError(t, "never tested",
502 td.Smuggle((func(string) int)(nil), 12),
503 expectedError{
504 Message: mustBe("bad usage of Smuggle operator"),
505 Path: mustBe("DATA"),
506 Summary: mustBe("Smuggle(FUNC): FUNC cannot be a nil function"),
507 })
508
509 checkError(t, "never tested",
510 td.Smuggle("bad[path", 12),
511 expectedError{
512 Message: mustBe("bad usage of Smuggle operator"),
513 Path: mustBe("DATA"),
514 Summary: mustBe(usage + `cannot find final ']' in FIELDS_PATH "bad[path"`),
515 })
516
517 // Bad number of args
518 checkError(t, "never tested",
519 td.Smuggle(func() int { return 0 }, 12),
520 expectedError{
521 Message: mustBe("bad usage of Smuggle operator"),
522 Path: mustBe("DATA"),
523 Summary: mustBe(usage + "FUNC must take only one non-variadic argument"),
524 })
525
526 checkError(t, "never tested",
527 td.Smuggle(func(x ...int) int { return 0 }, 12),
528 expectedError{
529 Message: mustBe("bad usage of Smuggle operator"),
530 Path: mustBe("DATA"),
531 Summary: mustBe(usage + "FUNC must take only one non-variadic argument"),
532 })
533
534 checkError(t, "never tested",
535 td.Smuggle(func(a int, b string) int { return 0 }, 12),
536 expectedError{
537 Message: mustBe("bad usage of Smuggle operator"),
538 Path: mustBe("DATA"),
539 Summary: mustBe(usage + "FUNC must take only one non-variadic argument"),
540 })
541
542 // Bad number of returned values
543 const errMesg = usage + "FUNC must return value or (value, bool) or (value, bool, string) or (value, error)"
544
545 checkError(t, "never tested",
546 td.Smuggle(func(a int) {}, 12),
547 expectedError{
548 Message: mustBe("bad usage of Smuggle operator"),
549 Path: mustBe("DATA"),
550 Summary: mustBe(errMesg),
551 })
552
553 checkError(t, "never tested",
554 td.Smuggle(
555 func(a int) (int, bool, string, int) { return 0, false, "", 23 },
556 12),
557 expectedError{
558 Message: mustBe("bad usage of Smuggle operator"),
559 Path: mustBe("DATA"),
560 Summary: mustBe(errMesg),
561 })
562
563 // Bad returned types
564 checkError(t, "never tested",
565 td.Smuggle(func(a int) (int, int) { return 0, 0 }, 12),
566 expectedError{
567 Message: mustBe("bad usage of Smuggle operator"),
568 Path: mustBe("DATA"),
569 Summary: mustBe(errMesg),
570 })
571
572 checkError(t, "never tested",
573 td.Smuggle(func(a int) (int, bool, int) { return 0, false, 23 }, 12),
574 expectedError{
575 Message: mustBe("bad usage of Smuggle operator"),
576 Path: mustBe("DATA"),
577 Summary: mustBe(errMesg),
578 })
579
580 checkError(t, "never tested",
581 td.Smuggle(func(a int) (int, error, string) { return 0, nil, "" }, 12), //nolint: staticcheck
582 expectedError{
583 Message: mustBe("bad usage of Smuggle operator"),
584 Path: mustBe("DATA"),
585 Summary: mustBe(errMesg),
586 })
587
588 //
589 // String
590 test.EqualStr(t,
591 td.Smuggle(func(n int) int { return 0 }, 12).String(),
592 "Smuggle(func(int) int, 12)")
593
594 test.EqualStr(t,
595 td.Smuggle(func(n int) (int, bool) { return 23, false }, 12).String(),
596 "Smuggle(func(int) (int, bool), 12)")
597
598 test.EqualStr(t,
599 td.Smuggle(func(n int) (int, error) { return 23, nil }, 12).String(),
600 "Smuggle(func(int) (int, error), 12)")
601
602 test.EqualStr(t,
603 td.Smuggle(func(n int) (int, MyBool, MyString) { return 23, false, "" }, 12).
604 String(),
605 "Smuggle(func(int) (int, td_test.MyBool, td_test.MyString), 12)")
606
607 test.EqualStr(t,
608 td.Smuggle(reflect.TypeOf(42), 23).String(),
609 "Smuggle(type:int, 23)")
610
611 test.EqualStr(t,
612 td.Smuggle(666, 23).String(),
613 "Smuggle(type:int, 23)")
614
615 test.EqualStr(t,
616 td.Smuggle("", 23).String(),
617 "Smuggle(type:string, 23)")
618
619 test.EqualStr(t,
620 td.Smuggle("name", "bob").String(),
621 `Smuggle("name", "bob")`)
622
623 // Erroneous op
624 test.EqualStr(t,
625 td.Smuggle((func(int) int)(nil), 12).String(),
626 "Smuggle(<ERROR>)")
627 }
628
629 func TestSmuggleFieldsPath(t *testing.T) {
630 num := 42
631 gotStruct := MyStruct{
632 MyStructMid: MyStructMid{
633 MyStructBase: MyStructBase{
634 ValBool: true,
635 },
636 ValStr: "foobar",
637 },
638 ValInt: 123,
639 Ptr: &num,
640 }
641
642 type A struct {
643 Num int
644 Str string
645 }
646 type C struct {
647 A A
648 PA1 *A
649 PA2 *A
650 Iface1 any
651 Iface2 any
652 Iface3 any
653 Iface4 any
654 }
655 type B struct {
656 A A
657 PA *A
658 PppA ***A
659 Iface any
660 Iface2 any
661 Iface3 any
662 C *C
663 }
664 pa := &A{Num: 3, Str: "three"}
665 ppa := &pa
666 b := B{
667 A: A{Num: 1, Str: "one"},
668 PA: &A{Num: 2, Str: "two"},
669 PppA: &ppa,
670 Iface: A{Num: 4, Str: "four"},
671 Iface2: &ppa,
672 Iface3: nil,
673 C: &C{
674 A: A{Num: 5, Str: "five"},
675 PA1: &A{Num: 6, Str: "six"},
676 PA2: nil, // explicit to be clear
677 Iface1: A{Num: 7, Str: "seven"},
678 Iface2: &A{Num: 8, Str: "eight"},
679 Iface3: nil, // explicit to be clear
680 Iface4: (*A)(nil),
681 },
682 }
683
684 //
685 // OK
686 checkOK(t, gotStruct, td.Smuggle("ValInt", 123))
687 checkOK(t, gotStruct,
688 td.Smuggle("MyStructMid.ValStr", td.Contains("oob")))
689 checkOK(t, gotStruct,
690 td.Smuggle("MyStructMid.MyStructBase.ValBool", true))
691 checkOK(t, gotStruct, td.Smuggle("ValBool", true)) // thanks to composition
692 checkOK(t, gotStruct, td.Smuggle("Ptr", td.Ptr(42)))
693
694 // OK across pointers
695 checkOK(t, b, td.Smuggle("PA.Num", 2))
696 checkOK(t, b, td.Smuggle("PppA.Num", 3))
697
698 // OK with any
699 checkOK(t, b, td.Smuggle("Iface.Num", 4))
700 checkOK(t, b, td.Smuggle("Iface2.Num", 3))
701 checkOK(t, b, td.Smuggle("C.Iface1.Num", 7))
702 checkOK(t, b, td.Smuggle("C.Iface2.Num", 8))
703
704 // Errors
705 checkError(t, 12, td.Smuggle("foo.bar", 23),
706 expectedError{
707 Message: mustBe("ran smuggle code with %% as argument"),
708 Path: mustBe("DATA"),
709 Summary: mustBe(" value: 12\nit failed coz: it is a int and should be a struct or a map[string]…"),
710 })
711 checkError(t, gotStruct, td.Smuggle("ValInt.bar", 23),
712 expectedError{
713 Message: mustBe("ran smuggle code with %% as argument"),
714 Path: mustBe("DATA"),
715 Summary: mustContain("\nit failed coz: field \"ValInt\" is a int and should be a struct"),
716 })
717 checkError(t, gotStruct, td.Smuggle("MyStructMid.ValStr.foobar", 23),
718 expectedError{
719 Message: mustBe("ran smuggle code with %% as argument"),
720 Path: mustBe("DATA"),
721 Summary: mustContain("\nit failed coz: field \"MyStructMid.ValStr\" is a string and should be a struct"),
722 })
723
724 checkError(t, gotStruct, td.Smuggle("foo.bar", 23),
725 expectedError{
726 Message: mustBe("ran smuggle code with %% as argument"),
727 Path: mustBe("DATA"),
728 Summary: mustContain("\nit failed coz: field \"foo\" not found"),
729 })
730
731 checkError(t, b, td.Smuggle("C.PA2.Num", 456),
732 expectedError{
733 Message: mustBe("ran smuggle code with %% as argument"),
734 Path: mustBe("DATA"),
735 Summary: mustContain("\nit failed coz: field \"C.PA2\" is nil"),
736 })
737 checkError(t, b, td.Smuggle("C.Iface3.Num", 456),
738 expectedError{
739 Message: mustBe("ran smuggle code with %% as argument"),
740 Path: mustBe("DATA"),
741 Summary: mustContain("\nit failed coz: field \"C.Iface3\" is nil"),
742 })
743 checkError(t, b, td.Smuggle("C.Iface4.Num", 456),
744 expectedError{
745 Message: mustBe("ran smuggle code with %% as argument"),
746 Path: mustBe("DATA"),
747 Summary: mustContain("\nit failed coz: field \"C.Iface4\" is nil"),
748 })
749 checkError(t, b, td.Smuggle("Iface3.Num", 456),
750 expectedError{
751 Message: mustBe("ran smuggle code with %% as argument"),
752 Path: mustBe("DATA"),
753 Summary: mustContain("\nit failed coz: field \"Iface3\" is nil"),
754 })
755
756 // Referencing maps and array/slices
757 x := B{
758 Iface: map[string]any{
759 "test": []int{2, 3, 4},
760 },
761 C: &C{
762 Iface1: []any{
763 map[int]any{42: []string{"pipo"}, 66: [2]string{"foo", "bar"}},
764 map[int8]any{42: []string{"pipo"}},
765 map[int16]any{42: []string{"pipo"}},
766 map[int32]any{42: []string{"pipo"}},
767 map[int64]any{42: []string{"pipo"}},
768 map[uint]any{42: []string{"pipo"}},
769 map[uint8]any{42: []string{"pipo"}},
770 map[uint16]any{42: []string{"pipo"}},
771 map[uint32]any{42: []string{"pipo"}},
772 map[uint64]any{42: []string{"pipo"}},
773 map[uintptr]any{42: []string{"pipo"}},
774 map[float32]any{42: []string{"pipo"}},
775 map[float64]any{42: []string{"pipo"}},
776 },
777 },
778 }
779 checkOK(t, x, td.Smuggle("Iface[test][1]", 3))
780 checkOK(t, x, td.Smuggle("Iface.test[1]", 3)) // shortcut for map[string]…
781 checkOK(t, x, td.Smuggle("C.Iface1[0][66][1]", "bar"))
782 for i := 0; i < 12; i++ {
783 checkOK(t, x,
784 td.Smuggle(fmt.Sprintf("C.Iface1[%d][42][0]", i), "pipo"))
785
786 checkOK(t, x,
787 td.Smuggle(fmt.Sprintf("C.Iface1[%d][42][-1]", i-12), "pipo"))
788 }
789
790 checkOK(t, x, td.Lax(td.Smuggle("PppA", nil)))
791 checkOK(t, x, td.Smuggle("PppA", td.Nil()))
792
793 checkOK(t, x.Iface, td.Smuggle("[test][1]", 3))
794 checkError(t, x.Iface, td.Smuggle("[unknown][1]", 42),
795 expectedError{
796 Message: mustBe("ran smuggle code with %% as argument"),
797 Path: mustBe("DATA"),
798 Summary: mustContain(`
799 it failed coz: field "[unknown]", "unknown" map key not found`),
800 })
801
802 checkOK(t, x.C.Iface1, td.Smuggle("[0][66][1]", "bar"))
803 checkError(t, x.C.Iface1, td.Smuggle("[42][66][1]", "bar"),
804 expectedError{
805 Message: mustBe("ran smuggle code with %% as argument"),
806 Path: mustBe("DATA"),
807 Summary: mustContain(`
808 it failed coz: field "[42]", 42 is out of slice/array range (len 13)`),
809 })
810
811 //
812 type D struct {
813 Iface any
814 }
815
816 got := D{
817 Iface: []any{
818 map[complex64]any{complex(42, 0): []string{"pipo"}},
819 map[complex128]any{complex(42, 0): []string{"pipo"}},
820 },
821 }
822
823 for i := 0; i < 2; i++ {
824 checkOK(t, got, td.Smuggle(fmt.Sprintf("Iface[%d][42][0]", i), "pipo"))
825 checkOK(t, got, td.Smuggle(fmt.Sprintf("Iface[%d][42][0]", i-2), "pipo"))
826 }
827 }
828
829 func TestSmuggleFieldsPathMethod(t *testing.T) {
830 pipo := td.SmuggleBuild{Field: struct{ Path string }{"pipo"}}
831
832 checkOK(t, td.SmuggleBuild{Next: &pipo},
833 td.Smuggle(`FollowNext().Field.Path`, "pipo"))
834
835 checkOK(t, &td.SmuggleBuild{Next: &pipo},
836 td.Smuggle(`FollowNext().Field.Path`, "pipo"))
837
838 checkOK(t, &td.SmuggleBuild{Next: &pipo},
839 td.Smuggle(`PtrFollowNext().Field.Path`, "pipo"))
840
841 checkOK(t, td.SmuggleBuild{Iface: pipo},
842 td.Smuggle(`FollowIface().Field.Path`, "pipo"))
843
844 checkOK(t, &td.SmuggleBuild{Iface: pipo},
845 td.Smuggle(`FollowIface().Field.Path`, "pipo"))
846
847 checkOK(t, &td.SmuggleBuild{Iface: &pipo},
848 td.Smuggle(`PtrFollowIface().Field.Path`, "pipo"))
849
850 checkOK(t, td.SmuggleBuild{Iface: pipo},
851 td.Smuggle(`MayFollowIface().Field.Path`, "pipo"))
852
853 // Method call on typed nil is OK as PNum() is a method on *td.SmuggleBuild
854 checkOK(t, td.SmuggleBuild{}, td.Smuggle(`Next.PNum()`, 42))
855 checkOK(t, td.SmuggleBuild{Iface: (*td.SmuggleBuild)(nil)},
856 td.Smuggle(`Iface.PNum()`, 42))
857
858 // Method call on typed nil is KO as Num() is a method on td.SmuggleBuild
859 checkError(t, td.SmuggleBuild{}, td.Smuggle(`Next.Num()`, 42),
860 expectedError{
861 Message: mustBe("ran smuggle code with %% as argument"),
862 Path: mustBe("DATA"),
863 Summary: mustMatch(`
864 it failed coz: method Next.Num\(\) panicked: value method .+/td.SmuggleBuild.Num called using nil \*SmuggleBuild pointer`),
865 })
866
867 checkError(t, td.SmuggleBuild{Next: &pipo},
868 td.Smuggle(`Next.Panic()`, "dummy"),
869 expectedError{
870 Message: mustBe("ran smuggle code with %% as argument"),
871 Path: mustBe("DATA"),
872 Summary: mustContain(`
873 it failed coz: method Next.Panic() panicked: oops!`),
874 })
875
876 checkError(t, td.SmuggleBuild{Next: &td.SmuggleBuild{}},
877 td.Smuggle(`Next.MayFollowNext().Field.Path`, "pipo"),
878 expectedError{
879 Message: mustBe("ran smuggle code with %% as argument"),
880 Path: mustBe("DATA"),
881 Summary: mustContain(`
882 it failed coz: method Next.MayFollowNext() returned an error: Next is nil`),
883 })
884
885 checkError(t, td.SmuggleBuild{Next: &td.SmuggleBuild{}},
886 td.Smuggle(`Next.MayFollowIface().Field.Path`, "pipo"),
887 expectedError{
888 Message: mustBe("ran smuggle code with %% as argument"),
889 Path: mustBe("DATA"),
890 Summary: mustContain(`
891 it failed coz: method Next.MayFollowIface() returned an error: Iface is nil`),
892 })
893
894 // Test with reflect
895 checkOK(t, reflect.ValueOf(pipo),
896 td.Smuggle(`Interface().Field.Path`, "pipo"))
897
898 checkOK(t, reflect.ValueOf(reflect.ValueOf(&pipo)),
899 td.Smuggle(`Interface().Elem().Interface().Field.Path`, "pipo"))
900 }
901
902 func TestSmuggleTypeBehind(t *testing.T) {
903 // Type behind is the smuggle function parameter one
904
905 equalTypes(t, td.Smuggle(func(n int) bool { return n != 0 }, true), 23)
906
907 type MyTime time.Time
908
909 equalTypes(t,
910 td.Smuggle(
911 func(t MyTime) time.Time { return time.Time(t) },
912 time.Now()),
913 MyTime{})
914
915 equalTypes(t,
916 td.Smuggle(func(from any) any { return from }, nil),
917 reflect.TypeOf((*any)(nil)).Elem())
918
919 equalTypes(t,
920 td.Smuggle("foo.bar", nil),
921 reflect.TypeOf((*any)(nil)).Elem())
922
923 // Erroneous op
924 equalTypes(t, td.Smuggle((func(int) int)(nil), 12), nil)
925 }
926
927 // Here instead of in example_test.go, as chained Smuggle is not
928 // usable with T.Smuggle nor CmpSmuggle.
929 func ExampleSmuggle_chained() {
930 t := &testing.T{}
931
932 got := "+123"
933
934 ok := td.Cmp(t, got, td.Smuggle(
935 strconv.Atoi,
936 strconv.Itoa,
937 strconv.Atoi,
938 123))
939 fmt.Printf("chaining Atoi/Itoa: %t\n", ok)
940
941 // echo hello | gzip | perl -nE 'printf "%*v02x\n", " ", $_'
942 got = "1f 8b 08 00 b4 c4 3f 6a 00 03 cb 48 cd c9 c9 e7 02 00 20 30 3a 36 06 00 00 00"
943
944 ok = td.Cmp(t, got, td.Smuggle(
945 strings.NewReplacer(" ", "").Replace, // remove spaces
946 hex.DecodeString, // hex string → []byte
947 bytes.NewReader, // []byte → io.Reader
948 gzip.NewReader, // io.Reader → gunzipped io.Reader
949 io.ReadAll, // gunzipped io.Reader → []byte
950 "", // []byte → string
951 "hello\n")) // expected
952
953 fmt.Printf("hex decode, gunzip: %t", ok)
954
955 // Output:
956 // chaining Atoi/Itoa: true
957 // hex decode, gunzip: true
958 }