-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasserter.go
402 lines (339 loc) · 8.88 KB
/
asserter.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package justest
import (
"fmt"
"path/filepath"
"regexp"
"time"
"github.com/arikkfir/justest/internal"
)
const SlowFactorEnvVarName = "JUSTEST_SLOW_FACTOR"
//go:noinline
func With(t T) VerifyOrEnsure {
if t == nil {
panic("given T instance must not be nil")
}
GetHelper(t).Helper()
return &verifier{t: t}
}
type VerifyOrEnsure interface {
// EnsureThat adds a description to the upcoming assertion, which will be printed in case it fails.
EnsureThat(string, ...any) Ensurer
// Deprecated: Ensure is a synonym for EnsureThat.
Ensure(string, ...any) Ensurer
// VerifyThat starts an assertion without a description.
VerifyThat(actuals ...any) Asserter
// Deprecated: Verify is a synonym for VerifyThat.
Verify(actuals ...any) Asserter
}
type Ensurer interface {
ByVerifying(actuals ...any) Asserter
}
type verifier struct {
t T
desc string
}
//go:noinline
func (v *verifier) EnsureThat(format string, args ...any) Ensurer {
GetHelper(v.t).Helper()
v.desc = fmt.Sprintf(format, args...)
return v
}
//go:noinline
func (v *verifier) Ensure(format string, args ...any) Ensurer {
GetHelper(v.t).Helper()
v.desc = fmt.Sprintf(format, args...)
return v
}
//go:noinline
func (v *verifier) ByVerifying(actuals ...any) Asserter {
GetHelper(v.t).Helper()
return &asserter{t: v.t, desc: v.desc, actuals: actuals}
}
//go:noinline
func (v *verifier) VerifyThat(actuals ...any) Asserter {
GetHelper(v.t).Helper()
return &asserter{t: v.t, desc: v.desc, actuals: actuals}
}
//go:noinline
func (v *verifier) Verify(actuals ...any) Asserter {
GetHelper(v.t).Helper()
return &asserter{t: v.t, desc: v.desc, actuals: actuals}
}
type Asserter interface {
Will(m Matcher) Assertion
}
type asserter struct {
t T
actuals []any
desc string
}
//go:noinline
func (a *asserter) Will(m Matcher) Assertion {
GetHelper(a.t).Helper()
aa := &assertion{
t: a.t,
desc: a.desc,
location: nearestLocation(),
actuals: a.actuals,
matcher: m,
}
location := nearestLocation()
a.t.Cleanup(func() {
if !a.t.Failed() && !aa.evaluated {
a.t.Fatalf("An assertion was not evaluated!\n%s:%d: --> %s", filepath.Base(location.File), location.Line, location.Source)
}
})
return aa
}
type Assertion interface {
// Now will perform the assertion and fail immediately if it mismatches.
Now()
// Deprecated: OrFail is a synonym for Now.
OrFail()
// For will continually perform the assertion until the given duration has passed or until it mismatches. If it
// mismatched once, the assertion is considered failed.
For(duration time.Duration, interval time.Duration)
// Within will continually perform the assertion until the given duration has passed or until it successfully
// matches. If the duration has passed without any successful matches, the assertion is considered failed.
Within(duration time.Duration, interval time.Duration)
}
type assertion struct {
t T
location Location
actuals []any
matcher Matcher
contain bool
cleanup []func()
evaluated bool
desc string
}
//go:noinline
func (a *assertion) OrFail() {
GetHelper(a.t).Helper()
if a.evaluated {
panic("assertion already evaluated")
} else {
a.evaluated = true
}
a.matcher.Assert(a, a.actuals...)
}
//go:noinline
func (a *assertion) Now() {
GetHelper(a.t).Helper()
if a.evaluated {
panic("assertion already evaluated")
} else {
a.evaluated = true
}
a.matcher.Assert(a, a.actuals...)
}
//go:noinline
func (a *assertion) For(duration time.Duration, interval time.Duration) {
GetHelper(a.t).Helper()
duration = transformDurationIfNecessary(a.t, duration)
if a.evaluated {
panic("assertion already evaluated")
} else {
a.evaluated = true
}
timer := time.NewTimer(duration)
defer timer.Stop()
ticker := time.NewTicker(interval)
defer ticker.Stop()
ticking := false
cleaningUp := false
var failure *internal.FormatAndArgs
succeeded := false
tick := func() {
GetHelper(a).Helper()
// Notify we're no longer in a "tick"
defer func() { ticking = false }()
// Contain the potential "Fatal" calls from this tick as failures
defer func() {
if r := recover(); r != nil {
if fa, ok := r.(internal.FormatAndArgs); ok {
failure = &fa
} else if !a.Failed() {
panic(r)
}
} else {
succeeded = true
}
}()
// Perform cleanups for this tick
a.cleanup = nil
defer func() {
cleaningUp = true
defer func() { cleaningUp = false }()
// TODO: decide what to do with failures during cleanups
for i := len(a.cleanup) - 1; i >= 0; i-- {
a.cleanup[i]()
}
}()
a.matcher.Assert(a, a.actuals...)
}
a.contain = true
started := time.Now()
for {
select {
case <-timer.C:
for cleaningUp {
time.Sleep(50 * time.Millisecond)
}
a.contain = false
if failure != nil {
a.Fatalf("%s\nAssertion failed while waiting for %s", failure, duration)
} else if !succeeded {
a.Fatalf("Timed out after %s waiting for assertion to pass (tick never finished once)", duration)
} else {
return
}
case <-ticker.C:
verifyNotInterrupted(a.t)
if failure != nil {
for cleaningUp {
time.Sleep(50 * time.Millisecond)
}
a.contain = false
a.Fatalf("%s\nAssertion failed after %s and did not pass repeatedly for %s", failure, time.Since(started), duration)
} else if !ticking {
ticking = true
go tick()
}
}
}
}
//go:noinline
func (a *assertion) Within(duration time.Duration, interval time.Duration) {
GetHelper(a.t).Helper()
duration = transformDurationIfNecessary(a.t, duration)
if a.evaluated {
panic("assertion already evaluated")
} else {
a.evaluated = true
}
timer := time.NewTimer(duration)
defer timer.Stop()
ticker := time.NewTicker(interval)
defer ticker.Stop()
ticking := false
cleaningUp := false
var failure *internal.FormatAndArgs
succeeded := false
tick := func() {
GetHelper(a).Helper()
// Notify we're no longer in a "tick"
defer func() { ticking = false }()
// Contain the potential "Fatal" calls from this tick as failures
defer func() {
if r := recover(); r != nil {
if fa, ok := r.(internal.FormatAndArgs); ok {
failure = &fa
} else if !a.Failed() {
panic(r)
}
} else {
succeeded = true
}
}()
// Perform cleanups for this tick
a.cleanup = nil
defer func() {
cleaningUp = true
defer func() { cleaningUp = false }()
// TODO: decide what to do with failures during cleanups
for i := len(a.cleanup) - 1; i >= 0; i-- {
a.cleanup[i]()
}
}()
a.matcher.Assert(a, a.actuals...)
}
a.contain = true
started := time.Now()
for {
select {
case <-timer.C:
for cleaningUp {
time.Sleep(50 * time.Millisecond)
}
if succeeded {
return
}
a.contain = false
if failure != nil {
a.Fatalf("%s\nTimed out after %s waiting for assertion to pass", failure, time.Since(started))
} else {
a.Fatalf("Timed out after %s waiting for assertion to pass (tick never finished once)", duration)
}
case <-ticker.C:
verifyNotInterrupted(a.t)
if succeeded {
for cleaningUp {
time.Sleep(50 * time.Millisecond)
}
return
} else if !ticking {
ticking = true
go tick()
}
}
}
}
//go:noinline
func (a *assertion) Name() string {
return a.t.Name()
}
//go:noinline
func (a *assertion) Cleanup(f func()) {
GetHelper(a).Helper()
if a.contain {
a.cleanup = append(a.cleanup, f)
} else {
a.t.Cleanup(f)
}
}
//go:noinline
func (a *assertion) Failed() bool {
GetHelper(a).Helper()
return a.t.Failed()
}
//go:noinline
func (a *assertion) Fatalf(format string, args ...any) {
GetHelper(a).Helper()
if a.desc != "" {
format = fmt.Sprintf("Assertion that %s failed: %s", a.desc, format)
}
if a.contain {
panic(internal.FormatAndArgs{Format: &format, Args: args})
} else {
caller := internal.CallerAt(1)
callerFunction, callerFile, callerLine := caller.Location()
// Check if direct caller is from within the "justest" package; if NOT (application test code) print the caller
if internalCall, err := regexp.MatchString(`.*/arikkfir/justest\.`, callerFunction); err != nil {
panic(fmt.Errorf("illegal regexp matching: %+v", err))
} else if !internalCall {
// Direct caller is NOT from the "justest" package; thus we also print the caller, in addition to the
// location of the actual assertion (which is always printed)
format = format + "\n%s:%d --> %s"
args = append(args, filepath.Base(callerFile), callerLine, indentIfMultiLine(readSourceAt(callerFile, callerLine)))
}
// Always print the assertion location
format = format + "\n%s:%d --> %s"
args = append(args, filepath.Base(a.location.File), a.location.Line, indentIfMultiLine(a.location.Source))
a.t.Fatalf(format, args...)
}
}
//go:noinline
func (a *assertion) Log(args ...any) {
GetHelper(a).Helper()
a.t.Log(args...)
}
//go:noinline
func (a *assertion) Logf(format string, args ...any) {
GetHelper(a).Helper()
a.t.Logf(format, args...)
}
//go:noinline
func (a *assertion) GetParent() T {
return a.t
}