【问题标题】:Force testthat to ignore warnings强制 testthat 忽略警告
【发布时间】:2017-05-01 03:31:54
【问题描述】:

我对一个包进行了测试,用于检查可能返回或不返回警告的函数,例如:

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) 似乎也不适用于此。

【问题讨论】:

  • 我使用了以下解决方法:expect_warning(a <- is.na(log(NA)))expect_true(a); ...
  • @Christoph 我通常使用expect_warning(expect_true(is.na(log(-1)))),但问题如上:对于某些功能会有警告,而对于某些不会,所以我期待警告对于每个案例。此外,我不想将每个函数都打包在suppressWarnings() 中,因为它需要大量的复制和粘贴。
  • 如果我希望能够对a 进行多次测试,我会使用a <- ...(就像解释一样)。但我同意,处理警告有时很奇怪。你用RSudio吗? RStudio 会不会有问题?老实说,我从来没有检查过......
  • options(warn = -1) 为我工作。
  • 你确定使用 suppressWarnings({expect_true(is.na(log(NA))); expect_true(is.na(log(-1)))}) 这样的 suppressWarnings 不起作用吗?

标签: r testthat


【解决方案1】:

在你的脚本周围使用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 package (v2.0.1) 于 2021 年 11 月 23 日创建

【讨论】:

  • 据我记得写问题时它不起作用,但现在起作用了,所以我接受了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 2015-03-10
  • 2010-10-07
  • 2018-03-24
  • 2021-01-15
  • 2018-12-09
相关资源
最近更新 更多