【问题标题】:Report extra information from a test_that block when failing失败时报告来自 test_that 块的额外信息
【发布时间】:2021-06-02 01:33:01
【问题描述】:

我想在测试失败的情况下向控制台发送cat() 一些信息(我确信这不会发生,但我无法证明它不会发生),以便我可以调查问题。

现在我的代码大致如下:

testthat::test_that('Maybe fails', {
  seed <- as.integer(Sys.time())
  set.seed(seed)
  
  testthat::expect_true(maybe_fails(runif(100L)))
  testthat::expect_equal(long_vector(runif(100L)), target, tol = 1e-8)

  if (failed()) {
    cat('seed: ', seed, '\n')
  }
})

很遗憾,failed() 不存在。

expect_*() 的返回值似乎没有用,它们只是返回实际参数。

我正在考虑使用all.equal() 再次检查,但这是一个非常丑陋的重复。

【问题讨论】:

    标签: r testing testthat


    【解决方案1】:

    除了使用cat,您可以使用testthat 管理的info 参数及其reporters 用于所有expect 函数(argument kept for compatibility reasons):

    library(testthat)
    
    testthat::test_that("Some tests",{
      
      testthat::expect_equal(1,2,info=paste('Test 1 failed at',Sys.time()))
      testthat::expect_equal(1,1,info=paste('Test 2 failed at',sys.time()))
    
    })
    #> -- Failure (<text>:5:3): Some tests --------------------------------------------
    #> 1 not equal to 2.
    #> 1/1 mismatches
    #> [1] 1 - 2 == -1
    #> Test 1 failed at 2021-03-03 17:25:37
    

    【讨论】:

    • 您在问题中提供的示例中是否提到了&lt;&lt;-
    • 如何运行测试?即使在交互模式下使用&lt;&lt;-,我也会得到相同的结果
    • 对不起,我的错误:我提供的例子太简单了)-:
    • TryCatch 如果适合您,可以使用:tryCatch(testthat::expect_equal(1,2),error = function(e) {cat('test')})
    • 是的,没错,这就是我刚刚发现的 :-)。很重,但能胜任
    猜你喜欢
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    相关资源
    最近更新 更多