Skip to content

Commit

Permalink
Ensure global defers run on exit (#173)
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley authored Nov 4, 2021
1 parent 3b61d05 commit f25fb5f
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ Imports:
graphics,
grDevices,
stats
Suggests:
Suggests:
callr,
covr,
DBI,
knitr,
Expand Down
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# withr (development version)

* Handlers registered with the global environment (as happens when `local_()`
is run at the top-level, outside a function) are now automatically run
when the R session ends (#173).

* New `with_language()` and `local_language()` to temporarily control the
language used for translations (#180).

Expand Down
2 changes: 2 additions & 0 deletions R/compat-defer.R
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ defer <<- defer <- function(expr, envir = parent.frame(), priority = c("first",
if (identical(envir, .GlobalEnv) && is.null(get_handlers(envir))) {
message(
"Setting deferred event(s) on global environment.\n",
" * Will be run automatically when session ends\n",
" * Execute (and clear) with `withr::deferred_run()`.\n",
" * Clear (without executing) with `withr::deferred_clear()`."
)
reg.finalizer(envir, function(env) deferred_run(env), onexit = TRUE)
}
invisible(
add_handler(
Expand Down
1 change: 1 addition & 0 deletions tests/testthat/_snaps/defer.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
defer(print("howdy"), envir = globalenv())
Message <simpleMessage>
Setting deferred event(s) on global environment.
* Will be run automatically when session ends
* Execute (and clear) with `withr::deferred_run()`.
* Clear (without executing) with `withr::deferred_clear()`.

11 changes: 11 additions & 0 deletions tests/testthat/test-defer.R
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,17 @@ test_that("defer()'s global env facilities work", {
expect_null(h)
})

test_that("defered actions in global env are run on exit", {
path <- local_tempfile()
callr::r(
function(path) {
withr::defer(writeLines("a", path), env = globalenv())
},
list(path = path)
)
expect_equal(readLines(path), "a")
})

test_that("defer executes all handlers even if there is an error in one of them", {

old <- options("test_option" = 1)
Expand Down

0 comments on commit f25fb5f

Please sign in to comment.