← Cookbook Testing Beginner · Pooka 0.5.0

Write your first test

A small module about a kettle, and four tests that keep it honest. Then break it on purpose, to see what a failure looks like.

You will use

  • Spec files in test/, ending in .spec.pooka
  • test "name" { … } and assert
  • let assert to unwrap a value you expect

The whole program

src/kettle.pooka
//// A kettle that knows how many cups it holds.

module kettle

import pooka/int

/// Whole cups of tea in `millilitres` of water, at 250 ml a cup.
cups(millilitres: Int) -> Int {
  match int.divide(millilitres, 250) {
    Ok(whole) -> whole
    Error(_) -> 0
  }
}

/// What to say when someone asks for tea.
pour(millilitres: Int) -> Result(String, String) {
  match cups(millilitres) {
    0 -> Error("the kettle is empty")
    1 -> Ok("one cup of tea")
    many -> Ok(int.to_string(many) + " cups of tea")
  }
}
test/kettle.spec.pooka
module kettle_test

import kettle

test "a litre makes four cups" {
  assert kettle.cups(1000) == 4
}

test "half a cup is not a cup" {
  assert kettle.cups(120) == 0
}

test "pouring says how many" {
  assert kettle.pour(500) == Ok("2 cups of tea")
  assert kettle.pour(250) == Ok("one cup of tea")
}

test "an empty kettle explains itself" {
  let assert Error(reason) = kettle.pour(0)
  assert reason == "the kettle is empty"
}

Run it

$ pooka test
  Running tests...

  • test module: kettle_test

  ✓ a litre makes four cups
  ✓ half a cup is not a cup
  ✓ pouring says how many
  ✓ an empty kettle explains itself

  4 tests, 4 passed

Now change 250 to 200 in kettle.cups and run the tests again. One of them notices straight away:

$ pooka test
  ✗ a litre makes four cups
      expected 4
      got 5
      test/kettle.spec.pooka:6

  4 tests, 3 passed, 1 failed

How it works

  1. A spec file is a module. test/kettle.spec.pooka imports kettle like any other module. Spec files never end up in what you ship.
  2. A test passes if its block finishes. assert stops it when the condition is False. For an == comparison, the report shows both sides: what you expected and what you got.
  3. let assert unwraps. let assert Error(reason) = kettle.pour(0) fails the test if the result is not an Error, and otherwise names the reason so the next line can check it.

Try next: run pooka test --compact for a one-line summary, and read Testing for skipping tests and writing your own helpers.