Modules, tests and lawsSlide 42 of 86
42testModules, tests and laws

Testing

Grammar: test-decl
testSTRINGblock
test-decl = "test" STRING block ;

A test is a top-level declaration, test "what it shows" { … }, named in prose because the name is documentation, not something anything calls. It takes no parameters and answers with nothing — a bare return leaves it early — and a file holding only tests needs no main. The report names a test by its title, so no two tests may share one, nor have titles that differ only in a space against an _.

hive test entrypoint.hive runs every test the entrypoint reaches, with no framework and no vocabulary beyond assert, and exits non-zero when any fails, as a commit hook or a CI step needs. Tests run side by side, as many at once as the machine has cores; --threads N sets how many, and --threads 1 runs them one after another, so two tests should never write the same file. Inside a test:

  • a failed assert is recorded with its condition as written and, for == or !=, both sides, and the test carries on, so every failure in it is listed;
  • a panic fails that test alone, and the rest of the suite still runs;
  • what a test echos is shown only when it fails.

Every run reports coverage: the statements your own declarations have, and which of them no test reached, an imported one named as its module spells it. Two known gaps:

  • a failure points at the generated main_test.go, not at the .hive line;
  • a test runs with the working directory set to the generated project, not the entrypoint's folder, so a test that needs files writes them itself.
Tests beside the code
type Item {
	name:  Str
	price: Int
}

func total(items: Item[]): Int {
	mut sum := 0
	for each item in items {
		sum = sum + item.price
	}
	return sum
}

test "an empty cart costs nothing" {
	Item[0] empty = []
	assert total(empty) == 0
}

test "two items add up" {
	assert total([Item("wax", 5), Item("comb", 3)]) == 8
}
basket.hive, wrong on purpose
func total(prices: Int[]): Int {
	mut sum := 0
	for each p in prices {
		sum += p
	}
	return sum
}

func unused(n: Int): Int {
	return n
}

test "an empty basket costs nothing" {
	Int[0] empty = []
	assert total(empty) == 0
}

test "this one is wrong on purpose" {
	echo "shown, because this test fails"
	assert total([3, 4]) == 8
	assert total([1]) == 2
}
What a failure looks like
$ hive test basket.hive
  PASS  an empty basket costs nothing
  FAIL  this one is wrong on purpose
        shown, because this test fails
        main_test.go:24: assert total([3, 4]) == 8
          left:  7
          right: 8
        main_test.go:27: assert total([1]) == 2
          left:  1
          right: 2

  2 tests: 1 passed, 1 failed
  coverage: 77.7% of statements (7/9)
  never exercised: unused