r - R:如何在测试结果和警告时从测试报告中省略测试警告消息
问题描述
我想在 R 中测试一个函数
- 返回正确的值
- 在计算过程中抛出正确的警告
为此,我创建了一个可重现的示例。有两个脚本,第一个(例如test-warning-and-result.R)工作正常且没有任何错误:
library(testthat)
f <- function(x) {
if (x < 0) {
warning("*x* is already negative")
return(x)
}
-x
}
test_that("warning and result", {
x = f(-1)
expect_that(x, equals(-1))
expect_warning(f(-1), "already negative")
})
但是,当我从外部脚本(例如run-test.R)运行测试时,它在逻辑上会在“x = f(-1)”处引发警告
library(testthat)
test_dir(".")
因为我知道会有一个警告并且正在测试它,所以我正在寻找一种方法来从测试报告中省略 test_that() 中的警告。理想情况下,我不必在一次测试中运行该函数两次。
任何想法,将不胜感激
解决方案
好吧,睡了一晚之后,我找到了一个简单的解决方案:
不要将函数结果存储在变量 x 中。将两个测试相互嵌套,将 expect_warning 放在外面
从改变
test_that("warning and result", {
x = f(-1)
expect_that(x, equals(-1))
expect_warning(f(-1), "already negative")
})
至
test_that("warning and result", {
expect_warning(expect_that(f(-1), equals(-1)), "already negative")
})
推荐阅读
- c# - 使用 OData 在 ASP.NET Web API 中转义 JSON 字符串
- c++ - 为什么使用以下函数从字符串流中过滤掉 ASCII 值 32 (' ') 也会过滤掉 '\n' 和 '\t'?
- javascript - 异步函数 try catch 块是否可以包装一个调用的异步函数,该函数也可能引发错误?
- mysql - MySQL SELECT 与子查询和 GROUP BY 的性能
- angular - Validators.email 不适用于 Angular Reactive Forms 中的法语字符
- sql - oracle 脚本上的 LOOP/FOR 语句
- python - 从 python 代码返回全局和局部变量及其值
- android - 在 Android 中使用动画移动和调整测试大小
- three.js - 从 Three.js v122 到 v123 的更改隐藏了 Mapbox 自定义层上的阴影
- azure - AKS maxPods 更新而不重新创建集群