raz / lib / Prop.raz

584 lines · 19.2 KiB · raw · history · last change e0d008cd

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. *)
28module Prop;
29import Rt, Sys, Buf, Heap, Str, Fmt, Files, Rand, Check;
30
31const
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
39type
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
51var
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: []const 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. *)
66proc next(var s: Source): U8;
67var c: U8;
68begin
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;
77end;
78
79(* 64 bits, from 8 bytes, the first the highest: a byte-wise smaller
80 case is a smaller number. *)
81proc bits*(var s: Source): U64;
82var i: INT; v: U64;
83begin
84 for i := 1 to 8 do v := v shl 8 | U64(next(s)); end;
85 return v;
86end;
87
88(* A number from lo to hi, both included, the whole I64 range too;
89 zeros give lo. lo must not exceed hi. *)
90proc int*(var s: Source; lo, hi: I64): I64;
91var span, v: U64;
92begin
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);
98end;
99
100(* One of 0 to n - 1; n must be at least 1. *)
101proc pick*(var s: Source; n: INT): INT;
102begin
103 if n < 1 then Rt.stop("Prop.pick: n < 1"); end;
104 return INT(int(s, 0, I64(n - 1)));
105end;
106
107(* A byte's lowest bit: odd is true. *)
108proc bool*(var s: Source): BOOL;
109begin
110 return next(s) & 1 = 1;
111end;
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. *)
117proc bytes*(var s: Source; max: INT; var b: Buf.Buf);
118var mark: INT;
119begin
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;
124end;
125
126(* Makes s a fresh case, its bytes from s.rand. *)
127proc fresh(var s: Source);
128begin
129 Buf.reset(s.data);
130 s.drawn := 0;
131 s.fresh := true;
132end;
133
134(* Makes s replay the case data; past its end, bytes are 0. *)
135proc replay(var s: Source; data: []const U8);
136begin
137 Buf.reset(s.data);
138 Buf.str(s.data, data);
139 s.drawn := 0;
140 s.fresh := false;
141end;
142
143(* Runs p on the case in src, with Check muted; whether a check failed. *)
144proc fails(p: Property): BOOL;
145begin
146 Check.mute(true);
147 underway := true;
148 p(src);
149 underway := false;
150 return Check.mutedFailures() > 0;
151end;
152
153(* Runs p on data once more, with Check heard, so that it shows the
154 failure and counts it. *)
155proc aloud(p: Property; data: []const U8);
156begin
157 Check.mute(false);
158 replay(src, data);
159 p(src);
160end;
161
162(* Whether case a is simpler than b: shorter, or as long and smaller
163 byte by byte. *)
164proc simpler(a, b: []const U8): BOOL;
165begin
166 return (LEN(a) < LEN(b)) or ((LEN(a) = LEN(b)) and (Str.cmp(a, b) < 0));
167end;
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. *)
171proc improves(p: Property): BOOL;
172var drawn: []const U8;
173begin
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;
183end;
184
185(* best's w bytes from i, as a number, the first the highest. *)
186proc chunk(i, w: INT): U64;
187begin
188 return Str.be(Buf.bytes(best)[i..i + w]);
189end;
190
191(* Makes cand best without its w bytes from i. *)
192proc without(i, w: INT);
193var b: []const U8;
194begin
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)]);
199end;
200
201(* Makes cand best with its w bytes from i the number v. *)
202proc setChunk(i, w: INT; v: U64);
203begin
204 Buf.reset(cand);
205 Buf.str(cand, Buf.bytes(best));
206 Str.putBE(Buf.bytes(cand)[i..i + w], v);
207end;
208
209(* Tries best without each run of 8, 4, 2 and 1 bytes; whether any
210 made it simpler. *)
211proc deletePass(p: Property): BOOL;
212var w, i: INT; better: BOOL;
213begin
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;
224end;
225
226(* Tries best with each run of 8, 4, 2 and 1 bytes made zeros; whether
227 any made it simpler. *)
228proc zeroPass(p: Property): BOOL;
229var w, i: INT; better: BOOL;
230begin
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;
244end;
245
246(* Looks, by binary search, for the least number for best's w bytes
247 from i that still fails; whether best changed. *)
248proc lower(p: Property; i, w: INT): BOOL;
249var lo, hi, mid: U64; better: BOOL;
250begin
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;
258end;
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. *)
263proc lowerPass(p: Property): BOOL;
264var w, i: INT; better: BOOL;
265begin
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;
276end;
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. *)
280proc shrink(p: Property);
281var better: BOOL;
282begin
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);
289end;
290
291(* Stops the program: the environment variable called key is not a
292 number, as it must be. *)
293proc badEnv(key: []const U8);
294begin
295 Fmt.eprint("Prop: ${} is not a whole number\n", [Fmt.str(key)]);
296 Rt.exit(2);
297end;
298
299(* The environment variable called key, a number from 0; otherwise
300 unset, and 0. *)
301proc envNumber(key: []const U8): I64;
302var n: I64; ok: BOOL;
303begin
304 if LEN(Sys.env(key)) = 0 then return 0; end;
305 n, ok := Str.toInt(Sys.env(key));
306 if not ok or (n < 0) then badEnv(key); end;
307 return n;
308end;
309
310(* The seed for the fresh cases: $PROP_SEED, or a new one. *)
311proc envSeed(): U64;
312var v: U64; ok: BOOL;
313begin
314 if LEN(Sys.env("PROP_SEED")) = 0 then return Rand.seed(); end;
315 v, ok := Str.toU64(Sys.env("PROP_SEED"));
316 if not ok then badEnv("PROP_SEED"); end;
317 return v;
318end;
319
320(* Runs fresh cases, $PROP_CASES of them or for $PROP_TIME seconds;
321 if one fails, it is shrunk into best, and the result is true. *)
322proc freshFailing(p: Property): BOOL;
323var cases, n, deadline: I64;
324begin
325 seed := envSeed();
326 Rand.init(src.rand, seed);
327 cases := Cases;
328 if LEN(Sys.env("PROP_CASES")) > 0 then cases := envNumber("PROP_CASES"); end;
329 deadline := 0;
330 if envNumber("PROP_TIME") > 0 then deadline := Sys.clock() + envNumber("PROP_TIME") * Second; end;
331 n := 0;
332 while ((deadline = 0) and (n < cases)) or ((deadline # 0) and ((n mod Look # 0) or (Sys.clock() < deadline))) do
333 fresh(src);
334 if fails(p) then
335 Buf.reset(best);
336 Buf.str(best, Buf.bytes(src.data));
337 found := best.len;
338 shrink(p);
339 return true;
340 end;
341 INC(n);
342 end;
343 return false;
344end;
345
346(* The 16 hex digits of v. *)
347proc hex(v: U64): [16]U8;
348var d: [16]U8; i: INT;
349begin
350 for i := 15 to 0 by -1 do
351 d[i] := Digits[INT(v & 15)];
352 v := v shr 4;
353 end;
354 return d;
355end;
356
357(* Makes path the file called file in dir. *)
358proc caseFile(file: []const U8);
359begin
360 Buf.reset(path);
361 Buf.str(path, Buf.bytes(dir));
362 Buf.add(path, '/');
363 Buf.str(path, file);
364end;
365
366(* Saves data in dir, made with the directories it needs, in a file
367 named by the hash of data, so that a case is saved once; whether it
368 was written. path names the file. *)
369proc save(data: []const U8): BOOL;
370var d: []const U8; i: INT; h: [16]U8;
371begin
372 d := Buf.bytes(dir);
373 for i := 1 to LEN(d) - 1 do
374 if d[i] = '/' then _ := Sys.makeDir(d[0..i]); end;
375 end;
376 _ := Sys.makeDir(d);
377 h := hex(Str.hash(data));
378 caseFile(h);
379 return Files.write(Buf.bytes(path), data);
380end;
381
382(* What became of a case save tried to save, for a message. *)
383proc saved(ok: BOOL): []const U8;
384begin
385 if ok then return "saved"; end;
386 return "could not save";
387end;
388
389(* Runs each case saved in dir; if one fails, it is in cand, its file
390 in path, and the result is true. *)
391proc savedFailing(p: Property): BOOL;
392var d: Sys.Dir; file: []const U8; more: BOOL;
393begin
394 if Sys.openDir(d, Buf.bytes(dir)) < 0 then return false; end; (* none saved yet *)
395 file, more := Sys.nextEntry(d);
396 while more do
397 caseFile(file);
398 Buf.reset(cand);
399 if Files.read(Buf.bytes(path), cand) then
400 replay(src, Buf.bytes(cand));
401 if fails(p) then Sys.closeDir(d); return true; end;
402 end;
403 file, more := Sys.nextEntry(d);
404 end;
405 Sys.closeDir(d);
406 return false;
407end;
408
409(* Run at exit: a case still under way stopped the program, so it is
410 saved, to be replayed first next run. *)
411proc crashed;
412var ok: BOOL;
413begin
414 if not underway then return; end;
415 underway := false;
416 ok := save(Buf.bytes(src.data));
417 Fmt.eprint("Prop {}: crashed; case {} {}\n",
418 [Fmt.str(name), Fmt.str(saved(ok)), Fmt.str(Buf.bytes(path))]);
419end;
420
421(* Makes the buffers and registers crashed, the first time; then sets
422 the property's name and directory. *)
423proc prepare(n: []const U8);
424var root: []const U8;
425begin
426 if not ready then
427 Buf.init(src.data, Heap.heap);
428 Buf.init(best, Heap.heap);
429 Buf.init(cand, Heap.heap);
430 Buf.init(dir, Heap.heap);
431 Buf.init(path, Heap.heap);
432 if Rt.atExit(crashed) # nil then Rt.stop("Prop: no room for the exit procedure"); end;
433 ready := true;
434 end;
435 name := n;
436 root := Sys.env("PROP_DIR");
437 if LEN(root) = 0 then root := Seeds; end;
438 Buf.reset(dir);
439 Buf.str(dir, root);
440 Buf.add(dir, '/');
441 Buf.str(dir, n);
442end;
443
444(* Checks the property p, called name: the saved cases, then fresh
445 ones; the first that fails is said, saved if fresh, and run aloud. *)
446proc check*(name: []const U8; p: Property);
447var ok: BOOL;
448begin
449 prepare(name);
450 if savedFailing(p) then
451 Fmt.eprint("Prop {}: saved case {} fails\n", [Fmt.str(name), Fmt.str(Buf.bytes(path))]);
452 aloud(p, Buf.bytes(cand));
453 elsif freshFailing(p) then
454 ok := save(Buf.bytes(best));
455 Fmt.eprint("Prop {}: failed, seed {}; shrunk from {} to {} bytes, {} {}\n",
456 [Fmt.str(name), Fmt.uint(seed), Fmt.int(found), Fmt.int(best.len),
457 Fmt.str(saved(ok)), Fmt.str(Buf.bytes(path))]);
458 aloud(p, Buf.bytes(best));
459 end;
460 Check.mute(false);
461end;
462
463var
464 got: Buf.Buf; (* what the test's properties drew with bytes *)
465
466(* A property that holds. *)
467proc holds(var s: Source);
468begin
469 Check.ok(int(s, 0, 9) <= 9, "int within its range");
470end;
471
472(* A property that fails from 1000 on. *)
473proc below1000(var s: Source);
474begin
475 Check.ok(int(s, 0, 1000000) < 1000, "int below 1000");
476end;
477
478(* A property that fails when the bytes hold an x. *)
479proc noX(var s: Source);
480begin
481 bytes(s, 100, got);
482 Check.ok(Str.find(Buf.bytes(got), "x") < 0, "no x in the bytes");
483end;
484
485(* The draws, on cases given byte by byte. *)
486proc testDraws;
487begin
488 replay(src, "");
489 Check.int("int of zeros", int(src, -5, 5), -5);
490 Check.ok(not bool(src), "bool of zero");
491 bytes(src, 10, got);
492 Check.int("bytes of zeros", got.len, 0);
493 Check.int("pick of zeros", pick(src, 3), 0);
494 Check.int("past the end, all drawn", src.drawn, 8 + 1 + 1 + 8);
495 replay(src, "\x01\x02\x03\x04\x05\x06\x07\x08");
496 Check.ok(bits(src) = 0102030405060708H, "bits big-endian");
497 replay(src, "\x00\x00\x00\x00\x00\x00\x01\x02\x00\x00\x00\x00\x00\x00\x00\x07");
498 Check.int("int from lo", int(src, 10, 1000), 10 + 258);
499 Check.int("int mod the span", int(src, 0, 4), 2);
500 replay(src, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF");
501 Check.int("int whole range", int(src, -9223372036854775807 - 1, 9223372036854775807), 9223372036854775807);
502 replay(src, "\x03");
503 Check.ok(bool(src) and not bool(src), "bool odd, then 0 past the end");
504 replay(src, "\x05a\x05b\x00");
505 bytes(src, 100, got);
506 Check.str("bytes until a byte below the mark", Buf.bytes(got), "ab");
507 replay(src, "\x80a\x80b");
508 bytes(src, 1, got);
509 Check.str("bytes at most max", Buf.bytes(got), "a");
510 Check.int("bytes at max draw no more", src.drawn, 2);
511end;
512
513(* Small private procedures. *)
514proc testHelpers;
515var h: [16]U8;
516begin
517 h := hex(0123456789ABCDEFH);
518 Check.str("hex", h, "0123456789abcdef");
519 Check.ok(simpler("ab", "abc") and simpler("ab", "ac") and not simpler("ab", "ab"), "simpler");
520end;
521
522(* Fresh cases found and shrunk, with a fixed seed so the test is the
523 same each run. *)
524proc testShrink;
525var failed: BOOL;
526begin
527 prepare("int");
528 failed := freshFailing(below1000);
529 Check.mute(false);
530 Check.ok(failed, "int: a failing case found");
531 replay(src, Buf.bytes(best));
532 Check.int("int: shrunk to 1000", int(src, 0, 1000000), 1000);
533 Check.int("int: shrunk to 8 bytes", best.len, 8);
534 prepare("bytes");
535 failed := freshFailing(noX);
536 Check.mute(false);
537 Check.ok(failed, "bytes: a failing case found");
538 replay(src, Buf.bytes(best));
539 bytes(src, 100, got);
540 Check.str("bytes: shrunk to x", Buf.bytes(got), "x");
541 Check.int("bytes: shrunk to 3 bytes", best.len, 3);
542 check("holds", holds);
543end;
544
545(* A case saved, then replayed. *)
546proc testSaved;
547var failed: BOOL; h: [16]U8; b: Buf.Buf;
548begin
549 prepare("saved");
550 Check.ok(save("\x00\x00\x00\x00\x00\x00\x03\xE8"), "save");
551 h := hex(Str.hash("\x00\x00\x00\x00\x00\x00\x03\xE8"));
552 Check.ok(Str.hasSuffix(Buf.bytes(path), h), "saved under its hash");
553 Buf.init(b, Heap.heap);
554 Check.ok(Files.read(Buf.bytes(path), b), "saved file read");
555 Check.str("saved bytes", Buf.bytes(b), "\x00\x00\x00\x00\x00\x00\x03\xE8");
556 failed := savedFailing(below1000);
557 Check.mute(false);
558 Check.ok(failed, "saved case replayed and fails");
559 failed := savedFailing(holds);
560 Check.mute(false);
561 Check.ok(not failed, "saved case passes another property");
562 check("saved", holds);
563 Check.int("remove the case", Sys.remove(Buf.bytes(path)), 0);
564 Check.int("remove its directory", Sys.removeDir(Buf.bytes(dir)), 0);
565 Buf.done(b);
566end;
567
568(* The module's test, with its cases in build/proptest, removed after. *)
569proc main*;
570begin
571 _ := Sys.setEnv("PROP_DIR", "build/proptest");
572 _ := Sys.setEnv("PROP_SEED", "1");
573 _ := Sys.setEnv("PROP_CASES", "");
574 _ := Sys.setEnv("PROP_TIME", "");
575 Buf.init(got, Heap.heap);
576 prepare("draws");
577 testDraws;
578 testHelpers;
579 testShrink;
580 testSaved;
581 Check.int("remove build/proptest", Sys.removeDir("build/proptest"), 0);
582end;
583
584end Prop.