Skip to content
Jennifer Programming Language

testing - assertions and test-runner primitives

Enable with use testing;. An assertion vocabulary plus the system-side runner surface: name-based function invocation, a per-process result accumulator, and a format dispatcher for human / TAP / JUnit output. The jennifer test subcommand (discovery, setUp / tearDown, --format, --isolated) orchestrates on top; see technical/cli_test.md.

jennifer
use io;
use testing;

func addPasses() {
    testing.assertEqual(1 + 1, 2);
}

testing.run("addPasses");
io.printf("%s", testing.report("text", testing.results()));

Quick start

The everyday path is the jennifer test subcommand: write func test* functions with assertions, and the runner discovers and runs them - no testing.run / report boilerplate.

jennifer
use testing;

func testMath() {
    testing.assertEqual(2 + 3, 5);
    testing.assertTrue(len("abc") == 3);
}
text
$ jennifer test math_test.j
PASS testMath (0 ms)

1 passed, 0 failed, 1 total

setUp / tearDown functions (run before / after each test) and the flags (--filter, --format=text|tap|junit, --isolated) are documented in technical/cli_test.md. The rest of this page covers the testing primitives the runner is built from, for a custom harness.

Why this is a system library

testing.run dispatches a test by its function name (a string), exposing the interpreter's name-based function lookup so a .j harness can run discovered tests without its own indirection.

It is also the one place in the language where exit is intercepted. try/catch does not catch exit (see control-flow.md); the runner catches it at the Go level so an exit in a test body stays scoped to the runner. That is why the primitive cannot live in .j.

Surface

CallReturnsNotes
testing.run(name)testing.ResultLook up a zero-arg function by name, call it, catch every failure mode, append.
testing.runArgs(name, args)testing.ResultLike run, but binds the args list to the function's parameters (arity + declared-type checked). For framework dispatchers, not the zero-arg tests the runner discovers.
testing.results()list of testing.ResultSnapshot of the accumulator. Value semantics - safe to modify.
testing.reset()nullClear the accumulator between independent runs.
testing.report(format, results)stringRender results to "text", "tap", or "junit".

Assertions

Builtins for test bodies. Each is a Value.Equal / Kind comparison in Go (native speed) and, on failure, throws Error{kind: "assertion"} positioned at the assertion call, which testing.run catches and records.

CallFails (throws) when
testing.assertEqual(actual, expected)actual != expected (deep structural equality: lists / maps / structs compare by value).
testing.assertNotEqual(actual, expected)actual == expected.
testing.assertTrue(cond)cond is false (cond must be bool).
testing.assertFalse(cond)cond is true (cond must be bool).
testing.assertContains(haystack, needle)needle is absent: substring for a string, element for a list, key for a map (by haystack kind).
testing.assertThrows(name, kind)the named zero-arg function doesn't throw, or throws an Error - or a struct with string kind and message fields, such as rest.HttpError - whose kind differs. kind "exit" matches a body that calls exit; the exit is absorbed.
testing.assertThrowsArgs(name, args, kind)as assertThrows, but binds the list args to the function's parameters - no per-case zero-arg wrapper function needed.
jennifer
use testing;

func add(a as int, b as int) { return $a + $b; }

func testAdd() {
    testing.assertEqual(add(2, 3), 5);
    testing.assertContains([1, 2, 3], 2);
    testing.assertThrows("mustFail", "boom");
    testing.assertThrowsArgs("parse", ["1 ~ 2"], "syntax");
}

The former names runWith and assertThrowsWith were removed in 0.28.0 (With means an options struct everywhere else).

assertThrowsArgs is the argument-passing form: where assertThrows needs a zero-arg wrapper function per failing input, assertThrowsArgs("parse", [input], kind) calls parse(input) directly, so one helper covers every case.

An unknown function name, or args that do not fit its parameters (count or declared types), is a usage error raised by the assertion itself, not a match: a misspelt name cannot pass as "the function threw".

Table-driven tests

There is no testing.subtest primitive; drive a set of cases with a plain loop inside one test function:

jennifer
use testing;

def struct Case { input as int, want as int };

func testDoubles() {
    def cases as list of Case init [
        Case{input: 0, want: 0},
        Case{input: 3, want: 6},
        Case{input: -2, want: -4}];
    for (def c in $cases) {
        testing.assertEqual($c.input * 2, $c.want);
    }
}

An assertion throws, so the first failing case stops that test function (later iterations do not run) and the reported position points at the assertEqual line. Put a distinguishing value in the case to tell which row failed.

The testing.Result struct

text
def struct testing.Result {
    name as string,
    ms as int,               # elapsed wall time in milliseconds
    passed as bool,
    errorKind as string,     # "" on pass; the thrown Error's kind ("assertion", ...), or "runtime" / "error" / "exit" / "unknown"
    errorMessage as string,
    file as string,          # position where the failure originated (if known)
    line as int,
    col as int
};

errorKind mirrors the strings surfaced by try/catch plus "exit" for the exit-intercept case:

ValueMeaning
""The test passed.
"runtime"An interpreter runtime error (out-of-bounds, missing key, type mismatch, ...).
"error"A throw whose thrown value wasn't an Error struct.
"assertion" etc.A throw Error{kind: "assertion", ...} - errorKind mirrors the struct's kind field.
"exit"The test body called exit. errorMessage is "exit code N".
"unknown"Anything else (function not found, wrong parameter count, ...).

How testing.run handles each failure mode

jennifer
# Pass path
func passing() {
    return;                     # any normal return counts as a pass
}

# Failure via user throw
func failing() {
    throw Error{
        kind: "assertion",
        message: "expected 42, got 41",
        file: "", line: 0, col: 0
    };
}

# Failure via runtime error
func indexing() {
    def xs as list of int init [];
    def x as int init $xs[5];   # out-of-bounds; kind=runtime
}

# Exit inside a test - captured, doesn't propagate
func earlyExit() {
    exit 1;                     # kind=exit; program keeps running
}

Every call to testing.run appends exactly one testing.Result to the accumulator. The result is also returned, so the caller can inspect it immediately.

Reports

testing.report(format, results) renders any list of testing.Result to a string. Format strings are case-sensitive, like the codec names of hash.compute, encoding.toText, fs.open.

"text" - human-readable

text
PASS addPasses (0 ms)
FAIL addFails (1 ms)
     [assertion] 1 + 1 != 2
FAIL earlyExit (0 ms)
     [exit] exit code 1

1 passed, 2 failed, 3 total

"tap" - Test Anything Protocol v14

text
TAP version 14
1..3
ok 1 - addPasses
not ok 2 - addFails
  ---
  kind: assertion
  message: 1 + 1 != 2
  ...
not ok 3 - earlyExit
  ---
  kind: exit
  message: exit code 1
  ...

Works with the prove command and most CI harnesses.

"junit" - JUnit XML

xml
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="jennifer" tests="3" failures="2">
  <testcase name="addPasses" time="0.000"></testcase>
  <testcase name="addFails" time="0.001">
    <failure type="assertion" message="1 + 1 != 2">1 + 1 != 2</failure>
  </testcase>
  <testcase name="earlyExit" time="0.000">
    <failure type="exit" message="exit code 1">exit code 1</failure>
  </testcase>
</testsuite>

Control characters in names, kinds, messages and file paths are written as escapes (\n, \r, \t, otherwise \uXXXX), so test data cannot emit terminal escape sequences or forge a TAP line. In TAP, kind and file are double-quoted when they hold anything but letters, digits, _, ., /, -.

An unknown format string is an error (see below).

Errors

CaseBehaviour
Wrong argument counttesting.run expects 1 argument (name), got 0
Wrong argument typetesting.run: name must be string, got int
Function with parameterstesting.run only invokes zero-argument functions; it records a failing Result with errorKind="unknown" and the reason in errorMessage. Use testing.runArgs(name, args) to pass arguments
Recursionrun, runArgs, assertThrows and assertThrowsArgs count toward the caller's call depth: recursion through them ends in the catchable limit error
Unknown formattesting.report: unknown format "html"; known: "text", "tap", "junit"

Concurrency

The accumulator is guarded by a mutex, so spawn { testing.run(...) } from multiple tasks does not race. Results are ordered by completion time, not spawn time; for stable ordering run tests sequentially or sort the results before rendering.

Running with jennifer test

The jennifer test subcommand orchestrates these builtins. It discovers test* functions (or --filter=REGEX), runs setUp / tearDown around each, renders --format=text|tap|junit, and with --isolated runs each test in a fresh interpreter subprocess so one test's crash, exit, or leaked global state cannot affect the others. A file with no test functions exits 2 (a runner error) unless --allow-empty is passed, so a gate cannot pass an empty suite by accident. Its flags and exit codes are documented in technical/cli_test.md > Test runner. testing.runArgs (and Interpreter.CallByNameWith beneath it) supplies the arg-taking dispatch that parameterised drivers use.

Not provided:

  • Per-test timeouts. A non-terminating test hangs its subprocess; --isolated isolates state, not runtime.
  • Skip / xfail. Runner-level policy, not a primitive.
  • First-class subtests. A body loop covers table-driven cases (see Table-driven tests); a testing.subtest(name) primitive would need new language surface.

See also

Academy talks

TalkWhat it shows
Testing in Jenniferassertions, assertThrows, table tests, setUp and tearDown