强制 testthat 忽略警告
Force testthat to ignore warnings
我有一个包的测试,它检查可能会或可能不会 return 警告的功能,例如:
test_that("test", {
expect_true(is.na(log(NA)))
expect_true(is.na(log(-1)))
})
我不有兴趣检查出现警告的天气。有什么方法可以让 testthat
忽略 警告并且在 运行 devtools::test()
时不显示警告?
我知道我可以将每个函数打包到 expect_warning
或 suppressWarnings
中,但我想做一些类似
的事情
test_that("test", {
ignoreAllTheWarningsInside({
expect_true(is.na(log(NA)))
expect_true(is.na(log(-1)))
})
})
不幸的是 options(warn = -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 创建
我有一个包的测试,它检查可能会或可能不会 return 警告的功能,例如:
test_that("test", {
expect_true(is.na(log(NA)))
expect_true(is.na(log(-1)))
})
我不有兴趣检查出现警告的天气。有什么方法可以让 testthat
忽略 警告并且在 运行 devtools::test()
时不显示警告?
我知道我可以将每个函数打包到 expect_warning
或 suppressWarnings
中,但我想做一些类似
test_that("test", {
ignoreAllTheWarningsInside({
expect_true(is.na(log(NA)))
expect_true(is.na(log(-1)))
})
})
不幸的是 options(warn = -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 创建