我在我的一个程序包中使用{cli}消息,但因为它们会使得测试结果混乱,因此我想在我的测试中隐藏这些消息。是否有办法可以做到这一点?
我看到 {cli} 有一个TESTTHAT环境变量,但我不知道它是否适用于此目的,也不知道如何使用它。请注意,我希望找到一个简单易行的解决方案,例如全局测试选项。我不想手动编辑所有的测试或消息。
可重现的示例:
library(testthat)
library(cli)
test_that("addition works", {
cli_alert_info("This message should not appear")
expect_equal(1+1, 2)
})
#> i This message should not appear
#> Test passed
编辑:我可以创建一个自定义的
test_that()
,它会像下面这样包装suppressMessages()
:my_test_that <- function(desc, code) {
test_that(desc, {
suppressMessages({
code
})
})
}
my_test_that("addition works", {
cli_alert_danger("This message should not appear")
expect_equal(1+1, 2)
})
#> Test passed
然后将其存储在tests/testthat/setup.R
中。问题是,如果测试失败,则指示my_test_that()
中的行,而不是实际出现错误的行(因此基本上所有错误和警告都将引用同一行):
my_test_that("addition works", {
cli_alert_danger("This message should not appear")
expect_equal(1+4, 2)
})
-- Failure (.active-rstudio-document:6:5): addition works ----------------------
1 + 4 (`actual`) not equal to 2 (`expected`).
在这里,错误指的是带有
suppressMessages()
的那一行。这使得找到问题的源头变得更加困难。