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

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

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

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

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

    Библиотека

    std.test.assertEq

    Assert equality within the ordinary equality domain.

    assertEq<T>(actual: T, expected: T) -> ()
    Модуль
    std.test →
    Получатель
    Неприменимо
    Минимальное число аргументов
    2
    Максимальное число аргументов
    2

    Declaration and parameters

    Ссылка

    Доступность

    Включено по умолчанию · Не определено

    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.

    Получатель

    Ограничения параметров

    The operands of std.test.assertEq(actual, expected) use the ordinary equality domain.

    Equal values return () and execution continues. Unequal values raise TPZ4007 with the rendered actual and expected values.

    Known noncomparable operands produce TPZ5007 during checking.

    Argument evaluation and assertion failure follow Test comparisons.

    Derivation follows the operation it generates. Eq asks whether two values are equal. Order supplies a total comparison. JSON supplies conversion to and from a JSON tree under the type's documented representation. These are different obligations, so admission is determined by the operation rather than a common whitelist. A nested nominal always uses the conformance described above. This table defines the listed component families; it does not assign capabilities to other built-ins. Duration capabilities follow its operations rule.

    ComponentEqOrderJSON
    int, string, boolValue equalityNumeric, Unicode scalar, or false-before-true orderJSON number, string, or boolean
    unit and nullEquality within the singleton typeZero within the same singleton typeJSON null, recovered through the requested target type
    floatIEEE numerical equalityNo total Order because NaN has no place in the existing numerical relationFinite numbers convert; NaN and infinities return Err
    ArraySame length and elementwise equalityLexicographic elements; a prefix precedes its extensionJSON array with recursive conversion
    OptionSame constructor and payload equalityNone() precedes Some(value). Compare present payloadsNone() encodes as null. Some(value) unwraps its payload. Null payloads normalize on decoding
    ResultSame constructor and payload equalityErr before Ok; compare payloads within the same constructorThe ordinary enum object with tag Ok or Err and one values entry
    MapSame lookup key identities and equal values, independent of insertion orderRequires an application-selected orderingString keys form a JSON object; other key types need an explicit schema
    SetSame membership key identities, independent of insertion orderRequires an application-selected orderingRequires an explicit sequence representation and duplicate policy
    Structural recordSame field set and fieldwise equalityCompare fields in Unicode scalar order of field namesString field names form a JSON object
    UnionCompare active member identities, then values within a memberAdmitted when every member widens to the same ordered scalar domainUntagged overlapping representations need an explicit nominal schema

    Map and Set equality reuse the key identity already used by lookup and membership. A custom Eq method does not replace stored-key equality. Map values use their Eq operation, including a manual nominal implementation. Insertion order does not affect either equality result. Functions and resources have no data-value equality, and regex denotation has no general equality operation. JSONValue and TOMLValue preserve representation information and require decoding or an explicit projection into the intended equality domain. Templates, ranges, mutable ByteBuffer values, and namespaces likewise have no automatic Eq conformance. Bytes compare bytes; Path and URL compare their canonical representations; Date, BigInt, and Decimal compare their values; Match and RoundingMode retain their declared value equality. IEEE equality is not an equivalence relation for NaN-containing values: NaN differs from itself and positive and negative zero compare equal. Eq does not promise otherwise.

    For Order, Bytes compare bytewise; Path and URL compare canonical strings; Date compares calendar days; BigInt and Decimal compare numbers. A record uses sorted field names, including a nominal record, so rearranging declarations cannot change priority. A derived enum compares variant names in Unicode scalar order and then positional payloads. A newtype compares its base. Each component must itself have Order. Map and Set describe membership rather than a selected key order; a heterogeneous union has no declared cross-type priority. A nominal manual implementation can state those application-specific choices. Float keeps its ordinary IEEE relational predicates, which may all be false for NaN, and therefore does not satisfy total Order. Opaque families without a declared total order do not gain one through derivation.

    JSON uses the existing record object, enum tag/values object, and transparent newtype representations. Result uses the enum representation rather than treating an Err payload as codec failure. Option converts through null and its payload values. Some(None()) and Some(()) can decode as None(). This normalization can map distinct source values to the same decoded value. JSONValue conversion preserves its tree, including stored number lexemes. Semantic scalar types such as Bytes, Path, URL, Date, BigInt, Decimal, Match, and RoundingMode need an explicitly chosen external schema through a nominal manual JSON implementation. Conversion does not silently pick a binary encoding, path base, unit, precision loss, or tag convention. Functions, resources, and templates cannot be reconstructed as data values. Derived conversion failure is TPZ5530 when a component type has no JSON capability. Malformed data and value-level encoding failures return an Err result during conversion.

    Finite float encoding chooses the shortest decimal significand that recovers the identical binary64 value under nearest, ties-to-even decoding. If shortest candidates differ, choose the decimal closest to the exact binary value, then the candidate with an even final significand digit. Render fixed notation when the normalized decimal exponent is at least -6 and below 21; otherwise use lowercase e, with no plus sign or redundant exponent zeroes. Omit redundant fractional zeroes. Positive zero is 0 and negative zero is -0. A nonfinite input returns Err without substituting null or a string. Decoding accepts any JSON number, including integer lexemes, rounds once to binary64 with nearest, ties-to-even, preserves a negative zero sign, and rejects overflow to a nonfinite result. Underflow rounds to a finite subnormal or signed zero. The shortest-number rule applies when encoding a float; parsing and re-serializing an existing JSONValue preserves its accepted number lexeme, and numberText/asInt retain their existing semantics. Recursive conversion follows the depth rule above and value semantics. Show remains the total debug-render operation and has no member capability gate.

    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.

    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.

    Результат

    The declared result type is ().

    Эффекты

    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.

    Ошибки

    The operands of std.test.assertEq(actual, expected) use the ordinary equality domain.

    Equal values return () and execution continues. Unequal values raise TPZ4007 with the rendered actual and expected values.

    Known noncomparable operands produce TPZ5007 during checking.

    Argument evaluation and assertion failure follow Test comparisons.

    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.

    Assertion failed →

    Value is not comparable or keyable →

    Result and effects

    Ссылка

    Evaluate actual and expected once from left to right. Equal values return unit without output. An unequal comparison raises TPZ4007 at the call and stops the test. Comparison faults retain their own diagnostics.

    Assertions share the language equality domain so tests preserve the meaning of ordinary comparisons.

    Related entries

    Ссылка

    std.test →

    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 →

    Меню

    Загрузка →