fn sort(items: []int) void = {
for (true) {
let sorted = true;
for (let i = 1z; i < len(items); i += 1) {
if (items[i - 1] > items[i]) {
const x = items[i - 1];
items[i - 1] = items[i];
items[i] = x;
sorted = false;
};
};
if (sorted) {
break;
};
};
};
@test fn sort() void = {
let items = [5, 4, 3, 2, 1];
sort(items);
for (let i = 1z; i < len(items); i += 1) {
assert(items[i - 1] <= items[i], "list is unsorted");
};
};
Hare has first-class support for tests via the @test
attribute on functions.
You can run tests with hare run
in the directory where the tests are present.
You do not need a main function, you can test library functions this way. The
assert
built-in is very useful for tests. Given a condition (a bool), if the
condition is false the program is stopped and the message is printed. You can
also skip the message if you don't need to be specific; the file name and line
number will be printed and you can generally figure out what went wrong
regardless.
table driven
@test fn calc_yearday() void = {
const cases = [
((-0768, 02, 05), 036),
((-0001, 12, 31), 365),
(( 0000, 01, 01), 001),
(( 0000, 01, 02), 002),
(( 0000, 12, 31), 366),
(( 0001, 01, 01), 001),
(( 0001, 01, 02), 002),
(( 1965, 03, 23), 082),
(( 1969, 12, 31), 365),
(( 1970, 01, 01), 001),
(( 1970, 01, 02), 002),
(( 1999, 12, 31), 365),
(( 2000, 01, 01), 001),
(( 2000, 01, 02), 002),
(( 2020, 02, 12), 043),
(( 2038, 01, 18), 018),
(( 2038, 01, 19), 019),
(( 2038, 01, 20), 020),
(( 2243, 10, 17), 290),
(( 4707, 11, 28), 332),
(( 4707, 11, 29), 333),
((29349, 01, 25), 025),
];
for (let i = 0z; i < len(cases); i += 1) {
const params = cases[i].0;
const expect = cases[i].1;
const actual = calc_yearday(params.0, params.1, params.2);
assert(expect == actual, "yearday miscalculation");
};
};