Examples · 16 of 339
16-tests
Tests live next to the code they test.
tin run examples/16-tests.tin// Tests live next to the code they test.
//
// tin test examples/16-tests.tin runs every `test` block
// tin run examples/16-tests.tin runs main; the tests are still type-checked
//
// Each test runs in a fresh instance of the program. A test fails if it panics,
// and `assert` and `assertEq` are the usual ways to make it.
type Cart = { items: string[], total: int }
fn add(cart: inout Cart, item: string, price: int) {
cart.items.push(item)
cart.total += price
}
fn discount(total: int, percent: int): Result<int, string> {
if percent < 0 || percent > 100 { return Err("percent must be between 0 and 100") }
Ok(total - total * percent / 100)
}
/// The price of an item, in cents.
tool fn price(item: string): int => match item {
"tea" => 300
"cake" => 450
_ => 0
}
agent Clerk { model: "mock", tools: [price] }
test "a cart adds up" {
var cart = Cart { items: [], total: 0 }
add(&cart, "tea", 300)
add(&cart, "cake", 450)
assertEq(cart.total, 750)
assertEq(cart.items, ["tea", "cake"])
}
test "discounts are checked" {
assertEq(discount(1000, 25), Ok(750))
assertEq(discount(1000, 0), Ok(1000))
assert(discount(1000, 150).isErr(), "150% should be refused")
}
test "tasks finish before a test does" {
let slow = spawn discount(200, 50)
sleep(5ms)
assertEq(await slow, Ok(100))
}
test "an agent can be tested offline" {
// the mock model calls the tool the prompt names, with the quoted string
assertEq(Clerk("what is the price of 'cake'?"), "mock: 450")
assertEq(Clerk.turns(), 2)
}
fn main() {
var cart = Cart { items: [], total: 0 }
add(&cart, "tea", price("tea"))
print("{cart.items} cost {discount(cart.total, 10)}")
} ["tea"] cost Ok(270)