11

我正在使用testthat类似于以下的文件树来测试一个包:

   .
    ├── 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

test1.r文件中,我需要将该data/testhaplom.out文件用作某个函数的输入数据,但如果我这样做test_file(test1.r),它会更改到inst/test目录并且看不到数据文件,并给出以下错误:

...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
4

1 回答 1

19

您的问题有两种解决方案:

您可以使用相对路径 ( ../data/testhaplom.out):

expect_true(file.exists(file.path("..", "data", "testhaplom.out")))

或者您可以使用system.file获取数据目录的位置:

expect_true(file.exists(file.path(system.file("data", package="YOUR_R_PACKAGE"), "testhaplom.out")))

我更喜欢第二种解决方案。

顺便说一句:file.path在每个平台上使用正确的路径分隔符。

于 2013-09-26T18:43:36.057 回答