Standard Library: Testing
The std::core::utils::testing module provides assertion functions for unit
testing Shape programs. All assertions return Result<bool, string> — Ok(true) on
success, Err(message) on failure.
Importing
Section titled “Importing”from std::core::utils::testing use { assert, assert_eq, assert_ne, assert_approx, assert_ok, assert_err }Assertions
Section titled “Assertions”assert
Section titled “assert”Assert that a condition is true. An optional message is included in the error on failure.
assert(x > 0, "x must be positive")assert(list.length > 0)assert_eq
Section titled “assert_eq”Assert that two values are equal. The error message includes both the expected and actual values.
assert_eq(add(2, 3), 5, "addition should work")assert_eq(name, "Alice")assert_ne
Section titled “assert_ne”Assert that two values are not equal.
assert_ne(result, 0, "result must not be zero")assert_ne(a, b)assert_approx
Section titled “assert_approx”Assert that two numbers are approximately equal within a tolerance. The default
tolerance is 1e-10.
assert_approx(sqrt(2.0) * sqrt(2.0), 2.0)assert_approx(pi(), 3.14, 0.01) // custom toleranceassert_ok
Section titled “assert_ok”Assert that a Result value is Ok.
assert_ok(parse_number("42"))assert_err
Section titled “assert_err”Assert that a Result value is Err.
assert_err(parse_number("not a number"))Function Reference
Section titled “Function Reference”| Function | Signature | Description |
|---|---|---|
assert(cond, msg?) | (bool, string?) -> Result<bool, string> | Assert condition is true |
assert_eq(actual, expected, msg?) | (T, T, string?) -> Result<bool, string> | Assert values are equal |
assert_ne(actual, expected, msg?) | (T, T, string?) -> Result<bool, string> | Assert values are not equal |
assert_approx(actual, expected, tol?) | (number, number, number?) -> Result<bool, string> | Assert approximate equality |
assert_ok(result) | (Result<T, string>) -> Result<bool, string> | Assert result is Ok |
assert_err(result) | (Result<T, string>) -> Result<bool, string> | Assert result is Err |
Example: Test Suite
Section titled “Example: Test Suite”from std::core::utils::testing use { assert_eq, assert_approx, assert_ok }
fn test_arithmetic() { assert_eq(2 + 2, 4)? assert_eq(10 / 3, 3)? assert_approx(10.0 / 3.0, 3.333, 0.001)?}
fn test_string_ops() { let greeting = "hello" + " " + "world" assert_eq(greeting, "hello world")? assert_eq(greeting.length, 11)?}
test_arithmetic()?test_string_ops()?print("All tests passed")See Also
Section titled “See Also”- Error Handling —
Result,?operator, and error propagation