【问题标题】:R - testthat using data file outside the testing directoryR - 使用测试目录外的数据文件进行测试
【发布时间】:2013-10-02 18:15:42
【问题描述】:

我正在使用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

【问题讨论】:

    标签: r testing testthat


    【解决方案1】:

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

    您可以使用相对路径 (../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 在每个平台上使用正确的路径分隔符。

    【讨论】:

    • 可以说,正如所讨论的here system.file 是一种更好的方法。
    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 2020-09-22
    • 2023-04-08
    • 2014-08-02
    • 2019-02-16
    • 2019-04-18
    • 2022-08-02
    • 1970-01-01
    相关资源
    最近更新 更多