R - testthat using data file outside the testing d

2019-06-15 21:36发布

问题:

I am using testthat to test a package with a file tree similar to the following:

   .
    ├── data
    │   └── testhaplom.out
    ├── inst
    │   └── test
    │       ├── test1.r
    │       ├── tmp_S7byVksGRI6Q
    │       │   └── testm.desc
    │       └── tmp_vBcIkMN1arbn
    │           ├──testm.bin
    │           └── testm.desc
    ├── R
    │   ├── haplom.r
    │   └── winIdx.r
    └── tmp_eUG3Qb0PKuiN
        └── testhaplom.hap2.desc

In the test1.r file, I need to use the data/testhaplom.out file as input data for a certain function, but if I do test_file(test1.r), it changes into the inst/test directory and cannot see the data file, giving the error below:

...Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'data/testhaplom.out': No such file or directory

回答1:

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.