Docs/Tools

Testing

Write and run tests, benchmarks, and code coverage.

On this page

Tests are test blocks next to your code, and benchmarks are bench blocks. A build with --test or --bench runs them instead of main; normal builds leave both out. For other build options see Command line.

Write a test#

Valk
fn line_total(price: int, quantity: int) int {
    return price * quantity
}

test "Line total uses the requested quantity" {
    assert(line_total(12, 3) == 36)
    assert(line_total(12, 0) == 0)
}

assert records a check. Every executed assert counts in the summary, so in a long loop collect the result in a variable and assert once after it.

Run tests#

Terminal
valk build src --test --run
valk build src tests --test --run               # tests in their own directory
valk build src tests --test --filter "Line total" --run
valk build src tests --test -o test-bin         # build once
./test-bin --filter "Line total"                # pick tests without rebuilding

--filter keeps only tests whose name contains the text. A failed comparison shows both sides and where it is:

Text
#1 [code] assert(user.name == "Ada")
#1 [left] "ada"
#1 [right] "Ada"
#1 [file] tests/users.valk:12

The test program exits with a non-zero status when a test fails, so CI can run it directly.

Isolate tests that change shared state#

Regular tests run at the same time. Use synctest for a test that changes globals, environment variables or other process-wide state:

Valk
global counter: int (0)

synctest "Reset shared test state" {
    counter = 0
    counter++
    assert(counter == 1)
}

All regular tests finish before synctests start; synctests then run one at a time in declaration order. A test can still start its own coroutines to check concurrent code.

Test errors#

Valk
union ParseError { empty }

fn parse_name(text: String) String !ParseError {
    if text == "" : throw .empty
    return text
}

test "Empty names are rejected" {
    let failed = parse_name("") ! {
        assert(E is .empty)
        return
    }
    assert(false)
}

Test helpers and platforms#

Valk
#if TEST
fn sample_users() Array[String] {
    return Array[String]{ "ada", "bob" }
}
#end

test "Paths use the platform separator" {
    #if OS == "win"
    assert("a\\b".contains("\\"))
    #else
    assert("a/b".contains("/"))
    #end
    assert(sample_users().length == 2)
}

TEST is true in test builds, so helpers inside #if TEST are not part of the release. OS and ARCH select code per platform; see Compile-time code. To check that code builds for another platform, lint for that target as shown in Cross compiling.

Benchmarks#

Benchmarks live in bench blocks. Inside every bench block, the compiler binds b (core.Bencher) automatically:

Valk
fn sum_up(n: int) int {
    let total = 0
    let i = 0
    while i < n {
        total += i
        i++
    }
    return total
}

bench "sum 100" {
    b.keep(sum_up(100))
}

bench "hash payload" {
    let data = "0123456789abcdef0123456789abcdef"
    b.set_bytes(data.bytes)
    while b.loop() {
        b.keep(data.hash())
    }
}

Write the benchmarked code directly for automatic iteration, or put one-time setup before while b.loop() { ... } so setup is excluded from timing and allocation counts.

Method Effect
b.loop() Drives the timed loop; code before the first call runs once as untimed setup
b.keep(value) Prevents the optimizer from eliminating value
b.stop_timer(), b.start_timer() Pause and resume timing and allocation tracking around per-iteration setup
b.reset_timer() Zero the elapsed timer, allocation counters, and iteration count
b.set_bytes(n) Record bytes processed per iteration to report throughput (MB/s)

Run benchmarks with valk bench, which builds with --bench --opt and runs them:

Terminal
valk bench src                               # build optimized and run
valk bench src --filter "hash"               # only benchmarks whose name contains "hash"
valk bench src -- --bench-time 1000          # target duration in ms (default 250)
valk bench src -- --bench-iters 10000        # fixed iteration count
valk build src --bench --release -o bench    # build once, run later
./bench --filter "hash" --bench-time 500

Each row reports iterations, time per operation, rate (ops/s), GC heap allocations (B/op and allocs/op), and throughput (MB/s) when b.set_bytes is set:

Text
--------- BENCH RESULTS ---------
> sum 100 . . . . . . . . . . . . . . . . .     2,840,000 iters |    88.4 ns/op |   11.31M ops/s |       0 B/op |    0 allocs/op
> hash payload . . . . . . . . . . . . . . .   12,450,000 iters |    20.1 ns/op |   49.75M ops/s |       0 B/op |    0 allocs/op |   1518.2 MB/s
---------------------------------
Benchmarks: 2

--test and --bench cannot be combined in the same build.

Code coverage#

Code coverage tracks which lines and functions of your code actually ran while your tests (or program) executed, so you can spot untested branches, error paths, and unused functions. Only your own project's source files are measured — the standard library, dependencies, and test/bench blocks are excluded.

Add --coverage to your build to print a summary table when the program exits:

Terminal
valk build src tests --test --coverage --run
Text
--------- COVERAGE ---------
File                                       Lines       Funcs    Line %
src/math.valk                              11/14         3/4     78.6%
----------------------------
Total                                      11/14         3/4     78.6%
----------------------------

Here 11/14 means 11 of the 14 executable lines in src/math.valk ran at least once, and 3/4 means 3 of its 4 functions were called.

See missed lines and export a report#

--coverage is a build flag for valk build. Two extra runtime flags are read by the compiled program itself, so pass them after -- when using --run (or directly to a built binary like ./test-bin --coverage-uncovered):

Terminal
# List the exact line numbers that never ran under each file
valk build src tests --test --coverage --run -- --coverage-uncovered

# Also save the report in standard LCOV format
valk build src tests --test --coverage --run -- --coverage-out coverage.lcov

With --coverage-uncovered, missed line numbers and ranges appear under each file (below, line 3 and lines 12–13 never ran):

Text
--------- COVERAGE ---------
File                                       Lines       Funcs    Line %
src/math.valk                              11/14         3/4     78.6%
  uncovered: 3, 12-13
----------------------------
Total                                      11/14         3/4     78.6%
----------------------------

The coverage.lcov file can be opened in editor extensions (to highlight covered and missed lines inline), turned into a browsable HTML report with genhtml coverage.lcov -o html, or uploaded to CI coverage tools.

Runtime flag Environment variable Effect
--coverage-uncovered VALK_COVERAGE_SHOW=1 Print missed line numbers and ranges under each file
--coverage-out <file> VALK_COVERAGE_FILE=<file> Write an LCOV coverage report to <file>

--coverage works with normal builds too (valk build src --coverage --run), not only --test.