【问题标题】:"Random unit" testing“随机单元”测试
【发布时间】: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)
})

问题是当我收到失败时,我不知道ab 的哪些值触发了失败。

我可以通过逆向工程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


    【解决方案1】:

    虽然我没有直接回答您的问题,但我建议使用 quickcheck 包,因为它提供了随机测试的框架。它带有用于检查失败案例的好工具(参见tutorial 中的repro 函数用法)。

    【讨论】:

      猜你喜欢
      • 2014-02-08
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      • 2018-03-19
      相关资源
      最近更新 更多