Testing behaviour that uses a suggested package

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.

I need to get out of the habit of finding a solution 10 minutes after posting the question. Split process_file into 2 parts, one that is used if readr is installed and the other if not. These functions can then be tested separately.

#' @export
process_file <- function(file, ...)
{
    if(requireNamespace("readr"))
        process_file_readr(file, ...)
    else process_file_base(file, ...)
}

# these are not exported
process_file_readr <- function(file, ...)
{
    df <- readr::read_csv(file, ...)
    # ... do more stuff ...
}

process_file_base <- function(file, ...)
{
    df <- read.csv(file, ...)
    # ... do more stuff ...
}

If the commented "do more stuff" is nontrivial, it too can be split out into a new function that is then called from both process_file_readr and process_file_base.

I see you found a good solution (I think it's nice for all of us that you document your problem solving :slight_smile:) , but wanted to mention this challenge was mentioned in an R-hub blog post.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.