R tryCatch 和 testthat 期望

标签 r testthat

我有以下功能:

fun = function(expr) {
  mc = match.call()

  env = as.environment(within(
    list(),
    expr = eval(mc$expr)
  ))

  return(env)
}

tryCatch() 中调用,以便妥善处理 expr 中的任何错误条件。

它在标准错误条件下工作正常:

tryCatch({
  fun({
    stop('error')
  })
}, error = function(e) {
  message('error happened')
})

# error happened

但是,它不会捕获 testthat 期望错误(这是我的特定用例的首选):

library(testthat)

tryCatch({
  fun({
    expect_true(FALSE)
  })
}, error = function(e) {
  message('expectation not met')
})

# Error: FALSE isn't true.

或更简单地说:

library(testthat)

tryCatch({
  expect_true(FALSE)
}, error = function(e) {
  message('expectation not met')
})

# Error: FALSE isn't true.

未捕获期望错误。

从 R 3.2.2 升级到 R 3.3.0 后出现此问题 - 即在 R 3.2.2 中发现了预期错误。

有没有办法让 R 3.3.0 中的 tryCatch() 捕获 testthat 期望?

最佳答案

我将调试器设置为 expect(),然后单步执行几行代码(为简洁起见,对输出进行了编辑),并查看了发出信号的条件的类

> debug(expect)
> xx = expect_true(FALSE)
...
Browse[2]> n
debug: exp <- as.expectation(exp, ..., srcref = srcref)
Browse[2]>
...
Browse[2]> class(exp)
[1] "expectation_failure" "expectation"         "condition"   
Browse[2]> Q
> undebug(expect)       

所以它不是类“错误”的条件,并且可以显式捕获

> tryCatch(expect_true(FALSE), expectation_failure=conditionMessage)
[1] "FALSE isn't true.\n"

您还可以捕获expectation 类。

重新启动可以让您继续,如果这在某种程度上很重要。

result <- withCallingHandlers({
    expect_true(FALSE)
    expect_true(!TRUE)
    expect_true("this sentence")
}, expectation_failure=function(e) {
    cat(conditionMessage(e))
    invokeRestart("continue_test")
})

带输出

FALSE isn't true.
!TRUE isn't true.
"this sentence" isn't true.
> result
[1] FALSE

人们也可以捕获或处理成功

> tryCatch(expect_true(TRUE), expectation_success=class)
[1] "expectation_success" "expectation"         "condition"  

关于R tryCatch 和 testthat 期望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37870941/

相关文章:

r - 在 RUnit 或 testthat 中自动生成测试用例

R:本地环境中的 testthat test_file() 问题

r - 在 ggplot barplot 中添加自定义行

r - 自动将 y 轴文本和网格线对齐到 ggplot 的底部和顶部

r - 输出表未显示在 R Shiny 应用程序中

r - 抑制 test_that 输出 "Test passed :)"

regex - 使用 lapply 在列表中绘制数据并使用列表元素的名称作为绘图标题

r - as.numeric 函数更改我的数据框中的值

r - 如何在 R 中进行数据库连接/查询以进行单元测试

r - 控制test_package中脚本执行的顺序