Home / Docs / Language guide

Examples as tests

Release v0.4.0
una
module demo

import std.testing (fake_hash)

pub kind Availability = SoldOut | Few | Open

pub kind Registration
  name: Text
  status: Availability

pub kind StoreError = Timeout | Corrupted

pub kind CheckInError = NotRegistered | Unavailable

pub capability Registrations
  op find(key: internal Hashed) -> Option[Registration]
    fails StoreError
    accepts internal

pub capability Audit
  op record(key: internal Hashed, status: Availability) -> Unit
    fails StoreError
    accepts internal

pub check_in(key: internal Hashed) -> Availability
  uses @registrations: Registrations[find]
  uses @audit: Audit[record]
  fails CheckInError
=
  let registration = @registrations.find(key)
    if error fail Unavailable
    if none fail NotRegistered
  @audit.record(key, status: registration.status)
    if error fail Unavailable
  registration.status

handler one_registration(r: Registration) for Registrations
  op find(key) = Some(r)

handler no_registrations() for Registrations
  op find(key) = None

handler audit_log() for Audit
  op record(key, status) = unit

example "a registered attendee is checked in and audited"
  given @registrations = one_registration(Registration(name: "Ana", status: Open))
  given @audit = audit_log()
  do check_in(fake_hash(1))
  expect result is Open
  expect performed @audit.record

example "an unknown attendee fails and is not audited"
  given @registrations = no_registrations()
  given @audit = audit_log()
  do check_in(fake_hash(1))
  expect fails NotRegistered
  expect not performed @audit.record
Line Meaning
given @x = h(args) install handler h as @x for this example
do e the expression under test
expect e e is a Bool over result and must be true
expect fails V do failed with variant V
expect performed @x.op the effect trace contains at least one op on @x
expect not performed @x.op the trace contains no op on @x

Constructs