R - testthat using data file outside the testing directory

百般思念 提交于 2019-12-23 07:27:25

问题


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.



来源:https://stackoverflow.com/questions/19033987/r-testthat-using-data-file-outside-the-testing-directory

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