Debian Codegraph @

td/td_code_test.go

raw
1 // Copyright (c) 2018, 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 "encoding/json"
11 "errors"
12 "fmt"
13 "strings"
14 "testing"
15 "time"
16
17 "github.com/maxatome/go-testdeep/internal/ctxerr"
18 "github.com/maxatome/go-testdeep/internal/test"
19 "github.com/maxatome/go-testdeep/td"
20 )
21
22 func TestCode(t *testing.T) {
23 checkOK(t, 12, td.Code(func(n int) bool { return n >= 10 && n < 20 }))
24
25 checkOK(t, 12, td.Code(func(val any) bool {
26 num, ok := val.(int)
27 return ok && num == 12
28 }))
29
30 checkOK(t, errors.New("foobar"), td.Code(func(val error) bool {
31 return val.Error() == "foobar"
32 }))
33
34 checkOK(t, json.RawMessage(`[42]`),
35 td.Code(func(b json.RawMessage) error {
36 var l []int
37 err := json.Unmarshal(b, &l)
38 if err != nil {
39 return err
40 }
41 if len(l) != 1 || l[0] != 42 {
42 return errors.New("42 not found")
43 }
44 return nil
45 }))
46
47 // Lax
48 checkOK(t, 123, td.Lax(td.Code(func(n float64) bool { return n == 123 })))
49
50 checkError(t, 123, td.Code(func(n float64) bool { return true }),
51 expectedError{
52 Message: mustBe("incompatible parameter type"),
53 Path: mustBe("DATA"),
54 Got: mustBe("int"),
55 Expected: mustBe("float64"),
56 })
57
58 type xInt int
59 checkError(t, xInt(12),
60 td.Code(func(n int) bool { return n >= 10 && n < 20 }),
61 expectedError{
62 Message: mustBe("incompatible parameter type"),
63 Path: mustBe("DATA"),
64 Got: mustBe("td_test.xInt"),
65 Expected: mustBe("int"),
66 })
67
68 checkError(t, 12,
69 td.Code(func(n int) (bool, string) { return false, "custom error" }),
70 expectedError{
71 Message: mustBe("ran code with %% as argument"),
72 Path: mustBe("DATA"),
73 Summary: mustBe(" value: 12\nit failed coz: custom error"),
74 })
75
76 checkError(t, 12,
77 td.Code(func(n int) bool { return false }),
78 expectedError{
79 Message: mustBe("ran code with %% as argument"),
80 Path: mustBe("DATA"),
81 Summary: mustBe(" value: 12\nit failed but didn't say why"),
82 })
83
84 type MyBool bool
85 type MyString string
86 checkError(t, 12,
87 td.Code(func(n int) (MyBool, MyString) { return false, "very custom error" }),
88 expectedError{
89 Message: mustBe("ran code with %% as argument"),
90 Path: mustBe("DATA"),
91 Summary: mustBe(" value: 12\nit failed coz: very custom error"),
92 })
93
94 checkError(t, 12,
95 td.Code(func(i int) error {
96 return errors.New("very custom error")
97 }),
98 expectedError{
99 Message: mustBe("ran code with %% as argument"),
100 Path: mustBe("DATA"),
101 Summary: mustBe(" value: 12\nit failed coz: very custom error"),
102 })
103
104 // Internal use
105 checkError(t, 12,
106 td.Code(func(i int) error {
107 return &ctxerr.Error{
108 Message: "my message",
109 Summary: ctxerr.NewSummary("my summary"),
110 }
111 }),
112 expectedError{
113 Message: mustBe("my message"),
114 Path: mustBe("DATA"),
115 Summary: mustBe("my summary"),
116 })
117
118 //
119 // Bad usage
120 checkError(t, "never tested",
121 td.Code(nil),
122 expectedError{
123 Message: mustBe("bad usage of Code operator"),
124 Path: mustBe("DATA"),
125 Summary: mustBe("usage: Code(FUNC), but received nil as 1st parameter"),
126 })
127
128 checkError(t, "never tested",
129 td.Code((func(string) bool)(nil)),
130 expectedError{
131 Message: mustBe("bad usage of Code operator"),
132 Path: mustBe("DATA"),
133 Summary: mustBe("Code(FUNC): FUNC cannot be a nil function"),
134 })
135
136 checkError(t, "never tested",
137 td.Code("test"),
138 expectedError{
139 Message: mustBe("bad usage of Code operator"),
140 Path: mustBe("DATA"),
141 Summary: mustBe("usage: Code(FUNC), but received string as 1st parameter"),
142 })
143
144 checkError(t, "never tested",
145 td.Code(func(x ...int) bool { return true }),
146 expectedError{
147 Message: mustBe("bad usage of Code operator"),
148 Path: mustBe("DATA"),
149 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),
150 })
151
152 checkError(t, "never tested",
153 td.Code(func() bool { return true }),
154 expectedError{
155 Message: mustBe("bad usage of Code operator"),
156 Path: mustBe("DATA"),
157 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),
158 })
159
160 checkError(t, "never tested",
161 td.Code(func(a, b, c, d string) bool { return true }),
162 expectedError{
163 Message: mustBe("bad usage of Code operator"),
164 Path: mustBe("DATA"),
165 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),
166 })
167
168 checkError(t, "never tested",
169 td.Code(func(a int, b string) bool { return true }),
170 expectedError{
171 Message: mustBe("bad usage of Code operator"),
172 Path: mustBe("DATA"),
173 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),
174 })
175
176 checkError(t, "never tested",
177 td.Code(func(t *td.T, a int, b string) bool { return true }),
178 expectedError{
179 Message: mustBe("bad usage of Code operator"),
180 Path: mustBe("DATA"),
181 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),
182 })
183
184 checkError(t, "never tested", // because it is certainly an error
185 td.Code(func(assert, require *td.T) bool { return true }),
186 expectedError{
187 Message: mustBe("bad usage of Code operator"),
188 Path: mustBe("DATA"),
189 Summary: mustBe("Code(FUNC): FUNC must take only one non-variadic argument or (*td.T, arg) or (*td.T, *td.T, arg)"),
190 })
191
192 checkError(t, "never tested",
193 td.Code(func(n int) (bool, int) { return true, 0 }),
194 expectedError{
195 Message: mustBe("bad usage of Code operator"),
196 Path: mustBe("DATA"),
197 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),
198 })
199
200 checkError(t, "never tested",
201 td.Code(func(n int) (error, string) { return nil, "" }), //nolint: staticcheck
202 expectedError{
203 Message: mustBe("bad usage of Code operator"),
204 Path: mustBe("DATA"),
205 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),
206 })
207
208 checkError(t, "never tested",
209 td.Code(func(n int) (int, string) { return 0, "" }),
210 expectedError{
211 Message: mustBe("bad usage of Code operator"),
212 Path: mustBe("DATA"),
213 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),
214 })
215
216 checkError(t, "never tested",
217 td.Code(func(n int) (string, bool) { return "", true }),
218 expectedError{
219 Message: mustBe("bad usage of Code operator"),
220 Path: mustBe("DATA"),
221 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),
222 })
223
224 checkError(t, "never tested",
225 td.Code(func(n int) (bool, string, int) { return true, "", 0 }),
226 expectedError{
227 Message: mustBe("bad usage of Code operator"),
228 Path: mustBe("DATA"),
229 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),
230 })
231
232 checkError(t, "never tested",
233 td.Code(func(n int) {}),
234 expectedError{
235 Message: mustBe("bad usage of Code operator"),
236 Path: mustBe("DATA"),
237 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),
238 })
239
240 checkError(t, "never tested",
241 td.Code(func(n int) int { return 0 }),
242 expectedError{
243 Message: mustBe("bad usage of Code operator"),
244 Path: mustBe("DATA"),
245 Summary: mustBe("Code(FUNC): FUNC must return bool or (bool, string) or error"),
246 })
247
248 checkError(t, "never tested",
249 td.Code(func(t *td.T, a int) bool { return true }),
250 expectedError{
251 Message: mustBe("bad usage of Code operator"),
252 Path: mustBe("DATA"),
253 Summary: mustBe("Code(FUNC): FUNC must return nothing"),
254 })
255
256 checkError(t, "never tested",
257 td.Code(func(assert, require *td.T, a int) bool { return true }),
258 expectedError{
259 Message: mustBe("bad usage of Code operator"),
260 Path: mustBe("DATA"),
261 Summary: mustBe("Code(FUNC): FUNC must return nothing"),
262 })
263
264 //
265 // String
266 test.EqualStr(t,
267 td.Code(func(n int) bool { return false }).String(),
268 "Code(func(int) bool)")
269 test.EqualStr(t,
270 td.Code(func(n int) (bool, string) { return false, "" }).String(),
271 "Code(func(int) (bool, string))")
272 test.EqualStr(t,
273 td.Code(func(n int) error { return nil }).String(),
274 "Code(func(int) error)")
275 test.EqualStr(t,
276 td.Code(func(n int) (MyBool, MyString) { return false, "" }).String(),
277 "Code(func(int) (td_test.MyBool, td_test.MyString))")
278
279 // Erroneous op
280 test.EqualStr(t, td.Code(nil).String(), "Code(<ERROR>)")
281 }
282
283 func TestCodeCustom(t *testing.T) {
284 // Specific _checkOK func as td.Code(FUNC) with FUNC(t,arg) or
285 // FUNC(assert,require,arg) works in non-boolean context but cannot
286 // work in boolean context as there is no initial testing.TB instance
287 _customCheckOK := func(t *testing.T, got, expected any, args ...any) bool {
288 t.Helper()
289 if !td.Cmp(t, got, expected, args...) {
290 return false
291 }
292 // Should always fail in boolean context as no original testing.TB available
293 err := td.EqDeeplyError(got, expected)
294 if err == nil {
295 t.Error(`Boolean context succeeded and it shouldn't`)
296 return false
297 }
298 expErr := expectedError{
299 Message: mustBe("cannot build *td.T instance"),
300 Path: mustBe("DATA"),
301 Summary: mustBe("original testing.TB instance is missing"),
302 }
303 if !strings.HasPrefix(expected.(fmt.Stringer).String(), "Code") {
304 expErr = ifaceExpectedError(t, expErr)
305 }
306 if !matchError(t, err.(*ctxerr.Error), expErr, true, args...) {
307 return false
308 }
309 if td.EqDeeply(got, expected) {
310 t.Error(`Boolean context succeeded and it shouldn't`)
311 return false
312 }
313 return true
314 }
315
316 customCheckOK(t, _customCheckOK, 123, td.Code(func(t *td.T, n int) {
317 t.Cmp(t.Config.FailureIsFatal, false)
318 t.Cmp(n, 123)
319 }))
320
321 customCheckOK(t, _customCheckOK, 123, td.Code(func(assert, require *td.T, n int) {
322 assert.Cmp(assert.Config.FailureIsFatal, false)
323 assert.Cmp(require.Config.FailureIsFatal, true)
324 assert.Cmp(n, 123)
325 require.Cmp(n, 123)
326 }))
327
328 got := map[string]int{"foo": 123}
329
330 t.Run("Simple success", func(t *testing.T) {
331 mockT := test.NewTestingTB("TestCodeCustom")
332 td.Cmp(mockT, got, td.Map(map[string]int{}, td.MapEntries{
333 "foo": td.Code(func(t *td.T, n int) {
334 t.Cmp(n, 123)
335 }),
336 }))
337 test.EqualInt(t, len(mockT.Messages), 0)
338 })
339
340 t.Run("Simple failure", func(t *testing.T) {
341 mockT := test.NewTestingTB("TestCodeCustom")
342 td.NewT(mockT).
343 RootName("PIPO").
344 Cmp(got, td.Map(map[string]int{}, td.MapEntries{
345 "foo": td.Code(func(t *td.T, n int) {
346 t.Cmp(n, 124) // inherit only RootName
347 t.RootName(t.Config.OriginalPath()).Cmp(n, 125) // recover current path
348 t.RootName("").Cmp(n, 126) // undo RootName inheritance
349 }),
350 }))
351 test.IsTrue(t, mockT.HasFailed)
352 test.IsFalse(t, mockT.IsFatal)
353 missing := mockT.ContainsMessages(
354 `PIPO: values differ`,
355 ` got: 123`,
356 `expected: 124`,
357 `PIPO["foo"]: values differ`,
358 ` got: 123`,
359 `expected: 125`,
360 `DATA: values differ`,
361 ` got: 123`,
362 `expected: 126`,
363 )
364 if len(missing) != 0 {
365 t.Error("Following expected messages are not found:\n-", strings.Join(missing, "\n- "))
366 t.Error("================================ in:")
367 t.Error(strings.Join(mockT.Messages, "\n"))
368 t.Error("====================================")
369 }
370 })
371
372 t.Run("AssertRequire success", func(t *testing.T) {
373 mockT := test.NewTestingTB("TestCodeCustom")
374 td.Cmp(mockT, got, td.Map(map[string]int{}, td.MapEntries{
375 "foo": td.Code(func(assert, require *td.T, n int) {
376 assert.Cmp(n, 123)
377 require.Cmp(n, 123)
378 }),
379 }))
380 test.EqualInt(t, len(mockT.Messages), 0)
381 })
382
383 t.Run("AssertRequire failure", func(t *testing.T) {
384 mockT := test.NewTestingTB("TestCodeCustom")
385 td.NewT(mockT).
386 RootName("PIPO").
387 Cmp(got, td.Map(map[string]int{}, td.MapEntries{
388 "foo": td.Code(func(assert, require *td.T, n int) {
389 assert.Cmp(n, 124) // inherit only RootName
390 assert.RootName(assert.Config.OriginalPath()).Cmp(n, 125) // recover current path
391 assert.RootName(require.Config.OriginalPath()).Cmp(n, 126) // recover current path
392 assert.RootName("").Cmp(n, 127) // undo RootName inheritance
393 }),
394 }))
395 test.IsTrue(t, mockT.HasFailed)
396 test.IsFalse(t, mockT.IsFatal)
397 missing := mockT.ContainsMessages(
398 `PIPO: values differ`,
399 ` got: 123`,
400 `expected: 124`,
401 `PIPO["foo"]: values differ`,
402 ` got: 123`,
403 `expected: 125`,
404 `PIPO["foo"]: values differ`,
405 ` got: 123`,
406 `expected: 126`,
407 `DATA: values differ`,
408 ` got: 123`,
409 `expected: 127`,
410 )
411 if len(missing) != 0 {
412 t.Error("Following expected messages are not found:\n-", strings.Join(missing, "\n- "))
413 t.Error("================================ in:")
414 t.Error(strings.Join(mockT.Messages, "\n"))
415 t.Error("====================================")
416 }
417 })
418
419 t.Run("AssertRequire fatalfailure", func(t *testing.T) {
420 mockT := test.NewTestingTB("TestCodeCustom")
421 td.NewT(mockT).
422 RootName("PIPO").
423 Cmp(got, td.Map(map[string]int{}, td.MapEntries{
424 "foo": td.Code(func(assert, require *td.T, n int) {
425 mockT.CatchFatal(func() {
426 assert.RootName("FIRST").Cmp(n, 124)
427 require.RootName("SECOND").Cmp(n, 125)
428 assert.RootName("THIRD").Cmp(n, 126)
429 })
430 }),
431 }))
432 test.IsTrue(t, mockT.HasFailed)
433 test.IsTrue(t, mockT.IsFatal)
434 missing := mockT.ContainsMessages(
435 `FIRST: values differ`,
436 ` got: 123`,
437 `expected: 124`,
438 `SECOND: values differ`,
439 ` got: 123`,
440 `expected: 125`,
441 )
442 mesgs := strings.Join(mockT.Messages, "\n")
443 if len(missing) != 0 {
444 t.Error("Following expected messages are not found:\n-", strings.Join(missing, "\n- "))
445 t.Error("================================ in:")
446 t.Error(mesgs)
447 t.Error("====================================")
448 }
449
450 if strings.Contains(mesgs, "THIRD") {
451 t.Error("THIRD test found, but shouldn't, in:")
452 t.Error(mesgs)
453 t.Error("====================================")
454 }
455 })
456 }
457
458 func TestCodeTypeBehind(t *testing.T) {
459 // Type behind is the code function parameter one
460
461 equalTypes(t, td.Code(func(n int) bool { return n != 0 }), 23)
462 equalTypes(t, td.Code(func(_ *td.T, n int) {}), 23)
463 equalTypes(t, td.Code(func(_, _ *td.T, n int) {}), 23)
464
465 type MyTime time.Time
466
467 equalTypes(t,
468 td.Code(func(t MyTime) bool { return time.Time(t).IsZero() }),
469 MyTime{})
470 equalTypes(t, td.Code(func(_ *td.T, t MyTime) {}), MyTime{})
471 equalTypes(t, td.Code(func(_, _ *td.T, t MyTime) {}), MyTime{})
472
473 // Erroneous op
474 equalTypes(t, td.Code(nil), nil)
475 }