Skip to content

Commit

Permalink
Chain source errors (#1704)
Browse files Browse the repository at this point in the history
To make it easier to understand where problems are coming from
  • Loading branch information
hadley authored Apr 10, 2023
1 parent dd44f64 commit d4dd3ab
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 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)

* `source_file()`, which is used by various parts of the helper and
setup/teardown machinery, now reports the file name in the case of
errors (#1704).

* New `vignette("special-files")` describes the various special files
that testthat uses (#1638).

Expand Down
14 changes: 12 additions & 2 deletions R/source.R
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,15 @@ source_file <- function(path, env = test_env(), chdir = TRUE,
if (wrap) {
invisible(test_code(NULL, exprs, env))
} else {
invisible(eval(exprs, env))
withCallingHandlers(
invisible(eval(exprs, env)),
error = function(err) {
abort(
paste0("In path: ", encodeString(path, quote = '"')),
parent = err
)
}
)
}
}

Expand All @@ -45,7 +53,9 @@ source_file <- function(path, env = test_env(), chdir = TRUE,
source_dir <- function(path, pattern = "\\.[rR]$", env = test_env(),
chdir = TRUE, wrap = TRUE) {
files <- normalizePath(sort(dir(path, pattern, full.names = TRUE)))
lapply(files, source_file, env = env, chdir = chdir, wrap = wrap)
lapply(files, function(path) {
source_file(path, env = env, chdir = chdir, wrap = wrap)
})
}

#' @rdname source_file
Expand Down
10 changes: 10 additions & 0 deletions tests/testthat/_snaps/source.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# source_file wraps error

Code
source_file(test_path("reporters/error-setup.R"), wrap = FALSE)
Condition
Error in `source_file()`:
! In path: "reporters/error-setup.R"
Caused by error in `h()`:
! !

6 changes: 6 additions & 0 deletions tests/testthat/test-source.R
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,9 @@ test_that("source_file always uses UTF-8 encoding", {
run_test("German_Germany.1252")
run_test(Sys.getlocale("LC_CTYPE"))
})

test_that("source_file wraps error", {
expect_snapshot(error = TRUE, {
source_file(test_path("reporters/error-setup.R"), wrap = FALSE)
})
})

0 comments on commit d4dd3ab

Please sign in to comment.