我想運行所有測驗并獲取測驗結果并生成警告以編程方式創建降價報告,顯示測驗結果和測驗代碼中發生的潛在警告。
但是在試運行程序中似乎沒有辦法獲取或捕獲警告!我知道測驗是在封閉環境中執行的,但是真的沒有辦法讓 testthat 向我提供拋出的警告嗎?
在以下設定中,warn_list變數始終為空。
最小示例的三個檔案:
./tests/testthat.R
library(testthat)
warn_list <- list()
outcome <- withCallingHandlers(
testthat::test_dir(testthat::test_path(), stop_on_failure = FALSE),
warning = function(w) {
warn_list <<- c(warn_list, list(msg = w$message))
}
)
rmarkdown::render(input = './tests/create_test_report.Rmd')
請注意,在 Rmd 檔案中使用了outcome(and warn_list) 變數。
./tests/testthat/test_thrown_warn.R
test_that("Throws Warning", {
testthat::expect_gt(sum(3, 2), 3)
testthat::expect_equal(
{
warning('Example warning fired inside test!') # WHERE WARN IS THROWN
5
}, 5)
})
./tests/create_test_report.Rmd
---
title: "test_results_overview"
output: md_document
---
## Test outcomes overview
```{r test_outcome_summary, echo=FALSE}
# the test result
outcome2 <- as.data.frame(outcome)
outcome2 <- outcome2[, names(outcome2)[!names(outcome2) %in% c('result')]]
knitr::kable(t(data.frame(passed = sum(outcome2$passed),
warnings = sum(outcome2$warning),
failed = sum(outcome2$failed),
error = sum(outcome2$error))))
```
## Full test outcomes:
```{r test_outcome, echo=FALSE}
knitr::kable(outcome2)
```
## Produced warnings during the tests:
```{r warnings_during_testing, echo=FALSE}
knitr::kable(warn_list) # WHERE I TRY TO SHOW IT
```
uj5u.com熱心網友回復:
似乎SummaryReporter記者物件記錄了警告。正如您在評論中提到的,這些記錄非常少,但這似乎做到了:
library(testthat)
summary <- SummaryReporter$new()
test_file("somewarnings.R", reporter = summary)
summary$warnings$as_list()
每個警告都會在最后一條陳述句的串列中產生一個條目。它們存盤為條件物件,因此您可以執行以下操作
awarning <- summary$warnings$as_list()[[1]]
getSrcFilename(awarning$srcref)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/369323.html
下一篇:如何使條件替換在R中更有效?
