assert {testit}R Documentation

Assert that conditions are true, with an informative failure message

Description

Test that one or more conditions are TRUE. If any condition fails, an error is raised with the fact message, making it easy to identify which test failed and why. This is the primary function for writing tests with testit.

The infix operator ⁠%==%⁠ is a shortcut for identical() that provides helpful diagnostics on failure. x %==% y returns TRUE if x and y are identical, and FALSE otherwise. When used inside assert(), a failing ⁠%==%⁠ comparison will display both values via str() so you can see exactly what differed.

Usage

assert(fact, ...)

x %==% y

Arguments

fact

A character string describing what is being tested. This message is shown when an assertion fails, so make it descriptive (e.g., 'log() returns correct values'). If fact is not a character string, it is treated as a test expression (i.e., the message is optional).

...

An R expression wrapped in {}; see Details.

x, y

Two R objects to be compared for identity.

Details

The recommended usage is to pass a single expression wrapped in {} as the second argument. Inside {}, any statement-level sub-expression wrapped in parentheses ⁠()⁠ is treated as a test condition – its value is checked and must be TRUE. Parentheses used for grouping within a larger expression (e.g., (a + b) * c) are not checked. Sub-expressions without parentheses are ordinary R code (e.g., variable assignments or setup steps) and are never checked.

⁠()⁠ tests work inside if, for, while, and repeat bodies. Internally, assert() walks the expression tree and transforms statement-level ⁠()⁠ into checks before evaluating the entire block in one frame (so on.exit() works as expected).

Value

Invisible NULL if all conditions pass. If any condition fails, an error is signaled that includes the fact message and the expression that failed. For ⁠%==%⁠, TRUE or FALSE.

Note

Key differences from stopifnot():

Examples

library(testit)
assert('T is bad for TRUE, and so is F for FALSE', {
  T = FALSE; F = TRUE
  (T != TRUE)  # note the parentheses
  (F != FALSE)
})

assert('A Poisson random number is non-negative', {
  x = rpois(1, 10)
  (x >= 0)
  (x > -1)
})

# () works inside control structures too
assert('conditional test', {
  if (requireNamespace('base', quietly = TRUE)) (1 + 1 == 2)
})

[Package testit version 1.0 Index]