-
Notifications
You must be signed in to change notification settings - Fork 0
/
ghost.go
105 lines (85 loc) · 2.03 KB
/
ghost.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
package ghost
import (
"fmt"
"github.com/rliebz/ghost/ghostlib"
)
// T is the subset of [*testing.T] used in assertions.
//
// The Helper() method will be called in test helpers if available.
type T interface {
Log(args ...any)
Fail()
FailNow()
}
// Ghost runs test assertions.
type Ghost struct {
t T
}
// New creates a new [Ghost].
func New(t T) Ghost {
return Ghost{t}
}
// Should runs an assertion, returning true if the assertion was successful.
func (g Ghost) Should(result Result) bool {
if h, ok := g.t.(interface{ Helper() }); ok {
h.Helper()
}
if !result.Ok {
g.t.Log(result.Message)
g.t.Fail()
return false
}
return true
}
// ShouldNot runs an assertion that should not be successful, returning true if
// the assertion was not successful.
func (g Ghost) ShouldNot(result Result) bool {
if h, ok := g.t.(interface{ Helper() }); ok {
h.Helper()
}
if result.Ok {
g.t.Log(result.Message)
g.t.Fail()
return false
}
return true
}
// Must runs an assertion that must be successful, failing the test if it is not.
func (g Ghost) Must(result Result) {
if h, ok := g.t.(interface{ Helper() }); ok {
h.Helper()
}
if !g.Should(result) {
g.t.FailNow()
}
}
// MustNot runs an assertion that must not be successful, failing the test if it is.
func (g Ghost) MustNot(result Result) {
if h, ok := g.t.(interface{ Helper() }); ok {
h.Helper()
}
if !g.ShouldNot(result) {
g.t.FailNow()
}
}
// NoError asserts that an error should be nil, failing the test if it is not.
func (g Ghost) NoError(err error) {
if h, ok := g.t.(interface{ Helper() }); ok {
h.Helper()
}
args := ghostlib.ArgsFromAST(err)
if err != nil {
g.t.Log(fmt.Sprintf("%s has error value: %s", args[0], err))
g.t.FailNow()
}
}
// An Result represents the result of an assertion.
type Result struct {
// Ok returns whether the assertion was successful.
Ok bool
// Message returns a message describing the assertion.
//
// A message should be present regardless of whether or not the assertion was
// successful.
Message string
}