【发布时间】:2016-07-20 22:39:16
【问题描述】:
我想在每次测试时用一组新的数字测试一个函数。这个想法是在我没有预料到的情况下实现失败。
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_... 相同,但还包括传递的参数的值。 (解决方案Printing custom diagnostic information if `testthat` test fails in `R` 要么打印信息而不管测试结果如何,要么不适合现有测试。)
【问题讨论】:
标签: r unit-testing testthat