std

source of std::testing

1// Expectations for tests (LANGUAGE_SPEC.md section 6.5).2//3// A test, `test "name" { ... }`, runs on its own under `alloyc test`; a4// failed expectation stops it. The compiler reports a panic here as5// `test failed: <message>`, where the test called into this module rather6// than the line inside it.78import std::string;9import std::equal;10import std::format;1112// Fails the test unless the condition holds.13exp fn expect(condition: bool) {14    if (!condition) {15        panic "expected true, found false";16    }17}1819// Fails the test unless the values are equal, printing both when they20// declare Format (std::format), as numbers, `bool` and Strings do.21exp fn expect_equal<T: Equal>(actual: &T, expected: &T) {22    if (actual.equals(&expected)) {23        return;24    }25    if (T: Format) {26        var message = String::from(&"expected ");27        expected.format(&var message);28        message.append(&", found ");29        actual.format(&var message);30        panic message.view();31    }32    panic "the values differ";33}3435exp fn expect_equal(actual: &[u8], expected: &[u8]) {36    if (actual == expected) {37        return;38    }39    var message = String::from(&"expected ");40    quote(&expected, &var message);41    message.append(&", found ");42    quote(&actual, &var message);43    panic message.view();44}4546/* --- Showing values --- */4748// The text in double quotes, its quotes, backslashes and control bytes49// escaped.50fn quote(text: &[u8], out: &var String) {51    out.push('"');52    for (text) |byte| {53        if (byte == '"' || byte == '\\') {54            out.push('\\');55            out.push(byte);56        } else if (byte == '\n') {57            out.append(&"\\n");58        } else if (byte < 32) {59            out.append(&"\\x");60            out.push(hex_digit(byte >> 4));61            out.push(hex_digit(byte & 15));62        } else {63            out.push(byte);64        }65    }66    out.push('"');67}6869fn hex_digit(value: u8) -> u8 {70    return if (value < 10) '0' + value else 'a' + value - 10;71}