Bob Jansen
Bob Jansen

Reputation: 1287

Report extra information from a test_that block when failing

I want to cat() some information to the console in the case a test fails (I'm getting confident this won't happen but I can't prove it wont) so I can investigate the issue.

Now I have code that is approximately like this:

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')
  }
})

Unfortunately, failed() doesn't exist.

Return values of expect_*() don't seem useful, they just return the actual argument.

I'm considering to just check again using all.equal() but that is a pretty ugly duplication.

Upvotes: 1

Views: 48

Answers (1)

Waldi
Waldi

Reputation: 41220

Instead of using cat, you could use the info argument managed by testthat and its reporters for all expect functions (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

Upvotes: 1

Related Questions