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

Calling teardown_env() when testing Setup.R #2031

Open
ralmond opened this issue Nov 22, 2024 · 1 comment
Open

Calling teardown_env() when testing Setup.R #2031

ralmond opened this issue Nov 22, 2024 · 1 comment

Comments

@ralmond
Copy link

ralmond commented Nov 22, 2024

I'm trying to test my Setup.R file by sourcing the file. However, in that context, teardown_env() is not properly initialized so I get an error.

Here is a simple example:

handle <- file(tempfile())
withr::defer(close(handle),testthat::teardown_env())
#> Error in `testthat::teardown_env()`:
#> ! `teardown_env()` has not been initialized
#> ℹ This is an internal error that was detected in the testthat package.
#>   Please report it at <https://github.com/r-lib/testthat/issues> with a reprex (<https://tidyverse.org/help/>) and the full backtrace.

Created on 2024-11-22 with reprex v2.1.1

Here is the backtrace:

Backtrace:
    ▆
 1. ├─base::source("~/ralmond1/Projects/Peanut/tests/testthat/setup.R")
 2. │ ├─base::withVisible(eval(ei, envir))
 3. │ └─base::eval(ei, envir)
 4. │   └─base::eval(ei, envir)
 5. ├─withr::defer(...) at tests/testthat/setup.R:16:1
 6. └─testthat::teardown_env()

I don't think this is a bug so much as a bit of missing functionality. It would be good to have a way to artificially call Setup.R and then emulate the teardown, so that I can validate that my Setup code is working.

@ralmond
Copy link
Author

ralmond commented Nov 22, 2024

Okay, I found the workaround. I need to replace the call to teardown_env() in my Setup.R code with a reference to .GlobalEnv. Then I can call withr::deferred_run() to test my cleanup code.

It would be cool if there was an option which would make this available without tweaking my code.

Say:

teardown_env <- function () 
{
    if (is.null(the$teardown_env)) {
        if (isTRUE(getOption("testthat_test_setup"))) {
            message("Run 'withr::deferred_run()' to simulate teardown.")
            return(.GlobalEnv)
        }
        abort("`teardown_env()` has not been initialized", .internal = TRUE)
    }
    the$teardown_env
}

Then, setting options(testthat_test_setup=TRUE) would allow sourcing the Setup.R file during testing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant