forked from creachadair/mds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmtest.go
40 lines (36 loc) · 1.1 KB
/
mtest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Package mtest is a support library for writing tests.
package mtest
// TB is the subset of the testing.TB interface used by this package.
type TB interface {
Cleanup(func())
Fatalf(string, ...any)
Helper()
}
// MustPanic executes a function f that is expected to panic.
// If it does so, MustPanic returns the value recovered from the
// panic. Otherwise, it logs a fatal error in t.
func MustPanic(t TB, f func()) (val any) {
t.Helper()
defer func() { val = recover() }()
f()
t.Fatalf("expected panic was not observed")
return
}
// MustPanicf executes a function f that is expected to panic. If it does so,
// MustPanicf returns the value recovered from the panic. Otherwise it logs a
// fatal error in t.
func MustPanicf(t TB, f func(), msg string, args ...any) (val any) {
t.Helper()
defer func() { val = recover() }()
f()
t.Fatalf(msg, args...)
return
}
// Swap replaces the target of p with v, and restores the original value when
// the governing test exits. It returns the original value.
func Swap[T any](t TB, p *T, v T) T {
save := *p
*p = v
t.Cleanup(func() { *p = save })
return save
}