Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R testthat unit test data and helper function conventions

I am writing a R package, and I'm using testthat for unit testing. Many of my unit tests are for testing functions that work on a certain object specific to my package. For these tests I have made a helper function to set up a mock object. I have a few other helper functions as well to cut down the amount of code in my unit tests.

Currently these helper functions are in my R/ folder, because then they become available to my unit test files (which are in tests/testthat/). I find it a bit weird to place functions that are only used for the unit tests in the R/ folder. It would be nice if could place them somewhere in the tests/ folder. But it seems that doing so makes them unavailable during unit tests. Note that these helper functions are used for several different test files, so just placing the helper functions at the top of one file containing unit tests is not a solution.

Another related question is where to place data files that are used for unit tests. For example some of my functions work on ExpressionSet objects from the limma package (available on Bioconductor), which I load into R during the unit tests with the load() function. Currently I put them in the inst/extdata folder, because then I can acces them with system.file() during my unit tests. This folder also contains other data files which are meant for the users of the package. I find it a bit strange to place my test data, which is not meant for end users, in the same place as the package data, which is meant for the end users.

So my question is, is it possible to place the unit test helper functions and test data all in the tests/ directory. And if so, how do I acces these files from within the unit tests? What are the best practices/conventions for unit test helpers and unit test data?

like image 813
Sam De Meyer Avatar asked Mar 11 '16 13:03

Sam De Meyer


1 Answers

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")

like image 50
waferthin Avatar answered Nov 12 '22 23:11

waferthin