Skip to content

test_xxx() functions with message saved for later use #290

@phgrosjean

Description

@phgrosjean

Could you consider to rework the test_xxx() functions so that messages are saved for later use? It would look like this:

test_numeric <- function(x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, 
    all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, 
    unique = FALSE, sorted = FALSE, names = NULL, typed.missing = FALSE, 
    null.ok = FALSE) {

    is.logical(checkmate$message <- .Call(c_check_numeric, x, 
        lower, upper, finite, any.missing, all.missing, len, 
        min.len, max.len, unique, sorted, names, typed.missing, 
        null.ok))
}

Then, a function like last_checkmate_message() could retrieve the last message, if any:

last_checkmate_message <- function() {
  msg <- checkmate$message
  if (is.logical(msg) "", else msg
}

This would allow to use test_xxx() functions in if (...) constructs, while being able to retrieve the error message and use a different way to present the error. For instance, if you prefer to use rlang::abort():

x <- -1:3
if (!test_numeric(x, lower = 0)) rlang::abort(last_checkmate_message())

This would provide much more flexibility on the way the error message is handled.

Note that I used is.logical() instead of isTRUE() in the proposed test_numeric() version because isTRUE() makes several unnecessary verifications, providing the test_xxx() functions return either a logical TRUE, or in case of failure, a character string. This way, the new version is even faster that the old one, despite it also includes assignment to checkmate$message:

old_test_numeric <- checkmate::test_numeric
microbenchmark::microbenchmark(test_numeric(x), old_test_numeric(x))
# Unit: nanoseconds
#                expr min  lq    mean median   uq  max neval cld
#      test_numeric(x) 779 820  961.86    861  943 7585   100   a
#  old_test_numeric(x) 902 943 1111.51    984 1107 7421   100   a

microbenchmark::microbenchmark(test_numeric(1), old_test_numeric(1))
# Unit: nanoseconds
#                 expr min  lq   mean median  uq  max neval cld
#      test_numeric(1) 656 697 777.77    697 779 4059   100  a 
#  old_test_numeric(1) 779 820 929.88    861 943 5986   100   b

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions