Testing Contracts
Test blocks, assertions, the test runner, and the relationship between tests and contracts.
Contents
Contracts and tests answer different questions. A contract states a property that must hold for every value in a domain. A test checks a concrete example. A good Haze program uses contracts for the invariants of the interface and tests for the behaviour that the contracts do not capture.
Test Blocks#
A test is a top-level block with a string name.
test "addition is commutative" {
assert add(2, 3) == add(3, 2)
}
Tests may contain ordinary statements, local declarations, loops, matches, and calls. assert is allowed only inside a test block; using it elsewhere is a compile error. An assertion takes a boolean expression and panics if it is false.
test "checked construction rejects zero" {
assert to_positive(0) is Error(_)
assert to_positive(1) is Success(_)
}
The is test is the concise way to assert a variant without unwrapping the payload. When the payload matters, bind it and assert the value.
test "the error names the failing invariant" {
const result = to_positive(0)
match result {
Success(_) => {
assert false
}
Error(reason) => {
assert reason == "invariant failed for 'Positive'"
}
}
}
A test that reaches a failing assertion panics with the test name and the source location. The test runner reports the file as failed and continues with the next file.
Running Tests#
The command hz test path accepts a file or a directory. A directory is searched recursively for files ending in .hz. Each file is loaded as an entry module, its tests are compiled into a generated main, and the resulting program is run. A file with no tests is skipped.
hz test tests/account_test.hz
hz test tests
On success the runner prints a count such as ok: 3 test(s) in 1 file(s). On failure it prints the failing file and exits with a non-zero status.
Tests in imported modules are not run when the importer is tested. The loader keeps only the entry module's test blocks. To run a module's own tests, pass that module's file to hz test or pass a directory that includes it.
Assertions and Release Mode#
assert is a test-only statement. It is not removed by -release, because tests are expected to run with their assertions intact. A release build of a normal program has no assert statements to remove; the flag only affects contract and invariant checks.
Do not use assert as a substitute for a contract in production code. It is not available outside a test, and a test assertion checks one concrete execution rather than a property of all inputs.
What to Test#
A contract describes a property, but it does not exercise the implementation. Tests should cover the boundary values of the contract, the transitions that the contract permits, and the error paths that the type system cannot rule out.
| Area | Example cases |
|---|---|
| Precondition boundary | The smallest accepted value, the largest accepted value, and the first rejected value |
| Postcondition | A result that satisfies the guarantee and a case where the relationship is meaningful |
| Refinement construction | A valid value, an invalid value, and a value that becomes valid after a cast |
| Record invariant | A valid combination and a combination that violates a cross-field rule |
| Checked construction | Success for a valid input and Error for an invalid one |
Result propagation |
The success path, the error path, and an error from a nested call |
| Loop invariant | An empty range, a single iteration, and the terminal boundary |
| Defer | Cleanup on normal exit, early return, and error propagation |
A boundary test for a range loop is particularly valuable because the invariant is checked at the terminal index.
test "range length includes the terminal check" {
assert range(0, 0).len == 0
assert range(0, 1).len == 1
assert range(1, 4).len == 3
}
Testing Refinements and Checked Construction#
A refinement should be tested at its boundary. The compiler rejects constant violations, so a test that wants to exercise the runtime path must use a value the compiler cannot fold, such as a function parameter or a value read from a function call. A checked construction that needs a runtime check must be placed in a helper that returns Result, because the generated test function itself returns void.
fn build(n i32) Result[Positive, str] => Success(Positive { n }?)
test "checked construction boundary" {
assert build(0) is Error(_)
assert build(1) is Success(_)
}
The is form works because build returns a Result. On success the value is a Positive; on failure it is an Error with the invariant message. The test can match either outcome without unwrapping.
Testing Contracts Without Duplicating Them#
Do not rewrite every precondition as a test assertion. The compiler already checks constant calls and emits runtime checks for the rest. A test that calls a function with an invalid constant will not even compile, and a test that calls it with an invalid runtime value will panic at the contract rather than reach the assertion.
Use tests for the behaviour that the contract does not state: a particular error message, a particular branch of a match, a particular ordering of deferred cleanup, or a property that is too complex for a contract expression. Use contracts for the properties that must hold across every call.
Test Organisation#
A test may live in the same file as the code it tests. For a larger project, a tests/ directory with one file per module keeps the test runner output readable and lets each file be compiled independently. A test file is still a module and must obey the same import and visibility rules as production code.
use account {Account, deposit, withdraw}
test "deposit increases the balance" {
const account = Account { id = 1, balance = 100 }
const next = deposit(account, 25)
assert next.balance == 125
}
test "withdraw rejects an overdraft" {
const account = Account { id = 1, balance = 10 }
assert withdraw(account, 50) is Error(_)
}
The tests above assume that deposit returns a plain Account and that withdraw returns a Result. That is the right shape: a deposit within the documented domain is total, while a withdrawal that may exceed the balance is fallible.
Summary#
| Tool | Scope | Failure | Use for |
|---|---|---|---|
| Precondition | Every call | Compile error or panic | Caller obligations |
| Postcondition | Every return | Compile error or panic | Callee guarantees |
| Type invariant | Every construction | Compile error or Error from ? |
Valid values |
| Loop invariant | Every header | Compile error or panic | Loop correctness |
assert |
One test execution | Panic | Concrete examples |
Result |
Every call | Returned value | Expected failure |
The next chapter, Writing Idiomatic Haze Code, turns these tools into a consistent style.