Learn · 14

Testing & Debugging

Write built-in unit tests with fn test_*() and assert(), run ochre test, inspect bytecode with ochre disasm, and use ochre check and ochre fmt.

Ochre builds testing, static checking, formatting, and bytecode inspection directly into the CLI so you can verify code without installing external frameworks.

Writing Unit Tests (fn test_*())

Any zero-argument function whose name starts with test_ is automatically discovered and executed by ochre test. Use assert(cond) to verify invariants:

fn normalize(s: Str) -> Str {
    return trim(s)
}

fn test_normalize_trims_spaces() {
    assert(normalize("  ochre  ") == "ochre")
}

fn test_normalize_empty() {
    assert(normalize("   ") == "")
}

fn main() {
    test_normalize_trims_spaces()
    test_normalize_empty()
    println("all assertions passed")
}

Running Tests from the CLI

# Run all test_*() functions in a single file
ochre test math_tests.och

# Or discover all .och files recursively in the current directory
ochre test

Debugging Toolkit

  1. ochre check <file.och> — Run the full lexer, parser, and static type checker without executing side effects.
  2. type_of(val) — Inspect the dynamic runtime type name of a value (especially useful when handling json_parse payloads).
  3. ochre disasm <file.och> — Disassemble compiled bytecode chunks to inspect instructions, locals, and jump targets.
  4. ochre fmt --check <file.och> — Verify canonical formatting in CI without modifying files.
fn main() {
    let parsed = json_parse('{"count": 3, "tags": ["a", "b"]}') ?? #{}
    let count = parsed["count"] ?? 0
    let tags = parsed["tags"] ?? []
    println("count={count} ({type_of(count)}), tags={tags} ({type_of(tags)})")
}

Expected Output

count=3 (Int), tags=[a, b] (List)

Common Mistake: Non-Boolean Argument to assert()

fn main() {
    assert(1)
}

The compiler reports: argument type mismatch: expected 'Bool', found 'Int'. Write assert(1 == 1) or pass a Bool expression.

Exercise

Write a function is_even(n: Int) -> Bool and two test functions test_even_numbers() and test_odd_numbers() using assert.

Show Solution
fn is_even(n: Int) -> Bool {
    return n % 2 == 0
}

fn test_even_numbers() {
    assert(is_even(0))
    assert(is_even(42))
}

fn test_odd_numbers() {
    assert(!is_even(1))
    assert(!is_even(99))
}

fn main() {
    test_even_numbers()
    test_odd_numbers()
    println("tests passed")
}