This repository has been archived by the owner on Feb 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
assert.go
106 lines (91 loc) · 2.32 KB
/
assert.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package assert
import (
"cmp"
"errors"
"math"
"os/exec"
"reflect"
"strings"
"testing"
)
func OK(t testing.TB, err error) {
if err != nil {
t.Helper()
t.Fatal("error:", err)
}
}
func True(t testing.TB, value bool) {
t.Helper()
Equal(t, value, true)
}
func False(t testing.TB, value bool) {
t.Helper()
Equal(t, value, false)
}
func Error(t testing.TB, got, want error) {
if !errors.Is(got, want) {
t.Helper()
t.Fatalf("error mismatch\nwant = %v\ngot = %v", want, got)
}
}
func Equal[T comparable](t testing.TB, got, want T) {
if got != want {
t.Helper()
t.Fatalf("%T value must be equal\nwant = %+v\ngot = %+v", want, want, got)
}
}
func NotEqual[T comparable](t testing.TB, got, want T) {
if got == want {
t.Helper()
t.Fatalf("%T value must not be equal\nwant != %+v\ngot = %+v", want, want, got)
}
}
func FloatEqual[T ~float32 | ~float64](t testing.TB, got, want, epsilon T) {
if math.Abs(float64(got-want)) > float64(epsilon) {
t.Helper()
t.Fatalf("%T value must be equal\nwant = %+v\ngot = %+v\nepsilon = %v\n", want, want, got, epsilon)
}
}
func EqualAll[T comparable](t testing.TB, got, want []T) {
var zero T
if len(got) != len(want) {
t.Helper()
t.Fatalf("number of %T values mismatch\nwant = %+v\ngot = %+v", zero, want, got)
}
for i, value := range want {
if value != got[i] {
t.Helper()
t.Fatalf("%T value at index %d/%d mismatch\nwant = %+v\ngot = %+v", zero, i, len(want), value, got[i])
}
}
}
func Less[T cmp.Ordered](t testing.TB, less, more T) {
if less >= more {
t.Helper()
t.Fatalf("value is too large: %v >= %v", less, more)
}
}
func DeepEqual(t testing.TB, got, want any) {
if !reflect.DeepEqual(got, want) {
t.Helper()
t.Fatalf("%T value must be deeply equal\nwant = %+v\ngot = %+v", want, want, got)
}
}
func ExitError(t testing.TB, got error, wantExitCode int) {
switch e := got.(type) {
case *exec.ExitError:
if gotExitCode := e.ExitCode(); gotExitCode != wantExitCode {
t.Helper()
t.Fatalf("exit code mismatch\nwant = %d\ngot = %d", wantExitCode, gotExitCode)
}
default:
t.Helper()
t.Fatalf("error mismatch\nwant = exec.ExitError{%d}\ngot = %s", wantExitCode, got)
}
}
func HasPrefix(t testing.TB, got, want string) {
if !strings.HasPrefix(got, want) {
t.Helper()
t.Fatalf("prefix mismatch\nwant = %q\ngot = %q", want, got)
}
}