A lightweight, Bool-based, parallel-first, formally verified testing framework for Lean 4 with zero external dependencies.
LSpec combines ideas from:
- Hspec: ergonomic
SpecMdo-block DSL (describe,context,it,prop,shouldBe,beforeAll,parallel,sequential,xit/pending) - nest-core:
TestTreeIR, extensibleIsTesttypeclass, pluggableTestProcessors, and scoped resources - nest-unit:
AssertMmonad with compile-time source locations (file:line:col) viapos% - nest-slimcheck: per-test deterministic seeds always printed for reproducible property-test failures
- Zero import-time overhead:
- All tests are
Bool- andAssertM-based (noProp/Decidablesynthesis, proof-erasure overhead, or runtimeLeancompiler dependency). - Every leaf test (
it,itBool,prop,propWith) is deferred under aUnit →thunk insideSpec(StateT (Array TestTree) BaseIO Unit). For test libraries or declarations containing heavy closed pure expressions insideitblocks, settingcompiler.extract_closed false(e.g.moreLeanArgs = ["-Dcompiler.extract_closed=false"]on your test library) prevents Lean from hoisting them into module initializers. Importing test modules does zero test work.
- All tests are
- Bounded-thread parallel execution (
-j N/--threads N):- A fixed-size worker pool runs at most
Ntests concurrently while releasing each completed test closure immediately so peak RSS stays proportional toNrather than total suite size. - Per-test stdout/stderr isolation (
IO.FS.withIsolatedStreams) keeps output deterministic and readable. sequentialsubtrees and scopedwithResource/beforeAllfixtures compose cleanly with parallelism.
- A fixed-size worker pool runs at most
- Deterministic, thread-safe Bool property testing:
- Pure SplitMix64
Genmonad (never mutates globalIO.stdGenRef), with fuel-bounded shrinking and deterministic per-test seeds derived from(masterSeed, testPath).
- Pure SplitMix64
- Formally verified runner (
LSpecProofs):- Core filtering, reporting, and plan-compilation logic is total and verified directly in Lean with zero
sorrys, alongside a small-step operational semantics proof of bounded concurrency, sequential exclusion, resource bracket safety, deadlock freedom, and sequential–parallel equivalence—enforced in CI with zero overhead for consumers.
- Core filtering, reporting, and plan-compilation logic is total and verified directly in Lean with zero
Add LSpec as a dependency and register a test driver executable in lakefile.toml:
testDriver = "tests"
[[require]]
name = "LSpec"
git = "https://github.com/argumentcomputer/LSpec"
rev = "main"
[[lean_exe]]
name = "tests"
root = "Tests.Main"Write your test suite in Tests/Main.lean (see also Examples/Examples.lean):
import LSpec
open LSpec LSpec.Prop
def mySuite : Spec := do
describe "Arithmetic" do
it "adds numbers" do
shouldBe (2 + 2) 4
shouldBeLt (3 : Nat) 5
itBool "multiplies numbers" (3 * 4 == 12)
prop "addition is commutative" fun (a b : Nat) =>
a + b == b + a
prop "subtraction with guard" fun (a b : Nat) =>
(Nat.ble b a) ==> (a - b + b == a)
def main (args : List String) : IO UInt32 :=
lspecMain mySuite argsRun via lake test or invoke the compiled binary directly:
# Run sequentially (default)
lake test
# Run with 4 worker threads (bounded concurrency for CI speed vs. RSS tuning)
lake test -- -j 4
# List all tests without running tests or acquiring resources
lake test -- --list
# Filter by path, exact path, exclusion, or tags
lake test -- Arithmetic --exclude slow --tag fast
# Reproduce a property-test failure with its reported seed
lake test -- --seed 123456789 --num-tests 200Inside it "description" do ..., assertions run in AssertM Unit (ExceptT AssertStop IO Unit) and capture the exact file:line:col of any failure:
| Function | Purpose |
|---|---|
expect cond / assertTrue cond |
Fail if cond == false (note: assert is a Lean 4 do-keyword) |
expectFalse cond / assertFalse cond |
Fail if cond == true |
expectAll conds / assertAll conds |
Fail with index on first false in Array Bool |
shouldBe actual expected |
BEq equality with Repr diff |
shouldNotBe actual unexpected |
BEq inequality |
shouldSatisfy actual pred label |
Boolean predicate check |
shouldBeLt / shouldBeLe / shouldBeGt / shouldBeGe |
Ord-based comparisons |
shouldContain / shouldContainSubstr |
List / String containment |
shouldReturn action expected |
Assert IO return value |
shouldThrow action expectedSubstr? |
Assert IO throws an error |
expectSome / expectNone |
Unwrap Option in do-notation |
expectOk / expectOkRepr / expectErr |
Unwrap Except in do-notation |
fail msg / pending / pendingWith reason |
Explicit failure or pending skip |
Properties accept arbitrary-arity functions returning Bool, AssertM Unit, Except String Unit, precondition guards (==>), or explicit generators (forAll, forAllShrink, forAllNoShrink, forAllNamed). Use propWith or withPropConfig to override sample counts, size, or seeds per test/subtree:
def propSuite : Spec := do
describe "Lists" do
prop "reverse involution" fun (xs : List Nat) =>
xs.reverse.reverse == xs
prop "append length (using AssertM)" fun (xs ys : List Nat) =>
shouldBe (xs ++ ys).length (xs.length + ys.length)
propWith "custom generator" { numTests := 200 } <|
forAll (Gen.chooseNat 10 20) fun n =>
Nat.ble 10 n && Nat.ble n 20Custom types only need Sampleable, Shrinkable (no WellFoundedRelation proof required), and Repr (or ToString / FormatValue):
structure Pair where
left : Nat
right : Nat
deriving BEq, Repr
instance : Shrinkable Pair where
shrink p :=
(Shrinkable.shrink p.left).map (fun l => { p with left := l }) ++
(Shrinkable.shrink p.right).map (fun r => { p with right := r })
instance : Sampleable Pair where
sample := return { left := ← Gen.chooseNat 0 (← Gen.getSize),
right := ← Gen.chooseNat 0 (← Gen.getSize) }--threads N/-j N: caps concurrent test execution toNworker threads. Completed test closures are dropped immediately upon finishing to keep peak RSS bounded.- Preventing closed-term hoisting: plain
def mySuite : Spec := do ...works for both top-level and parameterized suites. If a test module contains expensive closed pure expressions insideit/itBoolbodies, addset_option compiler.extract_closed false(ormoreLeanArgs = ["-Dcompiler.extract_closed=false"]on your test library) so Lean never hoists them into module initializers. sequential do .../parallel do ...: override concurrency per subtree. Asequentialsubtree runs its tests strictly in order as one pool job, while siblingsequentialsubtrees may still run concurrently if their parent isparallel.withResource/beforeAll: acquire a shared resource once for a subtree and release it infinallyafter all tests in that subtree complete. Never acquired during--listor when filtered out.beforeEach/afterEach/aroundEach: per-leaf lifecycle hooks.withTag/withTags: tag subtrees for--tagand--exclude-tagselection.withOptions/withPropConfig: scope configuration overrides to a subtree.
Any test executable whose main delegates to lspecMain (or defaultMain / defaultMainTree) automatically parses the flags below via LSpec.parseCliArgs. Pass them via lake test -- <flags>, lake exe <target> <flags>, or directly to the compiled binary (projects with custom drivers calling runSpec / runTree programmatically can reuse parseCliArgs or define their own CLI):
-j, --threads <N> Run up to N tests concurrently (default: 1)
--sequential Run all tests sequentially (alias for --threads 1)
--list List matching test paths and exit without running
<pattern> Run only tests whose path contains <pattern>
--filter <pattern> Same as positional <pattern> (repeatable)
--exact <path> Run only tests matching <path> exactly (repeatable)
--exclude <pattern> Exclude tests whose path contains <pattern>
--tag <tag> Run only tests carrying <tag> (repeatable)
--exclude-tag <tag> Skip tests carrying <tag> (repeatable)
--seed <u64> Master seed for deterministic property tests
--num-tests <N> Override property-test sample count
--max-size <N> Override property-test maximum generator size
--fail-fast Stop starting new tests after the first failure
--color / --no-color Force or disable ANSI color output
-v, --verbose Show extra details and captured output on passes
-h, --help Show this help message
--exclude=a,b, --tag=a,b, and --exclude-tag=a,b also accept comma-separated lists, and NO_COLOR disables ANSI colors when neither --color nor --no-color is passed.
The core pure functions in LSpec.Runner (filterTree, listTests, ReportTree.summarize, ReportTree.failures, compilePlan, computeWorkerCount) are total and formally verified in the optional LSpecProofs library (zero sorrys, zero external dependencies, zero runtime overhead for consumers):
- LSpecProofs/Filter.lean: filter soundness & completeness (
listTests_filterTree_eq), idempotence (filterTree_idempotent), empty-filter identity, exclusion dominance, and non-empty survivingwithResourcescopes (filtered-out resources are never acquired). - LSpecProofs/Report.lean: exact report accounting (
passed + failed + skipped = leafCount,failed = failures.size,allPassed ↔ failures.isEmpty), permutation invariance of summary counts across parallel completion orders,compilePlanequivalence withlistTests, deterministic per-test seed assignment, andcomputeWorkerCountbounds. - LSpecProofs/Concurrency.lean: small-step operational semantics of the bounded
WorkerPool+ExecPlanscheduler proving bounded concurrency (activeWorkers ≤ cap), sequential exclusion & strict left-to-right ordering,withResourceacquire/release bracketing (no child before acquire, no release before children finish, exact-once release on termination), deadlock freedom & strong normalization, and sequential–parallel confluence (parallel_eq_sequential). - LSpecProofs/Axioms.lean: compile-time
#guard_msgs in #print axiomsgate ensuring all 31 headline theorems rely exclusively on Lean's standard axioms (propext,Quot.sound,Classical.choice) with zerosorryAxor custom axioms, built with-DwarningAsError=truein CI.
Build and verify all proofs with:
lake build LSpecProofs --wfail