我有以下功能:
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/