使用{testthat}在测试中隐藏{cli}消息

3

我在我的一个程序包中使用{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()的那一行。这使得找到问题的源头变得更加困难。
1个回答

2

这个Github问题中提供了一种解决方案。使用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()

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