-
Notifications
You must be signed in to change notification settings - Fork 0
/
toast.um
329 lines (268 loc) · 9.24 KB
/
toast.um
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
import "std.um"
//~~const VERSION
// The current version number of the library, formatted as specified by
// the [Semantic Versioning Specification](https://semver.org/).
const VERSION* = "0.4.1"
//~~
type (
//~~type TestFn
// The signature of a test function.
TestFn* = fn (ctx: ^Context)
//~~
//~~type TestInfo
// Information about a test.
TestInfo* = struct {
name: str // Name of the test.
func: TestFn // The function attached to this test.
result: std::Err // The final result of this test.
time: real // The time it took for this test to pass *or* to fail.
// other unexported fields
//~~
funcDepth: uint
}
Assertions = struct { ctx: weak ^Context }
//~~type Context
// The definition of a testing context.
Context* = struct {
// Holds all of the registered tests. You can query this array
// after calling `run()` to see the results and time taken for each test.
tests: []TestInfo
// A weak pointer to the currently processed test.
// It is only valid within the test functions.
current: weak ^TestInfo
// Holds the assertion functions.
assert: Assertions
// Toggles color printing.
printWithColor: bool
// Whether to use the compact or the verbose output.
compactOutput: bool
// other unexported fields...
//~~
customAsserts: []std::Err
}
)
fn eprintln(text: str = "") { fprintf(std::stderr(), "%s\n", text) }
fn eprint(text: str = "") { fprintf(std::stderr(), text) }
fn (c: ^Context) green(text: str): str { return c.printWithColor ? sprintf("\x1b[32m%s\x1b[m", text) : text }
fn (c: ^Context) red(text: str): str { return c.printWithColor ? sprintf("\x1b[31m%s\x1b[m", text) : text }
fn (c: ^Context) bold(text: str): str { return c.printWithColor ? sprintf("\x1b[1m%s\x1b[m", text) : text }
//~~fn newContext
// Returns a new, default `Context`.
//
// Defaults:
// - `compactOutput`: `true`
// - `printWithColor`: `false`
fn newContext*(): ^Context {
//~~
c := new(Context)
c.assert = Assertions { ctx: c }
c.compactOutput = true
c.printWithColor = false
return c
}
//~~fn (^Context) pass
// Marks this test as passing. You should immediately return once calling this.
fn (c: ^Context) pass*(msg: str = ""): bool {
//~~
t := c.current
std::assert(t != null, "attempt to call pass() outside of a test case")
s := "O"
if !c.compactOutput { s = sprintf("test '%s': %s", t.name, msg) }
eprint(c.green(s))
t.funcDepth++
t.result = std::error(0, msg)
return true
}
//~~fn (^Context) fail
// Marks this test as failed. You should immediately return once calling this.
fn (c: ^Context) fail*(msg: str, code: int = -1): bool {
//~~
t := c.current
std::assert(t != null, "attempt to call fail() outside of a test case")
s := c.bold("X")
if !c.compactOutput { s = sprintf("test '%s': %s", t.name, msg) }
eprint(c.red(s))
t.funcDepth++
t.result = std::error(code, msg)
return false
}
fn (c: ^Context) checkInvariants() {
t := c.current
std::assert(t != null, "attempt to call an assertion outside of a test case")
std::assert(t.result.code == 0, "a previous assertion failed, but its enclosing function did not return")
}
//~~fn (^Context) startCustom
// Marks the start of a custom assertion.
// This must be called at the beginning of all custom assertions.
fn (c: ^Context) startCustom*() {
//~~
c.checkInvariants()
t := c.current
c.customAsserts = append(c.customAsserts, std::error(-1))
t.funcDepth++
}
//~~fn (^Context) endCustom
// Marks the end of the custom assertion.
// The intended return boolean must be passed through this function
// and that value must be returned instead:
// `return T.endCustom(returnVal)`.
fn (c: ^Context) endCustom*(res: bool): bool {
//~~
std::assert(
c.current != null && len(c.customAsserts) != 0,
"attempt to call endCustom outside a custom assertion"
)
c.customAsserts = delete(c.customAsserts, len(c.customAsserts)-1)
c.current.funcDepth--
// returning from this function decrements once more
return res
}
fn (a: ^Assertions) startAssertion(): (weak ^Context, weak ^TestInfo) {
c := a.ctx
c.checkInvariants()
return c, c.current
}
fn (a: ^Assertions) failAssertion(err: str): bool {
c := a.ctx
t := c.current
t.funcDepth += 2
c.fail(err)
return false
}
//~~ fn (^Context) assert.isTrue
// Asserts that `cond` is true.
// If the resulting `bool` is false, the caller should return immediately.
// If `msg` is not `""`, prints an extra reason alongside the error.
fn (a: ^Assertions) isTrue*(cond: bool, msg: str = ""): bool {
//~~
a.startAssertion()
if !cond {
s := "assertion failed!"
if msg != "" { s += sprintf("\nreason: '%s'", msg) }
return a.failAssertion(s)
}
return true
}
//~~ fn (^Context) assert.isFalse
// Asserts that `cond` is false. Everything else from `assert.isTrue` applies.
// (Currently, this is literally just a call to `assert.isTrue` with the condition inverted.)
fn (a: ^Assertions) isFalse*(cond: bool, msg: str = ""): bool {
//~~
a.ctx.current.funcDepth++
return a.isTrue(!cond, msg)
}
//~~fn (^Context) assert.isOk
// Asserts that `e`'s code is 0.
// If the resulting `bool` is false, the caller should return immediately.
//
// If `msg` is not `""`, prints an extra reason alongside the error.
// If it is, it defaults to `e`'s error message.
fn (a: ^Assertions) isOk*(e: std::Err, msg: str = ""): bool {
//~~
a.startAssertion()
if e.code != 0 {
s := sprintf("error code is not std::StdErr.ok (%i)", e.code)
m := msg
if m == "" { m = e.msg }
if m != "" { s += sprintf("\nreason: '%s'", m) }
return a.failAssertion(s)
}
return true
}
//~~ fn (^Context) assert.sameType
// Asserts that `a` and `b` have the same type.
// If the resulting `bool` is false, the caller should return immediately.
// If `msg` is not `""`, prints an extra reason alongside the error.
fn (a: ^Assertions) sameType*(va, vb: any, msg: str = ""): bool {
//~~
a.startAssertion()
if !selftypeeq(va, vb) {
s := sprintf("expected %v and %v to have the same type", va, vb)
if msg != "" { s += sprintf("\nreason: '%s'", msg)}
return a.failAssertion(s)
}
return true
}
//~~fn (^Context) registerTest
// Registers a single new test.
// Will throw a fatal error if the name is already registered with this context.
fn (c: ^Context) registerTest*(name: str, func: TestFn) {
//~~
e := sprintf("test '%s' already registered", name)
for _, t^ in c.tests { std::assert(name != t.name, e) }
c.tests = append(c.tests, TestInfo{ name: name, func: func })
}
//~~fn (^Context) registerTests
// Registers various tests consecutively.
// Will throw a fatal error if any of the keys are registered as names for tests with this context.
fn (c: ^Context) registerTests*(tests: []TestInfo) {
//~~
for _, t in tests {
// in case it was set, since it's checked for later
t.result.msg = ""
n := t.name
e := sprintf("test '%s' already registered", n)
for _, u^ in c.tests { std::assert(n != u.name, e) }
c.tests = append(c.tests, t)
}
}
//~~fn (^Context) run
// Runs each of the tests registered to this context,
// and returns whether any single one of them had an error.
//
// `quitIfErr` exits the application after every test is run,
// if any single one of them threw an error.
fn (c: ^Context) run*(quitIfErr: bool = true): bool {
//~~
didFail := false
passedTests := 0
if c.compactOutput { eprint("results: ") }
for _, t^ in c.tests {
c.current = t
time := std::clock()
t.func(c)
t.time = std::clock() - time
if len(c.customAsserts) != 0 {
loc := c.customAsserts[len(c.customAsserts)-1].trace[1]
eprintln(c.red("\n\n[FATAL] you missed a call to T.endCustom"))
eprint(sprintf("in function %s, line %i\nin file %s", loc.func, loc.line, loc.file))
}
if t.result.code != 0 {
didFail = true
if !c.compactOutput {
pos := t.result.trace[t.funcDepth]
eprint(sprintf("\nin file %s\nline %i", pos.file, pos.line))
}
} else {
if t.result.msg == "" { c.pass("passed") }
passedTests++
}
if !c.compactOutput { eprintln(sprintf("\ntook %fms\n", t.time * 1000)) }
}
if c.compactOutput {
eprintln("\n")
if didFail {
eprintln(c.red(c.bold("failed tests:\n")))
// TODO: should loop through all tests again?
for _, t^ in c.tests {
if t.result.code == 0 { continue }
msg := sprintf(
"test '%s': %s",
t.name, t.result.msg
)
pos := t.result.trace[t.funcDepth]
eprintln(sprintf(
"%s\nin file %s\nline %i, took %fms\n",
c.red(msg), pos.file, pos.line, t.time * 1000
))
}
}
}
l := len(c.tests)
text := sprintf("%i of %i tests passed", passedTests, l)
text = passedTests == l ? c.green(text) : c.red(text)
eprintln(c.bold(text))
c.current = null
if quitIfErr && didFail { exit(-1) }
return didFail
}