Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ jobs:
- uses: leanprover/lean-action@50fcf42d2e460296f1a34b402e990d1b24f8b596 # v1.6.0
with:
build-args: "--wfail"
- name: Verify formal proofs
run: lake build LSpecProofs --wfail
- name: Run parallel test suite
run: lake exe tests -j 4
- name: Typecheck examples
run: lake env lean Examples/Examples.lean

# Builds the library and runs the test suite via Nix flake checks
nix-test:
Expand Down
282 changes: 73 additions & 209 deletions Examples/Examples.lean
Original file line number Diff line number Diff line change
@@ -1,219 +1,83 @@
import LSpec

/-!
# LSpec Examples

This file provides comprehensive examples of using LSpec for testing in Lean 4.

## Quick Reference

| Function | Use Case | Output |
|----------|----------|--------|
| `test` | Unit tests | `✓ ∃: name` |
| `check` | Property tests (simple) | `✓ ∃: name` |
| `check'` | Property tests (with syntax) | `✓ ∃₁₀₀: "name" (property)` |
| `checkIO` | Runtime property tests | Same as check |
| `checkIO'` | Runtime tests (with syntax) | Same as check' |
-/

section LSpec

open LSpec

/-! ## Basic Usage

The simplest way to run tests is with the `#lspec` command.
-/

#lspec test "Nat equality" (4 ≠ 5)
-- ✓ ∃: Nat equality

/-!
Tests can be composed into sequences using `$` or `++`.
The output shows `✓ ∃:` for each passing unit test.
-/

#lspec test "bool equality" (42 == 42) $
test "list length" ([42].length = 2) $ -- This fails
test "list nonempty" ¬ [42].isEmpty
-- ✓ ∃: bool equality
-- × ∃: list length
-- Expected to be equal: '1' and '2'
-- ✓ ∃: list nonempty

/-!
## Bounded Universal Quantification
open LSpec LSpec.Prop

Tests like `∀ n, n < 10 → P n` are automatically iterated.
-/

#lspec test "all lt" $ ∀ n, n < 10 → n - 5 < 5
-- ✓ ∃: all lt

/-!
## IO-based Tests

For runtime tests, use `lspecIO` with a HashMap of test suites.
-/

def fourIO : IO Nat := return 4
def fiveIO : IO Nat := return 5

def main := do
let four ← fourIO
let five ← fiveIO
lspecIO (.ofList [("IO tests", [
test "fourIO equals 4" (four = 4) $
test "fiveIO equals 5" (five = 5)])]) []

#eval main
-- IO tests
-- ✓ ∃: fourIO equals 4
-- ✓ ∃: fiveIO equals 5
-- 0

end LSpec

section SlimCheck
/-!
## Property-Based Testing with SlimCheck

SlimCheck generates random test cases to verify properties.
The output shows how many samples were tested.

### Basic Property Tests

Use `check` for simple output or `check'` to see the property syntax.
-/

open LSpec SlimCheck

-- Nat has a SampleableExt instance for random generation
example : SampleableExt Nat := by infer_instance

/-!
### Using `check'` (Recommended)

The `check'` macro captures the property syntax for display:
- Success shows: `✓ ∃₁₀₀: "name" (∀ n m : Nat, n + m = m + n)`
- Failure shows: `× ∃²/₁₀₀: "name" (property)` with counterexample
# LSpec Examples

The superscript indicates which sample failed, subscript shows total samples.
Demonstrates:
- Hspec-style `describe` / `context` / `it` / `itBool` / `xit`
- Bool-based expectations (`shouldBe`, `shouldContainSubstr`, `expect`)
- Bool-based property testing (`prop`, `==>`, `forAll`, custom `Sampleable`/`Shrinkable`)
- Scoped resources (`withResource`), tags (`withTag`), and `sequential` execution
- Bounded-thread CLI runner (`lspecMain`)
-/

#lspec check' "add_comm" (∀ n m : Nat, n + m = m + n)
-- ✓ ∃₁₀₀: "add_comm" (∀ n m : Nat, n + m = m + n)
/-! ## Custom type with `Sampleable` & `Shrinkable` -/

#lspec check' "mul_comm_wrong" (∀ n m : Nat, n * m = m * m)
-- × ∃⁶/₁₀₀: "mul_comm_wrong" (∀ n m : Nat, n * m = m * m)
-- ===================
-- Found problems!
-- n := 1
-- m := 2
-- issue: 2 = 4 does not hold
-- (2 shrinks)
-- -------------------

/-!
### Custom Types with SlimCheck

To use SlimCheck with custom types, define `Shrinkable` and `SampleableExt` instances.
-/

structure Pairs where
structure Pair where
left : Nat
right : Nat
deriving Repr

private def mkPairs (as : List α) (bs : List β) : List (α × β) :=
let mkPairsAux (a : α) (bs : List β) : List (α × β) := bs.map fun b => (a, b)
as.foldl (fun abs a => mkPairsAux a bs ++ abs) []

