Source   Edit

This module provides various assertion utilities.

Note: This module is reexported by system and thus does not need to be imported directly (with system/assertions).


proc failedAssertImpl(msg: string) {....raises: [], tags: [].}
Raises an AssertionDefect with msg, but this is hidden from the effect system. Called when an assertion failed.   Source   Edit
proc raiseAssert(msg: string) {.noinline, noreturn, nosinks, ...raises: [],
                                tags: [].}
Raises an AssertionDefect with msg.   Source   Edit


template assert(cond: untyped; msg = "")

Raises AssertionDefect with msg if cond is false. Note that AssertionDefect is hidden from the effect system, so it doesn't produce {.raises: [AssertionDefect].}. This exception is only supposed to be caught by unit testing frameworks.

No code will be generated for assert when passing -d:danger (implied by --assertions:off). See command line switches.


assert 1 == 1

Example: cmd: --assertions:off

assert 1 == 2 # no code generated, no failure here

Example: cmd: -d:danger

assert 1 == 2 # ditto
  Source   Edit
template doAssert(cond: untyped; msg = "")
Similar to assert but is always turned on regardless of --assertions.


doAssert 1 == 1 # generates code even when built with `-d:danger` or `--assertions:off`
  Source   Edit
template doAssertRaises(exception: typedesc; code: untyped)
Raises AssertionDefect if specified code does not raise exception.


doAssertRaises(ValueError): raise newException(ValueError, "Hello World")
doAssertRaises(CatchableError): raise newException(ValueError, "Hello World")
doAssertRaises(AssertionDefect): doAssert false
  Source   Edit
template onFailedAssert(msg, code: untyped): untyped {.dirty.}
Sets an assertion failure handler that will intercept any assert statements following onFailedAssert in the current scope.


type MyError = object of CatchableError
  lineinfo: tuple[filename: string, line: int, column: int]
# block-wide policy to change the failed assert exception type in order to
# include a lineinfo
  raise (ref MyError)(msg: msg, lineinfo: instantiationInfo(-2))
doAssertRaises(MyError): doAssert false
  Source   Edit