Report the test of an expression in TAP format.

ok(test, description)

Arguments

test

Expression to be tested. Evaluating to TRUE is treated as success, anything else as failure.

description

Character string describing the test. If a description is not given a character representation of the test expression will be used.

Value

ok() returns whatever was returned when test is evaluated. More importantly it has the side effect of printing the result of the test in TAP format.

Details

See unittest package documentation.

The unittest.stop_on_fail option tells unit test to stop on the first test failure. This is useful when debugging long test scripts with multiple failures.

The unittest.output option tells unittest where output should be sent. This is most useful for vignettes, where sending output to stderr separates the unittest output from the vignette itself.

Examples


ok(1==1, "1 equals 1")
#> ok - 1 equals 1

ok(1==1)
#> ok - 1 == 1

ok(1==2, "1 equals 2")
#> not ok - 1 equals 2
#> # Test returned non-TRUE value:
#> # [1] FALSE

ok(all.equal(c(1,2),c(1,2)), "compare vectors")
#> ok - compare vectors

fn <- function () stop("oops")
ok(fn(), "something with a coding error")
#> not ok - something with a coding error
#> # Test resulted in error:
#> #  oops
#> # Traceback:
#> #  1: fn()
#> #  2: stop("oops")

ok(c("Some diagnostic", "messages"), "A failure with diagnostic messages")
#> not ok - A failure with diagnostic messages
#> # Test returned non-TRUE value:
#> # Some diagnostic
#> # messages

## Write a failing unit test script
test_path <- tempfile(fileext = ".R")
writeLines('
library(unittest)

ok(1==1)
ok(1==2)
ok(2==2)
ok(3==3)
', con = test_path)

# Without unittest.stop_on_fail, we see all failures:
options(unittest.stop_on_fail = NULL)
tryCatch(source(test_path), error = function (e) { print("=== error ===") })
#> ok - 1 == 1
#> not ok - 1 == 2
#> # Test returned non-TRUE value:
#> # [1] FALSE
#> ok - 2 == 2
#> ok - 3 == 3

# With, we stop at the first failing test:
options(unittest.stop_on_fail = TRUE)
tryCatch(source(test_path), error = function (e) { print("=== error ===") })
#> ok - 1 == 1
#> not ok - 1 == 2
#> # Test returned non-TRUE value:
#> # [1] FALSE
#> [1] "=== error ==="
options(unittest.stop_on_fail = NULL)

## Send unittest output to stderr()
options(unittest.output = stderr())
ok(ut_cmp_equal(4, 5), "4 == 5? Probably not")

## Reset unittest output to default (stdout())
options(unittest.output = NULL)
ok(ut_cmp_equal(4, 5), "4 == 5? Probably not")
#> not ok - 4 == 5? Probably not
#> # Test returned non-TRUE value:
#> # Mean relative difference: 0.25
#> # --- 4
#> # +++ 5
#> # [1] [-4-]{+5+}