summaryrefslogtreecommitdiff
path: root/lib/testr/testr.myr
blob: 19cdad68565ebc3a4352153146f37d524341530a (plain)
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
use std

pkg testr =
	type ctx = struct
		ok	: bool
		reason	: byte[:]
		jmpbuf	: std.jmpbuf#
	;;

	type spec = struct
		name	: byte[:]
		fn	: (ctx : ctx# -> void)
	;;

	const run	: (specs : spec[:] -> void)
	const bench	: (specs : spec[:] -> void)
	const ok	: (ctx : ctx# -> void)
	const fail	: (ctx : ctx#, msg : byte[:], args : ... -> void)
	const check	: (ctx : ctx#, cond : bool, msg : byte[:], args : ... -> void)

	const softfail	: (ctx : ctx#, msg : byte[:], args : ... -> void)
;;

const bench = {specs
	std.put("MTEST {}\n", specs.len)
	for s : specs
		benchspec(&s)
	;;
}

const run = {specs
	std.put("MTEST {}\n", specs.len)
	for s : specs
		testspec(&s)
	;;
}

const ok = {ctx
	/* nothing to do here */
}

const check = {ctx, cond, msg, args
	var ap
	
	if !cond
		ap = std.vastart(&args)
		failv(ctx, msg, &ap)
	;;
}

const fail = {ctx, msg, args
	var ap
	
	ap = std.vastart(&args)
	failv(ctx, msg, &ap)
}

const failv = {ctx, msg, ap
	softfailv(ctx, msg, ap)
	std.longjmp(ctx.jmpbuf)
}

const softfail = {ctx, msg, args
	var ap
	
	ap = std.vastart(&args)
	softfailv(ctx, msg, &ap)
}

const softfailv = {ctx, msg, ap
	/* keep the first failure */
	if ctx.ok
		ctx.ok = false
		ctx.reason = std.fmtv(msg, ap)
	;;
}

const benchspec = {ts
	var avg, m, d, n, nsamp
	var start, dt
	var ctx : ctx
	var jmpbuf

	ctx.ok = true
	ctx.reason = ""
	ctx.jmpbuf = &jmpbuf

	avg = 0.0;
	m = 0.0;
	n = 0.0;
	nsamp = 0
	std.put("test {} <<{{!\n", ts.name)
	if !std.setjmp(&jmpbuf)
		/* estimate samples */
		start = std.now()
		ts.fn(&ctx)
		dt = (std.now() - start : flt64)

		if dt == 0.0
			nsamp = 1000_000
		else
			nsamp = (100_000.0/dt : int64)
			nsamp = std.max(10, nsamp)
		;;

		for var i = 0; i < nsamp; i++
			n +=1.0;
			start = std.now()
			ts.fn(&ctx)
			dt = (std.now() - start : flt64)/1_000_000.0
			d = (dt - avg);
			avg = avg + d/n;
			m = m + d*(dt - avg);
		;;
	;;

	if ctx.ok
		std.put("!}}>> timing {} {} {}\n", nsamp, avg, m)
	else
		std.put("!}}>> fail {}\n", ctx.reason)
		std.slfree(ctx.reason)
	;;
}

const testspec = {ts
	var ctx : ctx
	var jmpbuf

	ctx.ok = true
	ctx.reason = ""
	ctx.jmpbuf = &jmpbuf

	std.put("test {} <<{{!\n", ts.name)
	if !std.setjmp(&jmpbuf)
		ts.fn(&ctx)
	;;

	if ctx.ok
		std.put("!}}>> ok\n")
	else
		std.put("!}}>> fail {}\n", ctx.reason)
		std.slfree(ctx.reason)
	;;
}