强制testthat忽略警告

15

我有一个测试套件,用于检查可能会或可能不会返回警告的函数,例如:

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

我不想检查警告是否出现。有没有办法告诉testthat在运行devtools :: test()时忽略警告并不显示它们?

我知道我可以使用expect_warningsuppressWarnings包装每个函数,但我想做点其他的事情。

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

不幸的是,options(warn = -1) 看起来对此也没有用。


1
我使用了以下解决方法:expect_warning(a <- is.na(log(NA)))expect_true(a); ... - Christoph
4
@Christoph 我通常使用 expect_warning(expect_true(is.na(log(-1)))),但问题如上所述:对于某些函数,会有警告,而对于某些函数,则不会有警告,因此我并不希望针对每种情况都预期警告。此外,我不想在每个函数中打包 suppressWarnings(),因为这需要大量复制和粘贴。 - Tim
options(warn = -1) 对我很有效。 - Pavel Obraztcov
你确定使用类似于 suppressWarnings({expect_true(is.na(log(NA))); expect_true(is.na(log(-1)))}) 的 suppressWarnings 不起作用吗? - Karl Forner
@KarlForner 这个问题已经被问了将近5年,现在很难对它进行评论。 - Tim
显示剩余2条评论
1个回答

6

在你的脚本周围使用suppressWarnings()函数应该可以解决问题。这些示例显示了在测试中可以使用该函数的位置。无需自定义功能,所有警告都将被静音。

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

本示例由 reprex包 (v2.0.1)创建于2021年11月23日。


据我所记,当我提出问题时它并没有起作用,但现在可以了,因此我接受这个答案。 - Tim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接