Where should I put data for automated tests with testthat?

醉酒当歌 提交于 2019-11-30 02:47:51

Lifting from Ben Bolker's comments:

I use inst/testdata and then system.file("testdata",...,package="my_package")

The advantage of this method:

  • You can keep your file structure neat, especially if you have many data files and/or tests.
  • The fact that files in inst are installed is long-standing canonical R practice; it seems safer that system.file("testdata", "some_file") will always work than that ../testdata/some_file will do. I've had bad experiences using relative file paths when doing R CMD check.
  • Unlike Sathish's answer, it doesn't depend on your data being "stored" as R code.
  • tests are kept inside a file which is prefixed with 'test_'
  • data are kept inside files prefixed with 'helper_'

Package Directory and File Structure:

└──pkg_name/
    ├── DESCRIPTION
    ├── NAMESPACE
    ├──.Rbuildignore
    ├── data/
    ├── man/
    ├── R/
    ├── vignettes/
    └── tests/
        ├── testthat.R
        └── testthat/
             └── helper_myfunc1.R
             └── helper_myfunc2.R
             └── test_pkg_name.R

testthat.R

library(testthat)
library(pkg_name)
test_check("pkg_name")

helper_myfunc1.R contains data for testing myfunc1 function

a1 <- 2
a2 <- 2
b1 <- 2*3
b2 <- 6

helper_myfunc2.R contains data for testing myfunc2 function

c1 <- 50/2
c2 <- 25
d1 <- c(2,3)
d2 <- c(2,3)

test_pkg_name.R contains tests for functions and other objects in the package

context('pkg_name_functions')

test_that('myfunc1',
          {
            expect_identical(a1, a2)
            expect_identical(b1, b2)
          })

test_that('myfunc2',
          {
            expect_identical(c1, c2)
            expect_identical(d1, d2)
          })

Conduct unit testing

library("devtools")

devtools::load_all()
# Loading pkg_name

devtools::test()
# Loading pkg_name
# Testing pkg_name
# pkg_name_functions: ....

# DONE ================================================================

The Data chapter of the same R-Pkgs book says "it’s ok to put small files directly in your test directory". That's what I've done in the past. And it sounds like that's what you're already doing, plus the testdata directory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!