R - 测试使用测试目录外的数据文件

qed*_*qed 10 testing r testthat

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

sgi*_*ibb 17

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

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

expect_true(file.exists(file.path("..", "data", "testhaplom.out")))
Run Code Online (Sandbox Code Playgroud)

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

expect_true(file.exists(file.path(system.file("data", package="YOUR_R_PACKAGE"), "testhaplom.out")))
Run Code Online (Sandbox Code Playgroud)

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

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