# Testing

URL: /docs/tour/testing
Markdown: /docs/tour/testing.md

> Unit tests, property tests, contract-generated tests, snapshots, and deterministic handlers in Sakura Lang.

Tests are part of the language. You write `test` blocks next to the code they check, and `sakura test` runs them.

```sakura
fn greet(name: String) -> String { "Hello, {name}" }

test "greets by name" {
  expect_eq(greet("Ada"), "Hello, Ada")
}
```

```bash
sakura test
```

```text
test greets by name ... ok

1 passed, 0 failed, 0 skipped (seed 0)
```

- `test "name" { … }` is a top-level item, like a function. It has a name and a block.
- `expect_eq` is an **assertion**: a check that records a failure when it does not hold. The test keeps running after a failed assertion, and the runner marks the test failed at the end.
- The assertions are in the prelude, so you do not import them.

## Assertions [#assertions]

| Assertion                       | Passes when                                                           |
| ------------------------------- | --------------------------------------------------------------------- |
| `expect(cond)`                  | `cond` is `true`.                                                     |
| `expect_eq(actual, expected)`   | The values are equal. Both must be `Eq` and `Show`.                   |
| `expect_fail(fn() { … }, err)`  | The body fails with exactly `err`.                                    |
| `expect_fails_with(fn() { … }, pred)` | The body fails with an error for which `pred` returns `true`.   |
| `expect_defect(fn() { … })`     | The body defects. It runs in a child task.                            |
| `expect_output(lines)`          | The test's captured `Console` and `Log` output so far is exactly `lines`. |
| `expect_snapshot(name, value)`  | `value` renders the same as the stored snapshot.                      |

## Testing errors [#testing-errors]

An expected failure in Sakura Lang is a value, an `error` tag (see [Effects](/docs/tour/effects)). So a test can compare it like any other value. `try` without `catch` turns a failing call into a `Result`:

```sakura
error ParseError(input: String)

fn parse_age(s: String) -> Int ! {Fail<ParseError>} {
  match String.parse_int(s) {
    Some(n) if n >= 0 => n,
    _ => fail ParseError { input: s },
  }
}

test "bad age is a typed failure" {
  let r = try { parse_age("x") }
  expect_eq(r, Err(ParseError { input: "x" }))
}

test "same check with expect_fail" {
  expect_fail(fn() { parse_age("x") }, ParseError { input: "x" })
}

test "a typed failure that escapes fails the test" {
  let age = parse_age("41")    // a ParseError here fails the test with its Show
  expect_eq(age, 41)
}
```

- A test may call functions that fail. If a failure escapes the test body, the test fails and reports `failed with <the error>`, for example `failed with ParseError { input: "x" }`.
- Use `expect_fail` when the failure is the result you expect.
- Postfix `?` works on a `Result` inside a test, as it does anywhere else.

## Testing defects [#testing-defects]

A **defect** is a bug that stops the program, not a normal error. A broken [contract](/docs/tour/contracts) is a defect, and so is integer overflow. `try` cannot catch a defect, so use `expect_defect`:

```sakura
fn clamp(x: Int, lo: Int, hi: Int) -> Int
  requires lo <= hi
{ Int.clamp(x, lo, hi) }

test "precondition is a caller defect" {
  expect_defect(fn() { clamp(1, 5, 0) })
}
```

## Tests swap handlers [#tests-swap-handlers]

A **handler** is the code that decides what an effect does when it runs (see [Handlers](/docs/tour/handlers)). Tests run with fixed, predictable handlers, so a test gives the same result every time:

| Effect    | Default handler in tests          |
| --------- | --------------------------------- |
| `Clock`   | `Clock.fixed(Instant.from_unix_millis(0))` |
| `Random`  | `Random.seeded(seed)`, seed from `--seed` |
| `Env`     | `Env.of(Map.empty())`             |
| `Console` | `Console.captured()`              |
| `Log`     | `Log.captured()`                  |

Printed output is captured, so you can check it with `expect_output`:

```sakura
fn announce(name: String) -> Unit ! {Console} {
  Console.print("hello, {name}")
}

test "prints a greeting" {
  announce("Sakura Lang")
  expect_output(["hello, Sakura Lang"])
}
```

Any other effect must be handled inside the test with `with`. Otherwise the compiler reports `V3020` (for example, "test uses Sql; install a handler with `with`"). So a unit test cannot reach a real database or the network by accident. The runner also denies network access.

### No mocking library [#no-mocking-library]

An effect is already an interface, so a fake is just another handler. Here a user-defined effect gets an in-memory handler that keeps state:

```sakura
effect Counter {
  fn next() -> Int
  fn reset() -> Unit
}

fn memory_counter(start: Int) -> Handler<Counter> {
  handler Counter {
    var n: Int = start
    fn next() { n = n + 1; n }
    fn reset() { n = start }
  }
}

fn label_all(items: List<String>) -> List<String> ! {Counter} {
  List.map(items, fn(item) { "{Counter.next()}. {item}" })
}

test "labels count from the handler's start" {
  let out = with memory_counter(0) { label_all(["a", "b"]) }
  expect_eq(out, ["1. a", "2. b"])
}

test "inner handler shadows outer" {
  let out = with memory_counter(0) {
    with memory_counter(100) { Counter.next() }
  }
  expect_eq(out, 101)
}
```

