Module
СсылкаSuccessful assertions return unit or the requested payload without printing. Failed conditions raise TPZ4007 at the call and stop the current test. Golden assertions compare existing text without updating it. Use the language for loop to repeat assertions.
Why
СсылкаAssertions use the same comparisons and constructors as ordinary programs. A test failure identifies the expectation without changing the data used to judge it.
Availability
СсылкаImport std.test in language mode 5.21. The current compiler selects std/test.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.
Public API
СсылкаPending contracts
СсылкаRepeat assertions with for
СсылкаRepeat assertions with for
Test programs iterate supplied values with the ordinary for statement. The same statement applies to integers, booleans, strings, and other iterable element types.
std.test does not export forAllInt or forAllBool. Assertions inside a for body retain the same assertion behavior as a direct call.
Причина
The removed helpers repeated an existing loop and added no test meaning. Ordinary iteration works for every element type and keeps loop control and assertion order visible.
Use one loop for every element type
Ссылкаimport std.testimport std.iolet mut sum = 0for value in ([2, 3, 5]) {sum += value}let mut trueCount = 0for value in ([true, false, true]) {if (value) { trueCount += 1 }}let mut labels = ""for value in (["A", "B", "C"]) {labels = labels + value}test.assertEq(sum, 10)test.assertEq(trueCount, 2)test.assertEq(labels, "ABC")io.writeLine("all values checked")
all values checked
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
all values checked
Reject the removed forAllInt helper
Ссылкаimport std.test { forAllInt }
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения resolve. Ненулевой код завершения.
selected-name-not-exported at
main.tpz:1:19
Reject the removed forAllBool helper
Ссылкаimport std.test { forAllBool }
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения resolve. Ненулевой код завершения.
selected-name-not-exported at
main.tpz:1:19
Diagnostics
СсылкаAssert inequality and text containment
СсылкаAssert inequality and text containment
assert returns unit when ordinary value equality says the operands differ. It performs no string conversion before comparison.
The operands must have a common comparable type under the ordinary equality rules. Known noncomparable values produce TPZ5007 during checking. A comparison fault propagates with its own diagnostic.
assert returns unit when the exact needle occurs as a contiguous substring. Matching is case sensitive and preserves Unicode spelling. An empty needle succeeds even when the text is empty.
Arguments are evaluated once from left to right before testing the condition. Successful calls have no further side effects and print nothing.
A false assertion raises TPZ4007 at the assertion call. It returns no value and stops the current test before the next statement. Earlier argument side effects remain visible. Test runner handling of later test cases follows the test execution contract.
The inequality failure message uses the ordinary rendering of the shared value in this form.
assertNe failed: both values are `{value}`The containment failure message includes the original text and needle in this form.
assertContains failed: `{text}` does not contain `{needle}`These assertions add test failure reporting to ordinary equality and string containment. They do not define a separate comparison relation.
Причина
Tests should disagree with a program value only when the same ordinary comparison disagrees. Silent success keeps output useful, and immediate failure prevents a false premise from affecting later assertions.
Compare values and exact substrings
Ссылкаimport std.testimport std.iotest.assertNe([1, 2], [1, 3])let present: Option<int> = Some(1)let absent: Option<int> = None()test.assertNe(present, absent)test.assertContains("Topaz", "opa")test.assertContains("é", "é")test.assertContains("text", "")test.assertContains("", "")io.writeLine("comparisons passed")
comparisons passed
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
comparisons passed
Evaluate each operand once in source order
Ссылкаimport std.testimport std.iofunction operand(label: string, value: int) -> int {io.writeLine(label)return value}let result: () = test.assertNe(operand("actual", 3), operand("expected", 4))io.writeLine("{result}")
actual
expected
()
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
actualexpected()
Stop after equal operands fail assertNe
Ссылкаimport std.testimport std.iofunction operand(label: string, value: int) -> int {io.writeLine(label)return value}test.assertNe(operand("actual", 7), operand("expected", 7))io.writeLine("after")
actual
expected
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-ne-equal at
main.tpz:9:1
actualexpected
Keep substring matching case sensitive
Ссылкаimport std.testimport std.ioio.writeLine("before")test.assertContains("Topaz", "topaz")io.writeLine("after")
before
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-contains-case at
main.tpz:5:1
before
Keep composed and decomposed spellings distinct
Ссылкаimport std.testimport std.ioio.writeLine("before")test.assertContains("é", "é")io.writeLine("after")
before
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-contains-spelling at
main.tpz:5:1
before
Reject values that ordinary equality cannot compare
Ссылкаimport std.testlet value = () => 1test.assertNe(value, value)
Нет стандартного вывода.Ожидаемый результат
Ожидаемый результат
Этап отклонения check. Ненулевой код завершения.
stdlib-assert-ne-non-comparable at
main.tpz:4:1
Accept exact substrings and an empty needle
Ссылкаimport std.testimport std.iotest.assertContains("Topaz", "opa")test.assertContains("é", "é")test.assertContains("text", "")test.assertContains("", "")io.writeLine("text contained")
text contained
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
text contained
Diagnostics
СсылкаAssert a Result constructor and return its payload
СсылкаAssert a Result constructor and return its payload
assert accepts a Result<T, E>. It returns the T payload of Ok(value). An Err(error) raises TPZ4007.
assert accepts a Result<T, E>. It returns the E payload of Err(error). An Ok(value) raises TPZ4007.
The returned payload is unchanged. No conversion, recursive unwrapping, or equality comparison occurs. A nested Err inside an outer Ok still satisfies assertOk.
The argument is evaluated once before its outer constructor is inspected. Success prints nothing. Failure reports the assertion call and stops the current test without running its next statement. Earlier effects remain visible.
The failure messages identify the unexpected constructor and its ordinarily rendered payload.
assertOk failed: got Err({error})
assertErr failed: got Ok({value})These helpers express a test expectation. Match the Result in ordinary code when either constructor is part of normal control flow.
Причина
Inspecting the outer constructor preserves the distinction between an expected failure value and a failed test. Returning the payload lets later assertions examine its contents without repeating the match.
Extract both Result payloads and preserve a nested Err
Ссылкаimport std.testimport std.iolet okValue: Result<int, string> = Ok(7)let errValue: Result<int, string> = Err("bad")let nested: Result<Result<int, string>, string> = Ok(Err("inner"))let value = test.assertOk(okValue)let error = test.assertErr(errValue)let inner: Result<int, string> = test.assertOk(nested)let nestedError = test.assertErr(inner)io.writeLine("{value}/{error}/{nestedError}")
7/bad/inner
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
7/bad/inner
Fail assertOk with the rendered error
Ссылкаimport std.testimport std.iolet value: Result<int, string> = Err("bad")io.writeLine("before")test.assertOk(value)io.writeLine("after")
before
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-ok-err at
main.tpz:6:1
before
Fail assertErr with the rendered value
Ссылкаimport std.testimport std.iolet value: Result<int, string> = Ok(7)io.writeLine("before")test.assertErr(value)io.writeLine("after")
before
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-err-ok at
main.tpz:6:1
before
Assert presence or absence
СсылкаAssert presence or absence
assert accepts an Option<T> and returns the T payload of Some(value). Passing None() raises TPZ4007.
assert accepts an Option<T> and returns unit for None(). Passing Some(value) raises TPZ4007.
Presence depends on the outer constructor. Some(None()), Some(false), and Some(0) are present values. assertSome returns their payloads unchanged.
Each argument is evaluated once. A successful assertion prints nothing and performs no additional effects. Failure reports the assertion call and stops the current test before its next statement.
The failure messages identify the unexpected constructor. A present payload uses ordinary value rendering.
assertSome failed: got None
assertNone failed: got Some({value})Use a match to handle absence as normal program behavior. These assertions report a failed test when the chosen presence expectation is false.
Причина
Outer constructor checks keep absence separate from a stored false, zero, or absent nested value. They give tests the same Option meaning as ordinary pattern matching.
Distinguish nested absence from an absent outer value
Ссылкаimport std.testimport std.iolet present: Option<int> = Some(7)let absent: Option<int> = None()let nested: Option<Option<int>> = Some(None())let value = test.assertSome(present)let result: () = test.assertNone(absent)test.assertNone(test.assertSome(nested))io.writeLine("{value}/{result}")
7/()
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
7/()
Fail assertSome on an absent value
Ссылкаimport std.testimport std.iolet value: Option<int> = None()io.writeLine("before")test.assertSome(value)io.writeLine("after")
before
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-some-none at
main.tpz:6:1
before
Fail assertNone with the present payload
Ссылкаimport std.testimport std.iolet value: Option<int> = Some(7)io.writeLine("before")test.assertNone(value)io.writeLine("after")
before
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-none-some at
main.tpz:6:1
before
Compare existing golden text without updating it
СсылкаCompare existing golden text without updating it
assert accepts two strings. Read the existing file as UTF-8 and compare the entire decoded text with actual. UTF-8 validity and text preservation follow UTF-8 decoding. Equal text returns unit without printing.
Resolve the path using the same host path and read permission rules as filesystem text reads. For an ordinary installed CLI program, a relative path starts at the process working directory. The source file directory does not replace that directory.
Comparison preserves every scalar and line ending. CRLF and LF differ. A final newline, a byte order mark, Unicode spelling, and an empty file remain significant. Invalid UTF-8 is a read failure.
Evaluate the path expression and then the actual expression, once each, before reading the file. Open and read the expected text once. Release any opened resource before returning or reporting a read or comparison failure.
The assertion needs read access. It never creates a missing golden file, replaces its contents, or enables an update mode. Write a chosen expected result explicitly through the filesystem API.
Missing files, directories that cannot be read as text, permission denial, and invalid UTF-8 raise TPZ4007 at the assertion call. File failures identify the path and whether opening or reading failed. The host detail explains the cause and may vary by platform.
The file failure messages have these forms.
assertGolden failed: could not open `{path}`: {detail}
assertGolden failed: could not read `{path}`: {detail}Unequal text raises TPZ4007 and stops the current test before its next statement. The message has this form.
assertGolden failed: `{path}` did not match actual outputEarlier argument effects remain visible after failure. Reading does not promise a snapshot across concurrent host writes. Keep the expected file unchanged while the assertion reads it.
Причина
An existing expected file gives the test an independent reference. Exact comparison preserves document bytes that matter to generated text, and explicit writes keep failed tests from replacing their own expectations.
Match exact line endings and an empty golden file
Ссылкаimport std.testimport std.iotest.assertGolden("expected.txt", "alpha\r\nβ\n")test.assertGolden("empty.txt", "")io.writeLine("golden text matched")
golden text matched
alphaβ
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
golden text matched
Resolve a golden path from the working directory
Ссылкаimport std.testimport std.iotest.assertGolden("expected.txt", "working directory\n")io.writeLine("working directory matched")
working directory matched
working directory
source directory
Ожидаемый результат
Ожидаемый результат
Выполнение завершается. Код завершения 0.
working directory matched
Fail when the final newline is missing from actual text
Ссылкаimport std.testimport std.ioio.writeLine("before")test.assertGolden("expected.txt", "line")io.writeLine("after")
before
line
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-golden-mismatch at
main.tpz:5:1
before
Fail instead of creating a missing golden file
Ссылкаimport std.testimport std.ioio.writeLine("before")test.assertGolden("missing.txt", "new text")io.writeLine("after")
before
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-golden-missing at
main.tpz:5:1
before
Fail instead of replacing invalid UTF-8 with a character
Ссылкаimport std.bytes { Bytes }import std.fsimport std.testimport std.iolet bytes = test.assertOk(Bytes.fromArray([255]))test.assertOk(fs.writeBytes("invalid.txt", bytes))io.writeLine("before")test.assertGolden("invalid.txt", "�")io.writeLine("after")
before
Ожидаемый результат
Ожидаемый результат
Этап отклонения run. Ненулевой код завершения.
stdlib-assert-golden-invalid-utf8 at
main.tpz:9:1
before