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