API reference
testingx: a test runner that replaces the built-in one, and benchmarks that sit beside your tests.
This file is the library root. The bench side lives in bench.zig.
runner.zig is the --test-runner replacement and compiles as its own
module.
module
bench
src
Benchmarks that sit beside your tests: Go's testing.B, in Zig.
more
A benchmark suite is a program that registers what runs. The entrypoint
is pub fn benchmarkMain(b: *B) !void in the suite root:
const sort_bench = @import("bench/sort.zig");
pub fn benchmarkMain(b: *testingx.B) !void {
try b.addMod(sort_bench); // bulk: every pub benchmark* at top level
try b.add("Parser/Baseline", benchmarkParserBaseline); // one-off
}
add and addMod register. finish executes everything registered.
Inside a running benchmark, b.run executes a sub-benchmark immediately
(Go's b.Run); registering there is an error.
addMod walks top-level declarations only, never nested structs. The
convention inside a module: pub fn benchmark*(b: *B) !void.
Flags (parsed by the generated main, Go's set): --benchtime D run for duration D (default 1s), or Nx for exactly N --count N run each benchmark N times (default 1) --filter P comma-separated patterns: contains, ^ anchors start, $ anchors end, * matches any bytes --benchmem print B/op and allocs/op --parallelism N default B.runParallel multiplier --config K=V add a config line to the output header (repeatable) --jsonl emit one JSON object per record instead of benchfmt text
Text output is the Go benchmark format (benchfmt.zig); FAIL and SKIP
rows are comments so the result stream stays parseable. --jsonl is an
opt-in machine-readable mode.
Environment, for CI policy: TESTINGX_BENCH_FILTER (same as --filter),
TESTINGX_BENCH_JSONL (1 or true, same as --jsonl), and
TESTINGX_BENCH_CYCLES (same as --cycles, so a shell can make counters
the local default). Flags win.
Constants
Panic handler for benchmark executables: print the active benchmark,
dump the stack trace, and exit 1 instead of aborting into a core file.
src/bench_main.zig wires this automatically; a custom main can bind
pub const panic = testingx.benchPanic;.
value
error{
BenchmarkFailed,
BenchmarkSkipped,
InvalidMetricUnit,
// `b.run` before `finish` executes anything, or `add`/`addMod` while a
// benchmark is running. Registration happens in `benchmarkMain`; `b.run`
// belongs inside a benchmark function.
InvalidPhase,
}Functions
Run one benchmark function in isolation and return its result.
The generated bench main calls this: parse flags, run benchmarkMain,
exit non-zero on failure.
pub fn printUsage(writer: *Io.Writer) !void
src
Types
struct
Options
src
The flags, as parsed by benchMain or built by a test.
Fields
benchtime: DurationOrCount = .{ .duration_ns = time.ns_per_s }
benchmem: bool = false
count: usize = 1
parallelism: usize = 1
filter: ?[]const u8 = null
emit_environment: bool = true
jsonl: bool = false
disasm: ?[]const u8 = null
--disasm: print the linker symbol and disassembly of matching
benchmarks instead of running anything.
cycles: bool = false
--cycles: read hardware counters around each timed section.
help: bool = false
writer: ?*Io.Writer = null
config: std.ArrayList(benchfmt.Config) = .empty
Extra config lines from --config, emitted before the environment.
The list and its values are owned by this Options.
Functions
Accepts a standard-library argument iterator. Skips argv[0].
Returned filter strings borrow the iterator's storage; --config
values are duplicated with allocator, which also owns the list.
defaults must not already carry config entries.
union
DurationOrCount
src
pub const DurationOrCount = union(enum)
Fields
duration_ns: u64
count: u64
Functions
struct
Result
src
Fields
Constants
value
.{
.n = 0,
.t_ns = 0,
.bytes = 0,
.mem_allocs = 0,
.mem_bytes = 0,
.extra = .empty,
}Nothing measured: no iterations, time, bytes, allocations, or metrics.
Functions
pub fn allocsPerOp(self: *const Result) i64
src
pub fn allocedBytesPerOp(self: *const Result) i64
src
pub fn appendValues(
self: *const Result,
allocator: Allocator,
values: *std.ArrayList(benchfmt.Value),
include_mem: bool,
) !void
src
Append this result's measurements in print order. ns/op is always
present, so the encoded result line always has a value/unit pair.
struct
B
src
A B is the suite during registration (benchmarkMain) and one running
benchmark during execution. The phase decides what add/addMod/run do.
Fields
internal_allocator: Allocator
io: Io
The I/O of this B. In the suite phase it is the process I/O; in a
spawned benchmark it is io_instance.io() (mirrors testing.io:
a fresh Io.Threaded per benchmark, on the same counting allocator
as allocator, so its allocations are counted).
io_instance: Io.Threaded
argv0: Io.Threaded.Argv0
environ: std.process.Environ
options: Options
specs: std.ArrayList(Spec)
writer: ?*Io.Writer
stdout_buf: [4096]u8
stdout: Io.File.Writer
executing: bool
allocator: Allocator
counting_allocator: CountingAllocator
name: []const u8
n: u64
failed: bool
skipped: bool
bench_func: ?Function
bench_time: DurationOrCount
bytes: i64
timer: Timer
timer_on: bool
duration_ns: u64
start_allocs: u64
start_bytes: u64
net_allocs: u64
net_bytes: u64
show_alloc_result: bool
benchmem: bool
jsonl: bool
filter_pattern: ?[]const u8
counters: perfcounter.Counters
counters_error: ?anyerror
counters_warned: bool
result: Result
parallelism: usize
previous_n: u64
previous_duration_ns: u64
loop_state: LoopState
has_sub: bool
missing_bytes: bool
extra: MetricMap
Functions
Create a suite for registration. io is required: everything here
does I/O and refuses to guess.
pub fn initProcess(entry: std.process.Init) !B
src
Create a suite from a process entry: parses flags from argv.
Register one benchmark by name.
Register every top-level pub fn benchmark*(b: *B) !void in mod.
One line per module, zero per function. Names drop the prefix:
benchmarkSort registers as "Sort".
Execute everything registered. Returns true when all passed.
Execute a sub-benchmark (Go's b.Run). Only valid inside a running
benchmark: benchmarkMain registers with add/addMod instead.
pub fn startTimer(self: *B) void
src
pub fn resetTimer(self: *B) void
src
pub fn reportAllocs(self: *B) void
src
pub fn reportCounters(self: *B) void
src
Count hardware events for this benchmark, the per-benchmark form of
--cycles: the row gains cycles/op, instructions/op, ipc, and
whatever else the PMU granted. Counters open here, inside the timed
body, so a benchmark that asks for them pays for them whether or not
the suite passed --cycles. A host without a PMU reports timings
alone; requesting counters never fails a run.
pub fn reportMetric(self: *B, n: f64, unit: []const u8) !void
src
pub fn runParallel(self: *B, body: *const fn (*Pb) anyerror!void) !void
src
pub fn setParallelism(self: *B, p: usize) void
src
Keep a computed value from being optimized away. Idiomatic shape:
declare the sink, defer b.keepAlive(sink);, then compute in the
loop. The defer guarantees the final value is observed, which keeps
every iteration that contributes to it.
module
benchfmt
src
The Go benchmark file format: https://golang.org/design/14313-benchmark-format
more
A stream is a sequence of lines. Configuration lines set key/value pairs for
the results that follow, result lines name a benchmark and its measurements,
and everything else (including # comments) is ignorable for tooling:
rev: 4f2b1c9
target: aarch64-linux-gnu
BenchmarkSort/Quick 1200 99.18 ns/op 16 B/op 1 allocs/op
# FAIL: BenchmarkBroken
The reader and writer mirror golang.org/x/perf/benchfmt: the writer streams records, and the reader parses a byte slice into records plus an accumulated configuration map. Reader records are valid until the next call, and syntax errors are records, not fatal errors.
Keys are checked against the ASCII subset of the benchfmt key rule: a key
begins with a lowercase letter and contains no whitespace, uppercase letter,
or colon. Values are free text without newlines. Result names are the text
after the Benchmark prefix; the writer adds the prefix, and the reader
strips it, matching benchfmt.Name.Full(). Unit metadata lines
(Unit <unit> key=value) are not interpreted; the reader ignores them and
the writer never emits them.
Constants
value
error{
InvalidConfigKey,
InvalidConfigValue,
InvalidCommentText,
InvalidName,
InvalidUnit,
MissingValues,
}Functions
pub fn isValidConfigKey(key: []const u8) bool
src
Types
struct
Writer
src
Writer emits benchfmt lines to writer.
Fields
writer: *Io.Writer
Functions
pub fn writeConfig(self: *Writer, key: []const u8, value: []const u8) !void
src
Write one configuration line. An empty value is written as key:,
which readers interpret as deleting the key.
pub fn writeResult(
self: *Writer,
name: []const u8,
iters: u64,
values: []const Value,
) !void
src
Write one result line. The writer supplies the Benchmark prefix and
keeps the columns aligned; any run of whitespace parses as a separator.
pub fn writeComment(self: *Writer, text: []const u8) !void
src
Write one comment line, e.g. a FAIL or SKIP marker that must stay out of the result stream.
pub fn writeCommentFmt(self: *Writer, comptime format: []const u8, args: anytype) !void
src
Write one formatted comment line.
struct
Name
src
Fields
full: []const u8
The name without the Benchmark prefix, e.g. Sort/Quick-8.
Functions
The base name, without any /part or trailing -N GOMAXPROCS suffix.
pub fn splitGomaxprocs(self: Name) Gomaxprocs
src
Split off Go's trailing -N GOMAXPROCS suffix, if present.
Split the name into its base and sub-benchmark parts. Each part is one
of /key=value, /positional, or a trailing -N GOMAXPROCS suffix.
items[0] is the base; concatenating items rebuilds full.
Types
struct
SyntaxError
src
A recoverable parse error. Scanning continues after one is returned.
Fields
Functions
Types
enum
Kind
src
Fields
missing_name missing_name
missing_iterations missing_iterations
invalid_iterations invalid_iterations
missing_measurements missing_measurements
invalid_measurement invalid_measurement
missing_unit missing_unit
struct
Reader
src
Reader parses a benchfmt stream held in memory.
Fields
allocator: Allocator
input: []const u8
offset: usize
line: usize
config: ConfigMap
Configuration accumulated from every config line read so far.
values: std.ArrayList(Value)
Constants
Functions
Return the next record, or null at end of input. Syntax errors are returned as records; parsing resumes on the next line.
struct
B
src
pub const B = bench.B
A B is the suite during registration (benchmarkMain) and one running
benchmark during execution. The phase decides what add/addMod/run do.
Fields
internal_allocator: Allocator
io: Io
The I/O of this B. In the suite phase it is the process I/O; in a
spawned benchmark it is io_instance.io() (mirrors testing.io:
a fresh Io.Threaded per benchmark, on the same counting allocator
as allocator, so its allocations are counted).
io_instance: Io.Threaded
argv0: Io.Threaded.Argv0
environ: std.process.Environ
options: Options
specs: std.ArrayList(Spec)
writer: ?*Io.Writer
stdout_buf: [4096]u8
stdout: Io.File.Writer
executing: bool
allocator: Allocator
counting_allocator: CountingAllocator
name: []const u8
n: u64
failed: bool
skipped: bool
bench_func: ?Function
bench_time: DurationOrCount
bytes: i64
timer: Timer
timer_on: bool
duration_ns: u64
start_allocs: u64
start_bytes: u64
net_allocs: u64
net_bytes: u64
show_alloc_result: bool
benchmem: bool
jsonl: bool
filter_pattern: ?[]const u8
counters: perfcounter.Counters
counters_error: ?anyerror
counters_warned: bool
result: Result
parallelism: usize
previous_n: u64
previous_duration_ns: u64
loop_state: LoopState
has_sub: bool
missing_bytes: bool
extra: MetricMap
Functions
Create a suite for registration. io is required: everything here
does I/O and refuses to guess.
pub fn initProcess(entry: std.process.Init) !B
src
Create a suite from a process entry: parses flags from argv.
Register one benchmark by name.
Register every top-level pub fn benchmark*(b: *B) !void in mod.
One line per module, zero per function. Names drop the prefix:
benchmarkSort registers as "Sort".
Execute everything registered. Returns true when all passed.
Execute a sub-benchmark (Go's b.Run). Only valid inside a running
benchmark: benchmarkMain registers with add/addMod instead.
pub fn startTimer(self: *B) void
src
pub fn resetTimer(self: *B) void
src
pub fn reportAllocs(self: *B) void
src
pub fn reportCounters(self: *B) void
src
Count hardware events for this benchmark, the per-benchmark form of
--cycles: the row gains cycles/op, instructions/op, ipc, and
whatever else the PMU granted. Counters open here, inside the timed
body, so a benchmark that asks for them pays for them whether or not
the suite passed --cycles. A host without a PMU reports timings
alone; requesting counters never fails a run.
pub fn reportMetric(self: *B, n: f64, unit: []const u8) !void
src
pub fn runParallel(self: *B, body: *const fn (*Pb) anyerror!void) !void
src
pub fn setParallelism(self: *B, p: usize) void
src
Keep a computed value from being optimized away. Idiomatic shape:
declare the sink, defer b.keepAlive(sink);, then compute in the
loop. The defer guarantees the final value is observed, which keeps
every iteration that contributes to it.
struct
Options
src
pub const Options = bench.Options
The flags, as parsed by benchMain or built by a test.
Fields
benchtime: DurationOrCount = .{ .duration_ns = time.ns_per_s }
benchmem: bool = false
count: usize = 1
parallelism: usize = 1
filter: ?[]const u8 = null
emit_environment: bool = true
jsonl: bool = false
disasm: ?[]const u8 = null
--disasm: print the linker symbol and disassembly of matching
benchmarks instead of running anything.
cycles: bool = false
--cycles: read hardware counters around each timed section.
help: bool = false
writer: ?*Io.Writer = null
config: std.ArrayList(benchfmt.Config) = .empty
Extra config lines from --config, emitted before the environment.
The list and its values are owned by this Options.
Functions
Accepts a standard-library argument iterator. Skips argv[0].
Returned filter strings borrow the iterator's storage; --config
values are duplicated with allocator, which also owns the list.
defaults must not already carry config entries.
struct
Result
src
pub const Result = bench.Result
Fields
Constants
value
.{
.n = 0,
.t_ns = 0,
.bytes = 0,
.mem_allocs = 0,
.mem_bytes = 0,
.extra = .empty,
}Nothing measured: no iterations, time, bytes, allocations, or metrics.
Functions
pub fn allocsPerOp(self: *const Result) i64
src
pub fn allocedBytesPerOp(self: *const Result) i64
src
pub fn appendValues(
self: *const Result,
allocator: Allocator,
values: *std.ArrayList(benchfmt.Value),
include_mem: bool,
) !void
src
Append this result's measurements in print order. ns/op is always
present, so the encoded result line always has a value/unit pair.
Run one benchmark function in isolation and return its result.
The generated bench main calls this: parse flags, run benchmarkMain,
exit non-zero on failure.
pub const benchPanic = bench.panic
src
Panic handler for benchmark executables: print the active benchmark,
dump the stack trace, and exit 1 instead of aborting into a core file.
src/bench_main.zig wires this automatically; a custom main can bind
pub const panic = testingx.benchPanic;.
module
filter
src
Functions
pub fn matchesAny(patterns: []const u8, name: []const u8) bool
src
pub fn mayMatchAnyChild(patterns: []const u8, name: []const u8) bool
src
pub fn mayMatchChild(pattern: []const u8, name: []const u8) bool
src
module
artifacts
src
Retention for test output.
A test asks for a directory, writes files into it, and the runner keeps the directory only when the test fails. The path appears under the failure, so the files are where the person reading the failure looks.
Functions
pub fn artifactDir(allocator: Allocator) !?[]const u8
src
The directory this test may write files into, or null when the runner was
not asked to collect artifacts with --artifacts=DIR or
TESTINGX_ARTIFACTS.
more
Call this from a test. The directory is created on the first call. The
runner keeps it when the test fails, deletes it when the test passes, and
prints its path with the failure. The returned path belongs to allocator.
The value travels on testing.environ, the one channel the runner and
the test module share.
pub fn writeArtifact(allocator: Allocator, name: []const u8, bytes: []const u8) !void
src
Write name into the test's artifact directory. Does nothing when the
runner was not asked to keep artifacts.
name is relative to the directory, which already exists. A name that
contains a path separator needs the parent directory to exist first.
pub fn artifactDir(allocator: Allocator) !?[]const u8
src
The directory this test may write files into, or null when the runner was
not asked to collect artifacts with --artifacts=DIR or
TESTINGX_ARTIFACTS.
more
Call this from a test. The directory is created on the first call. The
runner keeps it when the test fails, deletes it when the test passes, and
prints its path with the failure. The returned path belongs to allocator.
The value travels on testing.environ, the one channel the runner and
the test module share.
pub fn writeArtifact(allocator: Allocator, name: []const u8, bytes: []const u8) !void
src
Write name into the test's artifact directory. Does nothing when the
runner was not asked to keep artifacts.
name is relative to the directory, which already exists. A name that
contains a path separator needs the parent directory to exist first.
module
txtar
src
Compile-time txtar parsing, and one runtime writer for artifacts.
The grammar matches mattrobenolt/txtar: a comment, then -- name --
markers with section text between them. parse runs at comptime; format
is the inverse at runtime, so a test can dump an archive that fixtures()
reads back after it is checked in.
Constants
pub const FormatError = …
src
value
error{
InvalidName,
OutOfMemory,
}Functions
pub fn format(
allocator: Allocator,
comment: []const u8,
files: []const File,
) FormatError![]u8
src
Format files as a txtar archive. The result is owned by allocator.
parse reads this back. Section text that does not end in a newline gains
one, matching what the parser does on the way in, so a round trip is stable.
pub fn markerName(line: []const u8) ?[]const u8
src
The marker name for a line, or null when the line is content.
Types
An embedded txtar archive, read at comptime.
more
archive must be comptime-known; @embedFile provides that. The value
holds the comment and the section list; the decoded bytes live in
compile-time constants on the generated type. A local
const fx = fixtures(@embedFile(...)) works.
The value has:
comment: the archive comment.files: every section, asFixture { name, text }.get(name): the section text.b64(name)andhex(name): decoded bytes.find(name): runtime lookup, returning aFixture.
Base64-decode one embedded file at comptime.
Hex-decode one embedded file at comptime.
pub fn fuzzBytes(
context: anytype,
comptime max_len: usize,
comptime testOne: fn (@TypeOf(context), []const u8) anyerror!void,
options: testing.FuzzInputOptions,
) anyerror!void
src
Adapt std.testing.fuzz to a byte-slice target.
more
Fills a max_len stack buffer with bytes from the fuzzer's Smith and
calls testOne with the filled slice. max_len is comptime because it
sizes that buffer. Under testingx's runner the adapter replays
options.corpus and one empty input. Under the built-in runner in fuzz
mode it mutates.
A corpus entry is the bytes the target receives, so a seed file named for
what the target should see holds exactly that. Smith.slice reads a length
before the bytes, so the adapter frames each entry and no seed file carries
a hand-written prefix.
Two consequences follow. An entry longer than max_len reaches the target
as its first max_len bytes: the adapter writes the length that will
arrive, because an untouched length is read back as 0 during corpus replay
and as an arbitrary length under the fuzzer. And an input the fuzzer saved
is already framed, so a crash file cannot be copied into options.corpus
as-is; unwrap it first, or keep it out of the corpus.