Skip to content

Commit d4dd3ab

Browse files
authored
Chain source errors (#1704)
To make it easier to understand where problems are coming from
1 parent dd44f64 commit d4dd3ab

File tree

4 files changed

+32
-2
lines changed

4 files changed

+32
-2
lines changed

NEWS.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# testthat (development version)
22

3+
* `source_file()`, which is used by various parts of the helper and
4+
setup/teardown machinery, now reports the file name in the case of
5+
errors (#1704).
6+
37
* New `vignette("special-files")` describes the various special files
48
that testthat uses (#1638).
59

R/source.R

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,15 @@ source_file <- function(path, env = test_env(), chdir = TRUE,
3636
if (wrap) {
3737
invisible(test_code(NULL, exprs, env))
3838
} else {
39-
invisible(eval(exprs, env))
39+
withCallingHandlers(
40+
invisible(eval(exprs, env)),
41+
error = function(err) {
42+
abort(
43+
paste0("In path: ", encodeString(path, quote = '"')),
44+
parent = err
45+
)
46+
}
47+
)
4048
}
4149
}
4250

@@ -45,7 +53,9 @@ source_file <- function(path, env = test_env(), chdir = TRUE,
4553
source_dir <- function(path, pattern = "\\.[rR]$", env = test_env(),
4654
chdir = TRUE, wrap = TRUE) {
4755
files <- normalizePath(sort(dir(path, pattern, full.names = TRUE)))
48-
lapply(files, source_file, env = env, chdir = chdir, wrap = wrap)
56+
lapply(files, function(path) {
57+
source_file(path, env = env, chdir = chdir, wrap = wrap)
58+
})
4959
}
5060

5161
#' @rdname source_file

tests/testthat/_snaps/source.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# source_file wraps error
2+
3+
Code
4+
source_file(test_path("reporters/error-setup.R"), wrap = FALSE)
5+
Condition
6+
Error in `source_file()`:
7+
! In path: "reporters/error-setup.R"
8+
Caused by error in `h()`:
9+
! !
10+

tests/testthat/test-source.R

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,9 @@ test_that("source_file always uses UTF-8 encoding", {
3939
run_test("German_Germany.1252")
4040
run_test(Sys.getlocale("LC_CTYPE"))
4141
})
42+
43+
test_that("source_file wraps error", {
44+
expect_snapshot(error = TRUE, {
45+
source_file(test_path("reporters/error-setup.R"), wrap = FALSE)
46+
})
47+
})

0 commit comments

Comments
 (0)