raz / commit 3a69bc7e

commit
3a69bc7ebdf8e46add132e962e89efb61bcf156c
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
db52f39e
Prop: property tests and fuzzing over recorded choices, shrunk

A property draws from a Source (bits, int, pick, bool, bytes) and
checks with Check. A case is the bytes it drew; a failing one is
shrunk by deleting, zeroing and lowering runs of its bytes, so no
type needs a shrinker. Prop.check replays the cases saved in
test/seeds/name, then runs PROP_CASES fresh ones (100) from PROP_SEED
or a new seed, or fuzzes for PROP_TIME seconds; the first failure is
shrunk, saved under its hash, said with the seed, and run aloud. A
case that crashes the program is saved at exit.

Check gains mute and mutedFailures, for Prop's search. raztest gains
--seed and --fuzz, which set PROP_SEED and PROP_TIME. Step 6 of
TESTING-PLAN.md.

make check: 1042 passed, 0 failed.

patch · log

5 files changed, +715 -10

TESTING-PLAN.md modified +7 -3

@@ -27,7 +27,7 @@
2727 and replay). No reals until a user needs them.
2828
2929 **Check.** `ok(cond, what)`, `str(what, got, want)` (escaped),
30-`int(what, got, want)`, `mute`/`unmute`. A failure is a block on
30+`int(what, got, want)`, `mute(on)` and `mutedFailures()` for Prop. A failure is a block on
3131 standard error:
3232
3333 FAIL what
@@ -44,11 +44,15 @@
4444 (`int(s, lo, hi)`, `bool(s)`, `bytes(s, max, buf)`, `pick(s, n)`) and
4545 checks them with `Check`. A case is the bytes it drew (as Hypothesis
4646 does), so shrinking works on those bytes (cut chunks, zero, lower) and
47-replays the property: no shrinker per type, no closures. A property
47+replays the property: no shrinker per type, no closures. A number is 8
48+bytes, big-endian, lowered as a whole; `bytes` puts before each byte
49+one that may end them, so that they shrink one by one. A property
4850 reading only `bytes` is a byte fuzzer. While searching, `Check` is
4951 muted; the smallest failing case is run again aloud and saved to
5052 `test/seeds/<name>`; saved seeds are replayed first, every run.
51-`PROP_SEED` replays one case, `PROP_TIME=60` fuzzes for a minute.
53+`PROP_SEED` replays a run's fresh cases, `PROP_CASES` sets how many
54+(100), `PROP_TIME=60` fuzzes for a minute, `PROP_DIR` moves the seeds;
55+a case that crashes is saved at exit.
5256
5357 **raztest.** Finds modules with `proc main*` in `src/` and `test/*.raz`
5458 (`-I`, default `src`); builds with `-Werror`; runs them, `-j n`, a

doc/raztest.1 (history) modified +34 -0

@@ -15,6 +15,8 @@
1515 .Op Fl w
1616 .Op Fl \-tap
1717 .Op Fl \-junit Ar file
18+.Op Fl \-seed Ar n
19+.Op Fl \-fuzz Ar secs
1820 .Ar file.raz Ns | Ns Ar dir ...
1921 .Sh DESCRIPTION
2022 .Nm
@@ -163,6 +165,31 @@
163165 Control bytes XML 1.0 forbids in a log are written as
164166 .Ql \&? ;
165167 invalid UTF-8 is passed through.
168+.It Fl \-seed Ar n
169+For tests that use the library's
170+.Ic Prop :
171+set
172+.Ev PROP_SEED
173+to
174+.Ar n ,
175+a whole number from 0, so that their fresh cases are those of an
176+earlier run, which a failing property names.
177+.It Fl \-fuzz Ar secs
178+For tests that use
179+.Ic Prop :
180+set
181+.Ev PROP_TIME
182+to
183+.Ar secs ,
184+so that each property is tried on fresh cases for that many seconds,
185+not on 100 of them.
186+It raises
187+.Fl t
188+to
189+.Ar secs
190++ 60, unless
191+.Fl t
192+is given.
166193 .It Fl h , Fl \-help
167194 Say the options, and exit.
168195 .El
@@ -191,6 +218,13 @@
191218 In CI, with a report for the service to show:
192219 .Bd -literal -offset indent
193220 raztest -j 4 -I src --junit build/junit.xml test
221+.Ed
222+.Pp
223+Fuzz each property of the tests in
224+.Pa test
225+for ten minutes:
226+.Bd -literal -offset indent
227+raztest -I src --fuzz 600 test
194228 .Ed
195229 .Pp
196230 A Makefile's check that uses

lib/Check.raz (history) modified +35 -3

