我在我的一个包中使用{cli]消息。我想在我的测试中隐藏这些消息,因为它们扰乱了结果的测试。有办法吗?
我已经看到{cli}有一个检验环境变量,但我不知道它是否存在,也不知道如何使用它。请注意,我更喜欢实现简单的解决方案,例如测试全局选项。我不想手动编辑我的所有测试或消息。
可复制的例子:
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()的行。这使得很难找到问题的根源。
发布于 2022-03-11 09:46:07
在这个吉特布问题中给出了一个解决方案。将withr::with_options()或withr::local_options()与option cli.default_handler = function(...) { }一起使用似乎是可行的。
library(testthat)
library(cli)
my_test_that <- function(desc, code) {
withr::with_options(
list(
cli.default_handler = function(...) { },
usethis.quiet = TRUE
),
test_that(desc, {
code
})
)
}
my_test_that("addition works", {
cli_alert_danger("This message should not appear")
expect_equal(1+2, 2)
})
-- Failure (.active-rstudio-document:15:3): addition works ---------------------
1 + 2 not equal to 2.
1/1 mismatches
[1] 3 - 2 == 1请注意,这将删除所有cli消息,因此不可能在my_test_that()中使用expect_message()。
https://stackoverflow.com/questions/71406719
复制相似问题