如何根据 testthat::test_dir 的结果判断是否有任何测试失败

How to tell if any tests failed from result of testthat::test_dir

我有一个使用 testthat

的小测试程序
library(testthat)
source("src/MyFile.r")
results <- test_dir("tests", reporter="summary")

所以,我是 运行 这个来自 Rscript。问题是即使测试失败,退出代码也始终为 0。所以,如果有任何失败,我想调用 stop。但我似乎无法获得正确的代码来做到这一点。 results 中是否有我应该查看的方法或字段以确定是否存在任何错误?

目前,我的解决方案是像这样迭代结果:

for (i in 1:length(results)) {
  if (!is(results[[i]]$result[[1]], "expectation_success")) {
    stop("There were test failures")
  }
}

您只需将 stop_on_failure=TRUE 作为参数传递给 test_dir。如果您遇到任何测试失败,它将引发错误并退出非零。

例如:

results <- test_dir("mypath", stop_on_failure=TRUE)

这已记录在案 here

您还可以调整 jamesatha 的答案以检索测试失败的次数。

failed.tests <- sapply(results, function(r) {
  !is(r$result[[1]], "expectation_success")
})

然后你允许你像以前一样失败:

if (any(failed.tests)) {
  stop("There were test failures")
}

或者做一些更像

这样定制的事情
if (any(failed.tests)) {
  failed.test.count <- length(which(failed.tests))
  stop(paste(failed.test.count,"failed tests is",failed.test.count,"too many!")
}