Search code examples
rdynamicr-package

How to create a function with dynamic input for an R package?


I'm creating an R package. I have a function that needs some dynamic input from the user in order to produce the desired output. I'm currently using readline() as the dynamic input method. Problem is I don't know how to make it work for both roxygen2 examples, nor how to properly test it with testthat (or any other method).

If there's a better way to get user input that'd be good as well.

Here's a minimal function with the same issues as my function.

#' Dynamic Input Example
#'
#' @param input A number
#'
#' @return Console input times 2 minus 1
#' @export
#'
#' @examples
#' exampler(4)
exampler <- function(input){
  dynamic_input <- as.numeric(readline(prompt=paste("Give a value between", input*3-1, "and", input*7+2)))
  return(dynamic_input*2-1)
}

Solution

  • Use this syntax to prevent functions examples from being run during check:

    #' @examples \dontrun{interactive_function()}
    

    And for the test suite we can use the following (needs the mockery package):

    test_that("interactive_function works with defaults", {
    
        mockery::stub(interactive_function, "readline", "dummy return value for mock function")
     
        testvalue <- interactive_function()
    
        [testcode ...]
     
    })
    

    With that code, mockery will replace the readline function during the test if it is called by the interactive_function and return "dummy return value for mock function". mockery also offers functions to track function calls and even the arguments that were used when calling the functions. All very handy stuff ;)