@@ -6,6 +6,8 @@
66 end, and a run with no failures says nothing. A program that stops
77 otherwise after a check failed, by Rt.stop or a failed check of the
88 language, ends with status 1 too.
9+ While mute is on, as Prop searches for a failing case, checks say
10+ nothing and aren't counted, but mutedFailures counts those failed.
911
1012 FAIL what
1113 got: "a\nb"
@@ -26,11 +28,30 @@
2628 failures: INT; (* of them, failed *)
2729 registered: BOOL; (* the exit procedure is on Rt's list *)
2830 sink: proc(s: []U8); (* where text goes, or nil for standard error; a test sets it *)
31+ muted: BOOL; (* checks say nothing and aren't counted, as Prop searches *)
32+ mutedFails: INT; (* checks failed since mute was turned on *)
2933
30-(* Writes s to standard error, trying again after a short or interrupted write. *)
34+(* Turns muting on or off. While it is on, checks write nothing and
35+ count neither as checks nor as failures; turning it on zeroes the
36+ failures mutedFailures gives. *)
37+proc mute*(on: BOOL);
38+begin
39+ muted := on;
40+ if on then mutedFails := 0; end;
41+end;
42+
43+(* How many checks failed while muted, since mute was turned on. *)
44+proc mutedFailures*(): INT;
45+begin
46+ return mutedFails;
47+end;
48+
49+(* Writes s to standard error, trying again after a short or interrupted
50+ write; nothing while muted. *)
3151 proc put(s: []U8);
3252 var n: INT;
3353 begin
54+ if muted then return; end;
3455 if sink # nil then sink(s); return; end;
3556 while LEN(s) > 0 do
3657 n := Sys.write(Sys.stderr, s);
@@ -107,14 +128,17 @@
107128 any did, and ends the program with status 1. *)
108129 proc report;
109130 begin
131+ muted := false; (* a program that stopped while muted still reports *)
110132 if failures = 0 then return; end;
111133 put("Check: "); putInt(failures); put(" of "); putInt(checks); put(" failed\n");
112134 Rt.exit(1);
113135 end;
114136
115-(* Counts a check, and the first time registers report to run at exit. *)
137+(* Counts a check, unless muted, and the first time registers report
138+ to run at exit. *)
116139 proc count;
117140 begin
141+ if muted then return; end;
118142 if not registered then
119143 if Rt.atExit(report) # nil then Rt.stop("Check: no room for the exit procedure"); end;
120144 registered := true;
@@ -123,9 +147,11 @@
123147 end;
124148
125149 (* Counts a failure and begins its report with the FAIL line. Standard
126- output is flushed first, so the two come in order. *)
150+ output is flushed first, so the two come in order. While muted, it
151+ only counts it among the muted failures. *)
127152 proc fail(what: []U8);
128153 begin
154+ if muted then INC(mutedFails); return; end;
129155 INC(failures);
130156 Out.flush;
131157 put("FAIL "); put(what); put("\n");
@@ -208,6 +234,12 @@
208234 ok(true, "ok passes");
209235 str("str passes", "same", "same");
210236 int("int passes", -5, -5);
237+ mute(true);
238+ ok(false, "muted ok");
239+ str("muted str", "a", "b");
240+ int("muted int", 1, 2);
241+ mute(false);
242+ if mutedFailures() # 3 then Rt.stop("Check: muted failures are wrong"); end;
211243 if (checks # 10 + 3) or (failures # 0) then Rt.stop("Check: counts are wrong"); end;
212244 end;
213245 end Check.

lib/Prop.raz (history) added +604 -0

@@ -0,0 +1,604 @@
1+(* Property tests and fuzzing over recorded choices, with shrinking.
2+
3+ A property is a procedure that draws values from a Source and checks
4+ them with Check. A case is the bytes the property drew: a fresh case
5+ takes them from Rand, and a failing case is shrunk by changing its
6+ bytes, not its values, and running the property again, so no type
7+ needs a shrinker of its own. A property that draws only bytes is a
8+ fuzzer. Fewer and smaller bytes give simpler values:
9+
10+ 01 00 00 00 00 00 00 03 E8 05 78 00
11+ -- ----------------------- --------
12+ bool int(0, 1000000): 1000 bytes: "x"
13+
14+ check(name, p) runs p on each case saved in $PROP_DIR/name (default
15+ test/seeds/name), then on $PROP_CASES fresh cases (100) from the
16+ seed $PROP_SEED or a new one, or on as many as $PROP_TIME seconds
17+ allow, if it is set. Check is muted while it searches. The first
18+ case that fails is shrunk, saved in a file named by its hash, said
19+ on standard error with the seed, and run once more aloud, so that
20+ Check shows its failures and the program ends with status 1. A
21+ passing check says nothing. A case that stops the program, by a
22+ failed check of the language, Rt.stop or a signal, can't be shrunk:
23+ it is saved as it is, at exit, and so is replayed first next run.
24+
25+ Needs Rt, Sys, Buf, Heap, Str, Fmt, Files, Rand and Check. Leaves
26+ out generators of composite types (a property builds them from
27+ draws), shrinking by type, coverage guidance, and threads. *)
28+module Prop;
29+import Rt, Sys, Buf, Heap, Str, Fmt, Files, Rand, Check;
30+
31+const
32+ Budget = 5000; (* the most runs a shrink makes *)
33+ Cases = 100; (* fresh cases when $PROP_CASES is unset *)
34+ Seeds = "test/seeds"; (* where cases are saved when $PROP_DIR is unset *)
35+ Second = 1000000000; (* a second in Sys.clock's nanoseconds *)
36+ Look = 64; (* fresh cases between looks at the clock, a system call *)
37+ Digits = "0123456789abcdef"; (* the digits of a saved case's name *)
38+
39+type
40+ (* A case: the bytes a property draws from, kept as they are drawn. *)
41+ Source* = record
42+ data: Buf.Buf; (* the bytes: given, then those drawn past them *)
43+ drawn: INT; (* how many the property has drawn *)
44+ fresh: BOOL; (* bytes past data come from rand, not 0 *)
45+ rand: Rand.Rand; (* where a fresh case's bytes come from *)
46+ end;
47+
48+ (* A property: draws from s, and checks what it drew with Check. *)
49+ Property* = proc(var s: Source);
50+
51+var
52+ src: Source; (* the case being run; one at a time *)
53+ best: Buf.Buf; (* the simplest failing case found *)
54+ cand: Buf.Buf; (* a case to try: a shrink of best, or a saved one *)
55+ runs: INT; (* runs the shrink under way has made *)
56+ found: INT; (* bytes of the failing fresh case, before shrinking *)
57+ name: []U8; (* the property being checked *)
58+ dir: Buf.Buf; (* where its cases are saved *)
59+ path: Buf.Buf; (* the file of a saved case *)
60+ seed: U64; (* the seed of the fresh cases *)
61+ underway: BOOL; (* a case is being run, for crashed *)
62+ ready: BOOL; (* the buffers are made and crashed is registered *)
63+
64+(* The next byte of the case. Past the bytes given it is a fresh random
65+ one, or 0 in a replayed case; either way it is added to the case. *)
66+proc next(var s: Source): U8;
67+var c: U8;
68+begin
69+ if s.drawn = s.data.len then
70+ c := 0;
71+ if s.fresh then c := U8(Rand.next(s.rand)); end;
72+ Buf.add(s.data, c);
73+ end;
74+ c := Buf.bytes(s.data)[s.drawn];
75+ INC(s.drawn);
76+ return c;
77+end;
78+
79+(* 64 bits, from 8 bytes, the first the highest: a byte-wise smaller
80+ case is a smaller number. *)
81+proc bits*(var s: Source): U64;
82+var i: INT; v: U64;
83+begin
84+ for i := 1 to 8 do v := v shl 8 | U64(next(s)); end;
85+ return v;
86+end;
87+
88+(* A number from lo to hi, both included, the whole I64 range too;
89+ zeros give lo. lo must not exceed hi. *)
90+proc int*(var s: Source; lo, hi: I64): I64;
91+var span, v: U64;
92+begin
93+ if lo > hi then Rt.stop("Prop.int: lo > hi"); end;
94+ span := U64(hi) - U64(lo);
95+ v := bits(s);
96+ if span # 0FFFFFFFFFFFFFFFFH then v := v mod (span + 1); end;
97+ return I64(U64(lo) + v);
98+end;
99+
100+(* One of 0 to n - 1; n must be at least 1. *)
101+proc pick*(var s: Source; n: INT): INT;
102+begin
103+ if n < 1 then Rt.stop("Prop.pick: n < 1"); end;
104+ return INT(int(s, 0, I64(n - 1)));
105+end;
106+
107+(* A byte's lowest bit: odd is true. *)
108+proc bool*(var s: Source): BOOL;
109+begin
110+ return next(s) & 1 = 1;
111+end;
112+
113+(* b, emptied, then given at most max bytes. Before each comes a byte
114+ that ends them if it is below a mark, so that deleting two bytes of
115+ the case deletes one of b: a length drawn first could not shrink with
116+ them. The mark makes a fresh b about max / 2 long. *)
117+proc bytes*(var s: Source; max: INT; var b: Buf.Buf);
118+var mark: INT;
119+begin
120+ Buf.reset(b);
121+ mark := 256 div ((max + 1) div 2 + 1);
122+ if mark < 1 then mark := 1; end;
123+ while (b.len < max) and (INT(next(s)) >= mark) do Buf.add(b, next(s)); end;
124+end;
125+
126+(* Makes s a fresh case, its bytes from s.rand. *)
127+proc fresh(var s: Source);
128+begin
129+ Buf.reset(s.data);
130+ s.drawn := 0;
131+ s.fresh := true;
132+end;
133+
134+(* Makes s replay the case data; past its end, bytes are 0. *)
135+proc replay(var s: Source; data: []U8);
136+begin
137+ Buf.reset(s.data);
138+ Buf.str(s.data, data);
139+ s.drawn := 0;
140+ s.fresh := false;
141+end;
142+
143+(* Runs p on the case in src, with Check muted; whether a check failed. *)
144+proc fails(p: Property): BOOL;
145+begin
146+ Check.mute(true);
147+ underway := true;
148+ p(src);
149+ underway := false;
150+ return Check.mutedFailures() > 0;
151+end;
152+
153+(* Runs p on data once more, with Check heard, so that it shows the
154+ failure and counts it. *)
155+proc aloud(p: Property; data: []U8);
156+begin
157+ Check.mute(false);
158+ replay(src, data);
159+ p(src);
160+end;
161+
162+(* Whether case a is simpler than b: shorter, or as long and smaller
163+ byte by byte. *)
164+proc simpler(a, b: []U8): BOOL;
165+begin
166+ return (LEN(a) < LEN(b)) or ((LEN(a) = LEN(b)) and (Str.cmp(a, b) < 0));
167+end;
168+
169+(* Runs p on cand, within the budget; if it fails and the bytes it drew
170+ are simpler than best, they become best, and the result is true. *)
171+proc improves(p: Property): BOOL;
172+var drawn: []U8;
173+begin
174+ if runs >= Budget then return false; end;
175+ INC(runs);
176+ replay(src, Buf.bytes(cand));
177+ if not fails(p) then return false; end;
178+ drawn := Buf.bytes(src.data)[0..src.drawn];
179+ if not simpler(drawn, Buf.bytes(best)) then return false; end;
180+ Buf.reset(best);
181+ Buf.str(best, drawn);
182+ return true;
183+end;
184+
185+(* best's w bytes from i, as a number, the first the highest. *)
186+proc chunk(i, w: INT): U64;
187+begin
188+ return Str.be(Buf.bytes(best)[i..i + w]);
189+end;
190+
191+(* Makes cand best without its w bytes from i. *)
192+proc without(i, w: INT);
193+var b: []U8;
194+begin
195+ b := Buf.bytes(best);
196+ Buf.reset(cand);
197+ Buf.str(cand, b[0..i]);
198+ Buf.str(cand, b[i + w..LEN(b)]);
199+end;
200+
201+(* Makes cand best with its w bytes from i the number v. *)
202+proc setChunk(i, w: INT; v: U64);
203+begin
204+ Buf.reset(cand);
205+ Buf.str(cand, Buf.bytes(best));
206+ Str.putBE(Buf.bytes(cand)[i..i + w], v);
207+end;
208+
209+(* Tries best without each run of 8, 4, 2 and 1 bytes; whether any
210+ made it simpler. *)
211+proc deletePass(p: Property): BOOL;
212+var w, i: INT; better: BOOL;
213+begin
214+ w := 8;
215+ while w > 0 do
216+ i := 0;
217+ while i + w <= best.len do
218+ without(i, w);
219+ if improves(p) then better := true; else INC(i); end; (* on success, the next run moved to i *)
220+ end;
221+ w := w div 2;
222+ end;
223+ return better;
224+end;
225+
226+(* Tries best with each run of 8, 4, 2 and 1 bytes made zeros; whether
227+ any made it simpler. *)
228+proc zeroPass(p: Property): BOOL;
229+var w, i: INT; better: BOOL;
230+begin
231+ w := 8;
232+ while w > 0 do
233+ i := 0;
234+ while i + w <= best.len do
235+ if chunk(i, w) # 0 then
236+ setChunk(i, w, 0);
237+ if improves(p) then better := true; end;
238+ end;
239+ INC(i);
240+ end;
241+ w := w div 2;
242+ end;
243+ return better;
244+end;
245+
246+(* Looks, by binary search, for the least number for best's w bytes
247+ from i that still fails; whether best changed. *)
248+proc lower(p: Property; i, w: INT): BOOL;
249+var lo, hi, mid: U64; better: BOOL;
250+begin
251+ hi := chunk(i, w); (* fails; all below lo don't, as far as is known *)
252+ while (lo < hi) and (runs < Budget) and (i + w <= best.len) do
253+ mid := lo + (hi - lo) div 2;
254+ setChunk(i, w, mid);
255+ if improves(p) then hi := mid; better := true; else lo := mid + 1; end;
256+ end;
257+ return better;
258+end;
259+
260+(* Lowers each run of 8, 4, 2 and 1 bytes of best, as a number; whether
261+ any made it simpler. A number drawn from several bytes shrinks as a
262+ whole, where lowering byte by byte would stop at 1024 above 1000. *)
263+proc lowerPass(p: Property): BOOL;
264+var w, i: INT; better: BOOL;
265+begin
266+ w := 8;
267+ while w > 0 do
268+ i := 0;
269+ while i + w <= best.len do
270+ if lower(p, i, w) then better := true; end;
271+ INC(i);
272+ end;
273+ w := w div 2;
274+ end;
275+ return better;
276+end;
277+
278+(* Makes best, a failing case, as simple as the passes can within the
279+ budget: until a round of them finds nothing simpler. *)
280+proc shrink(p: Property);
281+var better: BOOL;
282+begin
283+ runs := 0;
284+ repeat
285+ better := deletePass(p);
286+ if zeroPass(p) then better := true; end;
287+ if lowerPass(p) then better := true; end;
288+ until not better or (runs >= Budget);
289+end;
290+
291+(* s as a decimal U64, and true; false if it is not one. *)
292+proc decimal(s: []U8): (U64, BOOL);
293+var v, d: U64; i: INT;
294+begin
295+ if LEN(s) = 0 then return 0, false; end;
296+ for i := 0 to LEN(s) - 1 do
297+ if not Str.isDigit(s[i]) then return 0, false; end;
298+ d := U64(s[i] - '0');
299+ if v > (0FFFFFFFFFFFFFFFFH - d) div 10 then return 0, false; end;
300+ v := v * 10 + d;
301+ end;
302+ return v, true;
303+end;
304+
305+(* Stops the program: the environment variable called key is not a
306+ number, as it must be. *)
307+proc badEnv(key: []U8);
308+begin
309+ Fmt.eprint("Prop: ${} is not a whole number\n", [Fmt.str(key)]);
310+ Rt.exit(2);
311+end;
312+
313+(* The environment variable called key, a number from 0; otherwise
314+ unset, and 0. *)
315+proc envNumber(key: []U8): I64;
316+var n: I64; ok: BOOL;
317+begin
318+ if LEN(Sys.env(key)) = 0 then return 0; end;
319+ n, ok := Str.toInt(Sys.env(key));
320+ if not ok or (n < 0) then badEnv(key); end;
321+ return n;
322+end;
323+
324+(* The seed for the fresh cases: $PROP_SEED, or a new one. *)
325+proc envSeed(): U64;
326+var v: U64; ok: BOOL;
327+begin
328+ if LEN(Sys.env("PROP_SEED")) = 0 then return Rand.seed(); end;
329+ v, ok := decimal(Sys.env("PROP_SEED"));
330+ if not ok then badEnv("PROP_SEED"); end;
331+ return v;
332+end;
333+
334+(* Runs fresh cases, $PROP_CASES of them or for $PROP_TIME seconds;
335+ if one fails, it is shrunk into best, and the result is true. *)
336+proc freshFailing(p: Property): BOOL;
337+var cases, n, deadline: I64;
338+begin
339+ seed := envSeed();
340+ Rand.init(src.rand, seed);
341+ cases := Cases;
342+ if LEN(Sys.env("PROP_CASES")) > 0 then cases := envNumber("PROP_CASES"); end;
343+ deadline := 0;
344+ if envNumber("PROP_TIME") > 0 then deadline := Sys.clock() + envNumber("PROP_TIME") * Second; end;
345+ n := 0;
346+ while ((deadline = 0) and (n < cases)) or ((deadline # 0) and ((n mod Look # 0) or (Sys.clock() < deadline))) do
347+ fresh(src);
348+ if fails(p) then
349+ Buf.reset(best);
350+ Buf.str(best, Buf.bytes(src.data));
351+ found := best.len;
352+ shrink(p);
353+ return true;
354+ end;
355+ INC(n);
356+ end;
357+ return false;
358+end;
359+
360+(* The 16 hex digits of v. *)
361+proc hex(v: U64): [16]U8;
362+var d: [16]U8; i: INT;
363+begin
364+ for i := 15 to 0 by -1 do
365+ d[i] := Digits[INT(v & 15)];
366+ v := v shr 4;
367+ end;
368+ return d;
369+end;
370+
371+(* Makes path the file called file in dir. *)
372+proc caseFile(file: []U8);
373+begin
374+ Buf.reset(path);
375+ Buf.str(path, Buf.bytes(dir));
376+ Buf.add(path, '/');
377+ Buf.str(path, file);
378+end;
379+
380+(* Saves data in dir, made with the directories it needs, in a file
381+ named by the hash of data, so that a case is saved once; whether it
382+ was written. path names the file. *)
383+proc save(data: []U8): BOOL;
384+var d: []U8; i: INT; h: [16]U8;
385+begin
386+ d := Buf.bytes(dir);
387+ for i := 1 to LEN(d) - 1 do
388+ if d[i] = '/' then _ := Sys.makeDir(d[0..i]); end;
389+ end;
390+ _ := Sys.makeDir(d);
391+ h := hex(Str.hash(data));
392+ caseFile(h);
393+ return Files.write(Buf.bytes(path), data);
394+end;
395+
396+(* What became of a case save tried to save, for a message. *)
397+proc saved(ok: BOOL): []U8;
398+begin
399+ if ok then return "saved"; end;
400+ return "could not save";
401+end;
402+
403+(* Runs each case saved in dir; if one fails, it is in cand, its file
404+ in path, and the result is true. *)
405+proc savedFailing(p: Property): BOOL;
406+var d: Sys.Dir; file: []U8; more: BOOL;
407+begin
408+ if Sys.openDir(d, Buf.bytes(dir)) < 0 then return false; end; (* none saved yet *)
409+ file, more := Sys.nextEntry(d);
410+ while more do
411+ caseFile(file);
412+ Buf.reset(cand);
413+ if Files.read(Buf.bytes(path), cand) then
414+ replay(src, Buf.bytes(cand));
415+ if fails(p) then Sys.closeDir(d); return true; end;
416+ end;
417+ file, more := Sys.nextEntry(d);
418+ end;
419+ Sys.closeDir(d);
420+ return false;
421+end;
422+
423+(* Run at exit: a case still under way stopped the program, so it is
424+ saved, to be replayed first next run. *)
425+proc crashed;
426+var ok: BOOL;
427+begin
428+ if not underway then return; end;
429+ underway := false;
430+ ok := save(Buf.bytes(src.data));
431+ Fmt.eprint("Prop {}: crashed; case {} {}\n",
432+ [Fmt.str(name), Fmt.str(saved(ok)), Fmt.str(Buf.bytes(path))]);
433+end;
434+
435+(* Makes the buffers and registers crashed, the first time; then sets
436+ the property's name and directory. *)
437+proc prepare(n: []U8);
438+var root: []U8;
439+begin
440+ if not ready then
441+ Buf.init(src.data, Heap.heap);
442+ Buf.init(best, Heap.heap);
443+ Buf.init(cand, Heap.heap);
444+ Buf.init(dir, Heap.heap);
445+ Buf.init(path, Heap.heap);
446+ if Rt.atExit(crashed) # nil then Rt.stop("Prop: no room for the exit procedure"); end;
447+ ready := true;
448+ end;
449+ name := n;
450+ root := Sys.env("PROP_DIR");
451+ if LEN(root) = 0 then root := Seeds; end;
452+ Buf.reset(dir);
453+ Buf.str(dir, root);
454+ Buf.add(dir, '/');
455+ Buf.str(dir, n);
456+end;
457+
458+(* Checks the property p, called name: the saved cases, then fresh
459+ ones; the first that fails is said, saved if fresh, and run aloud. *)
460+proc check*(name: []U8; p: Property);
461+var ok: BOOL;
462+begin
463+ prepare(name);
464+ if savedFailing(p) then
465+ Fmt.eprint("Prop {}: saved case {} fails\n", [Fmt.str(name), Fmt.str(Buf.bytes(path))]);
466+ aloud(p, Buf.bytes(cand));
467+ elsif freshFailing(p) then
468+ ok := save(Buf.bytes(best));
469+ Fmt.eprint("Prop {}: failed, seed {}; shrunk from {} to {} bytes, {} {}\n",
470+ [Fmt.str(name), Fmt.uint(seed), Fmt.int(found), Fmt.int(best.len),
471+ Fmt.str(saved(ok)), Fmt.str(Buf.bytes(path))]);
472+ aloud(p, Buf.bytes(best));
473+ end;
474+ Check.mute(false);
475+end;
476+
477+var
478+ got: Buf.Buf; (* what the test's properties drew with bytes *)
479+
480+(* A property that holds. *)
481+proc holds(var s: Source);
482+begin
483+ Check.ok(int(s, 0, 9) <= 9, "int within its range");
484+end;
485+
486+(* A property that fails from 1000 on. *)
487+proc below1000(var s: Source);
488+begin
489+ Check.ok(int(s, 0, 1000000) < 1000, "int below 1000");
490+end;
491+
492+(* A property that fails when the bytes hold an x. *)
493+proc noX(var s: Source);
494+begin
495+ bytes(s, 100, got);
496+ Check.ok(Str.find(Buf.bytes(got), "x") < 0, "no x in the bytes");
497+end;
498+
499+(* The draws, on cases given byte by byte. *)
500+proc testDraws;
501+begin
502+ replay(src, "");
503+ Check.int("int of zeros", int(src, -5, 5), -5);
504+ Check.ok(not bool(src), "bool of zero");
505+ bytes(src, 10, got);
506+ Check.int("bytes of zeros", got.len, 0);
507+ Check.int("pick of zeros", pick(src, 3), 0);
508+ Check.int("past the end, all drawn", src.drawn, 8 + 1 + 1 + 8);
509+ replay(src, "\x01\x02\x03\x04\x05\x06\x07\x08");
510+ Check.ok(bits(src) = 0102030405060708H, "bits big-endian");
511+ replay(src, "\x00\x00\x00\x00\x00\x00\x01\x02\x00\x00\x00\x00\x00\x00\x00\x07");
512+ Check.int("int from lo", int(src, 10, 1000), 10 + 258);
513+ Check.int("int mod the span", int(src, 0, 4), 2);
514+ replay(src, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF");
515+ Check.int("int whole range", int(src, -9223372036854775807 - 1, 9223372036854775807), 9223372036854775807);
516+ replay(src, "\x03");
517+ Check.ok(bool(src) and not bool(src), "bool odd, then 0 past the end");
518+ replay(src, "\x05a\x05b\x00");
519+ bytes(src, 100, got);
520+ Check.str("bytes until a byte below the mark", Buf.bytes(got), "ab");
521+ replay(src, "\x80a\x80b");
522+ bytes(src, 1, got);
523+ Check.str("bytes at most max", Buf.bytes(got), "a");
524+ Check.int("bytes at max draw no more", src.drawn, 2);
525+end;
526+
527+(* Small private procedures. *)
528+proc testHelpers;
529+var v: U64; ok: BOOL; h: [16]U8;
530+begin
531+ h := hex(0123456789ABCDEFH);
532+ Check.str("hex", h, "0123456789abcdef");
533+ v, ok := decimal("18446744073709551615");
534+ Check.ok(ok and (v = 0FFFFFFFFFFFFFFFFH), "decimal largest");
535+ v, ok := decimal("18446744073709551616");
536+ Check.ok(not ok, "decimal too big");
537+ v, ok := decimal("12a");
538+ Check.ok(not ok, "decimal not digits");
539+ Check.ok(simpler("ab", "abc") and simpler("ab", "ac") and not simpler("ab", "ab"), "simpler");
540+end;
541+
542+(* Fresh cases found and shrunk, with a fixed seed so the test is the
543+ same each run. *)
544+proc testShrink;
545+var failed: BOOL;
546+begin
547+ prepare("int");
548+ failed := freshFailing(below1000);
549+ Check.mute(false);
550+ Check.ok(failed, "int: a failing case found");
551+ replay(src, Buf.bytes(best));
552+ Check.int("int: shrunk to 1000", int(src, 0, 1000000), 1000);
553+ Check.int("int: shrunk to 8 bytes", best.len, 8);
554+ prepare("bytes");
555+ failed := freshFailing(noX);
556+ Check.mute(false);
557+ Check.ok(failed, "bytes: a failing case found");
558+ replay(src, Buf.bytes(best));
559+ bytes(src, 100, got);
560+ Check.str("bytes: shrunk to x", Buf.bytes(got), "x");
561+ Check.int("bytes: shrunk to 3 bytes", best.len, 3);
562+ check("holds", holds);
563+end;
564+
565+(* A case saved, then replayed. *)
566+proc testSaved;
567+var failed: BOOL; h: [16]U8; b: Buf.Buf;
568+begin
569+ prepare("saved");
570+ Check.ok(save("\x00\x00\x00\x00\x00\x00\x03\xE8"), "save");
571+ h := hex(Str.hash("\x00\x00\x00\x00\x00\x00\x03\xE8"));
572+ Check.ok(Str.hasSuffix(Buf.bytes(path), h), "saved under its hash");
573+ Buf.init(b, Heap.heap);
574+ Check.ok(Files.read(Buf.bytes(path), b), "saved file read");
575+ Check.str("saved bytes", Buf.bytes(b), "\x00\x00\x00\x00\x00\x00\x03\xE8");
576+ failed := savedFailing(below1000);
577+ Check.mute(false);
578+ Check.ok(failed, "saved case replayed and fails");
579+ failed := savedFailing(holds);
580+ Check.mute(false);
581+ Check.ok(not failed, "saved case passes another property");
582+ check("saved", holds);
583+ Check.int("remove the case", Sys.remove(Buf.bytes(path)), 0);
584+ Check.int("remove its directory", Sys.removeDir(Buf.bytes(dir)), 0);
585+ Buf.done(b);
586+end;
587+
588+(* The module's test, with its cases in build/proptest, removed after. *)
589+proc main*;
590+begin
591+ _ := Sys.setEnv("PROP_DIR", "build/proptest");
592+ _ := Sys.setEnv("PROP_SEED", "1");
593+ _ := Sys.setEnv("PROP_CASES", "");
594+ _ := Sys.setEnv("PROP_TIME", "");
595+ Buf.init(got, Heap.heap);
596+ prepare("draws");
597+ testDraws;
598+ testHelpers;
599+ testShrink;
600+ testSaved;
601+ Check.int("remove build/proptest", Sys.removeDir("build/proptest"), 0);
602+end;
603+
604+end Prop.

tools/Test.raz (history) modified +35 -4

@@ -1,7 +1,8 @@
11 (* Test: raztest, which builds and runs the tests of a raz program.
22
33 raztest [-I dir] [-j n] [-t secs] [-o dir] [-r text] [-w]
4- [--tap] [--junit file] file.raz|dir ...
4+ [--tap] [--junit file] [--seed n] [--fuzz secs]
5+ file.raz|dir ...
56
67 A test is a module whose main is its test: it passes if it builds
78 with raz -Werror and then exits with status 0, as a program that
@@ -46,6 +47,11 @@
4647 each time, so a new test file is found. On a terminal the screen is
4748 cleared before each run.
4849
50+ --seed n and --fuzz secs are for tests that use Prop: they set
51+ PROP_SEED, the seed of the fresh cases, and PROP_TIME, how long each
52+ property is fuzzed, in the tests' environment. --fuzz raises -t to
53+ secs + 60, unless -t is given.
54+
4955 Needs only the library. Leaves out: arguments to a test, tests not
5056 in raz, and the number of processors as -j's default, which Sys
5157 can't tell: it is 1. *)
@@ -56,8 +62,10 @@
5662 const
5763 TapKey = 1; (* the keys of --tap and --junit, which have no letter *)
5864 JunitKey = 2;
65+ SeedKey = 3; (* and of --seed and --fuzz *)
66+ FuzzKey = 4;
5967 Table: []Opt.Row = [
60- Opt.usage("", "raztest [-I dir] [-j n] [-t secs] [-o dir] [-r text] [-w] [--tap] [--junit file] file.raz|dir ..."),
68+ Opt.usage("", "raztest [-I dir] [-j n] [-t secs] [-o dir] [-r text] [-w] [--tap] [--junit file] [--seed n] [--fuzz secs] file.raz|dir ..."),
6169 Opt.option("", 'I', "include", "dir", "look for modules in dir too, as raz -I"),
6270 Opt.option("", 'j', "jobs", "n", "run n tests at once (1)"),
6371 Opt.option("", 't', "timeout", "secs", "kill a build or run after secs (60)"),
@@ -65,7 +73,9 @@
6573 Opt.option("", 'r', "run", "text", "run only the tests whose name holds text"),
6674 Opt.option("", 'w', "watch", "", "run again whenever a .raz file changes"),
6775 Opt.option("", TapKey, "tap", "", "write TAP version 14 instead of the usual lines"),
68- Opt.option("", JunitKey, "junit", "file", "also write the results to file as JUnit XML")];
76+ Opt.option("", JunitKey, "junit", "file", "also write the results to file as JUnit XML"),
77+ Opt.option("", SeedKey, "seed", "n", "give Prop's fresh cases the seed n"),
78+ Opt.option("", FuzzKey, "fuzz", "secs", "fuzz each Prop property for secs")];
6979 PollMs = 10; (* how long to wait between looks at the running tests *)
7080 WatchMs = 300; (* how long to wait between looks at the watched files *)
7181 Clear = "\x1b[H\x1b[2J"; (* home the cursor and clear the screen *)
@@ -207,9 +217,26 @@
207217 end;
208218 end;
209219
220+(* Sets the environment variable name to value, for the tests. *)
221+proc setProp(name, value: []U8);
222+begin
223+ if Sys.setEnv(name, value) # 0 then die("can't set {}", [Fmt.str(name)]); end;
224+end;
225+
226+(* --seed: PROP_SEED, a whole number from 0, as Prop reads it. *)
227+proc setSeed(const p: Opt.Parser);
228+var i: INT;
229+begin
230+ if LEN(p.value) = 0 then Opt.refuse(p, "a whole number"); end;
231+ for i := 0 to LEN(p.value) - 1 do
232+ if not Str.isDigit(p.value[i]) then Opt.refuse(p, "a whole number"); end;
233+ end;
234+ setProp("PROP_SEED", p.value);
235+end;
236+
210237 (* Reads the command line into the settings and the list of tests. *)
211238 proc readArgs;
212-var p: Opt.Parser; arg: []U8; ok: BOOL;
239+var p: Opt.Parser; arg: []U8; ok, timed: BOOL; fuzz: I64;
213240 begin
214241 jobs := 1; timeout := 60 * Second; outDir := "build/raztest";
215242 Names.init(includes, Heap.heap);
@@ -224,8 +251,12 @@
224251 elsif p.letter = 'w' then watch := true;
225252 elsif p.letter = TapKey then tap := true;
226253 elsif p.letter = JunitKey then junit := p.value;
254+ elsif p.letter = SeedKey then setSeed(p);
255+ elsif p.letter = FuzzKey then fuzz := Opt.number(p, 1, 1000000); setProp("PROP_TIME", p.value);
227256 end;
257+ timed := timed or (p.letter = 't');
228258 end;
259+ if (fuzz > 0) and not timed then timeout := (fuzz + 60) * Second; end;
229260 arg, ok := Opt.operand(p);
230261 if not ok then Opt.fail(p, "no tests named; raztest --help says how"); end;
231262 repeat