Testing in Osprey: real code, fake services

A test runs your real code with fake services. Code that charges a card, writes a file or calls an API asks for it through an effect. Production answers with a handler that does the real thing; a test answers with whatever the case needs: an approval, a decline, a full disk. No mocking library, no dependency injection, no test-only interface.

Tests are ordinary Osprey: test(name, body) runs a case and expect(actual, expected) checks a value. osprey test builds and runs them natively and prints the results.

Testing in Osprey: real code, fake services (4:16). Captions are on; choose a chapter to jump to it.

The code under test

A checkout charges a card through a Payments effect. It does not know which bank, or whether there is one:

/// Takes payment for an order. The caller decides who answers.
effect Payments {
    /// Charge `cents` to `card`; the receipt id, or why it was declined.
    charge: fn(string, int) -> Result<string, string>
}

/// The message a shopper sees after checkout.
fn checkout(card, cents) = match cents <= 0 {
    true => "nothing to pay"
    false => match perform Payments.charge(card, cents) {
        Success { value } => "paid, receipt ${value}"
        Error { message } => "declined: ${message}"
    }
}

The tests

Each test installs its own Payments handler, then calls the real checkout:

/// A stub: approves every charge with the same receipt.
fn approved(work) = {
    handle Payments {
        charge _card _cents => Success { value: "r-42" }
    }
    work()
}

/// A stub: declines every charge, as a bank does for an expired card.
fn declined(work) = {
    handle Payments {
        charge _card _cents => Error { message: "card expired" }
    }
    work()
}

test("an approved card gets a receipt", fn() => {
    expect(approved(fn() => checkout("4242", 1999)), "paid, receipt r-42")
})

test("a declined card says why", fn() => {
    expect(declined(fn() => checkout("4000", 1999)), "declined: card expired")
})

test("an empty order never reaches the bank", exactly(fn() => {
    mut charges = 0
    handle Payments {
        charge _card _cents => {
            charges = charges + 1
            Success { value: "r-42" }
        }
    }
    expect(checkout("4242", 0), "nothing to pay")
    expect(charges, 0)
}))
  • Stubs give canned answers: approved always approves and declined always declines.
  • Spies record what the code asked for: the third test counts charges and checks there were none.
  • Failure injection is a stub that returns Error. Every failure path is one handler away.

exactly makes integer arithmetic in a test fail the case on overflow instead of wrapping, so a test cannot pass on a wrong number.

Run them

The tests live beside the code in their own project. Its osprey.toml adds the code's folder as a source root:

[project]
name = "checkout-tests"
source_roots = [".", "../src"]
entry = "checkout.test.osp"
osprey test src/osprey/examples/testing/tests
ok 1 - an approved card gets a receipt
ok 2 - a declined card says why
ok 3 - an empty order never reaches the bank
1..3
# tests=3 passed=3 failed=0 skipped=0
# suites: 1 passed, 0 failed

The output is TAP; any failure exits with status 1. A directory without osprey.toml is searched for *.test.osp, *.test.ospml, *.test.py and *.test.ts files, one per flavor.

A failing test

Change cents <= 0 to cents < 0 in checkout, and an empty order reaches the bank. The spy catches it:

ok 1 - an approved card gets a receipt
ok 2 - a declined card says why
# expect failed: expected nothing to pay, got paid, receipt r-42
# expect failed: expected 0, got 1
not ok 3 - an empty order never reaches the bank
1..3
# tests=3 passed=2 failed=1 skipped=0
# suites: 0 passed, 1 failed

Assertions are soft: the case carries on, so you see every mismatch at once.

One case, and coverage

Run a single case by name with --filter:

osprey test src/osprey/examples/testing/tests --filter "a declined card says why"

Add --coverage to see which lines ran:

# coverage: 100.0% (5/5 lines) …/src/checkout.osp
# coverage: 84.6% (11/13 lines) …/tests/checkout.test.osp
# coverage total: 88.9% (16/18 lines)

The two uncovered lines are the spy's charge arm: the bank was never called. --coverage-json <path> writes the report for CI.

In VS Code

