Where Should I Put Data for Automated Tests with Testthat

Where to put test data in R package for R CMD CHECK

The correct answer is to use readRDS, which means saving each object separately via saveRDS

eg.

my_data <- readRDS(file= system.file("testdata", 'dat-mydata.rds', package= "synthACS"))

R testthat unit test data and helper function conventions

I understand that files in tests/testthat/ that begin with helper are sourced before running any tests by testthat. So you can place helper functions for tests inside suitably named helper-*.R within tests/testthat/.

From R help for source_file from testthat (?testthat::source_file)

 The expectation is that the files can be sourced in alphabetical
order. Helper scripts are R scripts accompanying test scripts but
prefixed by ‘helper’. These scripts are once before the tests are
run.

An example can be seen in the source code for dplyr on github.

As for testdata. I follow the advice from one comment from this question: Where to put data for automated tests with testthat? and use inst/testdata, then access the files with system.file("testdata",...,package="my_package")

Where to put external files for testthat tests

You put these in the testthat folder (inside tests). There, you include any "external" file that you might use for your tests (or that provides some additional explanation that the user might find informative, such as in a ".txt") file. You also have your .r testfiles here.

Alternatively (or, in addition): you can also load your file from another location, by including the path to the file (e.g., to your data folder--use a relative path). However, this can result in a fragile infrastructure, since you might not be able to rely on that external location to be available at all times, in which case testthat will raise an error when it can not find the file.

An example of linking to a file outside of tests, see here. Beware when you do this, though.

R - testthat using data file outside the testing directory

There are two solutions for your problem:

You could use the relative path (../data/testhaplom.out):

expect_true(file.exists(file.path("..", "data", "testhaplom.out")))

Or you could use system.file to get the location of the data directory:

expect_true(file.exists(file.path(system.file("data", package="YOUR_R_PACKAGE"), "testhaplom.out")))

I prefer the second solution.

BTW: file.path use the correct path separator on each platform.



Related Topics



Leave a reply



Submit