Skip to content

Commit

Permalink
test_example() tweaks
Browse files Browse the repository at this point in the history
Fixes #841
  • Loading branch information
hadley committed Jul 19, 2019
1 parent feb5c93 commit 4000f83
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 23 deletions.
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# testthat (development version)

* `test_examples()` gets some minor fixes: it now returns the results
invisibly, doesn't assume that examples should contain tests, and
documents that you shouldn't be using it routinely (#841).

* `fail()` and `suceed()` gain `info` argument, which is passed along to
`expect()`.

Expand Down
35 changes: 16 additions & 19 deletions R/test-example.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
#'
#' These helper functions make it easier to test the examples in a package.
#' Each example counts as one test, and it succeeds if the code runs without
#' an error.
#' an error. Generally, this is redundant with R CMD check, and is not
#' recommended in routine practice.
#'
#' @keywords internal
#' @param path For `test_examples()`, path to directory containing Rd files.
#' For `test_example()`, path to a single Rd file. Remember the working
#' directory for tests is `tests/testthat`.
Expand All @@ -14,7 +16,7 @@ test_examples <- function(path = "../..") {
if (is.null(res)) {
stop("Could not find examples", call. = FALSE)
}
res
invisible(res)
}

test_examples_source <- function(path = "../..") {
Expand All @@ -40,33 +42,28 @@ test_examples_installed <- function(package = env_test$package) {
lapply(Rd, test_rd)
}


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

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

ok <- test_code(path, parse(ex_path, encoding = "UTF-8"), env = env)
if (ok) succeed(path)

invisible()
test_rd <- function(rd) {
test_example(attr(rd, "Rdfile"))
}

#' @export
#' @rdname test_examples
test_rd <- function(rd) {
path <- attr(rd, "Rdfile")
test_example <- function(path) {
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()
tools::Rd2ex(path, ex_path)
if (!file.exists(ex_path)) return(invisible())

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

ok <- test_code(path, parse(ex_path, encoding = "UTF-8"), env = env)
ok <- test_code(path,
parse(ex_path, encoding = "UTF-8"),
env = env,
skip_on_empty = FALSE
)
if (ok) succeed(path)

invisible()
invisible(ok)
}
10 changes: 6 additions & 4 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 4000f83

Please sign in to comment.