Debian Codegraph @

td/td_catch_test.go

raw
1 // Copyright (c) 2019, 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 "testing"
11
12 "github.com/maxatome/go-testdeep/internal/test"
13 "github.com/maxatome/go-testdeep/td"
14 )
15
16 func TestCatch(t *testing.T) {
17 var num int
18 checkOK(t, 12, td.Catch(&num, 12))
19 test.EqualInt(t, num, 12)
20
21 var num64 int64
22 checkError(t, 12, td.Catch(&num64, 12),
23 expectedError{
24 Message: mustBe("type mismatch"),
25 Got: mustBe("int"),
26 Expected: mustBe("int64"),
27 })
28
29 checkOK(t, 12, td.Lax(td.Catch(&num64, 12)))
30 test.EqualInt(t, int(num64), 12)
31
32 // Lax not needed for interfaces
33 var val any
34 if checkOK(t, 12, td.Catch(&val, 12)) {
35 if n, ok := val.(int); ok {
36 test.EqualInt(t, n, 12)
37 } else {
38 t.Errorf("val is not an int but a %T", val)
39 }
40 }
41
42 //
43 // Bad usages
44 checkError(t, "never tested",
45 td.Catch(12, 28),
46 expectedError{
47 Message: mustBe("bad usage of Catch operator"),
48 Path: mustBe("DATA"),
49 Summary: mustBe("usage: Catch(NON_NIL_PTR, EXPECTED_VALUE), but received int as 1st parameter"),
50 })
51
52 checkError(t, "never tested",
53 td.Catch(nil, 28),
54 expectedError{
55 Message: mustBe("bad usage of Catch operator"),
56 Path: mustBe("DATA"),
57 Summary: mustBe("usage: Catch(NON_NIL_PTR, EXPECTED_VALUE), but received nil as 1st parameter"),
58 })
59
60 checkError(t, "never tested",
61 td.Catch((*int)(nil), 28),
62 expectedError{
63 Message: mustBe("bad usage of Catch operator"),
64 Path: mustBe("DATA"),
65 Summary: mustBe("usage: Catch(NON_NIL_PTR, EXPECTED_VALUE), but received *int (ptr) as 1st parameter"),
66 })
67
68 //
69 // String
70 test.EqualStr(t, td.Catch(&num, 12).String(), "12")
71 test.EqualStr(t,
72 td.Catch(&num, td.Gt(4)).String(),
73 td.Gt(4).String())
74 test.EqualStr(t, td.Catch(&num, nil).String(), "nil")
75
76 // Erroneous op
77 test.EqualStr(t, td.Catch(nil, 28).String(), "Catch(<ERROR>)")
78 }
79
80 func TestCatchTypeBehind(t *testing.T) {
81 var num int
82 equalTypes(t, td.Catch(&num, 8), 0)
83 equalTypes(t, td.Catch(&num, td.Gt(4)), 0)
84 equalTypes(t, td.Catch(&num, td.Ignore()), 0) // fallback on *target
85 equalTypes(t, td.Catch(&num, nil), nil)
86
87 // Erroneous op
88 equalTypes(t, td.Catch(nil, 28), nil)
89 }