Test package function that writes to disk

Viewed 457

I am trying to write a test for a package function in R.

Let's say we have a function that simply writes a string x to disk using writeLines():

exporting_function <- function(x, file) {

 writeLines(x, con = file)

 invisible(NULL)
}

One way of testing it would be to check if a file exists. Typically, it should not exist at first, but after the exporting function was run it should. Also, you might want to test the file size to be greater than 0:

library(testthat)

test_that("file is written to disk", {
 file = 'output.txt'
 expect_false(file.exists(file))

 exporting_function("This is a test",
                    file = file)


 expect_true(file.exists(file))

 expect_gt(file.info('output.txt')$size, 0)
})

Is this a good way to test it? In the CRAN Repository Policy it states that Packages should not write in the user’s home filespace (including clipboards), nor anywhere else on the file system apart from the R session’s temporary directory. Would this test violate this constraint?

There is a expect_output_file function. From the documentation and examples I am not sure if this is a more appropriate expectation to test the function. It requires a.o. an object argument which should be the object to test. What is the object to test in my case?

1 Answers

That looks as if it violates CRAN policy. Why not simply write to the temporary directory, using

file <-  tempfile()

in place of

file = 'output.txt'

?

As to whether it is a good test: wouldn't it be better to try reading the file back in, and confirming that what was read matches what was written? That's easy in your toy example. It might be harder in the real one, but having an import function paired with your export function is always a good idea.

Related