简体   繁体   中英

R package code coverage with test_that and readline()

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 eg this answer on SO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM