Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force testthat to ignore warnings

Tags:

r

testthat

I have tests for a package that check functions that may or may not return warnings, for example:

test_that("test", {
  expect_true(is.na(log(NA)))
  expect_true(is.na(log(-1)))
})

I am not interested in checking weather the warnings appeared. Is there a way how I could tell testthat to ignore the warnings and not display them when running devtools::test()?

I know I could pack each function in expect_warning, or suppressWarnings, but instead I'd like to do something like

test_that("test", {  
  ignoreAllTheWarningsInside({
     expect_true(is.na(log(NA)))
     expect_true(is.na(log(-1)))
  })
})

Unfortunately options(warn = -1) also does not seem to work for this.

like image 926
Tim Avatar asked Dec 15 '16 13:12

Tim


1 Answers

Using suppressWarnings() around your script should do the trick. These examples show where you can use the function within your tests. No need for a custom function as all warnings will be silenced.

testthat::test_that("no suppression", {
  testthat::expect_true({
    warning()
    TRUE
  })
})
#> -- Warning (<text>:2:3): no suppression ----------------------------------------
#> 
#> Backtrace:
#>  1. testthat::expect_true(...)
#>  2. testthat::quasi_label(enquo(object), label, arg = "object")
#>  3. rlang::eval_bare(expr, quo_get_env(quo))

testthat::test_that("suppress inside", {
  testthat::expect_true(
    suppressWarnings({
      warning()
      warning()
      TRUE
    })
  )
})
#> Test passed

testthat::test_that("suppress outside", {
  suppressWarnings(
    testthat::expect_true({
      warning()
      warning()
      TRUE
    })
  )
})
#> Test passed

Created on 2021-11-23 by the reprex package (v2.0.1)

like image 65
Jordan Avatar answered Nov 19 '22 05:11

Jordan