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.

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)

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