-- Shrinkable instance for reducing counterexamples
open Shrinkable in
instance : Shrinkable Pairs where
shrink := fun p =>
let shrinkl := shrink p.left
let shrinkr := shrink p.right
mkPairs shrinkl shrinkr |>.map fun (a, b) => ⟨a, b⟩

-- SampleableExt instance for random generation
open SampleableExt

def pairsGen : Gen Pairs := return ⟨← Gen.chooseAny Nat, ← Gen.chooseAny Nat⟩

instance : SampleableExt Pairs := mkSelfContained pairsGen

-- Now we can test properties over Pairs
#lspec check' "left + 2 ≤ right" (∀ pair : Pairs, pair.left + 2 ≤ pair.right)
-- × ∃¹/₁₀₀: "left + 2 ≤ right" (∀ pair : Pairs, pair.left + 2 ≤ pair.right)
-- ===================
-- Found problems!
-- pair := { left := 0, right := 1 }
-- issue: 2 ≤ 1 does not hold
-- ...

-- This passes (but note: ⟨0, 0⟩ would fail, showing shrink limitations)
#lspec check' "left + right > right" (∀ pair : Pairs, pair.left + pair.right > pair.right)
-- ✓ ∃₁₀₀: "left + right > right" (∀ pair : Pairs, pair.left + pair.right > pair.right)

/-!
### Weighted Random Generation with Gen.frequency

`Gen.frequency` creates weighted random generators for more realistic test data.
-/

inductive Command where
| noop
| read
| write
| delete
deriving Repr, DecidableEq

/--
Weighted command generator:
- noop: 10%, read: 50%, write: 30%, delete: 10%
-/
def commandGen : Gen Command :=
Gen.frequency #[
(1, pure Command.noop),
(5, pure Command.read),
(3, pure Command.write),
(1, pure Command.delete)
] (pure Command.noop)

instance : Shrinkable Command where
shrink := fun _ => []

instance : SampleableExt Command := mkSelfContained commandGen

#lspec check' "commands are valid" (∀ cmd : Command,
cmd = Command.noop ∨ cmd = Command.read ∨ cmd = Command.write ∨ cmd = Command.delete)
-- ✓ ∃₁₀₀: "commands are valid" (∀ cmd : Command, ...)

/-!
### Biased Number Generation

Generate numbers with custom distributions.
-/

def biasedSmallGen : Gen Nat :=
Gen.frequency #[
(5, Gen.choose Nat 0 10), -- 50%: small (0-10)
(3, Gen.choose Nat 11 100), -- 30%: medium (11-100)
(2, Gen.choose Nat 101 1000) -- 20%: larger (101-1000)
] (pure 0)

structure BiasedNat where
val : Nat
deriving Repr

instance : Shrinkable BiasedNat where
shrink := fun n => (Shrinkable.shrink n.val).map BiasedNat.mk

instance : SampleableExt BiasedNat := mkSelfContained (BiasedNat.mk <$> biasedSmallGen)

#lspec check' "biased numbers bounded" (∀ n : BiasedNat, n.val ≤ 1000)
-- ✓ ∃₁₀₀: "biased numbers bounded" (∀ n : BiasedNat, n.val ≤ 1000)

end SlimCheck
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) }

/-! ## Defining Suites -/

def mathSuite : Spec := do
describe "Math" do
context "addition" do
it "adds two numbers" do
shouldBe (2 + 2) 4
shouldBe (0 + 5) 5

itBool "is associative on small values" ((1 + 2) + 3 == 1 + (2 + 3))

prop "is commutative" fun (a b : Nat) =>
a + b == b + a

prop "with precondition guard" fun (a b : Nat) =>
(Nat.ble b a) ==> (a - b + b == a)

context "custom Pair generator" do
prop "sum is at least each component" fun (p : Pair) =>
Nat.ble p.left (p.left + p.right) && Nat.ble p.right (p.left + p.right)

prop "with explicit weighted generator" <|
let biasedGen : Gen Nat :=
Gen.frequency #[
(5, Gen.chooseNat 0 10),
(3, Gen.chooseNat 11 100),
(2, Gen.chooseNat 101 1000)
] (pure 0)
forAll biasedGen fun n => Nat.ble n 1000

def resourceExample : Spec := do
describe "Resources & Execution Modes" do
let tempResource : ResourceSpec String := {
description := "shared greeting"
acquire := pure "hello from fixture"
release := fun _ => pure ()
}
withResource tempResource fun getGreeting => do
it "reads shared resource" do
let msg ← getGreeting
shouldContainSubstr msg "fixture"

sequential do
it "runs first" do expect true
it "runs second" do expect true

withTag "slow" do
xit "pending integration check" do
pendingWith "not yet implemented"

def main (args : List String) : IO UInt32 :=
lspecMain (do mathSuite; resourceExample) args { threads := 4 }
Loading