Search code examples
runit-testingtestingtestthat

How to test an R function which uses Sys.time()?


I have the following R function within a software package, which outputs Sys.time() to the output for users to know how the algorithm is proceeding:

func = function(num1, num2){
    result = num1 + num2
    return(paste0(' ', as.character(Sys.time()), ':  with result: ', result))
}

An example of using this function is as follows:

> func(2, 2)
[1] " 2018-03-11 07:24:05:  with result: 4"
> 

I need to test this function. Normally, I would use the testthat package:

https://cran.r-project.org/web/packages/testthat/index.html

Question: How does one set the Sys.time() in order to test this function? Are there other methods available to test this?

If there was no Sys.time(), this process would be simple:

library(testthat)
expect_equal(func(2, 2), 4)
expect_equal(func(2, -2), 0)
expect_error(func('a', 'b'))

Solution

  • You could use something like this.

    func <- function(num1, num2){
        result = num1 + num2
        return(paste0(' ', as.character(Sys.time()), ':  with result: ', result))
    }
    
    library(testthat)
    

    uses stringr

    expect_equal(as.numeric(stringr::str_extract(func(2, 2), "[0-9]*\\.*[0-9]*$")), 4)
    expect_equal(as.numeric(stringr::str_extract(func(2, -2), "[0-9]*\\.*[0-9]+$")), 0)
    expect_equal(as.numeric(stringr::str_extract(func(15, 21.3), "[0-9]*\\.*[0-9]+$")), 36.3)
    

    uses base r

    expect_equal(as.numeric(regmatches(func(2, 2), regexpr("[0-9]*\\.*[0-9]*$", func(2, 2)))), 4)
    expect_equal(as.numeric(regmatches(func(2, -2), regexpr("[0-9]*\\.*[0-9]*$", func(2, -2)))), 0)
    expect_equal(as.numeric(regmatches(func(15, 21.3), regexpr("[0-9]*\\.*[0-9]*$",func(15, 21.3)))), 36.3)
    

    or test the internals of function exactly, but that depends on what is exactly in your function internals.

    expect_equal(func(2, 2), paste0(' ', as.character(Sys.time()), ': with result: ', 4))
    expect_equal(func(2, -2), paste0(' ', as.character(Sys.time()), ': with result: ', 0))
    expect_equal(func(15, 21.3), paste0(' ', as.character(Sys.time()), ': with result: ', 36.3))