toast.um

const VERSION

The current version number of the library, formatted as specified by the Semantic Versioning Specification.

const VERSION* = "0.4.1"

type TestFn

The signature of a test function.

TestFn* = fn (ctx: ^Context)

type TestInfo

Information about a test.

TestInfo* = struct {
name: str        // Name of the test.
func: TestFn     // The function attached to this test.
result: std::Err // The final result of this test.
time: real       // The time it took for this test to pass *or* to fail.
// other unexported fields

type Context

The definition of a testing context.

Context* = struct {
// Holds all of the registered tests. You can query this array
// after calling `run()` to see the results and time taken for each test.
tests: []TestInfo

// A weak pointer to the currently processed test.
// It is only valid within the test functions.
current: weak ^TestInfo

// Holds the assertion functions.
assert: Assertions

// Toggles color printing.
printWithColor: bool

// Whether to use the compact or the verbose output.
compactOutput: bool

// other unexported fields...

fn newContext

Returns a new, default Context.

Defaults:

  • compactOutput: true
  • printWithColor: false
fn newContext*(): ^Context {

fn (^Context) pass

Marks this test as passing. You should immediately return once calling this.

fn (c: ^Context) pass*(msg: str = ""): bool {

fn (^Context) fail

Marks this test as failed. You should immediately return once calling this.

fn (c: ^Context) fail*(msg: str, code: int = -1): bool {

fn (^Context) startCustom

Marks the start of a custom assertion. This must be called at the beginning of all custom assertions.

fn (c: ^Context) startCustom*() {

fn (^Context) endCustom

Marks the end of the custom assertion. The intended return boolean must be passed through this function and that value must be returned instead: return T.endCustom(returnVal).

fn (c: ^Context) endCustom*(res: bool): bool {

fn (^Context) assert.isTrue

Asserts that cond is true. If the resulting bool is false, the caller should return immediately. If msg is not "", prints an extra reason alongside the error.

fn (a: ^Assertions) isTrue*(cond: bool, msg: str = ""): bool {

fn (^Context) assert.isFalse

Asserts that cond is false. Everything else from assert.isTrue applies. (Currently, this is literally just a call to assert.isTrue with the condition inverted.)

fn (a: ^Assertions) isFalse*(cond: bool, msg: str = ""): bool {

fn (^Context) assert.isOk

Asserts that e's code is 0. If the resulting bool is false, the caller should return immediately.

If msg is not "", prints an extra reason alongside the error. If it is, it defaults to e's error message.

fn (a: ^Assertions) isOk*(e: std::Err, msg: str = ""): bool {

fn (^Context) assert.sameType

Asserts that a and b have the same type. If the resulting bool is false, the caller should return immediately. If msg is not "", prints an extra reason alongside the error.

fn (a: ^Assertions) sameType*(va, vb: any, msg: str = ""): bool {

fn (^Context) registerTest

Registers a single new test. Will throw a fatal error if the name is already registered with this context.

fn (c: ^Context) registerTest*(name: str, func: TestFn) {

fn (^Context) registerTests

Registers various tests consecutively. Will throw a fatal error if any of the keys are registered as names for tests with this context.

fn (c: ^Context) registerTests*(tests: []TestInfo) {

fn (^Context) run

Runs each of the tests registered to this context, and returns whether any single one of them had an error.

quitIfErr exits the application after every test is run, if any single one of them threw an error.

fn (c: ^Context) run*(quitIfErr: bool = true): bool {

import "std.um"

//~~const VERSION
// The current version number of the library, formatted as specified by
// the [Semantic Versioning Specification](https://semver.org/).
const VERSION* = "0.4.1"
//~~

type (

//~~type TestFn
// The signature of a test function.
TestFn* = fn (ctx: ^Context)
//~~

//~~type TestInfo
// Information about a test.
TestInfo* = struct {
    name: str        // Name of the test.
    func: TestFn     // The function attached to this test.
    result: std::Err // The final result of this test.
    time: real       // The time it took for this test to pass *or* to fail.
    // other unexported fields
//~~

    funcDepth: uint
}

Assertions = struct { ctx: weak ^Context }

//~~type Context
// The definition of a testing context.
Context* = struct {
    // Holds all of the registered tests. You can query this array
    // after calling `run()` to see the results and time taken for each test.
    tests: []TestInfo

    // A weak pointer to the currently processed test.
    // It is only valid within the test functions.
    current: weak ^TestInfo

    // Holds the assertion functions.
    assert: Assertions

    // Toggles color printing.
    printWithColor: bool

    // Whether to use the compact or the verbose output.
    compactOutput: bool

    // other unexported fields...
//~~

    customAsserts: []std::Err
}

)

fn eprintln(text: str = "") { fprintf(std::stderr(), "%s\n", text) }
fn eprint(text: str = "") { fprintf(std::stderr(), text) }

fn (c: ^Context) green(text: str): str { return c.printWithColor ? sprintf("\x1b[32m%s\x1b[m", text) : text }
fn (c: ^Context) red(text: str): str { return c.printWithColor ? sprintf("\x1b[31m%s\x1b[m", text) : text }
fn (c: ^Context) bold(text: str): str { return c.printWithColor ? sprintf("\x1b[1m%s\x1b[m", text) : text }

//~~fn newContext
// Returns a new, default `Context`.
//
// Defaults:
// - `compactOutput`: `true`
// - `printWithColor`: `false`
fn newContext*(): ^Context {
//~~
    c := new(Context)
    c.assert = Assertions { ctx: c }

    c.compactOutput = true
    c.printWithColor = false

    return c
}

//~~fn (^Context) pass
// Marks this test as passing. You should immediately return once calling this.
fn (c: ^Context) pass*(msg: str = ""): bool {
//~~
    t := c.current
    std::assert(t != null, "attempt to call pass() outside of a test case")

    s := "O"
    if !c.compactOutput { s = sprintf("test '%s': %s", t.name, msg) }
    eprint(c.green(s))

    t.funcDepth++
    t.result = std::error(0, msg)
    return true
}

//~~fn (^Context) fail
// Marks this test as failed. You should immediately return once calling this.
fn (c: ^Context) fail*(msg: str, code: int = -1): bool {
//~~
    t := c.current
    std::assert(t != null, "attempt to call fail() outside of a test case")

    s := c.bold("X")
    if !c.compactOutput { s = sprintf("test '%s': %s", t.name, msg) }
    eprint(c.red(s))

    t.funcDepth++
    t.result = std::error(code, msg)
    return false
}

fn (c: ^Context) checkInvariants() {
    t := c.current
    std::assert(t != null, "attempt to call an assertion outside of a test case")
    std::assert(t.result.code == 0, "a previous assertion failed, but its enclosing function did not return")
}

//~~fn (^Context) startCustom
// Marks the start of a custom assertion.
// This must be called at the beginning of all custom assertions.
fn (c: ^Context) startCustom*() {
//~~
    c.checkInvariants()
    t := c.current
    c.customAsserts = append(c.customAsserts, std::error(-1))
    t.funcDepth++
}

//~~fn (^Context) endCustom
// Marks the end of the custom assertion.
// The intended return boolean must be passed through this function
// and that value must be returned instead:
// `return T.endCustom(returnVal)`.
fn (c: ^Context) endCustom*(res: bool): bool {
//~~
    std::assert(
        c.current != null && len(c.customAsserts) != 0,
        "attempt to call endCustom outside a custom assertion"
    )

    c.customAsserts = delete(c.customAsserts, len(c.customAsserts)-1)
    c.current.funcDepth--
    // returning from this function decrements once more
    return res
}

fn (a: ^Assertions) startAssertion(): (weak ^Context, weak ^TestInfo) {
    c := a.ctx
    c.checkInvariants()
    return c, c.current
}

fn (a: ^Assertions) failAssertion(err: str): bool {
    c := a.ctx
    t := c.current

    t.funcDepth += 2
    c.fail(err)
    return false
}

//~~ fn (^Context) assert.isTrue
// Asserts that `cond` is true.
// If the resulting `bool` is false, the caller should return immediately.
// If `msg` is not `""`, prints an extra reason alongside the error.
fn (a: ^Assertions) isTrue*(cond: bool, msg: str = ""): bool {
//~~
    a.startAssertion()

    if !cond {
        s := "assertion failed!"
        if msg != "" { s += sprintf("\nreason: '%s'", msg) }
        return a.failAssertion(s)
    }

    return true
}

//~~ fn (^Context) assert.isFalse
// Asserts that `cond` is false. Everything else from `assert.isTrue` applies.
// (Currently, this is literally just a call to `assert.isTrue` with the condition inverted.)
fn (a: ^Assertions) isFalse*(cond: bool, msg: str = ""): bool {
//~~
    a.ctx.current.funcDepth++
    return a.isTrue(!cond, msg)
}

//~~fn (^Context) assert.isOk
// Asserts that `e`'s code is 0.
// If the resulting `bool` is false, the caller should return immediately.
//
// If `msg` is not `""`, prints an extra reason alongside the error.
// If it is, it defaults to `e`'s error message.
fn (a: ^Assertions) isOk*(e: std::Err, msg: str = ""): bool {
//~~
    a.startAssertion()

    if e.code != 0 {
        s := sprintf("error code is not std::StdErr.ok (%i)", e.code)
        m := msg
        if m == "" { m = e.msg }
        if m != "" { s += sprintf("\nreason: '%s'", m) }
        return a.failAssertion(s)
    }

    return true
}

//~~ fn (^Context) assert.sameType
// Asserts that `a` and `b` have the same type.
// If the resulting `bool` is false, the caller should return immediately.
// If `msg` is not `""`, prints an extra reason alongside the error.
fn (a: ^Assertions) sameType*(va, vb: any, msg: str = ""): bool {
//~~
    a.startAssertion()

    if !selftypeeq(va, vb) {
        s := sprintf("expected %v and %v to have the same type", va, vb)
        if msg != "" { s += sprintf("\nreason: '%s'", msg)}
        return a.failAssertion(s)
    }

    return true
}

//~~fn (^Context) registerTest
// Registers a single new test.
// Will throw a fatal error if the name is already registered with this context.
fn (c: ^Context) registerTest*(name: str, func: TestFn) {
//~~
    e := sprintf("test '%s' already registered", name)
    for _, t^ in c.tests { std::assert(name != t.name, e) }
    c.tests = append(c.tests, TestInfo{ name: name, func: func })
}

//~~fn (^Context) registerTests
// Registers various tests consecutively.
// Will throw a fatal error if any of the keys are registered as names for tests with this context.
fn (c: ^Context) registerTests*(tests: []TestInfo) {
//~~
    for _, t in tests {
        // in case it was set, since it's checked for later
        t.result.msg = ""

        n := t.name
        e := sprintf("test '%s' already registered", n)
        for _, u^ in c.tests { std::assert(n != u.name, e) }

        c.tests = append(c.tests, t)
    }
}

//~~fn (^Context) run
// Runs each of the tests registered to this context,
// and returns whether any single one of them had an error.
//
// `quitIfErr` exits the application after every test is run,
// if any single one of them threw an error.
fn (c: ^Context) run*(quitIfErr: bool = true): bool {
//~~
    didFail := false
    passedTests := 0

    if c.compactOutput { eprint("results: ") }

    for _, t^ in c.tests {
        c.current = t

        time := std::clock()
        t.func(c)
        t.time = std::clock() - time

        if len(c.customAsserts) != 0 {
            loc := c.customAsserts[len(c.customAsserts)-1].trace[1]
            eprintln(c.red("\n\n[FATAL] you missed a call to T.endCustom"))
            eprint(sprintf("in function %s, line %i\nin file %s", loc.func, loc.line, loc.file))
        }

        if t.result.code != 0 {
            didFail = true
            if !c.compactOutput {
                pos := t.result.trace[t.funcDepth]
                eprint(sprintf("\nin file %s\nline %i", pos.file, pos.line))
            }
        } else {
            if t.result.msg == "" { c.pass("passed") }
            passedTests++
        }

        if !c.compactOutput { eprintln(sprintf("\ntook %fms\n", t.time * 1000)) }
    }

    if c.compactOutput {
        eprintln("\n")
        if didFail {
            eprintln(c.red(c.bold("failed tests:\n")))

            // TODO: should loop through all tests again?
            for _, t^ in c.tests {
                if t.result.code == 0 { continue }

                msg := sprintf(
                    "test '%s': %s",
                    t.name, t.result.msg
                )

                pos := t.result.trace[t.funcDepth]

                eprintln(sprintf(
                    "%s\nin file %s\nline %i, took %fms\n",
                    c.red(msg), pos.file, pos.line, t.time * 1000
                ))
            }
        }
    }

    l := len(c.tests)
    text := sprintf("%i of %i tests passed", passedTests, l)

    text = passedTests == l ? c.green(text) : c.red(text)
    eprintln(c.bold(text))

    c.current = null
    if quitIfErr && didFail { exit(-1) }
    return didFail
}