Simple assertions with sensible defaults and customisable error messages.
Overview
The goals with assertions are to provide
Convenient assertion calls (e.g.
assert_number())A general
assertfunction that asserts any possible condition/s and throws informative error messagesExtremely user friendly error message defaults.
Easily customisable error messages, with inline code evaluation & styling powered by the
clipackageSimple creation of custom assertion functions with user-specified defaults
Installation
install.packages("assertions")Quick Start
All assertions start with assert, which means you just type it in and levarage autocomplete suggestions to look through all available options
Customizing Error Messages
# Customise any error messages using the `msg` argument
assert_number("A", msg = "Please supply a number!")
# Evaluate code in your error message using '{}' operators
foo = "A"
assert_number(foo, msg = "'{foo}' is not a number :(. Try again")
# Emphasise cetain words in error using {.strong text_to_emphasise}
assert_number("A", msg = "{.strong Try again}")For advanced customisation, see cli documentation
Create your own assertion functions
Have a custom assertion you want to use repeatedly?
Creating your own assertion functions is extremely easy
Just use assert_create(), you just need to supply:
a function that returns TRUE/FALSE when assertion should PASS/FAIL
a default error message
How about an example?
# Create a function that asserts input is lowercase
assert_lowercase <- assert_create(
func = function(x) {x == tolower(x)},
default_error_msg = "'{arg_name}' must be entirely lowercase"
)
#Assertion passes if input is lowercase
assert_lowercase("all lower case")
#But throws the expected error if uppercase characters are present
assert_lowercase("NOT all lower case") See ?assert_create() for details
Vectorised assertions
Assertions may have vectorised versions that test whether all elements in a vector/matrix meet a condition.
For example:
assert_greater_than()expects a single number as an inputassert_all_greater_than()works on vectors/matrices.
Vectorised functions have the assert_all_ prefix.
Contributing to this package
Two options
Request an assertion
- Open a github issue and request away. I’m happy to implement a tonne more assertions, just let me know what you want
Creating assertions yourself
Create a custom
assert_somethingfunction with a call toassert_create()orassert_create_chain()Create a github issue with the assertion creation code + any helper function you pass to the
funcargument (e.g.is_something())
Similar Packages
Great alternative packages for writing assertions include:
Each package has its own features and syntax. So hopefully there is one that suits your needs and preferences. I’m a big fan of checkmate for its speed, assertive for its huge library of ready-made assertion functions, and assertthat for its error message customization.
