Contents Open

DocsLanguage Guide

Documentation and Testing

Doc comments with runnable examples, tests, benchmarks and fuzz targets.

Code that others will use needs two things beyond working: documentation that says how to use it, and tests that show it keeps working. Sable builds both into the language and the toolchain. Doc comments are Markdown, and the examples in them are compiled and run as tests. Tests, benchmarks and fuzz targets are ordinary functions marked with an attribute, run by sable test, sable bench and sable fuzz.

This chapter covers comments and documentation first, then writing tests with the standard Sable.Testing module, then benchmarks and fuzzing, and finally the formatter and linter.

Comments#

Sable has the two comment forms you know from C, Swift and C#:

Sable
// A line comment runs to the end of the line./* A block comment can span   several lines. */

Unlike C's, block comments nest, so you can comment out a region that already contains one:

Sable
/*fn legacyTotal() -> Int {    /* the old way */    return 0}*/

An unterminated block comment is reported at its opening /*, not at the end of the file, so the error points at the comment that's missing its end.

To leave code out of the build depending on configuration, prefer #if (see Compile-Time Evaluation): the formatter preserves disabled regions exactly as written.

Documentation Comments#

A comment that starts with /// documents the declaration that follows it:

Sable
/// The number of items on hand, after reservations.public fn available(_ sku: String) -> Int {    // ...}

There are three forms:

Form Documents
/// text the declaration that follows; consecutive lines form one comment
/** text */ the declaration that follows, as a block
//! text the module; written as the first thing in a file
Sable
//! Stock levels, reservations and reorder points for the inventory service.module Inventory.Stock

Doc comments are Markdown#

The text of a doc comment is Markdown: paragraphs, code, emphasis, lists, links and fenced code blocks. By convention the first sentence is a summary that stands on its own, since tools show it in lists and completion popups.

Parameters, the result and errors are described with list items of a fixed shape:

Sable
/// Reserves stock for an order.////// Reservations are held until `release(_:)` is called or the order ships.////// - parameter sku: the item to reserve/// - parameter quantity: how many to hold; must be positive/// - returns: the quantity still available after the reservation/// - throws: `StockError.insufficient` if fewer than `quantity` are on handpublic fn reserve(_ sku: String, quantity: Int) throws(StockError) -> Int {    // ...}

Examples that run#

A fenced sable block in a doc comment is more than illustration: it is extracted, compiled and run as a test. An example that stops compiling, or whose assert fails, fails the build's tests, so documentation can't silently go out of date.

Sable
/// Adds two numbers.////// ```sable/// assert(add(2, 3) == 5)/// ```public fn add(_ a: Int, _ b: Int) -> Int {    return a + b}

sable test --doc runs these examples. Each block becomes a test in the documented file's module, with that file's imports and Sable.Testing, so an example can call the module's internal declarations and use expect as well as assert. The generated test keeps the example's original line numbers, so an error points into the doc comment itself.

