forked from r-lib/usethis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.R
81 lines (67 loc) · 1.89 KB
/
test.R
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#' Create tests
#'
#' `use_testthat()` sets up testing infrastructure, creating
#' \file{tests/testthat.R} and \file{tests/testthat/}, and
#' adding \pkg{testthat} to the suggested packages. `use_test()`
#' creates \file{tests/testthat/test-<name>.R} and opens it for editing.
#'
#' @export
#' @inheritParams use_template
use_testthat <- function() {
check_is_package("use_testthat()")
check_installed("testthat")
use_dependency("testthat", "Suggests")
use_directory("tests/testthat")
use_template(
"testthat.R",
"tests/testthat.R",
data = list(name = project_name())
)
invisible(TRUE)
}
#' @rdname use_testthat
#' @param name Test name. if `NULL`, and you're using RStudio, will use
#' the name of the file open in the source editor.
#' @export
use_test <- function(name = NULL, open = TRUE) {
name <- find_test_name(name)
if (!uses_testthat()) {
use_testthat()
}
path <- file.path("tests", "testthat", name)
if (file.exists(proj_path(path))) {
edit_file(proj_get(), path)
} else {
use_template(
"test-example.R",
path,
data = list(test_name = name),
open = open
)
}
invisible(TRUE)
}
uses_testthat <- function(base_path = proj_get()) {
paths <- c(
file.path(base_path, "inst", "tests"),
file.path(base_path, "tests", "testthat")
)
any(dir.exists(paths))
}
find_test_name <- function(name = NULL) {
if (!is.null(name)) {
return(paste0("test-", slug(name, ".R")))
}
if (!rstudioapi::isAvailable()) {
stop("Argument ", code("name"), " is missing, with no default", call. = FALSE)
}
active_file <- rstudioapi::getSourceEditorContext()$path
dir <- basename(dirname(active_file))
if (dir != "R") {
stop("Open file not in `R/` directory", call. = FALSE)
}
if (!grepl("\\.[Rr]$", active_file)) {
stop("Open file is does not end in `.R`", call. = FALSE)
}
paste0("test-", basename(active_file))
}