Search code examples
rseleniummessagerselenium

How can I test if a function returns a message


BACKGROUND: In R the package "testit" (here) has both the functions has_warning and has_error but I'm looking for a function that returns a logical TRUE/FALSE if has_message.

WHY: to identify when a webElem$submitElement() from the RSelenium package returns an RSelenium message since the selenium messages are not classified as warnings or errors in R.

Is there a way to test if a function returns a message at all in R?

Ideally something like below:

#Ideally a function like this made up one:
has_message(message("Hello ","World!"))
[1] TRUE

has_message(print("Hello World!"))
[1] FALSE

Solution

  • You can use tryCatch:

    has_message <- function(expr) {
      tryCatch(
        invisible(capture.output(expr)),
        message = function(i) TRUE
      ) == TRUE
    }
    
    has_message(message("Hello World!"))
    # TRUE
    has_message(print("Hello World!"))
    # FALSE
    has_message(1)
    # FALSE
    

    Evaluate expression within tryCatch with invisible(capture.output()) to suppress print or other output. We need final == TRUE to return FALSE when no message was present, otherwise for the last to examples there would be no output.