test
test declares a test: a name and a block that ant test runs. Tests live in test files, whose names end in _test.ant. Inside a test, a test statement runs a subtest.
Details
testis a keyword only in test files. Anywhere else it is an ordinary name. In a test file it is still a name after.or?.and before:, soRegex.test(re, s), a field namedtest, and a named argumenttest: xstill work.- A top-level test's name is a string literal without interpolation, not empty, and unique in its file. A subtest's name may interpolate; an empty one panics, and a repeated one gets
#2,#3, and so on appended. - A test fails when a panic leaves its body, when its body returns an
Err, when one of its subtests fails, or when a goroutine it started panics or outlives it. A failed subtest does not stop its parent's body. - A test body is like a script body:
returnends the test,tryreturns anErrfrom it, anddeferruns when the test ends. Its last expression is discarded. - Top-level tests run one at a time, in source order, after the modules are initialized. Subtests run in the order their statements run. A test that calls Test.parallel runs alongside the others that call it.
- A test passes silently. What it prints is shown only when it fails, or under
ant test -v.
Basic examples
A library, ports.ant, with an exported function and a private helper:
export func parsePort(text: string): Result[int, Error] {
let port = text.toInt() ?? return Result.fail("not a number: ${text}")
if !inRange(port) { return Result.fail("out of range: ${port}") }
Result.ok(port)
}
func inRange(port: int): bool {
port >= 1 && port <= 65535
}Its tests, in ports_test.ant. A test file may import the private names of the module it tests:
import "./ports.ant" { parsePort, inRange }
test "parsePort reads a number" {
assert(parsePort("8080").unwrap() == 8080)
}
test "parsePort rejects a word" {
let r = parsePort("http")
assert(r is Err)
assert(r.error.message == "not a number: http")
}
test "inRange" {
assert(inRange(1))
assert(!inRange(0))
assert(!inRange(70000))
}ant test runs every test and prints one line when they all pass:
ok 3 passed (0.00s)Scope
Subtests
A test statement inside a test's body runs a subtest. In a loop it runs one subtest per row of a table, and its name may interpolate the row:
import "./ports.ant" { parsePort }
type Case = { text: string, want: int | null }
test "parsePort" {
let cases = [
Case{ text: "80", want: 80 },
Case{ text: "0", want: null },
Case{ text: "65536", want: null },
Case{ text: "port", want: null },
]
for c in cases {
test "${c.text}" {
let got = parsePort(c.text)
if c.want == null {
assert(got is Err)
} else {
assert(got.unwrap() == c.want)
}
}
}
}ok 4 passed (0.00s)The run counts the four subtests, not the test that holds them. A subtest's full name joins the names with /, such as parsePort/65536, and ant test -run 'parsePort/655' runs only that row. ant test -list shows which top-level tests a pattern selects without running them; it does not list subtests.
A subtest sees the variables of the blocks around it, as a lambda does. Subtests nest to any depth.
Repeated subtest names
When two subtests of one test get the same name, the second gets #2, the third #3. Test.name gives the full name:
test "names" {
let names: Array[string] = []
for word in ["a", "b", "a"] {
test "${word}" {
names.push(Test.name())
}
}
assert(names == ["names/a", "names/b", "names/a #2"])
}ok 3 passed (0.00s)Failures
A failed assert ends its test and reports the condition and the values it used. A failed row does not stop the table: the other rows still run, and ant test exits with status 1:
test "even" {
for n in [2, 3, 4] {
test "${n}" {
assert(n % 2 == 0)
}
}
}--- FAIL: fail_test.ant: even/3 (0.00s)
assertion failed: n % 2 == 0 (1 == 0)
n = 3
at test "3" (fail_test.ant:4:13)
FAIL 1 failed, 2 passed (0.00s)try and Err
A test body may return an Err, which fails the test. try returns one early:
import "./ports.ant" { parsePort }
test "default port" {
let port = try parsePort("eighty")
assert(port == 80)
}--- FAIL: try_test.ant: default port (0.00s)
not a number: eighty
FAIL 1 failed, 0 passed (0.00s)Panics
To test that code panics, catch the panic with Panic.catch and check the Err:
func first(xs: Array[int]): int {
if xs.isEmpty() { panic("first of an empty array") }
xs[0]
}
test "first of an empty array panics" {
let r = Panic.catch({ first([]) })
assert(r is Err)
assert(r.error.message.contains("first of an empty array"))
}ok 1 passed (0.00s)defer and output
defer in a test body runs when the test ends, passed or failed. What the test prints is collected and shown with its failure:
test "cleanup runs" {
defer { println("cleaning up") }
println("starting")
assert(1 + 1 == 3)
}--- FAIL: defer_test.ant: cleanup runs (0.00s)
starting
cleaning up
assertion failed: 1 + 1 == 3 (2 == 3)
at test "cleanup runs" (defer_test.ant:4:9)
FAIL 1 failed, 0 passed (0.00s)Goroutines
A test owns the goroutines it starts. One still running shortly after the test ends fails it, and the runner ends it. A panic in one fails the test when the test ends, without interrupting its body. Here the goroutine waits on a channel that nothing sends to; the test's time includes the short wait for it:
test "leak" {
let c: Channel[int] = Channel.new()
go { c.receive() }
}--- FAIL: leak_test.ant: leak (0.10s)
goroutine started at leak_test.ant:3:3 outlived the test
FAIL 1 failed, 0 passed (0.10s)A test should wait for its goroutines, or close what they block on, before it ends.
test outside test files
In any other file, test is an ordinary name:
let test = "a name like any other"
println(test)a name like any otherApplications
Share helpers between test files in a test file of their own. Only a test file can import it:
export func assertErr(r: Result[int, Error], message: string): void {
assert(r is Err)
assert(r.error.message == message)
}import "./ports.ant" { parsePort }
import "./helpers_test.ant" { assertErr }
test "errors" {
assertErr(parsePort("x"), "not a number: x")
assertErr(parsePort("0"), "out of range: 0")
}ok 1 passed (0.00s)Skip a test that cannot run here with Test.skip:
test "needs a database" {
let url = Os.env("TEST_DATABASE_URL") ?? Test.skip("TEST_DATABASE_URL is not set")
assert(url.startsWith("postgres://"))
}ok 0 passed, 1 skipped (0.00s)Possible issues
A test file holds only imports, declarations, and tests. A top-level statement is an error:
println("setting up")
// error: a test file cannot have top-level statements: it holds imports, declarations, and testsA top-level test's name cannot interpolate, so ant test -list can list the tests without running anything. Use a subtest for a computed name:
let size = 3
test "size ${size}" {} // error: a top-level test's name is a string without interpolationEach top-level name appears once in a file:
test "parse" {}
test "parse" {} // error: test "parse" is already declared in this fileA subtest runs only in a test's body. A function, a lambda, a go block, or a defer block cannot hold one:
func check(n: int) {
test "${n}" {} // error: a test is declared at the top level of a test file, or runs as a subtest
}A test body returns void or an Err:
test "answer" {
return 42 // error: a test returns void or an Err, not int
}A test is not a value, and a test statement has no result to keep:
test "outer" {
let t = test "inner" {} // error: unexpected 'test'
}In a test file, test cannot name a variable:
test "t" {
let test = 1 // error: 'test' cannot be a variable name
}ant run refuses a test file; run it with ant test. In a file whose name does not end in _test.ant, a test declaration does not parse:
test "math" { // error: expected a newline or ';' before string literal
assert(1 + 1 == 2)
}