mercredi 26 février 2020

R: How to suppress warning message when testing for result AND warning

I want to test in R if a function

  1. returns the correct value
  2. throws the right warning during calculation

For that, I created a reproducible example. There a two scripts, the first one (e.g. test-warning-and-result.R) works fine and without any errors:

library(testthat)

f <- function(x) {
  if (x < 0) {
    warning("*x* is already negative")
    return(x)
  }
  -x
}

test_that("warning and result", {
  x = f(-1)
  expect_that(x, equals(-1))
  expect_warning(f(-1), "already negative")
})

However, when I run the tests from an external script (e.g. run-test.R), it logically throws a warning at "x = f(-1)"

library(testthat)
test_dir(".")

Picture of test results

Since I know there will be a warning and am testing for it, I'm searching for a way to suppress the warning which occurs when I'm checking for the result ("x = f(-1)")

Any Ideas would be appreciated

Aucun commentaire:

Enregistrer un commentaire