Slide 15
Slide 15 text
© 2023 OSInet 15
Testing an os.Exit-ing(0) function
func TestExit(t *testing.T) {
for _, test := range [...]struct {
name string
fn func()
}{{"Exit0", Exit0},{"Exit1", Exit1}} {
t.Run(fmt.Sprintf("%#v", test.name),
func(t *testing.T) {
defer func() {
rec := recover()
switch x := rec.(type) {
case nil:
t.Fatal("nothing recovered")
case string:
if !strings.Contains(x,
"unexpected call to os.Exit(0)") {
t.Fatalf("unexpected: %q", x)
}
t.Log("successful recovery")
default:
t.Fatalf("unexpected: %#v", x)
}
}()
test.fn()
})
}
}
As seen previously, this only works if the
exit code is zero: otherwise in os.Exit, the
value of PanicOnExit0 will not be
considered.
It might even be false with alternative test
runners using
internal.testlog.SetPanicOnExit
0