Hare offers built-in testing and tooling to make testing programs easy. By annotating functions with `@test` and using `assert` within those functions we get very simple and clear testing. Testing functions can be defined in the same files as your other Hare source code or in their own test files.
// We have just a simple add function to add numbers together.
fn add(a: int, b: int) int = {
return a + b;
};
// We can define another function with any name and annotate it with
// @test to tell the Hare toolchain it should treat these as test
// functions.
@test fn test_add_pass() void = {
// We use the built-in assert function to assert the truthiness
// holds for the given test. You may have multiple assert calls
// within a single test function.
assert(add(1, 2) == 3, "1 + 2 = 3");
assert(add(1, 1) != 4, "1 + 1 != 4");
};
// This test function shows that the first assert passes, but the second
// fails and immediately aborts testing.
@test fn test_add_fail() void = {
// This will pass
assert(add(1, 2) == 3, "1 + 2 = 3");
// This will fail and abort immediately
assert(add(2, 3) == 6, "2 + 3 = 6");
// This never gets call because the assert above aborted
assert(add(2, 2) == 4, "2 + 2 - 4");
};
$ hare test
Running 2/2 tests:
test_add_fail...FAIL in 0.000017750s
test_add_pass...PASS in 0.000000622s
Failures:
test_add_fail: examples/testing/testing.ha:24:15: 2 + 3 = 6
/usr/local/src/harebyexample.org/examples/testing/testing.ha:24:24 testfunc::1+0xda [0x803c5da]
| assert(add(2, 3) == 6, "2 + 3 = 6");
^
/usr/local/src/hare/stdlib/test/+test.ha:303:22 test::run_test+0x200 [0x8039ca0]
| test.func();
^
/usr/local/src/hare/stdlib/test/+test.ha:257:42 test::do_test+0xcb [0x8039ddb]
| const status = run_test(ctx, test);
^
/usr/local/src/hare/stdlib/test/+test.ha:139:35 __test_main+0x692 [0x803aa72]
| do_test(&ctx, test);
^
/usr/local/src/hare/stdlib/rt/+linux/start+test.ha:13:32 rt::start_ha+0x17 [0x8003d87]
| const nfail = test_main();
^
/usr/local/src/hare/stdlib/rt/+linux/platformstart-libc.ha:8:17 rt::start_linux+0x3e [0x8003f9e]
| start_ha();
^
1 passed; 1 failed; 2 completed in 0.000018372s
Back to table of contents