Skip to content

Commit

Permalink
Refactor the test_examples function
Browse files Browse the repository at this point in the history
Previously it would never run examples during R CMD check because there
was no '/man' directory for installed packages. This instead uses
tools::Rd_db to parse the Rd files into a database and uses that
directly, which does work for installed packages.
  • Loading branch information
jimhester committed Oct 6, 2016
1 parent d381f41 commit 6b032ab
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Expand Up @@ -119,6 +119,7 @@ export(test_examples)
export(test_file)
export(test_package)
export(test_path)
export(test_rd)
export(test_that)
export(throws_error)
export(try_again)
Expand Down
38 changes: 33 additions & 5 deletions R/test-example.R
Expand Up @@ -4,13 +4,26 @@
#' Each example counts as one test, and it succeeds if the code runs without
#' an error.
#'
#' @param path For \code{test_examples}, path to directory containing Rd files.
#' @param path For \code{test_examples}, path to the package directory.
#' For \code{test_example}, path to a single Rd file. Remember the working
#' directory for tests is \code{tests/testthat}.
#' @param rd A parsed Rd object, obtained from \code{\link[tools]{Rd_db}}.
#' @export
test_examples <- function(path = "../../man") {
man <- dir(path, "\\.Rd$", full.names = TRUE)
lapply(man, test_example)
test_examples <- function(path = "../..") {
Rd <- NULL
if (dir.exists(file.path(path, "man"))) {
Rd <- tools::Rd_db(dir = path)
} else {
# Installed packages (like when run from R CMD check) do not have a /man
# directory, so we need to find the Rd files using the package name.
if (!is.null(env_test$package)) {
Rd <- tools::Rd_db(env_test$package)
}
}
if (is.null(Rd)) {
stop("Could not find examples", call. = FALSE)
}
lapply(Rd, test_rd)
}

#' @export
Expand All @@ -22,9 +35,24 @@ test_example <- function(path) {

env <- new.env(parent = globalenv())

ok <- test_code(path, parse(ex_path), env = globalenv())
ok <- test_code(path, parse(ex_path), env = env)
if (ok) succeed(path)

invisible()
}

#' @export
#' @rdname test_examples
test_rd <- function(rd) {
path <- attr(rd, "Rdfile")
ex_path <- file.path(tempdir(), paste0(tools::file_path_sans_ext(basename(path)), ".R"))
tools::Rd2ex(rd, ex_path)
if (!file.exists(ex_path)) return()

env <- new.env(parent = globalenv())

ok <- test_code(path, parse(ex_path), env = env)
if (ok) succeed(path)

invisible()
}
9 changes: 7 additions & 2 deletions man/test_examples.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 6b032ab

Please sign in to comment.