Let's say I have a function in a package whose behaviour depends on whether another, optional, package is installed. For example, I might have a process_file
function that reads a CSV file and does some more stuff to it. Depending on whether the readr package is available, it might use either readr::read_csv
or read.csv
. The idea is that I want to take advantage of readr's features if it's there, but I don't want to require the user to install it.
#' @export
process_file <- function(file, ...)
{
df <- if(requireNamespace("readr"))
readr::read_csv(file, ...)
else read.csv(file, ...)
# ... do more stuff ...
}
How would I go about testing that process_file
works properly both in the presence and absence of readr (assuming I have it installed)?
If the function's behaviour was controlled by a global option, I could use withr::local_options
as described here. But I'd rather not create a new global option if I can help it. Similarly I could make using readr an argument to the function, but that seems inelegant.