assertify is a framework for making assertions in R.
The primary function is assert(). It accepts any R expression that evaluates
to a single logical. If the expression evaluates to TRUE, execution
continues. Otherwise, an error is signalled.
assert(1 + 1 == 2)
assert(is.character("metal"))
assert() also accepts a message argument that will used as the error message
if an assertion fails.
assert(5 %% 2 == 0, msg = "5 is not an even number")
There are a few helper functions that are useful for checking pre/post-conditions in functions.
is_string("string")
is_flag(TRUE)
has_attr(factor(c("foo", "bar", "baz")), "levels")
In addition to the msg parameter of assert(), a "fail" attribute can be
added to any function to generate custom error messages. The attribute must be
a function with the signature function(call, env, result) and return a
string which will be used as the error message. assert will call the function
with the call of the assertion, the execution environment of the assertion and
the result of the assertion to generate an error message.
custom_test <- fuction(x) length(x) == 2
attr(custom_test, "fail") <- function(call, env, result) {
paste0(deparse1(call$x), " is not length 2")
}
assert(custom_test(0:3))
# Error: x is not length 2