An example that shouldn't be run, such as one needing a network or a fragment that isn't complete code, is fenced as ```sable ignore.

sable doc#

sable doc turns a package's doc comments into documentation:

Shell
sable doc            # HTML in target/docsable doc --open     # and open it in a browsersable doc --json     # a JSON symbol graph instead

The HTML has an index with a filter box, a page per module and per type, signatures with every type name linked to its page, and the /// and //! comments rendered as Markdown. In a package, it documents the library as a build compiles it, with its dependencies but not its tests. --json writes a symbol graph: every symbol, with edges for which members belong to which type, which types conform to which protocols, and what extends what. That is what other tools build on.

Writing Tests#

A test is a function marked @test. Tests usually live in a package's tests/ directory, which an ordinary build leaves out, and use the Sable.Testing module:

Sable
module InventoryTestsimport Inventoryimport Sable.Testing@testfn aNewShelfIsEmpty() {    let shelf = Shelf(label: "A1", capacity: 10)    expect(shelf.isEmpty)    expect(shelf.freeSlots() == 10)}
Shell
sable test

sable test builds the package's library and everything under tests/ and benches/, finds every @test function and runs them. A test passes if it returns, and fails if an expectation isn't met, it throws, or it traps. A test may be async and may throw:

Sable
@testasync fn restockingRecordsTheDelivery() throws {    let store = try await Store.open(inMemory: true)    try await store.restock("pen", quantity: 40)    expect(try await store.count("pen") == 40)}

Each test runs in a process of its own (or sharing a process only with tests that share a fixture), as many at once as there are processors. A test that traps ends only its own process; the rest carry on.

expect and require#

The Sable.Testing style uses two functions for checks:

  • expect(condition) records a failure and carries on, so a single run reports everything that doesn't hold.
  • require(condition) records a failure and ends the test, for when nothing after it would make sense. require(optional) gives back the value inside, or ends the test if there is none.
Sable
@testfn findingAnOrderByNumber() {    let orders = sampleOrders()    let order = require(orders.first { $0.id == 7 })     // ends the test if missing    expect(order.items.count == 2)    expect(order.total == 15.5, "the total includes tax")}

There is one way to write each check: the condition is ordinary code (==, <, contains, isEmpty). Sable.Testing has no family of matchers such as toEqual or toBeGreaterThan.

That's possible because of how a failure is reported. expect and require take a parameter whose default value is #expression (introduced in Compile-Time Evaluation), which captures how the condition was written and the value each part of it had:

expectation failed: names.count == 3 (NamesTests.sb:12)    the values differ       left: 2      right: 3             ^ first difference at character 0    names: ["Ada", "Grace"]

The condition is still evaluated once, normally, and may throw or await. A message, the optional second argument, is an @autoclosure, worked out only if the expectation fails.

assert, assertEqual and fail(...) also end a test with a message. In a file that imports Sable.Testing, the bare name assert means the testing module's version, which checks in every build, not only debug ones.

Richer comparisons#

A few functions say more than a condition's parts can:

  • expectEquivalent(got, expected) { $0.exclude(\.id); $0.ignoresOrder = true } compares two Debug values part by part and names each part that differs by its path: orders[2].lines[0].price: got 12, expected 10.
  • expectAll(values) { predicate } reports which elements the predicate fails for.
  • expect(values, containsInOrder: [...]) reports what is missing, and after what.
  • expectClose(a, b, within: 0.001) reports how far apart two numbers are.
  • requireAll("name") { ... } is a group of soft assertions: every expectation in the body is checked, then the test ends if any failed.

Errors#

expectThrows checks that code throws, and gives the error back for more checks:

Sable
@testfn reservingTooMuchFails() {    var stock = Stock(onHand: ["pen": 3])    expectThrows(StockError.insufficient) { _ = try stock.reserve("pen", quantity: 5) }    let error = require(expectThrows(StockError.self) { _ = try stock.reserve("ink", quantity: 1) })    expect(error.description().contains("ink"))}

expectThrows(E.self) { ... } wants an error of a type, expectThrows(error) { ... } that very error, expectThrows(saying: "text") { ... } one whose description says that, and expectThrows { ... } any error. expectNoThrow { ... } wants none, and gives the body's result. Each has an async form.

Code that traps#

A test that is supposed to trap says so with traps, optionally with text the trap's message must contain:

Sable
@test(traps: "index 2 is out of range for count 2")fn readingPastTheEndTraps() {    let pair = [1, 2]    _ = pair[2]}

Inside a test, expectPanic("text") { ... } and expectExit(status) { ... } run a body in a separate process and report how it ended.

Test Options#

@test takes options that control how a test is run:

Sable
@test(arguments: [("1", 1), ("-7", -7), ("+42", 42)], tags: ["parsing", "fast"], timeout: .seconds(5))fn parsesSignedIntegers(_ text: String, _ value: Int) throws {    expect(try Int.parse(text) == value)}
Option Effect
arguments: [...] runs the test once per element (a tuple per case for several parameters), or once per pair if given one array per parameter. Each case is a test of its own, named for its arguments: InventoryTests.parsesSignedIntegers("1", 1)
tags: [...] what --filter may select it by, and what reports carry
timeout: .seconds(5) fails it when it runs longer (also .milliseconds, .minutes); the report shows where every thread and task was
traps, traps: "text" it passes by trapping
retry: 3 tried again while it fails, up to that many more times
skip: "why", skip(if: condition, "why") not run, and reported as skipped with the reason
explicit run only when asked for by name (--exact) or with --explicit
serialized not run at the same time as another serialized test of its suite
collection: "name" not run at the same time as another test of the same collection

skip(if:) is for things a runner may not have: a pseudoterminal, a time zone database, root privileges. Skipping with a reason is better than a test that silently passes. What can only be found out as a test runs uses the skip("why") and skip(if:) functions instead, which throw.

Choosing tests to run#

Shell
sable test parses                              # names containing "parses"sable test --exact InventoryTests.parsesSignedIntegerssable test --filter 'tag:fast & !name:*Slow*'

--filter takes tag:, name: and file: terms combined with &, |, ! and parentheses, with * standing for any text. --junit, --trx and --json write results for CI systems, and --coverage reports the lines and branches the tests ran, writing target/coverage/lcov.info for editors and report tools.

Fixtures and Suites#

A fixture is something tests run with: a temporary directory, a database, a server. It is a type conforming to Fixture, with optional setUp() and tearDown() methods that may be async and may throw, and a lifetime:

Sable
final class Database: Fixture {    static var lifetime: FixtureLifetime => .PerSuite    var rows: String[>..] = []    async fn setUp() throws {        rows.append("seed")    }    async fn tearDown() throws {        print("database down")    }}

The lifetime is .PerTest unless the fixture says .PerSuite, .PerCollection or .PerPackage. A fixture may ask for other fixtures in its initialiser, provided they live at least as long.

A test function asks for a fixture by taking it as a parameter:

Sable
@testfn seededRowsAreThere(_ database: Database) {    expect(database.rows == ["seed"])}

A suite groups tests: a struct or class marked @suite, whose instance methods are @tests. It is made anew for each test, through an initialiser whose parameters are all fixtures. @suite takes the same options as @test, except arguments and traps; its tags are added to its tests', and what a test says itself wins. A suite that is itself a Fixture has its own setUp and tearDown around each test.

Sable
@suite(tags: ["storage"], collection: "stores")final class StoreTests: Fixture {    let database: Database    init(database: Database) {        self.database = database    }    @test    fn aFixtureIsSetUpBeforeItsTest() {        expect(database.rows == ["seed"])    }}

Tests that share a fixture run in one process, one after another, and the fixture is torn down after the last of them. Teardown happens whether the tests passed, failed, threw or were skipped.

TestContext.current describes the running test: its name, tags, which attempt it is, the time it has left, a cancellation token, and log and attach for output that is shown when the test fails.

Fakes#

Tests should not depend on the clock, the network or scheduling. Sable.Testing and friends provide fakes to pass in instead: TestClock (Sable.Concurrency) for time, InMemoryFileSystem (Sable.IO) for files, FakeLogger to capture log records, and FakeRandom for random numbers from the run's seed. Code under test takes a Clock, FileSystem, Logger or RandomNumberGenerator, and the test gives it the fake.

Snapshots#

assertSnapshot(value, named: "summary") compares a value's description with a file kept in __snapshots__/ beside the test. sable test --bless writes the snapshots from what the tests produce, to create one or accept a change after reviewing it. A missing snapshot is a failure.

Mocks#

@mockable on a protocol has a source generator (see Derivation and Source Generators) write Mock<Name>, a class conforming to it. Through its on property you stub calls and verify them:

Sable
import Sable.Testing@mockableprotocol PaymentGateway {    fn charge(amount: Int, to card: String) throws(PaymentError) -> Receipt    fn balance() -> Int}@testfn aDeclinedCardIsReported() {    let gateway = MockPaymentGateway()    gateway.on.charge().returns(Receipt(id: 1)).throwing(.Declined)    expect(checkout(gateway) == 1)    expect(checkout(gateway) == -1)    gateway.on.charge().verify(.exactly(2))}

Stubs answer in turn, the last one repeating: .returns(v), .throwing(e), or .does { arguments in ... }. Arguments are matched with .any (the default), .equal(x), .matching { ... } or plain values. A loose mock, the default, answers unstubbed calls with an empty value; a strict one fails the test.

Property Tests#

An example test checks one input. A property test checks that something holds for many inputs. forAll runs its body with a hundred arbitrary values, from small to large:

Sable
@testfn sortingTwiceChangesNothing() {    forAll { (xs: Int[>..]) in        let once = xs.sorted()        expect(once.sorted() == once)        expect(once.count == xs.count)    }}

If the property fails, forAll shrinks the failing input to the simplest one it can find and reports it with the seed that reproduces it. The inputs are the same on every run, so a failure means something changed, not bad luck. sable test --seed <n> runs with another seed, such as the one a failure reported.

The values come from the Arbitrary protocol, from Derivation and Source Generators: the built-in types, optionals, arrays, dictionaries, sets and ranges conform, and @derive(Arbitrary) makes your own structs, enums and unions conform too. For values with an invariant, write arbitrary(from:) yourself or pass a generator:

Sable
struct Even: Arbitrary {    let value: Int    static fn arbitrary(from choices: Choices) -> Even {        return Even(value: Int(choices.draw(upTo: 1000)) * 2)    }}@testfn evenNumbersHalveExactly() {    forAll { (even: Even) in        expect(even.value / 2 * 2 == even.value)    }    forAll(Gen.number(in: 0...9).array(count: 1...5)) { digits in        expect(digits.allSatisfy { $0 < 10 })    }}

A value is made from Choices, numbers drawn at random and recorded, and is shrunk by simplifying those choices rather than the value itself. So Arbitrary has a single requirement, with no separate shrink, and values made with Gen's map, flatMap and filter shrink too.

Benchmarks#

A benchmark is a function marked @bench, usually in a package's benches/ directory. It takes a Bencher and hands its iterate the code to measure:

Sable
import Sable.Testing@bench(arguments: [64, 65536], tags: ["hash"])fn digest(_ b: Bencher, _ size: Int) {    let bytes = U8[>..](repeating: 7, count: size)    b.bytesPerIteration = size    let last = b.iterate { Sha256.hash(bytes) }    b.check("\(last.bytes[0])")}
  • iterate { ... } runs the body many times and gives back what it returned last. What it returns is hidden from the optimiser, so the work isn't optimised away.
  • bytesPerIteration and itemsPerIteration add a throughput to the report.
  • check(text) records what was computed, which must be the same in every run; if it isn't, the run fails.

Without a Bencher parameter, the whole body is timed.

Shell
sable benchsable bench --save-baseline beforesable bench --baseline beforesable bench --compare main --fail-on-regression

sable bench builds optimised and runs each benchmark in its own process: a pilot to choose how many iterations make a sample, a warm-up, then samples until the result is precise enough, plus a run counting allocations, bytes, retains and releases. The report gives the mean with its confidence interval, the median and the allocations per operation. --counters also reads instruction and cycle counts where the system allows.

--save-baseline keeps the samples under a name, and --baseline compares a later run with them. --compare <git ref> builds the benchmarks as they were at a commit and compares the two. A benchmark has regressed when a Mann-Whitney test is confident it is slower and its median is slower by more than a threshold (5% by default). --fail-on-regression makes that fail the command, for CI.

Fuzzing#

A fuzz target is a function marked @fuzz that takes raw bytes, U8[:], or one to four Arbitrary values, and fails by trapping or throwing:

Sable
import Sable.Testing@fuzzfn parsingNeverTraps(_ input: U8[:]) {    _ = try? Manifest.parse(String.fromUtf8Lossy(input))}@fuzzfn roundTripsThroughJson(_ order: Order) throws {    let back = try Json.decode(Order.self, from: try Json.encode(order))    precondition(back == order)}
Shell
sable fuzz parsingNeverTraps --duration 1hsable fuzz --replay

sable fuzz builds the program with libFuzzer and AddressSanitizer and keeps generating inputs until --duration is up or you stop it. Inputs that reach new code are kept in target/fuzz/<target>/corpus/, and those that fail in crashes/, each then minimised and reported. A target that takes Arbitrary values has them made from the input bytes, so the fuzzer's mutations become changes of choices.

Everything the fuzzer kept becomes part of your tests: sable test runs each saved failure as a test, and the corpus as one more. A bug found once stays fixed.

@fuzz(mutator: f) names a function of the module, f(_ input: U8[:], _ seed: U64) -> U8[>..], that makes new inputs from an existing one, for formats where random byte changes rarely produce anything valid. A libFuzzer dictionary of tokens can be given as fuzz/<target>.dict or --dict.

Note

libFuzzer comes with LLVM's clang, not Apple's. On macOS with Apple's toolchain, sable fuzz says so and how to get LLVM's; sable fuzz --replay still works there.

Formatting and Linting#

sable fmt formats code in the one Sable style, and has no options, by design: there is nothing to configure and nothing to argue about. sable fmt --check reports files that aren't formatted, for CI.

sable check type-checks and runs the lints; sable lint runs only the lints, and sable lint --list lists them with their levels. A lint is error, warn or allow, configured per package in the manifest's lints and locally with attributes, which may be repeated:

Sable
@allow(unused_parameter)fn onEvent(_ event: Event, _ context: Context) {    handle(event)}

The built-in lints are unused_local, unused_parameter, unused_private, unused_import, unused_result, shadowed_local, shadowed_parameter, var_never_mutated, let_discard, self_assignment and constant_arithmetic. @warn(...) turns one back on for a declaration.

sable fix applies the fixes lints suggest, such as turning a var that is never changed into a let or removing an unused import; sable fix --check shows what it would change.

Sable

A systems language with value semantics, automatic reference counting, move-checked resources and compile-time checks on how memory is used, compiled ahead of time to native code through LLVM.

Sable is pre-1.0: the language, the standard library and the toolchain work end to end, but expect changes between versions.