R - testthat using data file outside the testing directory
Asked Answered
B

1

12

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
Birdie answered 26/9, 2013 at 16:45 Comment(0)
S
19

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.

Spinous answered 26/9, 2013 at 18:43 Comment(1)
Arguably, as discussed here system.file is a better approach.Pester

© 2022 - 2024 — McMap. All rights reserved.