File: test-path.R

package info (click to toggle)
r-cran-testthat 3.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,452 kB
  • sloc: cpp: 9,261; ansic: 37; sh: 14; makefile: 5
file content (42 lines) | stat: -rw-r--r-- 1,225 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#' Locate a file in the testing directory
#'
#' Many tests require some external file (e.g. a `.csv` if you're testing a
#' data import function) but the working directory varies depending on the way
#' that you're running the test (e.g. interactively, with `devtools::test()`,
#' or with `R CMD check`). `test_path()` understands these variations and
#' automatically generates a path relative to `tests/testthat`, regardless of
#' where that directory might reside relative to the current working directory.
#'
#' @param ... Character vectors giving path components.
#' @return A character vector giving the path.
#' @export
#' @examples
#' \dontrun{
#' test_path("foo.csv")
#' test_path("data", "foo.csv")
#' }
test_path <- function(...) {
  if (is_testing() && !isTRUE(getOption("testthat_interactive"))) {
    base <- NULL
  } else if (pkgload::is_loading()) {
    # Probably called from a helper file
    base <- NULL
  } else {
    base <- "tests/testthat"

    if (!dir.exists(base)) {
      cli::cli_abort("Can't find {.path {base}}.")
    }
  }

  file_path(base, ...)
}

file_path <- function(...) {
  paths <- compact(list2(...))
  if (length(paths) == 0) {
    "."
  } else {
    do.call(file.path, paths)
  }
}