Tests and runtime errors (M7)
test blocks
fn mean(xs: List[Int]) -> Int:
sum(xs) / len(xs)
test "mean of a few numbers":
assert_eq(mean([1, 2, 3]), 2)
assert(mean([4]) == 4, "one number is its own mean")
A test is a block at the top level of any .tr file, next to the code it tests. It is type-checked with the file every time (trine check counts the tests), but nothing calls it: trine run and trine build ignore it.
assert(c)/assert(c, why)fail withassertion failed(: why) whencis false.assert_eq(a, b)fails withassertion failed: 3 != 4, showing both values.
Both are checks at the call, so the failure points at the line that failed. They work in any program, not only in tests. A program that defines its own assert keeps it.
trine test
$ trine test
test lib/math.tr: mean of a few numbers ... ok
test lib/math.tr: mean of nothing ... FAILED
failures:
---- lib/math.tr: mean of nothing ----
about to divide
lib/math.tr:2:6: runtime error: sum of an empty list (give a start value: `sum(xs, 0)` or `sum(xs, 0.0)`)
2 | sum(xs) / len(xs)
^
in `mean`
called from `test "mean of nothing"` at lib/math.tr:12:17
1 passed, 1 failed (0.00 s)
trine testruns every test under the current directory (files with atest "...":line; hidden directories andtargetskipped);trine test a.tr dir/runs those.- Each test runs on its own: what it prints is shown only when it fails, with the error and its call stack. The exit status is 1 when any test fails or a file doesn't compile.
--filter TEXT: only tests whose name contains TEXT.- Engines: the ownership VM by default;
--interp;--nativebuilds each file once (a debug build: bounds re-checked, leaks checked) and runs each test as a run of it.
Call stacks
Every runtime error shows the calls that led to it:
util.tr:2:6: runtime error: division by zero
2 | 10 / n
^
in `util.bad`
called from `helper` at main.tr:4:11
called from `main` at main.tr:13:15
- A run of the same call (recursion) is one line with a count (
, 30 times); past 12 lines the middle is left out (... 70 more). - The interpreter, the VM and native debug builds (
trine run --native --debug,trine build --debug,trine test --native) print the same stack. Native release builds don't record it: one store per call costs little by itself, but it stops the C compiler from reshaping recursion (fib: 6 ms -> 45 ms). Run with--interpor--debugto see it. - With
--jsonthe error has astack:[{"function","file","line","col","times"}, ...], innermost first.