Zyn0.1.0

Testing

Tests are part of the language: a test block with a name, in any file, checked like the rest of the program.

fn add(a: Int, b: Int): Int = a + b

test "adding" {
    assertEq(add(2, 3), 5)
    assertEq(add(-1, 1), 0)
}

test "adding is the same both ways" {
    for a in -3..3 {
        assertEq(add(a, 10), add(10, a))
    }
}
Output$ zyn test main.zyn
Running 2 tests in main.zyn
  ✓ adding
  ✓ adding is the same both ways

2 passed, 0 failed

Run them with zyn test:

zyn test math.zyn

zyn run skips test blocks, so tests can sit right next to the code they test.

#Assertions

FunctionFails when
assert(condition)condition is false
assert(condition, message)condition is false, with your message
assertEq(actual, expected)the two aren't equal; shows both

#When a test fails

Each test runs on its own: a failing (or crashing) test is reported, and the others still run. zyn test ends with exit code 1 if any test failed, so it works in scripts and CI.

fn average(numbers: List<Int>): Int = numbers.sum() / numbers.size

test "average of a few numbers" {
    assertEq(average([2, 4, 6]), 4)
}

test "average of fractions" {
    assertEq(average([1, 2]), 2)
}

test "average of nothing" {
    assertEq(average([]), 0)
}
Output$ zyn test main.zyn
Running 3 tests in main.zyn
  ✓ average of a few numbers
  ✗ average of fractions
      Assertion failed: expected 2, but got 1
        --> main.zyn:8:13
        |
      8 |     assertEq(average([1, 2]), 2)
        |             ^
  ✗ average of nothing
      Runtime error: Division by zero
        --> main.zyn:1:53
        |
      1 | fn average(numbers: List<Int>): Int = numbers.sum() / numbers.size
        |                                                     ^

1 passed, 2 failed

#What runs in test mode

zyn test sets up the file's declarations and top-level lets and vars, then runs each test. Loose statements and main don't run, so a program's tests don't start the program.

let taxRate = 0.25

fn withTax(price: Float): Float = price * (1.0 + taxRate)

fn main() {
    println("This doesn't run in tests")
}

test "tax" {
    assertEq(withTax(100.0), 125.0)
}
Output$ zyn test main.zyn
Running 1 test in main.zyn
  ✓ tax

1 passed, 0 failed

#Testing compiled code

zyn test --jvm and zyn test --native compile the program first and run the tests compiled, to check it behaves the same there.

#Tests in their own file

A test file can import the code it tests:

shop.zyn
data Item(name: String, price: Int)

fn total(items: List<Item>): Int = items.sumOf { it.price }
import shop.{Item, total}

test "total of a basket" {
    assertEq(total([Item("tea", 3), Item("cake", 4)]), 7)
}

test "empty basket" {
    assertEq(total([]), 0)
}
Output$ zyn test main.zyn
Running 2 tests in main.zyn
  ✓ total of a basket
  ✓ empty basket

2 passed, 0 failed