assert: Assertions with a message

Description Usage Arguments Value Note Examples

View source: R/testit.R

Description

The function assert() was built from stopifnot(). It emits a message in case of errors, which can be a helpful hint for diagnosing the errors (stopifnot() only prints the possibly truncated source code of the expressions).

The infix operator %==% is simply an alias of the identical() function to make it slightly easier and intuitive to write test conditions. x %==% y is the same as identical(x, y).

Usage

1
2
3
assert(func, fact, time = NA, ...)

x %==% y

Arguments

func

name of the function to test

fact

a message for the assertions when any of them fails; treated the same way as expressions in ... if it is not a character string, which means you do not have to provide a message to this function

time

time the test takes to run

...

any number of R expressions, presumably to return vectors of TRUE's (if FALSE is returned anywhere, an error will show up)

x, y

two R objects to be compared

Value

Invisible NULL if all expressions returned TRUE, otherwise an error is signalled and the user-provided message is emitted.

Note

The internal implementation of stopifnot() is different with the function in R base: (1) the custom message fact is emitted if an error occurs (2) assert() requires the logical values to be non-empty (3) if ... contains a compound expression in {} which returns FALSE (e.g., if (TRUE) {1+1; FALSE}), the first and the last but one line of the source code from deparse() are printed in the error message, otherwise the first line is printed

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
assert('one equals one', 1==1)
assert('seq and : produce equal sequences', seq(1L, 10L) == 1L:10L)
assert('seq and : produce identical sequences', identical(seq(1L, 10L), 1L:10L))

# multile tests
T=FALSE; F=TRUE
assert('T is bad for TRUE, and so is F for FALSE', T!=TRUE, F!=FALSE)

# a mixture of tests
assert("Let's pray all of them will pass", 1==1, 1!=2, letters[4]=='d', rev(rev(letters))==letters)

# logical(0) cannot pass assert(), although stopifnot() does not care
try(assert('logical(0) cannot pass', 1==integer(0)))
stopifnot(1==integer(0)) # it's OK!

# a compound expression
try(assert('this if statement returns TRUE', if(TRUE){x=1;x==2}))

# no message
assert(!FALSE, TRUE, is.na(NA))

InsightRX/json2test documentation built on May 12, 2021, 9:49 p.m.