r - `testthat::expect_silent()` 似乎没有注意到 ggplot2 错误

标签 r ggplot2 testthat

我无法理解 expect_silent() 的以下行为函数来自 testthat .

当测试代码返回任何输出(例如错误或警告)时,

expect_silent() 应该会失败:

library(testthat)

test_that("expect_silent works as expected", {
  expect_silent( {
    stop()
  } )
} )
#> Error: Test failed: 'expect_silent works as expected'
#> * 
#> 1: expect_silent({
#>        stop()
#>    }) at <text>:5
#> 2: quasi_capture(enquo(object), evaluate_promise)
#> 3: capture(act$val <- eval_bare(get_expr(quo), get_env(quo)))
#> 4: withr::with_output_sink(temp, withCallingHandlers(withVisible(code), warning = handle_warning, 
#>        message = handle_message))
#> 5: force(code)
#> 6: withCallingHandlers(withVisible(code), warning = handle_warning, message = handle_message)
#> 7: withVisible(code)
#> 8: eval_bare(get_expr(quo), get_env(quo))
#> 9: stop() at <text>:6

(以上是预期行为:expect_silent() 检测到 stop() 产生的错误,并且测试失败。)

但是,由于某种原因,它似乎没有检测到 ggplot2 表达式中发生的错误。例如,以下 ggplot2 代码由于拼写错误而产生错误:

library(ggplot2)

ggplot(diamonds, aes(x = carrot, y = price)) +
  geom_point()
#> Error in FUN(X[[i]], ...): object 'carrot' not found

但是 expect_silent() 似乎没有检测到错误:

test_that("expect_silent fails when ggplot2 throws an error", {
  expect_silent( {
    ggplot(diamonds, aes(x = carrot, y = price)) +
      geom_point()
  } )
} )

(不产生任何输出。)

我是否误解了expect_silent()的目的?这让我非常头疼,因为我试图用它来测试 ggplot2 扩展。

最佳答案

try catch ggplot 的输出,然后测试是否可以打印:

library(ggplot2)
library(testthat)

# First test should succeed (no output)
test_that("silent when ggplot2 succeeds", {
  working.plot <- ggplot(diamonds, aes(x = carat, y = price)) + geom_point()
  expect_silent(print(working.plot))
} )

# Second test should fail
test_that("fails when ggplot2 throws an error", {
  broken.plot <- ggplot(diamonds, aes(x = carrot, y = price)) + geom_point()
  expect_silent(print(broken.plot))
} )

第二个测试失败,并产生大量输出,我在下面对其进行了缩减:

Error: Test failed: 'expect_silent fails when ggplot2 throws an error'
* object 'carrot' not found

更新 - 2018 年 12 月 15 日

关于您关于为什么 print() 是必要的评论:

ggplot() 函数返回 ggplot 类的对象。 ggplot2 包重载了 print() 函数,因此它不会将对象打印到 R session 终端中的 STDOUT,而是打印图表。 R session 终端中的交互模式假定大多数命令通过 print() 函数运行。

测试在自己的环境中进行评估。测试环境是非交互式的,因此运行 print() 函数的假设不再成立。您可以使用基本 R 附带的 interactive() 函数对此进行测试。它应该在 R session 终端中报告 TRUE,在 test_that() 调用中报告 FALSE。

关于r - `testthat::expect_silent()` 似乎没有注意到 ggplot2 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53761025/

相关文章:

r - geom_polygon 绘制正态分布和逻辑分布

在 Windows : "Error: DLL ' vctrs' not found: maybe not installed for this architecture? 上重现 CRAN 检查单元测试问题“

r - x[[method]](...) : attempt to apply non-function in testthat test when sourcing file 中的错误

r - 使用 geom_segment 创建时间轴可视化

regex - 如何从数据框中的列名中删除 ".x"?

r - 导出时,如何用单个空格替换read.csv()生成的列名中的 “.”?

r - 在 R 中强制字符向量编码从 "unknown"到 "UTF-8"

r - 是否有一种巧妙的方法可以使用来自 geom_quantile() 的方程和其他统计数据来标记 ggplot 图?

r - 从facet_wrap更改标题的字体大小