我想在每次测试时用一组新的数字测试一个函数。这个想法是在我没有预料到的情况下实现失败。
library(testthat)
hypotenuse_length <- function(a, b){
sqrt(a^2 + b^2)
}
bad_hypotenuse_length <- function(a, b){
sqrt(a^2 + b^2) + 1
}
test_that("Hypotenuse is always less than sum of other two sides", {
a <- abs(rcauchy(1))
b <- abs(rcauchy(1))
expect_lte(bad_hypotenuse_length(a, b), a + b)
})
问题是当我收到失败时,我不知道是什么值a
并b
触发了失败。
我可以通过逆向工程为特定操作实现这一点expect_lte
:
my_expect_lte <- function(a, b, actual, expected, label = NULL, expected.label = NULL){
op <- match.fun("<=")
lab_act <- testthat:::make_label(actual, label)
lab_exp <- testthat:::make_label(expected, expected.label)
stopifnot(is.numeric(actual), length(actual) == 1)
stopifnot(is.numeric(expected), length(expected) == 1)
msg <- "not less than"
diff <- actual - expected
testthat::expect(op(diff, 0),
sprintf("%s is %s %s. Difference: %.3g. a = %.3g b = %.3g",
lab_act, msg, lab_exp, diff, a, b))
}
set.seed(1) # not ordinarily present
a <- abs(rcauchy(1))
b <- abs(rcauchy(1))
my_expect_lte(a, b, bad_hypotenuse_length(a, b), a + b)
错误:bad_hypotenuse_length(a, b) 不小于 a + b。差异:0.143。a = 1.1 b = 2.35
有没有办法使用现有的函数来返回类似的信息?也就是说,返回与 相同expect_...
,但还包括传递的参数的值。(如果 `testthat` 测试在 `R` 中失败,则打印自定义诊断信息的解决方案要么打印信息,要么不管测试结果如何,或者不适合现有测试。)