Перейти к содержимому
Топаз6.0 · До релиза
Загрузка →

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Библиотека

    std.test

    Assert ordinary value conditions and compare output with existing golden text.

    API этого модуля

    9 API

    ИмяМодуль
    std.test.assert →std.test →
    std.test.assertContains →std.test →
    std.test.assertEq →std.test →
    std.test.assertErr →std.test →
    std.test.assertGolden →std.test →
    std.test.assertNe →std.test →
    std.test.assertNone →std.test →
    std.test.assertOk →std.test →
    std.test.assertSome →std.test →

    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.

    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

    Ссылка

    std.test.assert →

    std.test.assertEq →

    std.test.assertNe →

    std.test.assertContains →

    std.test.assertOk →

    std.test.assertErr →

    std.test.assertSome →

    std.test.assertNone →

    std.test.assertGolden →

    Pending contracts

    Ссылка

    Repeat assertions with for

    Ссылка
    Правилоtopaz.stdlib.contract.test-for-all.rule

    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

    Ссылка
    main.tpzUse one loop for every element typeОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. let mut sum = 0
    4. for value in ([2, 3, 5]) {
    5. sum += value
    6. }
    7. let mut trueCount = 0
    8. for value in ([true, false, true]) {
    9. if (value) { trueCount += 1 }
    10. }
    11. let mut labels = ""
    12. for value in (["A", "B", "C"]) {
    13. labels = labels + value
    14. }
    15. test.assertEq(sum, 10)
    16. test.assertEq(trueCount, 2)
    17. test.assertEq(labels, "ABC")
    18. io.writeLine("all values checked")
    Ожидаемый выводКод завершения 0
    all values checked
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. all values checked

    Reject the removed forAllInt helper

    Ссылка
    main.tpzReject the removed forAllInt helperОткрыть песочницу →
    1. import std.test { forAllInt }
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения resolve. Ненулевой код завершения.

    Reject the removed forAllBool helper

    Ссылка
    main.tpzReject the removed forAllBool helperОткрыть песочницу →
    1. import std.test { forAllBool }
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения resolve. Ненулевой код завершения.

    Diagnostics

    Ссылка

    Name is not exported →

    Assert inequality and text containment

    Ссылка
    Правилоtopaz.stdlib.contract.test-comparisons.rule

    Assert inequality and text containment

    assertNe(actual, expected) 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.

    assertContains(text, needle) 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

    Ссылка
    main.tpzCompare values and exact substringsОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. test.assertNe([1, 2], [1, 3])
    4. let present: Option<int> = Some(1)
    5. let absent: Option<int> = None()
    6. test.assertNe(present, absent)
    7. test.assertContains("Topaz", "opa")
    8. test.assertContains("é", "é")
    9. test.assertContains("text", "")
    10. test.assertContains("", "")
    11. io.writeLine("comparisons passed")
    Ожидаемый выводКод завершения 0
    comparisons passed
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. comparisons passed

    Evaluate each operand once in source order

    Ссылка
    main.tpzEvaluate each operand once in source orderОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. function operand(label: string, value: int) -> int {
    4. io.writeLine(label)
    5. return value
    6. }
    7. let result: () = test.assertNe(operand("actual", 3), operand("expected", 4))
    8. io.writeLine("{result}")
    Ожидаемый выводКод завершения 0
    actual
    expected
    ()
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. actual
    2. expected
    3. ()

    Stop after equal operands fail assertNe

    Ссылка
    main.tpzStop after equal operands fail assertNeОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. function operand(label: string, value: int) -> int {
    4. io.writeLine(label)
    5. return value
    6. }
    7. test.assertNe(operand("actual", 7), operand("expected", 7))
    8. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    actual
    expected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    Ожидаемый стандартный вывод
    1. actual
    2. expected

    Keep substring matching case sensitive

    Ссылка
    main.tpzKeep substring matching case sensitiveОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. io.writeLine("before")
    4. test.assertContains("Topaz", "topaz")
    5. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    before
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    Ожидаемый стандартный вывод
    1. before

    Keep composed and decomposed spellings distinct

    Ссылка
    main.tpzKeep composed and decomposed spellings distinctОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. io.writeLine("before")
    4. test.assertContains("é", "é")
    5. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    before
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    • TPZ4007 →

      stdlib-assert-contains-spelling at main.tpz:5:1

    Ожидаемый стандартный вывод
    1. before

    Reject values that ordinary equality cannot compare

    Ссылка
    main.tpzReject values that ordinary equality cannot compareОткрыть песочницу →
    1. import std.test
    2. let value = () => 1
    3. test.assertNe(value, value)
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения check. Ненулевой код завершения.

    • TPZ5007 →

      stdlib-assert-ne-non-comparable at main.tpz:4:1

    Accept exact substrings and an empty needle

    Ссылка
    main.tpzAccept exact substrings and an empty needleОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. test.assertContains("Topaz", "opa")
    4. test.assertContains("é", "é")
    5. test.assertContains("text", "")
    6. test.assertContains("", "")
    7. io.writeLine("text contained")
    Ожидаемый выводКод завершения 0
    text contained
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. text contained

    Diagnostics

    Ссылка

    Assertion failed →

    Value is not comparable or keyable →

    Assert a Result constructor and return its payload

    Ссылка
    Правилоtopaz.stdlib.contract.test-result-variants.rule

    Assert a Result constructor and return its payload

    assertOk accepts a Result<T, E>. It returns the T payload of Ok(value). An Err(error) raises TPZ4007.

    assertErr 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

    Ссылка
    main.tpzExtract both Result payloads and preserve a nested ErrОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. let okValue: Result<int, string> = Ok(7)
    4. let errValue: Result<int, string> = Err("bad")
    5. let nested: Result<Result<int, string>, string> = Ok(Err("inner"))
    6. let value = test.assertOk(okValue)
    7. let error = test.assertErr(errValue)
    8. let inner: Result<int, string> = test.assertOk(nested)
    9. let nestedError = test.assertErr(inner)
    10. io.writeLine("{value}/{error}/{nestedError}")
    Ожидаемый выводКод завершения 0
    7/bad/inner
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 7/bad/inner

    Fail assertOk with the rendered error

    Ссылка
    main.tpzFail assertOk with the rendered errorОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. let value: Result<int, string> = Err("bad")
    4. io.writeLine("before")
    5. test.assertOk(value)
    6. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    before
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    Ожидаемый стандартный вывод
    1. before

    Fail assertErr with the rendered value

    Ссылка
    main.tpzFail assertErr with the rendered valueОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. let value: Result<int, string> = Ok(7)
    4. io.writeLine("before")
    5. test.assertErr(value)
    6. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    before
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    Ожидаемый стандартный вывод
    1. before

    Assert presence or absence

    Ссылка
    Правилоtopaz.stdlib.contract.test-option-variants.rule

    Assert presence or absence

    assertSome accepts an Option<T> and returns the T payload of Some(value). Passing None() raises TPZ4007.

    assertNone 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

    Ссылка
    main.tpzDistinguish nested absence from an absent outer valueОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. let present: Option<int> = Some(7)
    4. let absent: Option<int> = None()
    5. let nested: Option<Option<int>> = Some(None())
    6. let value = test.assertSome(present)
    7. let result: () = test.assertNone(absent)
    8. test.assertNone(test.assertSome(nested))
    9. io.writeLine("{value}/{result}")
    Ожидаемый выводКод завершения 0
    7/()
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 7/()

    Fail assertSome on an absent value

    Ссылка
    main.tpzFail assertSome on an absent valueОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. let value: Option<int> = None()
    4. io.writeLine("before")
    5. test.assertSome(value)
    6. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    before
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    Ожидаемый стандартный вывод
    1. before

    Fail assertNone with the present payload

    Ссылка
    main.tpzFail assertNone with the present payloadОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. let value: Option<int> = Some(7)
    4. io.writeLine("before")
    5. test.assertNone(value)
    6. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    before
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    Ожидаемый стандартный вывод
    1. before

    Compare existing golden text without updating it

    Ссылка
    Правилоtopaz.stdlib.contract.test-golden-text.rule

    Compare existing golden text without updating it

    assertGolden(path, actual) 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 output

    Earlier 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

    Ссылка
    main.tpzMatch exact line endings and an empty golden fileОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. test.assertGolden("expected.txt", "alpha\r\nβ\n")
    4. test.assertGolden("empty.txt", "")
    5. io.writeLine("golden text matched")
    Ожидаемый выводКод завершения 0
    golden text matched
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    expected.txtMatch exact line endings and an empty golden fileОткрыть песочницу →
    1. alpha
    2. β
    empty.txtMatch exact line endings and an empty golden fileОткрыть песочницу →
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. golden text matched

    Resolve a golden path from the working directory

    Ссылка
    nested/main.tpzResolve a golden path from the working directoryОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. test.assertGolden("expected.txt", "working directory\n")
    4. io.writeLine("working directory matched")
    Ожидаемый выводКод завершения 0
    working directory matched
    
    $ topaz run nested/main.tpz · Целевой продукт 5.21.3
    expected.txtResolve a golden path from the working directoryОткрыть песочницу →
    1. working directory
    nested/expected.txtResolve a golden path from the working directoryОткрыть песочницу →
    1. source directory
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. working directory matched

    Fail when the final newline is missing from actual text

    Ссылка
    main.tpzFail when the final newline is missing from actual textОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. io.writeLine("before")
    4. test.assertGolden("expected.txt", "line")
    5. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    before
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    expected.txtFail when the final newline is missing from actual textОткрыть песочницу →
    1. line
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    • TPZ4007 →

      stdlib-assert-golden-mismatch at main.tpz:5:1

    Ожидаемый стандартный вывод
    1. before

    Fail instead of creating a missing golden file

    Ссылка
    main.tpzFail instead of creating a missing golden fileОткрыть песочницу →
    1. import std.test
    2. import std.io
    3. io.writeLine("before")
    4. test.assertGolden("missing.txt", "new text")
    5. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    before
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    • TPZ4007 →

      stdlib-assert-golden-missing at main.tpz:5:1

    Ожидаемый стандартный вывод
    1. before

    Fail instead of replacing invalid UTF-8 with a character

    Ссылка
    main.tpzFail instead of replacing invalid UTF-8 with a characterОткрыть песочницу →
    1. import std.bytes { Bytes }
    2. import std.fs
    3. import std.test
    4. import std.io
    5. let bytes = test.assertOk(Bytes.fromArray([255]))
    6. test.assertOk(fs.writeBytes("invalid.txt", bytes))
    7. io.writeLine("before")
    8. test.assertGolden("invalid.txt", "�")
    9. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    before
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    • TPZ4007 →

      stdlib-assert-golden-invalid-utf8 at main.tpz:9:1

    Ожидаемый стандартный вывод
    1. before

    Меню

    Загрузка →