31

I would like to know if it is possible in R using testthat test framework to set the tolerance for equality.

Currently, if example.R is:

library(testthat)
three_times<-function(x) 3*x

context('Test three_times')
test_that('Three times returns 3 times x',{
    expect_equal(three_times(3),9)
    expect_equal(three_times(pi),9.4247)
})

and executed with test_file('example.R','stop'), the first test passes, but the second fails with:

 Error: Test failed: 'Three times returns 3 times x'
Not expected: three_times(pi) not equal to 9.4247
Mean relative difference: 8.271963e-06. 

Is it possible to set a higher error threshold for the mean relative difference? for example 1e-3. I have some expected results with only a 3 decimal precision, meaning now my tests always fail...

Oneira
  • 1,365
  • 1
  • 14
  • 28

1 Answers1

43

You can pass arguments scale or tolerance. These arguments are passed to all.equal.

expect_equal(three_times(pi),9.4247, tolerance=1e-8)
Error: three_times(pi) not equal to 9.4247
Mean relative difference: 8.271963e-06

expect_equal(three_times(pi),9.4247, tolerance=1e-3)

See ?all.equal for more help

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • 2
    And you _must_ name `tolerance=` as from testthat 0.10.1 on CRAN May 2015. i.e. `expect_equal(pi*3, 9.4247, 1e-3)` no longer works and must be `expect_equal(pi*3, 9.4247, tolerance=1e-3)` – Matt Dowle Sep 10 '15 at 22:46