首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在带有{testthat}的测试中隐藏{cli}消息

在带有{testthat}的测试中隐藏{cli}消息
EN

Stack Overflow用户
提问于 2022-03-09 09:01:45
回答 1查看 117关注 0票数 2

我在我的一个包中使用{cli]消息。我想在我的测试中隐藏这些消息,因为它们扰乱了结果的测试。有办法吗?

我已经看到{cli}有一个检验环境变量,但我不知道它是否存在,也不知道如何使用它。请注意,我更喜欢实现简单的解决方案,例如测试全局选项。我不想手动编辑我的所有测试或消息。

可复制的例子:

代码语言:javascript
复制
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()包装如下:

代码语言:javascript
复制
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()中的行,而不是实际出现错误的行(因此,基本上所有错误和警告都将引用同一行):

代码语言:javascript
复制
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()的行。这使得很难找到问题的根源。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-11 09:46:07

这个吉特布问题中给出了一个解决方案。将withr::with_options()withr::local_options()option cli.default_handler = function(...) { }一起使用似乎是可行的。

代码语言:javascript
复制
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()

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71406719

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档