5

我有以下功能:

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

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

  return(env)
}

在 a 中调用它,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 中testthat的期望得到满足?tryCatch()

4

1 回答 1

9

我设置了调试器,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"  
于 2016-06-17T01:56:20.297 回答