### Fakes in the standard library [#fakes-in-the-standard-library]

The standard library ships fakes for its own effects:

| Fake                          | Replaces                                              |
| ----------------------------- | ----------------------------------------------------- |
| `Sql.memory()`                | A database.                                           |
| `Http.scripted(script)`       | The HTTP client, answering from a list of request matchers and responses. |
| `Fs.memory(files)`            | The filesystem, from a list of `(path, bytes)` pairs. `Dir.subdir` and `Fs.rooted` narrow it as on the host. |
| `Llm.scripted(responses)`     | A model provider. `Llm.replay(path)` replays a recording. |
| `Clock.virtual()`             | The clock. Time advances only when told to. Install it outermost, or a `Clock.sleep` inside your own handler sees the default `Clock.fixed`. |
| `Task.deterministic(seed)`    | The task scheduler. The order tasks run in is the same on every run. |

An in-memory filesystem works with directory narrowing too. The inner handler writes to the same store, using paths relative to its subdirectory:

```sakura
import std/fs.{Dir, Fs}
import std/path.{Path}

test "memory directories share writes through rooted handlers" {
  with Fs.memory([(Path.of("notes/a.txt"), String.to_bytes("before"))]) {
    let notes = Dir.subdir(Fs.root(), "notes")
    with Fs.rooted(notes) {
      expect_eq(Fs.read(Path.of("a.txt")), String.to_bytes("before"))
      Fs.write(Path.of("a.txt"), String.to_bytes("after"))
    }
    expect_eq(Fs.read(Path.of("notes/a.txt")), String.to_bytes("after"))
  }
}
```

## Property tests [#property-tests]

A **property test** checks a rule against many generated inputs instead of one example. A `property` takes typed parameters; the runner generates values for them and runs the body many times. Write the parameter types out.

```sakura
fn normalize(xs: List<Int>) -> List<Int> { List.unique(List.sort(xs)) }

property "normalize is idempotent"(xs: List<Int>) {
  expect_eq(normalize(normalize(xs)), normalize(xs))
}

property "normalize preserves membership"(xs: List<Int>, x: Int)
  requires List.contains(xs, x)
{ expect(List.contains(normalize(xs), x)) }
```

