2

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!

Toluene
  • 193
  • 6

1 Answers1

1

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.

jpiversen
  • 3,062
  • 1
  • 8
  • 12
  • Thanks! Your suggestion works if you require an input inmediatly after calling the function, but in my case needs to be somewhere in the middle of the process. But, its a really smart solution if you need an inmediate input! The link you suggested seems to be helping with my problem (for now). Cheers! – Toluene Mar 21 '22 at 11:25