# Testing and benchmarking

Vex compiles each discovered test file with a generated runner. This gives
tests the same ownership, contracts, SIMD, async and target semantics as normal
programs while retaining process isolation and bounded execution.

## A complete test file

Save the following as `tests/credit.test.vx`. The function applies a credit to
an invoice total in integer minor units. It rejects negative inputs and a
credit larger than the total before subtracting; valid inputs therefore
produce a nonnegative result within the `i32` range.

```vex [tests/credit.test.vx]
fn apply_credit(total: i32, credit: i32): Result<i32, i32> {
    if total < 0 || credit < 0 { return Err(1); }
    if credit > total { return Err(2); }
    return Ok(total - credit);
}

fn test_credit_amounts(): bool {
    let partial = match apply_credit(1000, 250) {
        Ok(value) => value == 750,
        Err(_) => false,
    };
    let full = match apply_credit(1000, 1000) {
        Ok(value) => value == 0,
        Err(_) => false,
    };
    let zero = match apply_credit(0, 0) {
        Ok(value) => value == 0,
        Err(_) => false,
    };
    return partial && full && zero;
}

fn test_credit_errors(): bool {
    let negative_total = match apply_credit(-1, 0) {
        Err(code) => code == 1,
        Ok(_) => false,
    };
    let negative_credit = match apply_credit(1000, -1) {
        Err(code) => code == 1,
        Ok(_) => false,
    };
    let excessive = match apply_credit(1000, 1001) {
        Err(code) => code == 2,
        Ok(_) => false,
    };
    return negative_total && negative_credit && excessive;
}
```

Run `vex test tests/credit.test.vx` from the project root. The intended result is
two passing tests and process exit status 0. The file has no `main`: the runner
supplies the entry point. Each test returns a boolean derived from the actual
result, so an incorrect value or error code fails the test.

This small example tests the function's contract, including zero, full-credit,
and invalid-input boundaries. A real billing system would additionally define
currency, rounding, persistence, and concurrency behavior; those concerns are
outside this integer calculation.

## Tests

The following **context-test fragment** shows subtest reporting. `decode` is an
application-provided parser returning a result; define or import it before
running this fragment.

```vex
import { TestCtx } from "testing";

fn test_decode(t: &TestCtx!) {
    t.run("valid", |child: &TestCtx!| {
        child.assertTrue(decode("42").isOk());
    });
    t.run("invalid", |child: &TestCtx!| {
        child.assertTrue(decode("?").isErr());
    });
}
```

Context tests return unit and report through `TestCtx`. Zero-argument tests may
return `bool` (`true` passes) or an integer status (`0` passes). A zero-argument
unit test can fail only by panic/abort, so use `TestCtx` for assertions.

Discovery reads parsed function declarations rather than source lines. Test
and benchmark names, `async`, context parameters and return types therefore
retain the same meaning when a legal signature spans multiple lines. Receiver
methods are not free test entrypoints.

Select an existing directory, an exact `.vx` file, or a quoted glob. Directory
discovery includes `*.test.vx`, `*_test.vx` and `*_bench.vx`; file globs can select
other `.vx` filenames explicitly. Missing paths and globs selecting no source
files fail with a nonzero exit status. An existing empty directory or a name
filter matching no functions is an empty selection, not a passing test suite.
Automatic traversal excludes generated runners and build/cache directories,
does not follow directory symlinks, and deduplicates source-file aliases. An
explicit directory-symlink root is supported. See the
[`vex test` reference](../../references/vex-test-reference.md) for the full selection rules.

Skipped contexts are reported as SKIP, not PASS. Test state is private and
cannot be overwritten by the test body. A test file containing discovered test
functions must not define `main`.

## Benchmarks

This **benchmark fragment** assumes an application-provided `table.lookup`
operation. Use a real table and representative keys when measuring it.

```vex
import { BenchCtx } from "testing";

fn bench_lookup(b: &BenchCtx!) {
    b.setBytes(4096);
    b.iter(17 as i64, |key: i64| table.lookup(key));
}
```

The duration-based `iter` family is preferred. Inputs and results cross a
compiler barrier, clock checks are adaptively batched, and temporary arena
allocations live in an isolated child region reclaimed every 128 operations.
The runner restores the caller's previous region and arena mode before
returning. For explicit setup, this fragment assumes application-provided
`prepare` and `run` functions and an imported `blackBox` from `testing`:

```vex
fn bench_manual(b: &BenchCtx!) {
    let data = prepare();
    b.resetTimer();
    for let i in 0..b.n {
        blackBox(run(data, i));
    }
    b.stopTimer();
}
```

Run performance measurements with optimization enabled:

```bash
vex test --bench -O3 --benchtime 1s --count 5 --benchmem path/to/tests
```

Benchmark files compile concurrently within a bounded worker pool, but run
serially for isolation. `--count` repeats execution of the same compiled
artifacts; it does not rebuild and relink every round.

Report the compiler revision, target, input distribution, optimization level,
iteration count and sample spread. Do not compare fastest outliers across
different workloads.

## Useful commands

```bash
vex test path/to/tests
vex test "lib/std/net/tests/*.test.vx"
vex test --run expression path/to/tests
vex test --no-parallel --timeout 60 path/to/tests
vex test --failfast path/to/tests
vex test --json path/to/tests
vex test --analyze-comptime path/to/tests
```

`--analyze-comptime` is observation-only; it does not change semantics or
enable speculative rewrites.

For tests, `--timeout` limits execution of each generated file runner, starting
at entry to `main`. It is not multiplied by the number of test functions.
Compilation and process startup use separate watchdogs; a slow compile does
not consume the runtime allowance.

A later timeout preserves completed test outcomes and partial diagnostics.
Failure during process finalization is reported separately from individual
tests, including when every test has already passed. JSON consumers should
check the process exit status and `file_errors` as well as test counts; see the
[`vex test` reference](../../references/vex-test-reference.md).
