assert Eq<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. 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.
Связанное правило · Equality assertions →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.
| Component | Eq | Order | JSON |
|---|---|---|---|
| int, string, bool | Value equality | Numeric, Unicode scalar, or false-before-true order | JSON number, string, or boolean |
| unit and null | Equality within the singleton type | Zero within the same singleton type | JSON null, recovered through the requested target type |
| float | IEEE numerical equality | No total Order because NaN has no place in the existing numerical relation | Finite numbers convert; NaN and infinities return Err |
| Array | Same length and elementwise equality | Lexicographic elements; a prefix precedes its extension | JSON array with recursive conversion |
| Option | Same constructor and payload equality | None() precedes Some(value). Compare present payloads | None() encodes as null. Some(value) unwraps its payload. Null payloads normalize on decoding |
| Result | Same constructor and payload equality | Err before Ok; compare payloads within the same constructor | The ordinary enum object with tag Ok or Err and one values entry |
| Map | Same lookup key identities and equal values, independent of insertion order | Requires an application-selected ordering | String keys form a JSON object; other key types need an explicit schema |
| Set | Same membership key identities, independent of insertion order | Requires an application-selected ordering | Requires an explicit sequence representation and duplicate policy |
| Structural record | Same field set and fieldwise equality | Compare fields in Unicode scalar order of field names | String field names form a JSON object |
| Union | Compare active member identities, then values within a member | Admitted when every member widens to the same ordered scalar domain | Untagged 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.
Связанное правило · Field capability domains for derivation →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.
Связанное правило · Repeat assertions with for →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.
Связанное правило · Assert inequality and text containment →Результат
The declared result type is ().
Эффекты
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.
Связанное правило · Assert inequality and text containment →Ошибки
The operands of std. 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.
Связанное правило · Equality assertions →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.
Связанное правило · Assert inequality and text containment →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.
Why
СсылкаAssertions share the language equality domain so tests preserve the meaning of ordinary comparisons.
Related entries
Ссылка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