Testing

A test is a block that checks one thing. Put tests in the same file as the code they check, and run them with cresset test.

fn double(n):
    return n * 2

test "doubling works":
    assert_eq(double(4), 8)

test "doubling zero stays zero":
    assert_eq(double(0), 0)

fn main() needs print:
    print(double(21))
cresset test mathy.crs
ok    doubling works
ok    doubling zero stays zero

2 passed, 0 failed

A normal cresset run ignores test blocks, so tests cost nothing when you just want to use the program. The exit code of cresset test is 0 when everything passed and 1 when anything failed, which is what a build system or CI wants.

Saying what you expect

CheckStops the test when
assert(cond, message)cond is false
assert_eq(actual, expected, message)the two values are not equal; the error shows both

The message is optional. assert_eq is the one to reach for: a failure tells you what it expected and what it got, so you rarely need to add a debugging print.

FAIL  this one fails
      error: expected 5 but got 4 (two doubled)
        --> mathy.crs:7
         |  assert_eq(double(2), 5, "two doubled")

Each test starts fresh

Every test runs in its own clean copy of your program, so one test can't change what another one sees, and the order does not matter. If a test fails, the others still run, and anything it printed before failing is shown under the failure.

Tests and permissions

A test is checked like any function: it can only use what it declares with needs, and cresset test only grants what you give it with --allow.

fn first_line(path) needs read:
    return ok(read(path)?.lines()[0])

test "an empty path is an error" needs read:
    assert_eq(first_line("no/such/file.txt").is_err(), true)

fn main() needs print:
    print("ok")

If a test needs a permission you did not grant, it is skipped, not run, and the report says which permission it was waiting for:

skip  an empty path is an error  (needs read; run with --allow read)

Tests that only call pure code need no permissions at all, so they can run anywhere, including on code you downloaded and don't yet trust.

Running some of them

cresset test mathy.crs --filter doubling

--filter runs only the tests whose name contains the text.

Tests with randomness

A test that uses rng(seed) gives the same answer every time, so it can check exact values. Tests that use random() are unpredictable by design; check properties (a roll is between 1 and 6) rather than exact values. See Simulations.

Limits today

Next

Look up every function in the Reference.