Where to place library calls with testthat?

I am looking for the best practice with brilliant testthat . Where is the best place to place your library(xyzpackage) calls to take full advantage of the package?

At first I set up runtest.R path and package settings. Then I run test_files(test-code.R) , where it only contains context and tests. Example for structure:

 # runtests.R library(testthat) library(data.table) source("code/plotdata-fun.R") mytestreport <- test_file("code/test-plotdata.R") # does other stuff like append date and log test report (not shown) 

and in my test files, for example. test-plotdata.R (stripped down version):

 #my tests for plotdata context("Plot Chart") test_that("Inputs valid", { test.dt = data.table(px = c(1,2,3), py = c(1,4,9)) test.notdt <- c(1,2,3) # illustrating the check for data table as first param in my code expect_error(PlotMyStandardChart(test.notdt, plot.me = FALSE), "Argument must be data table/frame") # then do other tests with test.dt etc... }) 
  • Is this the way that @hadley was meant to be used? From the article articles are not clear. Should I also duplicate library calls in my test files? Do you need a library configured in each context or only one at the beginning of the file?

  • Is it possible to convince a library (package) in r?

  • To use test_dir() and other functions , what is the best way to configure your files . I use require () in my functions, but I also set up sample test data in contexts. (In the example above, you will see that I will need the data.table package for test.dt for use in other tests).

Thank you for your help.

+6
source share
2 answers

Some suggestions / comments:

  • configure each file so that it can run independently using test_file without additional configuration. That way, you can easily run a separate file during development if you just focus on one small part of a larger project (useful if you run all your tests slowly).
  • there is a little penalty when calling library several times, since this function first checks to see if the package is already attached
  • if you configure each file so that it can be run using test_file , then test_dir will work fine without doing anything extra
  • you do not need library(testthat) in any of your test files, since you are supposedly running them with test_file or test_dir , which requires testthat to load

Alternatively, you can just take a look at one of Hadley's latest packages to see how he does it (e.g. dplyr tests ).

+4
source

If you use devtools::test(filter="mytestfile") , then devtools will take care of calling auxiliary files, etc. for you. This way you don’t have to do anything special for your test file to work on its own. Basically, this is exactly the same as if you were running a test, but only test_mytestfile.R in your testthat folder.

0
source

Source: https://habr.com/ru/post/984935/


All Articles