| assert | R Documentation |
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.
assert(fact, ...)
x %==% y
fact |
A character string describing what is being tested. This message
is shown when an assertion fails, so make it descriptive (e.g., |
... |
An R expression wrapped in |
x, y |
Two R objects to be compared for identity. |
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, as well as
inside a {} block passed as an argument to a function call (e.g.
xfun::in_dir(dir, { ... })). 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).
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.
Key differences from stopifnot():
assert() shows your custom fact message on failure, making errors
easier to diagnose.
logical(0) (empty logical) is treated as a failure, not a pass.
All conditions are evaluated even if earlier ones fail; all failures are reported together in a single error message.
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)
})
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.