The Osprey extension lists every test file and case in the Testing view. Run or debug one case, a file or all of them; breakpoints inside a test stop. Run with Coverage shades covered and uncovered lines in the editor. A failed case shows each expect failure, with the expected and actual values, at that test.

Assertions

Assertion Passes when
expect(actual, expected) the two values are equal
check(label, expected, actual) the same, with a label in the failure message
expectTrue(x), expectFalse(x) x is true, or false
expectAll([a, b, …]), checkAll(label, [a, b, …]) every condition holds; each is reported separately
expectError(result, payload) result is an Error carrying payload

Values compare whole: records, unions, lists and Results at any depth. Comparing values of different types is a compile error, so expect(5, "5") never builds.

Hunt for bugs searches for crashing inputs; formal verification proves a property for every input. The testing specification has the full contract.

Transcript

  1. In this tutorial, we'll test a checkout that charges a credit card, without a bank, a network, or a mocking library. The tests run the real code, and only the services are fake.
  2. Here's the idea. In Osprey, a test is ordinary code. There's no special syntax and no test framework to install.
  3. Anything that talks to the outside world, like a payment provider, is an effect. The code asks for it, and a handler answers. In production, the handler calls the bank. In a test, the handler is whatever the test needs.
  4. So there's no mocking library, no dependency injection, and no interface added just for testing.
  5. Tests compile to native code, print standard TAP output, and measure line coverage.
  6. Here's the code under test. Payments is an effect: a list of things the code can ask for, with no implementation.
  7. It has one operation. Charge takes a card and an amount in cents, and returns a Result: a receipt id, or the reason the charge was declined.
  8. Checkout builds the message a shopper sees. An order of zero cents or less needs no payment, so it never asks the bank.
  9. Otherwise, it performs Payments dot charge, and matches on the answer. A receipt means paid. An error means declined, with the reason. Checkout doesn't know who answers.
  10. Now the tests. Approved is a stub. It installs a Payments handler that approves every charge with the same receipt, R forty two, and then runs the work it was given.
  11. Declined is another stub, for the same effect. It declines every charge, the way a bank does for an expired card. Injecting a failure is just a handler that returns an error.
  12. Each test calls test with a name and a function. The first runs the real checkout under the approving stub, and expects a receipt.
  13. The second runs the same checkout under the declining stub, and expects the reason. Same code, two different worlds.
  14. The third test is a spy. It checks what the code did, not just what it returned. It starts a counter at zero.
  15. Its handler counts every charge before approving it. Only the handler can change that counter.
  16. An empty order should say nothing to pay, and the bank should never be called. So the count must still be zero. Exactly makes any arithmetic overflow in the test fail the case, instead of quietly wrapping.
  17. Run the suite with osprey test, and the path to the test project. The tests compile to a native binary and run.
  18. Three cases, three passes. The output is TAP, which any CI system can read, and the exit status is zero.
  19. Now break it. Change one character in the guard: less than or equal to zero becomes less than zero. An empty order now goes to the bank.
  20. The spy catches it. The message is wrong, and the bank was charged once. Assertions are soft, so a failing case keeps going and reports every mismatch at once.
  21. Case three fails, the summary says so, and osprey test exits with status one, which fails the build.
  22. To run one case, pass its name with dash dash filter. Only that case runs.
  23. Add dash dash coverage to see which lines ran. Every line of checkout ran.
  24. Two lines of the tests did not. They're the spy's charge arm, and that's exactly what the spy proves: the bank was never called.
  25. A few assertions cover most tests. Expect checks that two values are equal. Check does the same, with a label for the failure message. And expect error checks that a Result failed, with the reason you name.
  26. Values compare whole, so records, lists and Results are checked at any depth. Comparing a number with a string is a type error, so that test never builds.
  27. There's more. In VS Code, the Testing view runs, debugs and covers any case. Osprey hunt searches for inputs that crash your program. Proofs go further and cover every input. And test files work in all four flavors.
  28. To try it, run the example suite, then break the guard and watch the spy catch it. The Testing guide on ospreylang dot dev has every step. Osprey is actively evolving. Try it on your projects, and tell us what breaks.