Tests, properties, and examples¶
A module states what its code must do beside the code itself. A test checks one claim, a
property checks a claim for every value of its variables, and an example documents a use of the
code whose result is checked. qvr test runs all three on the
reference machine. By default it computes exactly
over the rational numbers, so an expected value is stated exactly rather than within a tolerance.
Tests are not part of the code they check. The parser keeps them apart from the module's
declarations, the compiler never sees them, and the content hash of the code
(code_digest) is the same with or without them. Each test
has a content hash of its own (declaration_digest),
and qvr test reruns a test only when its hash, the code's hash, or its options change.
Tests¶
A test has a title, optional options, and a body of steps:
define posterior(prior : Real, hit : Real, false_alarm : Real) : Real !{} =
let joint = prior * hit
return joint / (joint + (1.0 - prior) * false_alarm)
test "one positive observation halves a quarter prior's odds against" =
let p = posterior(prior=1/4, hit=3/5, false_alarm=1/5)
expect p == 1/2 exactly
expect p > 1/3
let NAME = TERM binds a value for the rest of the body. expect TERM asserts that the term is
true. When the term is a comparison, the report states both sides, so a failure reads
line 9: 1/2 == (exactly) 1/3 does not hold. The body stops at the first expectation that fails.
A term is a pure expression, evaluated by the test runner:
| Term | Value |
|---|---|
3, -2 |
an integer |
0.25, 1e-3 |
the rational the decimal spells: 0.25 is one quarter |
+, -, * |
exact arithmetic; integers stay integers |
/, % |
exact division (1/4 is one quarter) and integer remainder |
==, !=, <, <=, >, >=, &&, ||, not |
comparisons and truth values |
(a, b), [a, b] |
a tuple, or the entries of a tensor |
name |
a let binding or a property's variable, else a constructor without fields |
f(args) |
a run of the computation or program f, or the constructor f applied to its fields |
A call runs the named computation of the module on the reference machine. Arguments are positional
or named by the parameter (prior=1/4); a named argument whose name is a static binder of the
computation instantiates it (length(A=Int, xs=...)). Each argument is checked against the type of
the parameter it is passed to, which is how an integer literal becomes a Real and how a
constructor of a family with parameters gets its type. A constructor applied to fields builds a
value of its family, so Push(true, Empty) is a value a test can pass to a computation. A
computation over any deduction extending a signature takes its
deduction first, as it does in a declaration: is_sentence(Grammar, Grammar.span(0, 2, Grammar.S))
runs the instance of is_sentence at the deduction Grammar, and a deduction that does not extend
the parameter's signature is refused before any test runs.
Exact and floating tests¶
A test runs in one number domain. By default the domain is exact: every Real the machine
computes is a rational number, held exactly. The machine is the same machine, only its numbers
differ. An operation the rationals are closed under (the field operations, comparisons, rounding,
sums and products along axes, indexing) is computed exactly. Any other operation, such as exp,
log, sqrt, or sigmoid, stops the run with an error that names it, because its result is in
general irrational.
An equality between reals states which comparison it means:
| Form | Meaning |
|---|---|
expect a == b exactly |
a and b are the same rational; the test is exact |
expect a == b within t |
a and b differ by at most t; the test is floating (float64) |
An equality of reals that says neither is an error, and so is exactly in a floating test or
within in a test declared exact. The tolerance is written in the test and nowhere else: no
command-line option widens it.
define posterior(prior : Real, hit : Real, false_alarm : Real) : Real !{} =
let joint = prior * hit
return joint / (joint + (1.0 - prior) * false_alarm)
test "the float computation agrees within rounding" =
expect posterior(0.25, 0.6, 0.2) == 0.5 within 1e-12
A test that runs a program, or a computation that uses an operation outside the rationals,
declares floating numbers with [numbers=float64] (or float32). A program run draws with the
test's seed.
Properties¶
A property quantifies its body over typed variables:
define both(a : Bool, b : Bool) : Bool !{} =
if a then
return b
else
return false
define double(n : Int) : Int !{} =
return n + n
define posterior(prior : Real, hit : Real, false_alarm : Real) : Real !{} =
let joint = prior * hit
return joint / (joint + (1.0 - prior) * false_alarm)
property "conjunction commutes" forall (x : Bool, y : Bool) =
expect both(x, y) == both(y, x)
property "doubling makes even numbers" [cases=200, seed=7] forall (n : Int) =
expect double(n) % 2 == 0
property "a posterior is a probability" forall (p : Real in [0, 1/3, 1/2, 1], h : Real in [1/10, 1]) =
let q = posterior(p, h, 1/2)
expect q >= 0 && q <= 1
When every variable ranges over a finite set, the property is checked exhaustively: once for
every assignment. A variable's set is finite when it is listed with in [...], or when its type is
finite: Bool, Unit, a product of finite types, a tensor of a finite element type at a literal
shape, or a closed family without parameters or indices whose constructors never contain the family
again. The first property above runs four cases and the third eight. An exhaustive check
enumerates at most limit assignments and refuses to run a larger one, rather than sampling it.
Otherwise the property draws cases assignments from the seeded source, with sizes growing to
size, in the manner of QuickCheck (Claessen and Hughes, 2000). A variable of a finite type is drawn
uniformly. Int ranges over [-size, size], Real over rationals p/q with |p| <= size² and
q <= size, String over lowercase words of length at most size, and a recursive family over
values at most size constructors deep. Every family has a generator built from its constructors
alone, so no generator is written by hand. A family whose module declares a computation
F__arbitrary(size : Int) : F draws its values by running it instead, which is the form a derived
Arbitrary instance takes.
A failing assignment is shrunk. The runner tries smaller candidates for one variable at a time
and keeps the first that still fails, until none does or shrinks candidates have been tried. An
integer shrinks toward zero, a rational toward smaller denominators and then toward zero, a string
by deletion, a listed value to the values listed before it, and a data value first to its subterms of
the same type and then field by field. The report gives the minimal counterexample:
family Bits : Type
constructor Empty : Bits
constructor Push : Bool * Bits -> Bits
define size(xs : Bits) : Int !{} =
case xs motive => Int
Empty =>
return 0
Push(bit, rest) =>
let tail <- size(rest)
return 1 + tail
property "every word is short" [cases=60, seed=5] forall (xs : Bits) =
expect size(xs) < 3
FAIL bits.qvr:13 property 'every word is short' [24 drawn cases]
line 14: 3 < 3 does not hold
xs = Push(false, Push(false, Push(false, Empty)))
(shrunk in 1 step)
Options¶
Every option is pinned in the declaration. qvr test has no flag that changes one.
| Option | Default | Meaning |
|---|---|---|
numbers |
exact, or float64 when an expectation says within |
the number domain: exact, float64, or float32 |
cases |
100 |
assignments a property draws when a variable is infinite |
seed |
0 |
the seed of those draws and of every program run |
size |
20 |
the largest size a drawn value has |
limit |
10000 |
the most assignments an exhaustive check enumerates |
fuel |
1000000 |
the step budget of each run |
shrinks |
1000 |
the most candidates shrinking tries |
Examples¶
An example declaration has the same body as a test. It documents a use of the module, and its
expectations check what the use returns:
An example can also be written in the doc comment of the declaration it documents. A doc line
example "title": opens it, and the doc lines indented under it are its body:
#! The posterior probability of a hypothesis after one observation.
#! example "a quarter prior":
#! expect posterior(1/4, 3/5, 1/5) == 1/2 exactly
define posterior(prior : Real, hit : Real, false_alarm : Real) : Real !{} =
let joint = prior * hit
return joint / (joint + (1.0 - prior) * false_alarm)
Such an example is reported with the declaration it documents as its subject. A literate module
format registers its file suffix with
register_source_loader, and the examples its
prose carries run beside the module's own.
Running tests¶
qvr test model.qvr
qvr test models/
qvr test --match posterior model.qvr
qvr test --json models/ > report.json
qvr test --no-cache model.qvr
A file argument is one module and a directory argument is a package, every .qvr module under it.
The plain output prints one line per test, then the counterexample and the failing expectation of
each failure, and a summary. --json prints the report of
TestReport.to_data: ok, the counts by status
(passed, failed, error, cached, modules_failed), the same counts per package, and per
module its path, the content hash of its code, and one record per test. A test record holds its
kind, title, line, status, number domain, case count, whether it was exhaustive, its expectations
with both sides rendered, its message, its counterexample and shrink count, its content hash, and
whether its pass came from the cache. A test that fails reports failed. A test that cannot be
evaluated reports error: a term names nothing, an argument has the wrong type, an exact run meets
an inexact operation, or an option is ill-formed.
The exit status is 0 when every module loads and every test passes, and 1 otherwise. A pass is
cached under $XDG_CACHE_HOME/quivers/tests (or ~/.cache/quivers/tests). A failure is never
cached, and --no-cache runs every test.
Mutation testing¶
qvr test --mutate asks whether the tests would notice a wrong module. It makes one small change
to the module's code at a time, a mutant, and runs every test against each mutant:
| Operator | Change |
|---|---|
drop-rule |
remove one inference rule of a deduction, or a top-level rule |
drop-entry |
remove one lexical entry |
swap-category |
give one lexical entry the category of the next entry with a different one |
constant |
replace an integer n by n + 1 and by n - 1, a real c by 0 and 2c (or 1 when c is zero), a truth value by its negation |
A mutant is killed when some test fails or errs against it. It is invalid when the compiler rejects it, and it survives when every test still passes. A survivor is a change the tests cannot tell from the original: a behavior the suite does not check, or a change that does not alter the module's meaning. The module's tests must pass before any mutant runs.
qvr test --mutate suite.qvr
qvr test --mutate --operators drop-rule,drop-entry grammar.qvr
qvr test --mutate --json suite.qvr
--operators runs the mutants of the named operators only. For the module
define posterior(prior : Real, hit : Real, false_alarm : Real) : Real !{} =
let joint = prior * hit
return joint / (joint + (1.0 - prior) * false_alarm)
define unchecked(flag : Bool) : Int !{} =
if flag then
return 7
else
return 9
test "posterior at a quarter" =
expect posterior(1/4, 3/5, 1/5) == 1/2 exactly
test "unchecked runs" =
expect unchecked(true) > 0
the exact test kills both mutants of the constant 1.0, while the second test is too weak to
notice a change to 7 and nothing runs the else branch:
suite.qvr: 2/6 mutants killed (0 rejected by the compiler)
SURVIVED suite.qvr:7:15 constant: 7 -> 8
SURVIVED suite.qvr:7:15 constant: 7 -> 6
SURVIVED suite.qvr:9:15 constant: 9 -> 10
SURVIVED suite.qvr:9:15 constant: 9 -> 8
The exit status is 1 when any mutant survives. The JSON report lists every mutant with its operator, location, description, status, and the test that killed it.
Python¶
from pathlib import Path
from quivers.testing import ResultCache, run_paths
from quivers.testing.mutation import mutate_module
report = run_paths([Path("model.qvr")], cache=ResultCache())
assert report.ok, report.to_data()
mutation = mutate_module(Path("grammar.qvr"))
for mutant in mutation.survivors:
print(mutant.line, mutant.description)
run_paths returns a
TestReport;
mutate_module returns a
MutationReport. A run of one computation in the exact
domain passes NumberDomain.exact() to
run_named, whose real results are then
RationalTensor values.
Cited sources¶
Koen Claessen and John Hughes. QuickCheck: A Lightweight Tool for Random Testing of Haskell Programs. In Proceedings of the Fifth ACM SIGPLAN International Conference on Functional Programming (ICFP '00), 268–279. Association for Computing Machinery, 2000. URL: https://doi.org/10.1145/351240.351266, doi:10.1145/351240.351266.