Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chain source errors #1704

Merged
merged 6 commits into from
Apr 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
})
})