Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something in testthat like expect_no_warnings()?

Tags:

r

testthat

I'm writing tests for a function that under some conditions will generate warnings. I want to ensure that under the other conditions it does not produce warnings. I don't see an obvious way to easily test that with testthat. I guess I could do something like:

my.result <- 25
my.func <- function() my.result
expect_equal(
  withCallingHandlers(
    my.func(), warning=function() stop("A Warning!")
  ), 
  my.result
)

or use options(warn=2), but I was hoping there would be something like:

expect_no_warnings(my.func())

Am I missing something obvious?

like image 239
BrodieG Avatar asked Feb 25 '14 02:02

BrodieG


3 Answers

In even more recent versions of ´testthat´ (from 0.11.0) you can do:

expect_warning(my.func(), regexp = NA)

From the documentation of expect_error

regexp: regular expression to test against. If omitted, just asserts that code produces some output, messsage, warning or error. Alternatively, you can specify NA to indicate that there should be no output, messages, warnings or errors.

So in the same way you can test that there are no messages, errors and output.

like image 170
alko989 Avatar answered Nov 05 '22 02:11

alko989


In recent versions of testthat, you can simply do:

expect_that(my.func(), not(gives_warning()))
like image 42
Karl Forner Avatar answered Nov 05 '22 02:11

Karl Forner


Update: Use expect_silent() nowadays because expect_that is deprecated, see help for the function!.

Update 2: As mentioned by @eaglefreeman the answer using expect_warning with the param regexp set to NA is the best solution since my answer causes the test to fail even if no warning was raised but just a a message was printed. This is not what the OP wanted (but just ignore warnings). I do not delete this answer to make this difference clear for other readers.

From the help's examples:

expect_silent("123")

f <- function() {
  message("Hi!")
  warning("Hey!!")
  print("OY!!!")
}

expect_silent(f())

Warning: expect_silent also expects no output so the semantics is a little bit different!

like image 4
R Yoda Avatar answered Nov 05 '22 03:11

R Yoda