Debian Codegraph @

td/check_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 "fmt"
11 "os"
12 "reflect"
13 "regexp"
14 "strings"
15 "testing"
16
17 "github.com/maxatome/go-testdeep/helpers/tdutil"
18 "github.com/maxatome/go-testdeep/internal/color"
19 "github.com/maxatome/go-testdeep/internal/ctxerr"
20 "github.com/maxatome/go-testdeep/internal/dark"
21 "github.com/maxatome/go-testdeep/internal/test"
22 "github.com/maxatome/go-testdeep/td"
23 )
24
25 func TestMain(m *testing.M) {
26 color.SaveState()
27 os.Exit(m.Run())
28 }
29
30 type MyStructBase struct {
31 ValBool bool
32 }
33
34 type MyStructMid struct {
35 MyStructBase
36 ValStr string
37 }
38
39 type MyStruct struct {
40 MyStructMid
41 ValInt int
42 Ptr *int
43 }
44
45 func (s *MyStruct) MyString() string {
46 return "!"
47 }
48
49 type MyInterface interface {
50 MyString() string
51 }
52
53 type MyStringer struct{}
54
55 func (s MyStringer) String() string { return "pipo bingo" }
56
57 type expectedError struct {
58 Path expectedErrorMatch
59 Message expectedErrorMatch
60 Got expectedErrorMatch
61 Expected expectedErrorMatch
62 Summary expectedErrorMatch
63 Located bool
64 Under expectedErrorMatch
65 Origin *expectedError
66 Next *expectedError
67 }
68
69 var ignoreExpectedError = &expectedError{}
70
71 type expectedErrorMatch struct {
72 Exact string
73 Match *regexp.Regexp
74 Contain string
75 }
76
77 func ptr(x any) any {
78 v := reflect.New(reflect.TypeOf(x))
79 v.Elem().Set(reflect.ValueOf(x))
80 return v.Interface()
81 }
82
83 func mustBe(str string) expectedErrorMatch {
84 return expectedErrorMatch{Exact: str}
85 }
86
87 func mustMatch(str string) expectedErrorMatch {
88 return expectedErrorMatch{Match: regexp.MustCompile(str)}
89 }
90
91 func mustContain(str string) expectedErrorMatch {
92 return expectedErrorMatch{Contain: str}
93 }
94
95 func indent(str string, numSpc int) string {
96 return strings.ReplaceAll(str, "\n", "\n\t"+strings.Repeat(" ", numSpc))
97 }
98
99 func fullError(err *ctxerr.Error) string {
100 return strings.ReplaceAll(err.Error(), "\n", "\n\t> ")
101 }
102
103 func cmpErrorStr(t *testing.T, err *ctxerr.Error,
104 got string, expected expectedErrorMatch, fieldName string,
105 args ...any,
106 ) bool {
107 t.Helper()
108
109 if expected.Exact != "" && got != expected.Exact {
110 t.Errorf(`%sError.%s mismatch
111 got: %s
112 expected: %s
113 Full error:
114 > %s`,
115 tdutil.BuildTestName(args...),
116 fieldName, indent(got, 10), indent(expected.Exact, 10),
117 fullError(err))
118 return false
119 }
120
121 if expected.Contain != "" && !strings.Contains(got, expected.Contain) {
122 t.Errorf(`%sError.%s mismatch
123 got: %s
124 should contain: %s
125 Full error:
126 > %s`,
127 tdutil.BuildTestName(args...),
128 fieldName,
129 indent(got, 16), indent(expected.Contain, 16),
130 fullError(err))
131 return false
132 }
133
134 if expected.Match != nil && !expected.Match.MatchString(got) {
135 t.Errorf(`%sError.%s mismatch
136 got: %s
137 should match: %s
138 Full error:
139 > %s`,
140 tdutil.BuildTestName(args...),
141 fieldName,
142 indent(got, 14), indent(expected.Match.String(), 14),
143 fullError(err))
144 return false
145 }
146
147 return true
148 }
149
150 func matchError(t *testing.T, err *ctxerr.Error, expectedError expectedError,
151 expectedIsTestDeep bool, args ...any,
152 ) bool {
153 t.Helper()
154
155 if !cmpErrorStr(t, err, err.Message, expectedError.Message,
156 "Message", args...) {
157 return false
158 }
159
160 if !cmpErrorStr(t, err, err.Context.Path.String(), expectedError.Path,
161 "Context.Path", args...) {
162 return false
163 }
164
165 if !cmpErrorStr(t, err, err.GotString(), expectedError.Got, "Got", args...) {
166 return false
167 }
168
169 if !cmpErrorStr(t, err,
170 err.ExpectedString(), expectedError.Expected, "Expected", args...) {
171 return false
172 }
173
174 if !cmpErrorStr(t, err,
175 err.SummaryString(), expectedError.Summary, "Summary", args...) {
176 return false
177 }
178
179 // under
180 serr, under := err.Error(), ""
181 if pos := strings.Index(serr, "\n[under operator "); pos > 0 {
182 under = serr[pos+2:]
183 under = under[:strings.IndexByte(under, ']')]
184 }
185 if !cmpErrorStr(t, err, under, expectedError.Under, "[under operator …]", args...) {
186 return false
187 }
188
189 // If expected is a TestDeep, the Location should be set
190 if expectedIsTestDeep {
191 expectedError.Located = true
192 }
193 if expectedError.Located != err.Location.IsInitialized() {
194 t.Errorf(`%sLocation of the origin of the error
195 got: %v
196 expected: %v`,
197 tdutil.BuildTestName(args...), err.Location.IsInitialized(), expectedError.Located)
198 return false
199 }
200
201 if expectedError.Located &&
202 !strings.HasSuffix(err.Location.File, "_test.go") {
203 t.Errorf(`%sFile of the origin of the error
204 got: line %d of %s
205 expected: *_test.go`,
206 tdutil.BuildTestName(args...), err.Location.Line, err.Location.File)
207 return false
208 }
209
210 if expectedError.Origin != nil {
211 if expectedError.Origin != ignoreExpectedError {
212 if err.Origin == nil {
213 t.Errorf(`%sError should originate from another Error`,
214 tdutil.BuildTestName(args...))
215 return false
216 }
217
218 if !matchError(t, err.Origin, *expectedError.Origin,
219 expectedIsTestDeep, args...) {
220 return false
221 }
222 }
223 } else if err.Origin != nil {
224 t.Errorf(`%sError should NOT originate from another Error`,
225 tdutil.BuildTestName(args...))
226 return false
227 }
228
229 if expectedError.Next != nil {
230 if expectedError.Next != ignoreExpectedError {
231 if err.Next == nil {
232 t.Errorf(`%sError should have a next Error`,
233 tdutil.BuildTestName(args...))
234 return false
235 }
236
237 if !matchError(t, err.Next, *expectedError.Next,
238 expectedIsTestDeep, args...) {
239 return false
240 }
241 }
242 } else if err.Next != nil {
243 t.Errorf(`%sError should NOT have a next Error
244 Full error:
245 > %s`,
246 tdutil.BuildTestName(args...),
247 fullError(err))
248 return false
249 }
250
251 return true
252 }
253
254 func _checkError(t *testing.T, got, expected any,
255 expectedError expectedError, args ...any,
256 ) bool {
257 t.Helper()
258
259 err := td.EqDeeplyError(got, expected)
260 if err == nil {
261 t.Errorf("%sAn Error should have occurred", tdutil.BuildTestName(args...))
262 return false
263 }
264
265 _, expectedIsTestDeep := expected.(td.TestDeep)
266 if !matchError(t, err.(*ctxerr.Error), expectedError, expectedIsTestDeep, args...) {
267 return false
268 }
269
270 if td.EqDeeply(got, expected) {
271 t.Errorf(`%sBoolean context failed
272 got: true
273 expected: false`, tdutil.BuildTestName(args...))
274 return false
275 }
276
277 return true
278 }
279
280 func ifaceExpectedError(t *testing.T, expectedError expectedError) expectedError {
281 t.Helper()
282
283 if !strings.Contains(expectedError.Path.Exact, "DATA") {
284 return expectedError
285 }
286
287 newExpectedError := expectedError
288 newExpectedError.Path.Exact = strings.Replace(expectedError.Path.Exact,
289 "DATA", "DATA.Iface", 1)
290
291 if newExpectedError.Origin != nil {
292 newOrigin := ifaceExpectedError(t, *newExpectedError.Origin)
293 newExpectedError.Origin = &newOrigin
294 }
295
296 return newExpectedError
297 }
298
299 // checkError calls _checkError twice. The first time with the same
300 // parameters, the second time in an any context.
301 func checkError(t *testing.T, got, expected any,
302 expectedError expectedError, args ...any,
303 ) bool {
304 t.Helper()
305
306 if ok := _checkError(t, got, expected, expectedError, args...); !ok {
307 return false
308 }
309
310 type tmpStruct struct {
311 Iface any
312 }
313
314 return _checkError(t, tmpStruct{Iface: got},
315 td.Struct(
316 tmpStruct{},
317 td.StructFields{
318 "Iface": expected,
319 }),
320 ifaceExpectedError(t, expectedError),
321 args...)
322 }
323
324 func checkErrorForEach(t *testing.T,
325 gotList []any, expected any,
326 expectedError expectedError, args ...any,
327 ) (ret bool) {
328 t.Helper()
329
330 globalTestName := tdutil.BuildTestName(args...)
331 ret = true
332
333 for idx, got := range gotList {
334 testName := fmt.Sprintf("Got #%d", idx)
335 if globalTestName != "" {
336 testName += ", " + globalTestName
337 }
338 ret = checkError(t, got, expected, expectedError, testName) && ret
339 }
340 return
341 }
342
343 // customCheckOK calls chk twice. The first time with the same
344 // parameters, the second time in an any context.
345 func customCheckOK(t *testing.T,
346 chk func(t *testing.T, got, expected any, args ...any) bool,
347 got, expected any,
348 args ...any,
349 ) bool {
350 t.Helper()
351
352 if ok := chk(t, got, expected, args...); !ok {
353 return false
354 }
355
356 type tmpStruct struct {
357 Iface any
358 }
359
360 // Dirty hack to force got be passed as an interface kind
361 return chk(t, tmpStruct{Iface: got},
362 td.Struct(
363 tmpStruct{},
364 td.StructFields{
365 "Iface": expected,
366 }),
367 args...)
368 }
369
370 func _checkOK(t *testing.T, got, expected any,
371 args ...any,
372 ) bool {
373 t.Helper()
374
375 if !td.Cmp(t, got, expected, args...) {
376 return false
377 }
378
379 if !td.EqDeeply(got, expected) {
380 t.Errorf(`%sBoolean context failed
381 got: false
382 expected: true`, tdutil.BuildTestName(args...))
383 return false
384 }
385
386 if err := td.EqDeeplyError(got, expected); err != nil {
387 t.Errorf(`%sEqDeeplyError returned an error: %s`,
388 tdutil.BuildTestName(args...), err)
389 return false
390 }
391
392 return true
393 }
394
395 // checkOK calls _checkOK twice. The first time with the same
396 // parameters, the second time in an any context.
397 func checkOK(t *testing.T, got, expected any,
398 args ...any,
399 ) bool {
400 t.Helper()
401 return customCheckOK(t, _checkOK, got, expected, args...)
402 }
403
404 func checkOKOrPanicIfUnsafeDisabled(t *testing.T, got, expected any,
405 args ...any,
406 ) (ret bool) {
407 t.Helper()
408
409 cmp := func() {
410 t.Helper()
411 ret = _checkOK(t, got, expected, args...)
412 }
413
414 // Should panic if unsafe package is not available
415 if dark.UnsafeDisabled {
416 return test.CheckPanic(t, cmp,
417 "dark.GetInterface() does not handle private ")
418 }
419
420 cmp()
421 return
422 }
423
424 func checkOKForEach(t *testing.T, gotList []any, expected any,
425 args ...any,
426 ) (ret bool) {
427 t.Helper()
428
429 globalTestName := tdutil.BuildTestName(args...)
430 ret = true
431
432 for idx, got := range gotList {
433 testName := fmt.Sprintf("Got #%d", idx)
434 if globalTestName != "" {
435 testName += ", " + globalTestName
436 }
437 ret = checkOK(t, got, expected, testName) && ret
438 }
439 return
440 }
441
442 func equalTypes(t *testing.T, got td.TestDeep, expected any, args ...any) bool {
443 gotType := got.TypeBehind()
444
445 expectedType, ok := expected.(reflect.Type)
446 if !ok {
447 expectedType = reflect.TypeOf(expected)
448 }
449
450 if gotType == expectedType {
451 return true
452 }
453
454 var gotStr, expectedStr string
455
456 if gotType == nil {
457 gotStr = "nil"
458 } else {
459 gotStr = gotType.String()
460 }
461
462 if expected == nil {
463 expectedStr = "nil"
464 } else {
465 expectedStr = expectedType.String()
466 }
467
468 t.Helper()
469 t.Errorf(`%sFailed test
470 got: %s
471 expected: %s`,
472 tdutil.BuildTestName(args...), gotStr, expectedStr)
473 return false
474 }