- A `requires` clause on a property keeps only the inputs that satisfy it. Like every contract, it must be in the [contract subset](/docs/tour/contracts#the-contract-subset).
- Runs are seeded. `sakura test --json` reports each test's seed, and `sakura test --seed N --filter "normalize"` reruns a case.

Property parameters always get generators derived from their types. When you need different inputs, write a `test` that drives the generators in `std/gen` yourself:

```sakura context=normalize
import std/gen

test "normalize output is strictly ascending" {
  gen.for_all(gen.list(gen.int(-5, 5), 20), 200, fn(xs) {
    let ys = normalize(xs)
    if List.len(ys) > 1 {
      expect(List.zip(ys, List.slice(ys, 1, List.len(ys))).all(fn(p) { p.0 < p.1 }))
    }
  })
}
```

## Property tests from contracts [#property-tests-from-contracts]

`sakura test --contracts` writes property tests for you. For each eligible `pub fn` with a refined parameter or a `requires` clause, it adds a property named `contract: <fn>`:

- It generates inputs from the parameter types and keeps those that pass the refinements and `requires`. It does not solve arbitrary preconditions.
- Each call checks `ensures` and refinements at runtime. A defect fails the property; a typed `Fail` is an allowed outcome.

### Catching an ensures bug [#catching-an-ensures-bug]

Put this deliberately broken function in `src/main.sak` of a package with a `sakura.toml`:

```sakura
pub fn increment(x: Int) -> Int
  requires x >= 0
  ensures result > x
{ x }
```

Run:

```sh
sakura test --contracts --seed 42
```

The command exits `3` and reports `contract: increment` as failed. It shrinks the failing input to the smallest one it finds, `x = 0`, with defect `D021` (postcondition violated), and writes `tests/regressions/increment.json`:

```json
{
  "schema_version": "1.0",
  "kind": "regression",
  "function": "increment",
  "seed": 42,
  "inputs": {
    "x": 0
  },
  "failure": "defect D021: postcondition `increment` of increment violated"
}
```

- Run the same command again: the failure says `(stored regression replayed)`.
- Change the body to `{ x + 1 }` and it passes, including the saved case.
- Keep the regression file. Saved cases still run after they pass.
- Plain `sakura test` does not generate these properties; pass `--contracts`.

### Eligibility and limits [#eligibility-and-limits]

- Functions with effects other than `Fail`, `Clock` and `Random` need `@contract_test(handlers: [Sql.memory(), Log.captured()])`. Import the effect names. Each entry must be a zero-argument `Effect.constructor()` call that returns a handler. Handler state starts fresh for each case.
- Generic and effect-polymorphic functions, `@external` and `@llm` functions, and parameters the runner cannot generate (such as functions or handlers) are skipped. Generic refined types themselves work; see [refinements](/docs/tour/contracts#generic-refinements).
- If more than 90% of candidates are discarded, the property fails with exit `3` and warning `W7001`. That does not prove the precondition is impossible.
- The regression file is named after the function only, so same-named functions in different modules share a file.
- Passing generated tests gives the `tested` status, never `proved`.

## Snapshot tests [#snapshot-tests]

A **snapshot** is a stored copy of a value's printed form. `expect_snapshot` compares a value's [`Show` output](/docs/tour/types#show-output) with the file `tests/__snapshots__/<module>/<name>.snap`. Here the stored snapshot is `[1, 2, 3]`:

```sakura context=normalize
test "rendering is stable" {
  expect_snapshot("normalize_doc", normalize([3, 1, 3, 2]))
}
```

- The `Show` format is the same on every backend, so snapshots do not depend on the target.
- `Secret<T>` is not `Show`, so a secret cannot end up in a snapshot.
- After a reviewed change, `sakura test --update-snapshots` rewrites the stored files.

## Deterministic simulation [#deterministic-simulation]

Time, randomness, task scheduling and the network are all effects. Install predictable handlers for all of them and even a concurrent test runs the same way every time. There is no separate simulator; `with` is the whole mechanism.

```sakura context=fetch-both
test "deterministic under virtual time" {
  with Http.scripted([(Matcher.Any, Response.status(200, "x"))]), Clock.virtual(), Random.seeded(1), Task.deterministic(1) {
    expect_eq(fetch_both(Url.from("https://a"), Url.from("https://b")), ("x", "x"))
  }
}
```

`fetch_both` (from [Concurrency](/docs/tour/concurrency#timeouts-retries-and-budgets)) starts two tasks, retries with backoff, and wraps everything in a timeout. Under these handlers, sleeps and timeouts use virtual time, and tasks run in an order fixed by the seed.

Under the default `Clock.fixed`, `Clock.sleep` returns at once, so a `timeout` whose action waits fails at once. Install `Clock.virtual()` to test timeouts.

To test what happens while requests are in flight, hold them back with a handler that sleeps on virtual time before forwarding. Install it inside `Clock.virtual()`, so its `Clock.sleep` reaches the virtual clock. Two requests held 100 ms each, sent together, finish at 100 ms of virtual time, which shows they were in flight at once:

```sakura
import std/http.{Http, Matcher}
import std/request.{Method, Request}
import std/response.{HttpError, Response}
import std/url.{Url}

fn gate(ms: Int) -> Handler<Http, {Clock, Http}> {
  handler Http {
    fn send(req) {
      Clock.sleep(Duration.millis(ms))
      Http.send(req)
    }
    fn stream(req, body) { Http.stream(req, body) }
    fn read_chunk(b, max) { Http.read_chunk(b, max) }
  }
}

fn status(u: String) -> Int ! {Http, Fail<HttpError>} {
  Http.send(Request.of(Method.Get, Url.from(u))).status
}

test "two gated requests are in flight together" {
  with Clock.virtual(), Task.deterministic(1),
      Http.scripted([(Matcher.Any, Response.status(200, "ok"))]), gate(100) {
    let codes = Task.all([fn() { status("https://a.test/") }, fn() { status("https://b.test/") }])
    expect_eq(codes, [200, 200])
    expect_eq(Clock.monotonic(), Duration.millis(100))
  }
}
```

## Running tests [#running-tests]

```bash
sakura test                                  # all tests and properties
sakura test --filter "normalize"             # tests whose name matches
sakura test --seed 42                        # fix the seed
sakura test --contracts                     # also generate contract properties
sakura test --json                           # JSON Lines records for agents
sakura test --update-snapshots               # rewrite snapshot files
```

- `sakura test` exits `3` when tests fail and `1` when the program has compile errors.
- The runner limits each test's time and memory and denies network access.
- `sakura test` never gets host permissions. To test a program against the real host, run it with `sakura run` and drive it from a script, as [`repair-queue/integration.sh`](https://github.com/icantcodefyi/sakuralang/blob/main/dogfood/repair-queue/integration.sh) does: start it, send requests, stop it, restart it and read back.
- A passing test gives its claims the `tested` status in the [guarantee model](/docs/tour/contracts#the-guarantee-model), never `proved`.

## What the compiler and runner check [#what-the-compiler-and-runner-check]

- Tests and properties are type and effect checked like any other code.
- Every effect a test uses, other than `Fail`, is handled by a default or by a `with` in the test (`V3020`).
- Generated arguments satisfy parameter types, refinements, and `requires`.
- When an agent repairs code, test and property bodies are frozen (`V8020`), so an agent cannot edit a test to make it pass.

## Next [#next]

[Capabilities and security](/docs/tour/capabilities): how handlers decide what a program can reach.

Details for contributors: [design §5.8, §8.7, §10.6, §15.10](https://github.com/icantcodefyi/sakuralang/blob/main/docs/design.md).
