std/assertions

Source   Edit  

This module implements assertion handling.

Procs

proc failedAssertImpl(msg: string) {....raises: [], tags: [], forbids: [].}
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: [], forbids: [].}
Raises an AssertionDefect with msg. Source   Edit  

Templates

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.

Example:

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.

Example:

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.

Example:

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.

Example:

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
onFailedAssert(msg):
  raise (ref MyError)(msg: msg, lineinfo: instantiationInfo(-2))
doAssertRaises(MyError): doAssert false
Source   Edit