Testing and benchmarking#
A test "name" { ... } block runs under ms test and passes when it finishes normally. For timing, see Benchmark your code
. Assertions in @std/test/test.ms return Results; ? turns a failed check into the test’s error. Faults (including panic) and timeouts also fail a test.
Save this complete file as test.ms:
import expect_equal from "@std/test/test.ms"
fn add(a, b Int) Int {
return a + b
}
test "addition" {
expect_equal(add(1, 2), 3)?
}
test "zero is unchanged" {
expect_equal(add(0, 7), 7)?
}ms test test.ms2 tests, 0 failedOutput is quiet by default: failures and the summary. Add --verbose to print a RUN and PASS line for every test.
Select one test or set a per-test deadline:
ms test test.ms --filter addition
ms test test.ms --timeout 10sWith --filter addition, only the selected test runs:
1 tests, 0 failedexpect_equal works with numbers, text, collections, and Equal types. Change 3 to 4 to see FAIL test.ms::addition: expected 4, got 3 and a nonzero exit. A tests file needs no main.
Run tests in a project#
ms test ms.toml
ms test ms.toml --filter addition --timeout 10s
ms test ms.toml --json- A manifest run discovers
test.msand*_test.msfiles below the project root, plus tests in imports (discovery rules ). ms test file.msruns that module and its imports only.ms test a.ms b.msbuilds both into one executable and runs every test in one invocation.- Tests run from the manifest’s directory (or the file’s, for a single file), so relative fixture paths are stable; see build and test .
- Import app code with a relative path, e.g.
import add from "./src/math.ms"(modules ). --filtermatchesmodule::namesubstrings;--timeoutbounds each test (default 60s,0disables).- A bare
expect_equal(...)statement is a check error, because a discardedResultchecks nothing: writeexpect_equal(...)?, orvoid ...to drop a returned value. --jsonemits versioned per-test results, counts, diagnostics, and stdout; it cannot combine with--watch(JSON contract ).
For each standalone test example below, replace the contents of test.ms and run ms test test.ms. expect_ok(...)? checks success and keeps the payload:
import (
parse from "@std/data/json.ms",
expect_equal, expect_error, expect_ok, expect_value from "@std/test/test.ms",
)
test "typed JSON and Optional payloads" {
number := expect_ok(parse[Int]("3"))?
expect_equal(number, 3)?
cause := expect_error(parse[Int]("true"))?
expect_equal(cause.kind, "EBADMSG")?
expect_value([number].first())? | expect_equal(3)?
}Test output:
1 tests, 0 failedTests can also propagate an Error with ?. See Results
.
Select and repeat#
With the opening addition and zero is unchanged tests saved in test.ms, list their exact names:
ms test test.ms --listtest.ms::addition
test.ms::zero is unchangedRun one named test, select names with a pattern, or repeat the suite in a seeded order:
ms test test.ms --test 'test.ms::addition' --json
ms test test.ms --match 'addition|zero' --exclude 'slow' --fail-fast
ms test test.ms --repeat 10 --shuffle 42- Copy exact
module::nameidentities from--list; repeat--testto select several. --filter,--match, and--excludenarrow the selection; regexes match any part of the identity. Empty selections fail.--listbuilds but never runs test bodies.- Test files run concurrently, each in its own promise, in one process. A file’s tests run in order and share its fixture.
- Process-wide state (working directory, environment, files, services) is shared, so a test that changes it must restore it.
- A fault in a test ends its file: later tests in that file are reported not run.
--shuffletakes a seed.--fail-fastleaves remaining testsnot_runin JSON.
Property tests and fuzzing#
A property test checks a rule on many generated inputs instead of a few hand-picked ones. check in @std/test/property.ms takes a name, a generator, and a function that returns a Result like any assertion. It runs 100 cases by default.
import (
check, ints, lists from "@std/test/property.ms",
expect_equal from "@std/test/test.ms",
)
test "reversing twice restores a list" {
check(
"reverse twice",
lists(ints(-100, 100)),
xs => expect_equal(xs.reversed().reversed(), xs),
)?
}Test output:
1 tests, 0 failedWhen a case fails, check shrinks the input to a small counterexample and fails the test with it and the case seed:
FAIL test.ms::small sums: property 'small sums' failed after 3 cases (case seed 2039066943738375196; rerun with --seed 2039066943738375196)
counterexample: [50]
expected true, got false- Generators:
ints(low, high),bools(),floats(low, high),strings(alphabet, max_length),lists(gen, min_length, max_length),optionals(gen),pairs(a, b),element_of(values),one_of(gens), andconstant(value). - Combine them with the
Genmethodsmap,zip,flat_map, andfilter, as on lists:ints(1, 9).map(n => n * 2). Afilterthat cannot find a kept value discards the case; too many discards fail the test. - Shrinking is automatic for every generator, including your own compositions: generators draw from a recorded stream of integers and shrinking edits and replays it. Integers shrink toward 0, lists toward fewer elements,
optionalstowardnull,boolstowardfalse. - A generator value moves into the generator that uses it, so build a fresh
ints(...)for each use rather than reusing one binding. - A
panicinside a property counts as a failing case and shrinks like a returned error; each case runs underexpect_fault.
ms test controls property runs from the command line:
ms test ms.toml --runs 1000 # cases per property
ms test ms.toml --seed 2039066943738375196 # replay a reported failure
ms test ms.toml --fuzz 30s # keep generating fresh cases for 30s per property--fuzz replaces the case count with a time budget for each check call and prints the starting seed to standard error, so a fault that kills the process can still be replayed with --seed. It disables the default 60s --timeout unless you pass one. An explicit seed: argument to check overrides --seed. The property-testing example
shows a project with several properties.
All assertions return Result, so use ?:
expect_value,expect_ok,expect_erroryield the checked payload.expect_fault(operation)checks programming faults.fail(message)?fails explicitly;skip(reason)?skips the test.- Write each independently reported case as its own
testblock.
Golden files and misbehaving streams#
expect_golden(path, actual) in @std/test/golden.ms compares text with a file kept next to the test and names the first differing line on a mismatch. Run MS_UPDATE_GOLDEN=1 ms test ... to rewrite the files from the actual output, review the change in version control, then run again without it. expect_golden_bytes does the same for bytes.
@std/test/iotest.ms wraps streams to test code that reads and writes: one_byte(input) trickles one byte per read, fail_after(input, n, cause) fails every read after n bytes, and fail_writer_after(output, n, cause) fails like a full disk. check_reader(make, expected) checks a ReadStream you wrote: whole reads, one-byte reads, a respected chunk size, and an end of input that stays ended.
Benchmark your code#
A bench "name" { ... } block works like a test block, but ms bench times it instead of checking it. The body is one iteration; ms bench repeats it until a sample takes about 100ms (that calibration is also the warmup), takes ten samples, and reports the time per iteration. ms test skips bench blocks. Save this complete file as bench.ms:
import expect_equal from "@std/test/test.ms"
fn sum_to(n Int) Int {
var total = 0
for i in 0..n {
total += i
}
return total
}
bench "sum to one hundred" {
expect_equal(sum_to(100), 4950)?
}ms bench bench.ms
ms bench bench.ms --time 500ms --samples 20
ms bench ms.toml --filter "sum" --json- A project loads
bench.msand*_bench.msfiles; a bench may also sit in any module the command loads. Benches take the same selection options as tests (--filter,--match,--exclude,--bench,--list,--repeat,--fail-fast,--timeout). --timesets the target length of one sample,--samplesthe number of timed samples, and--iterationsfixes the iteration count and skips calibration.bench "name" per 1000 { ... }declares that one iteration performs 1000 operations (a loop over 1000 items, say); every statistic is then per operation.- The whole body is timed, and the harness keeps the body’s last statement: end it with a bare value (or a call, with
?for a fallible one) and the work cannot be removed. The compiler can still fold a body whose inputs are constants, so read inputs from the fixture. - To keep setup out of the timing, use a fixture as in tests:
fn make_fixture() Tand the hooksbefore_all,before_each,after_eachandafter_all, read in the body asfixture. They run once per bench process, outside the timed region. Because each bench runs in its own process,make_fixtureof a file runs once for every bench in it, so build only what the file’s benches share. - Each bench runs in its own process. A body that returns an error, faults, or exceeds
--timeout(default 10 minutes) fails that bench and the exit status is 1. Standard output written by a bench is discarded. --jsonaddsstatsto each entry ofbenches:iterations,operations,samples, andmin_ns,median_ns,mean_ns,max_ns,stddev_nsin nanoseconds per operation (per iteration whenoperationsis 1), andcpu_ns, the process CPU time (user plus kernel) per operation, which ignores time spent waiting for a CPU.--jsonalso reports the runtime’s work per operation from one extra counted run:allocations,allocated_bytes,list_copies,list_copy_bytes,string_clonesandstring_clone_bytes. Unlike times, these do not depend on machine load or on the host, so they can gate a build.- Save a run with
ms bench ms.toml --json > baseline.json. Thenms bench ms.toml --baseline baseline.json --fail-over 3exits 1 and names each count that rose more than 3% (times are never compared). - Allocations count the calling thread and finished threads. Copies count the calling thread. Work done inside native runtime calls (such as crypto and regex) shows only as allocations and bytes, so also watch the time for those.
ms bench --opsalso counts the MIR operations your own code executes (mir_opsin--json,MIR opsin the text). The build carries a counter and runs each bench once. The count is the same on every platform and backend, so a project such as a database driver can gate on its own code without depending on the runtime.- Times of an
--opsrun are not meaningful; run without--opsfor times.--baselinecomparesmir_opslike the other counts.
- Save a run with
- Put the measured work in the body and the setup in the fixture.
ms benchbuildsReleaseby default, which is what you want to measure.
Profile application work#
Use ms run --profile on a runnable project with an exported main:
ms run --profile ms.toml --out-dir capture --top 10This runs the application entry point, not its test blocks. Put the workload you want to measure in the application’s execution path. capture must be a new directory; the sampling profile includes folded stacks, pprof data, and a text report. The default build type is Release. See profiling and native debugging
for output files and source-attribution limits.
Shared setup and teardown#
Without make_fixture, no hooks run. Define fn make_fixture() T for a record or enum T and give it any of the hook methods before_all, before_each, after_each and after_all; tests then read it as fixture.
import expect_equal from "@std/test/test.ms"
type Counter {
count Int
}
fn make_fixture() Counter {
return Counter(0)
}
fn var Counter.before_each() Void! {
self.count = 0
}
test "increments" {
fixture.count += 1
expect_equal(fixture.count, 1)?
}
test "starts fresh" {
expect_equal(fixture.count, 0)?
}Test output:
2 tests, 0 failedA file’s tests share one fixture. make_fixture and before_all run once before the file’s first test, before_each and after_each run around each test, and after_all runs after the last. So before_each above resets the Counter that the second test reads. Each --repeat round runs the file again on a new fixture.
- One instance per file and run; a fault in a test still runs
after_eachandafter_all, and the file’s later tests are reported not run. - Optional hooks (use
self, no arguments, returnVoid!):before_all,before_each,after_each,after_all. A hook’s error fails the tests it guards;skip(reason)?skips them. - Build in
make_fixture, reset inbefore_each, release inafter_all.
Run tests only on some platforms#
There is no platform attribute on test blocks. Skip at run time instead, comparing os() from @std/os/system.ms with an Os case (Os.Linux, Os.Macos, Os.Windows, or Os.Other). The file must still compile on every platform.
To skip a single test, call skip in its body:
import (
Os, os from "@std/os/system.ms",
skip from "@std/test/test.ms",
)
test "unix permission bits" {
if os() == Os.Windows {
skip("Unix only")?
}
// Unix-only assertions follow.
}To skip every test in a file, call skip from a fixture hook. before_all and before_each both work; after_all and after_each still run, and each test is reported as SKIP with your reason:
import (
Os, os from "@std/os/system.ms",
skip from "@std/test/test.ms",
)
type WindowsOnly {
ok Bool
}
fn make_fixture() WindowsOnly {
return WindowsOnly(os() == Os.Windows)
}
fn var WindowsOnly.before_all() Void! {
if not self.ok {
skip("Windows only")?
}
}Skipped tests are counted in the ms test summary, so a platform that runs nothing stays visible.