Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place library calls with testthat?

I am looking for best practice help with the brilliant testthat. Where is the best place to put your library(xyzpackage) calls to use all the package functionality?

I first have been setting up a runtest.R setting up paths and packages. I then run test_files(test-code.R) which only holds context and tests. Example for structure follows:

# 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 e.g. test-plotdata.R (a 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...
})
  1. Is this the way @hadley intended it to be used? It is not clear from the journal article. Should I also be duplicating library calls in my test files as well? Do you need a library set up in each context, or just one at start of file?

  2. Is it okay to over-call library(package) in r?

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

Thanks for your help.

like image 712
micstr Avatar asked Apr 10 '15 08:04

micstr


1 Answers

Some suggestions / comments:

  • set up each file so that it can be run on its own with test_file without additional setup. This way you can easily run an individual file while developing if you are just focusing on one small part of a larger project (useful if running all your tests is slow)
  • there is little penalty to calling library multiple times as that function first checks to see if the package is already attached
  • if you set up each file so that it can be run with test_file, then test_dir will work fine without having to do anything additional
  • you don't need to library(testthat) in any of your test files since presumably you are running them with test_file or test_dir, which would require testthat to be loaded

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

like image 176
BrodieG Avatar answered Oct 07 '22 11:10

BrodieG