Good morning, I'm building an R package and trying to get code coverage (via codecov) as high as possible. But, I'm struggling to use test_that when the function requires input via readline(). Here is a simplified function using readline() in a similar way to mine.
fun<-function(){
y<-as.numeric(readline((prompt="Enter a number: ")))
res<-2*y
res
}
Any way to use test_that()
with this function without having to manually input a number everytime this runs? Like, setting up a default input number only for the test?
Thanks!
From ?readline()
:
This [function] can only be used in an interactive session.
In a case like this I would probably rewrite my function to something like this:
fun <- function(y = readline(prompt = "Enter a number: ")) {
y <- as.numeric(y)
res <- 2 * y
res
}
When used interactively it works just the same, but when you want to test the function you can do so programmatically, for example:
expect_equal(
fun(y = 10),
20
)
Other alternatives is to include some options in your package or an environment variable that tells your code that you are in testing mode, and alters the behavior of fun()
. See e.g. this answer on SO.