Skip to content

std::literals::testing

Tests for a CheckedLiteral (std::literals). Its check runs when the program is checked and its build when the program runs, and build may not fail once check has accepted the literal’s text. build_each runs both as the compiler and the program would, over slot values a test chooses, so a library’s tests can show that build keeps to this: a value that makes build trap fails the test.

Import with import std::literals::testing.

fn build_each<I, T>(statics: List<String>, values: List<I>, check: (List<String>) -> Result<Unit, LiteralError>, build: (List<Fragment<I>>) -> T) -> Result<List<T>, LiteralError>

Runs check over statics, the text around a literal’s slots, and when it accepts, runs build once per value with that value in every slot. Returns the built results in the order of values, or check’s error. A build that fails for a value traps, and the test fails there. Every slot gets the same value in one build; a test of mixed slot values calls build itself.

For a literal whose slots take an interface, name it as the first type argument so the values are held as it:

import std::display.Display
import std::url.Url

assert Ok(urls) = build_each<Display, Url>(["/users/", ""], ["a/b", 7], Url.check, Url.build)
assert Iter.map(urls, fn u -> "${u}") |> Iter.to_list() == ["/users/a%2Fb", "/users/7"]

built = build_each(["a", "b"], ["x", "y"], fn _ -> Ok(Unit), fn fragments -> Iter.count(fragments))
assert built == Ok([3, 3])

refused = build_each(["a"], ["x"], fn _ ->
    Err(LiteralError{fragment: 0, offset: 0, message: "no"})
end, fn _ ->
    0
end)

assert refused == Err(LiteralError{fragment: 0, offset: 0, message: "no"})