Debian Codegraph @

td/cmp_funcs_misc_121_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 //go:build go1.21
8 // +build go1.21
9
10 // Until go 1.21 in go.mod
11 //go:debug panicnil=0
12
13 package td_test
14
15 import (
16 "fmt"
17 "runtime"
18 "testing"
19
20 "github.com/maxatome/go-testdeep/td"
21 )
22
23 func ExampleCmpPanic() {
24 t := &testing.T{}
25
26 ok := td.CmpPanic(t,
27 func() { panic("I am panicking!") }, "I am panicking!",
28 "Checks for panic")
29 fmt.Println("checks exact panic() string:", ok)
30
31 // Can use TestDeep operator too
32 ok = td.CmpPanic(t,
33 func() { panic("I am panicking!") }, td.Contains("panicking!"),
34 "Checks for panic")
35 fmt.Println("checks panic() sub-string:", ok)
36
37 // Can detect panic(nil)
38 // Before Go 1.21, programs that called panic(nil) observed recover
39 // returning nil. Starting in Go 1.21, programs that call panic(nil)
40 // observe recover returning a *PanicNilError. Programs can change
41 // back to the old behavior by setting GODEBUG=panicnil=1.
42 // See https://pkg.go.dev/runtime#PanicNilError
43 ok = td.CmpPanic(t, func() { panic(nil) }, &runtime.PanicNilError{},
44 "Checks for panic(nil)")
45 fmt.Println("checks for panic(nil):", ok)
46
47 // As well as structured data panic
48 type PanicStruct struct {
49 Error string
50 Code int
51 }
52
53 ok = td.CmpPanic(t,
54 func() {
55 panic(PanicStruct{Error: "Memory violation", Code: 11})
56 },
57 PanicStruct{
58 Error: "Memory violation",
59 Code: 11,
60 })
61 fmt.Println("checks exact panic() struct:", ok)
62
63 // or combined with TestDeep operators too
64 ok = td.CmpPanic(t,
65 func() {
66 panic(PanicStruct{Error: "Memory violation", Code: 11})
67 },
68 td.Struct(PanicStruct{}, td.StructFields{
69 "Code": td.Between(10, 20),
70 }))
71 fmt.Println("checks panic() struct against TestDeep operators:", ok)
72
73 // Of course, do not panic = test failure, even for expected nil
74 // panic parameter
75 ok = td.CmpPanic(t, func() {}, nil)
76 fmt.Println("checks a panic occurred:", ok)
77
78 // Output:
79 // checks exact panic() string: true
80 // checks panic() sub-string: true
81 // checks for panic(nil): true
82 // checks exact panic() struct: true
83 // checks panic() struct against TestDeep operators: true
84 // checks a panic occurred: false
85 }