diff --git a/DESCRIPTION b/DESCRIPTION index a90548193..948779c53 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -72,6 +72,7 @@ Suggests: doRNG, unix, testthat, + withr (>= 3.0.3), vdiffr, knitr, rmarkdown, diff --git a/NEWS.md b/NEWS.md index 94ffe21cd..bd31bcf95 100644 --- a/NEWS.md +++ b/NEWS.md @@ -11,6 +11,8 @@ If you read this from a place other than 1) skip_if_not(run_vs) @@ -609,8 +597,6 @@ test_that("returns nterms_max when no criterion is met", { # ranking() --------------------------------------------------------------- -context("ranking()") - test_that("`object` of class `vsel` (created by varsel()) works", { skip_if_not(run_vs) for (tstsetup in names(rks_vs)) { @@ -643,8 +629,6 @@ test_that("`object` of class `vsel` (created by cv_varsel()) works", { # cv_proportions() -------------------------------------------------------- -context("cv_proportions()") - test_that("`object` of class `ranking` (based on varsel() output) fails", { skip_if_not(run_vs) expect_length(prs_vs, 0) @@ -691,9 +675,6 @@ test_that("cv_proportions.vsel() is a shortcut", { } }) -# Needed to clean up the workspace afterwards: -ls_bu <- ls() - ntrms <- 9L rk_fdata <- rev(head(letters, ntrms)) rk_fwise <- do.call(rbind, lapply(seq_len(ntrms), function(idx_trm) { @@ -740,13 +721,8 @@ test_that("ranking proportions are computed correctly", { expect_true(has_1_colwise, info = "cumulate = TRUE") }) -# Clean up the workspace: -rm(list = setdiff(ls(), ls_bu)) - # plot.cv_proportions() --------------------------------------------------- -context("plot.cv_proportions()") - test_that("`x` of class `cv_proportions` works", { skip_if_not(run_cvvs) for (tstsetup in names(plotprs)) { @@ -773,9 +749,6 @@ test_that("plot.ranking() is a shortcut", { } }) -# Needed to clean up the workspace afterwards: -ls_bu <- ls() - ntrms <- 20L pr_dummy <- matrix(seq(0, 1, length.out = ntrms^2), nrow = ntrms, ncol = ntrms, dimnames = list("size" = as.character(seq_len(ntrms)), @@ -818,6 +791,3 @@ test_that("the ggplot can be modified", { vdiffr::expect_doppelganger("plotprc_dummy_mod", plotprc_dummy_mod) } }) - -# Clean up the workspace: -rm(list = setdiff(ls(), ls_bu)) diff --git a/tests/testthat/test_misc.R b/tests/testthat/test_misc.R index 942d517aa..1d46cd3e3 100644 --- a/tests/testthat/test_misc.R +++ b/tests/testthat/test_misc.R @@ -1,5 +1,3 @@ -context("miscellaneous") - # get_refdist() ---------------------------------------------------------- ## ndraws and nclusters --------------------------------------------------- @@ -8,10 +6,8 @@ test_that(paste( "get_refdist(): `ndraws = NULL` and `nclusters = NULL` leads to", "`ndraws = S` (and `nclusters = NULL`)" ), { - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } - set.seed(seed2_tst) + skip_if_no_setups(refmods) + withr::local_seed(seed2_tst) for (tstsetup in names(refmods)) { refdist <- get_refdist(refmods[[tstsetup]]) if (args_ref[[tstsetup]]$prj_nm == "augdat") { @@ -31,17 +27,14 @@ test_that(paste( info_str = tstsetup ) } - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) }) test_that(paste( "`ndraws` and/or `nclusters` too big causes them to be cut off at the number", "of posterior draws in the reference model" ), { - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } - set.seed(seed2_tst) + skip_if_no_setups(refmods) + withr::local_seed(seed2_tst) for (tstsetup in names(refmods)) { for (ndraws_crr in list(nrefdraws + 1L)) { for (nclusters_crr in list(NULL, nrefdraws + 1L)) { @@ -64,7 +57,6 @@ test_that(paste( } } } - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) }) # force_search_terms() ---------------------------------------------------- @@ -193,10 +185,7 @@ test_that(paste( # ), then # changed function name and added seed reset: test_that(".srs_diff_est_w() works as expected", { - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } - set.seed(1234) + withr::local_seed(1234) N <- 1000 y_true <- 1:N sigma_hat_true <- sqrt(N * sum((y_true - mean(y_true))^2) / length(y_true)) @@ -226,15 +215,11 @@ test_that(".srs_diff_est_w() works as expected", { expect_equal(res$y_hat, 500500, tol = 0.0001) expect_equal(res$v_y_hat, 0, tol = 0.0001) expect_equal(sqrt(res$hat_v_y), sigma_hat_true, tol = 0.1) - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) }) # Adapted from the test above: test_that(".srs_diff_est_w() works as expected with `wobs` not full of ones", { - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } - set.seed(seed3_tst) + withr::local_seed(seed3_tst) N <- 1e3 y_true <- seq_len(N) wobs <- sample(2:7, size = N, replace = TRUE) @@ -277,13 +262,12 @@ test_that(".srs_diff_est_w() works as expected with `wobs` not full of ones", { expect_equal(res$y_hat, 500845, tol = 1e-4) expect_equal(res$v_y_hat, 0, tol = 1e-4) expect_equal(sqrt(res$hat_v_y), sigma_hat_true, tol = 1e-1) - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) }) test_that(".srs_diff_est_w() propagates input `NA`s to its output", { nloo_tst <- nobsv %/% 5L loo_inds_tst <- ceiling(seq(1L, nobsv, length.out = nloo_tst)) - skip_if_not(length(unique(loo_inds_tst)) == nloo_tst) + stopifnot(length(unique(loo_inds_tst)) == nloo_tst) srs_diff_res_NAs <- list( m = nloo_tst, N = nobsv, diff --git a/tests/testthat/test_parallel.R b/tests/testthat/test_parallel.R index 5de734c51..e3ff83412 100644 --- a/tests/testthat/test_parallel.R +++ b/tests/testthat/test_parallel.R @@ -1,15 +1,17 @@ -context("parallel") - # Setup ------------------------------------------------------------------- +# withr resets the options and the parallel backend at the end of this file, +# also if the file stops with an error. if (run_prll) { - trigger_default <- options(projpred.parallel_proj_trigger = 0L) + withr::local_options(list(projpred.parallel_proj_trigger = 0L)) if (dopar_backend == "doParallel") { doParallel::registerDoParallel(ncores) + withr::defer(doParallel::stopImplicitCluster()) } else if (dopar_backend == "doFuture") { doFuture::registerDoFuture() - export_default <- options(doFuture.foreach.export = ".export") + withr::local_options(list(doFuture.foreach.export = ".export")) + withr::defer(future::plan(future::sequential)) if (future_plan == "multicore") { future::plan(future::multicore, workers = ncores) } else if (future_plan == "multisession") { @@ -79,20 +81,3 @@ test_that("cv_varsel() in parallel gives the same results as sequentially", { expect_equal(cvvs_repr, cvvss[[tstsetup]], info = tstsetup) } }) - -# Teardown ---------------------------------------------------------------- - -if (run_prll) { - if (dopar_backend == "doParallel") { - doParallel::stopImplicitCluster() - } else if (dopar_backend == "doFuture") { - future::plan(future::sequential) - options(export_default) - rm(export_default) - } else { - stop("Unrecognized `dopar_backend`.") - } - - options(trigger_default) - rm(trigger_default) -} diff --git a/tests/testthat/test_proj_epred.R b/tests/testthat/test_proj_epred.R index eb77be9ab..d03f6c4ba 100644 --- a/tests/testthat/test_proj_epred.R +++ b/tests/testthat/test_proj_epred.R @@ -1,7 +1,5 @@ # proj_epred() ------------------------------------------------------------- -context("proj_epred()") - ## object ------------------------------------------------------------------ test_that("pe: `object` of class `projection` works", { diff --git a/tests/testthat/test_proj_pred.R b/tests/testthat/test_proj_pred.R index 2edd4eb6a..5fde3f6f0 100644 --- a/tests/testthat/test_proj_pred.R +++ b/tests/testthat/test_proj_pred.R @@ -1,7 +1,5 @@ # proj_linpred() ---------------------------------------------------------- -context("proj_linpred()") - ## object ----------------------------------------------------------------- test_that("pl: `object` of class `projection` works", { @@ -27,12 +25,12 @@ test_that("pl: `object` of class `projection` works", { info_str = tstsetup) if (run_snaps) { if (testthat_ed_max2) local_edition(3) - width_orig <- options(width = 145) - expect_snapshot({ - print(tstsetup) - print(rlang::hash(pls[[tstsetup]])) + withr::with_options(list(width = 145), { + expect_snapshot({ + print(tstsetup) + print(rlang::hash(pls[[tstsetup]])) + }) }) - options(width_orig) if (testthat_ed_max2) local_edition(2) } } @@ -76,12 +74,12 @@ test_that(paste( info_str = tstsetup) if (run_snaps) { if (testthat_ed_max2) local_edition(3) - width_orig <- options(width = 145) - expect_snapshot({ - print(tstsetup) - print(rlang::hash(pls_vs[[tstsetup]])) + withr::with_options(list(width = 145), { + expect_snapshot({ + print(tstsetup) + print(rlang::hash(pls_vs[[tstsetup]])) + }) }) - options(width_orig) if (testthat_ed_max2) local_edition(2) } } @@ -125,12 +123,12 @@ test_that(paste( info_str = tstsetup) if (run_snaps) { if (testthat_ed_max2) local_edition(3) - width_orig <- options(width = 145) - expect_snapshot({ - print(tstsetup) - print(rlang::hash(pls_cvvs[[tstsetup]])) + withr::with_options(list(width = 145), { + expect_snapshot({ + print(tstsetup) + print(rlang::hash(pls_cvvs[[tstsetup]])) + }) }) - options(width_orig) if (testthat_ed_max2) local_edition(2) } } @@ -797,13 +795,11 @@ test_that("`transform` works", { if (args_prj[[tstsetup]]$prj_nm != "latent") { pred_false2true <- prjs[[tstsetup]]$refmodel$family$linkinv(pred_false) } else { - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } - set.seed(args_prj[[tstsetup]]$seed) - clust_ref <- get_refdist(prjs[[tstsetup]]$refmodel, - ndraws = args_prj[[tstsetup]]$ndraws, - nclusters = args_prj[[tstsetup]]$nclusters) + clust_ref <- withr::with_seed(args_prj[[tstsetup]]$seed, { + get_refdist(prjs[[tstsetup]]$refmodel, + ndraws = args_prj[[tstsetup]]$ndraws, + nclusters = args_prj[[tstsetup]]$nclusters) + }) pred_false2true <- structure( prjs[[tstsetup]]$refmodel$family$latent_ilink( t(pred_false), cl_ref = clust_ref$cl @@ -812,7 +808,6 @@ test_that("`transform` works", { ) } expect_equal(pred_false2true, pred_true, info = tstsetup) - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) } }) @@ -1067,8 +1062,6 @@ test_that(paste( # proj_predict() ---------------------------------------------------------- -context("proj_predict()") - ## seed ------------------------------------------------------------------- test_that("`.seed` works (and restores the RNG state afterwards)", { @@ -1115,12 +1108,12 @@ test_that("pp: `object` of class `projection` works", { info_str = tstsetup) if (run_snaps) { if (testthat_ed_max2) local_edition(3) - width_orig <- options(width = 145) - expect_snapshot({ - print(tstsetup) - print(rlang::hash(pps[[tstsetup]])) + withr::with_options(list(width = 145), { + expect_snapshot({ + print(tstsetup) + print(rlang::hash(pps[[tstsetup]])) + }) }) - options(width_orig) if (testthat_ed_max2) local_edition(2) } } @@ -1149,12 +1142,12 @@ test_that(paste( info_str = tstsetup) if (run_snaps) { if (testthat_ed_max2) local_edition(3) - width_orig <- options(width = 145) - expect_snapshot({ - print(tstsetup) - print(rlang::hash(pps_vs[[tstsetup]])) + withr::with_options(list(width = 145), { + expect_snapshot({ + print(tstsetup) + print(rlang::hash(pps_vs[[tstsetup]])) + }) }) - options(width_orig) if (testthat_ed_max2) local_edition(2) } } @@ -1183,12 +1176,12 @@ test_that(paste( info_str = tstsetup) if (run_snaps) { if (testthat_ed_max2) local_edition(3) - width_orig <- options(width = 145) - expect_snapshot({ - print(tstsetup) - print(rlang::hash(pps_cvvs[[tstsetup]])) + withr::with_options(list(width = 145), { + expect_snapshot({ + print(tstsetup) + print(rlang::hash(pps_cvvs[[tstsetup]])) + }) }) - options(width_orig) if (testthat_ed_max2) local_edition(2) } } diff --git a/tests/testthat/test_proj_predfun.R b/tests/testthat/test_proj_predfun.R index caa083a4b..8bf4df8a0 100644 --- a/tests/testthat/test_proj_predfun.R +++ b/tests/testthat/test_proj_predfun.R @@ -1,5 +1,3 @@ -context("proj_predfun") - test_that("repair_re() works for GLMMs", { # Setup ------------------------------------------------------------------- @@ -9,10 +7,7 @@ test_that("repair_re() works for GLMMs", { # stan-dev/rstanarm#610, so don't run this test on CRAN: skip_on_cran() - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } - set.seed(seed2_tst) + withr::local_seed(seed2_tst) # Data -------------------------------------------------------------------- @@ -169,9 +164,6 @@ test_that("repair_re() works for GLMMs", { }) expect_equal(lpreds, lpreds_man, tolerance = 1e-15) - # Teardown ---------------------------------------------------------------- - - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) }) test_that("repair_re() works for multilevel cumulative() models", { @@ -179,10 +171,7 @@ test_that("repair_re() works for multilevel cumulative() models", { # Setup ------------------------------------------------------------------- - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } - set.seed(seed2_tst) + withr::local_seed(seed2_tst) # Data -------------------------------------------------------------------- @@ -331,23 +320,14 @@ test_that("repair_re() works for multilevel cumulative() models", { })) expect_equal(unname(lpreds), lpreds_man, tolerance = 1e-14) - # Teardown ---------------------------------------------------------------- - - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) }) # Multilevel categorical models ------------------------------------------- ## Setup ------------------------------------------------------------------ -# Needed to clean up the workspace afterwards (i.e, after this test file): -ls_bu <- ls() - # Set seed: -if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) -} -set.seed(seed2_tst) +withr::local_seed(seed2_tst) ## Data ------------------------------------------------------------------- @@ -910,10 +890,3 @@ test_that(paste( expect_equal(as.numeric(lpreds), as.numeric(lpreds_man), tolerance = 1e-14) }) - -# Teardown ---------------------------------------------------------------- - -if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) - -# Clean up the workspace: -rm(list = setdiff(ls(), ls_bu)) diff --git a/tests/testthat/test_project.R b/tests/testthat/test_project.R index 7c2162606..7ce8ad3d3 100644 --- a/tests/testthat/test_project.R +++ b/tests/testthat/test_project.R @@ -1,5 +1,3 @@ -context("project()") - # object, predictor_terms, ndraws / nclusters, nterms --------------------- test_that(paste( diff --git a/tests/testthat/test_refmodel.R b/tests/testthat/test_refmodel.R index 6a87083b0..810bc098c 100644 --- a/tests/testthat/test_refmodel.R +++ b/tests/testthat/test_refmodel.R @@ -1,8 +1,7 @@ # get_refmodel() ---------------------------------------------------------- -context("get_refmodel()") - test_that("`object` of class `stanreg` or `brmsfit` works", { + skip_if_no_setups(refmods) for (tstsetup in names(refmods)) { tstsetup_fit <- args_ref[[tstsetup]]$tstsetup_fit with_spclformul_crr <- grepl("\\.spclformul", tstsetup) @@ -199,6 +198,7 @@ test_that("extra arguments in s() or t2() terms fail", { }) test_that("get_refmodel() is idempotent", { + skip_if_no_setups(refmods) for (tstsetup in names(refmods)) { expect_identical(get_refmodel(refmods[[tstsetup]]), refmods[[tstsetup]], @@ -208,8 +208,6 @@ test_that("get_refmodel() is idempotent", { # predict.refmodel() ------------------------------------------------------ -context("predict.refmodel()") - test_that("invalid `type` fails", { skip_if_not(length(fits) > 0) expect_error(predict(refmods[[1]], dat, type = "zzz"), @@ -226,6 +224,7 @@ test_that(paste( "`object` of class `refmodel` and arguments `newdata`, `ynew`, and `type`", "work" ), { + skip_if_no_setups(refmods) for (tstsetup in names(refmods)) { pkg_crr <- args_ref[[tstsetup]]$pkg_nm mod_crr <- args_ref[[tstsetup]]$mod_nm @@ -355,15 +354,15 @@ test_that(paste( # Snapshots: if (run_snaps) { if (testthat_ed_max2) local_edition(3) - width_orig <- options(width = 145) - expect_snapshot({ - print(tstsetup) - print(rlang::hash(predref_resp)) - print(rlang::hash(predref_link)) - print(rlang::hash(predref_ynew_resp)) - print(rlang::hash(predref_ynew_link)) + withr::with_options(list(width = 145), { + expect_snapshot({ + print(tstsetup) + print(rlang::hash(predref_resp)) + print(rlang::hash(predref_link)) + print(rlang::hash(predref_ynew_resp)) + print(rlang::hash(predref_ynew_link)) + }) }) - options(width_orig) if (testthat_ed_max2) local_edition(2) } } diff --git a/tests/testthat/test_varsel.R b/tests/testthat/test_varsel.R index 9f5dda555..e1f8808dc 100644 --- a/tests/testthat/test_varsel.R +++ b/tests/testthat/test_varsel.R @@ -1,7 +1,5 @@ # varsel() ---------------------------------------------------------------- -context("varsel()") - test_that(paste( "`object` of class `refmodel` and arguments `method`, `nterms_max`,", "`nclusters`, and `nclusters_pred` work" @@ -34,6 +32,7 @@ test_that("invalid `object` fails", { }) test_that("invalid `method` fails", { + skip_if_no_setups(refmods) for (tstsetup in names(refmods)) { expect_error(varsel(refmods[[tstsetup]], method = "k-fold"), "^Unexpected value for argument `method`\\.$", @@ -181,9 +180,7 @@ test_that(paste( "posterior_epred() and log_lik()" ), { skip_if_not(run_vs) - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } + withr::local_preserve_seed() tstsetups <- names(vss) ### TODO (GAMMs): Currently, the following test setups (can) lead to the error ### ``` @@ -495,7 +492,6 @@ test_that(paste( expect_equal(vs_indep$summaries$ref$lppd, lppd_ref_ch2, tolerance = 1e2 * .Machine$double.eps, info = tstsetup) } - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) }) ## refit_prj -------------------------------------------------------------- @@ -553,7 +549,7 @@ if (run_more) { "the warning for full Gaussian multilevel models is thrown correctly" ), { skip_if_not(run_vs) - warn_instable_orig <- options(projpred.warn_instable_projections = NULL) + withr::local_options(list(projpred.warn_instable_projections = NULL)) tstsetups <- names(vss) pick_these <- sapply(tstsetups, function(tstsetup) { refmod_i <- refmods[[args_vs[[tstsetup]]$tstsetup_ref]] @@ -584,7 +580,6 @@ if (run_more) { info = tstsetup ) } - options(warn_instable_orig) }) } @@ -594,7 +589,7 @@ if (run_more) { test_that("the message when cutting off the search is thrown correctly", { skip_if_not(run_vs) skip_if_not_installed("rstanarm") - mssg_cut_search_orig <- options(projpred.mssg_cut_search = NULL) + withr::local_options(list(projpred.mssg_cut_search = NULL)) dat_gauss <- data.frame(y = df_gaussian$y, df_gaussian$x) stopifnot(sum(grepl("^X", names(dat_gauss))) > 19) fit_exceed <- suppressWarnings(rstanarm::stan_glm( @@ -628,7 +623,6 @@ if (run_more) { info = paste("fit_not_exceed, nterms_max =", nterms_max_i %||% "NULL") ) } - options(mssg_cut_search_orig) }) } @@ -959,7 +953,7 @@ test_that("for L1 search, `penalty` has an expected effect", { test_that("L1 search handles three-way (second-order) interactions correctly", { skip_if_not(run_vs) skip_if_not_installed("rstanarm") - warn_L1_ia_orig <- options(projpred.warn_L1_interactions = TRUE) + withr::local_options(list(projpred.warn_L1_interactions = TRUE)) main_terms_in_ia <- c("xca.2", "xco.3", "xco.1") all_ias_split <- lapply(seq_along(main_terms_in_ia), combn, x = main_terms_in_ia, simplify = FALSE) @@ -967,6 +961,7 @@ test_that("L1 search handles three-way (second-order) interactions correctly", { lapply(ia_split, all_ia_perms, is_split = TRUE) })) trms_universe_split_bu <- trms_universe_split + withr::defer(trms_universe_split <<- trms_universe_split_bu) trms_universe_split <<- union(trms_universe_split, all_ias) tstsetup <- head(grep("^rstanarm\\.glm\\.", names(fits), value = TRUE), 1) args_fit_i <- args_fit[[tstsetup]] @@ -1020,8 +1015,6 @@ test_that("L1 search handles three-way (second-order) interactions correctly", { })), info = tstsetup ) - trms_universe_split <<- trms_universe_split_bu - options(warn_L1_ia_orig) }) ## search_terms ----------------------------------------------------------- @@ -1170,8 +1163,6 @@ test_that("varsel.vsel() works for `vsel` objects from cv_varsel()", { # cv_varsel() ------------------------------------------------------------- -context("cv_varsel()") - test_that(paste( "`object` of class `refmodel` and arguments `method`, `cv_method`,", "`nterms_max`, `nclusters`, and `nclusters_pred` work" @@ -1213,6 +1204,7 @@ test_that("invalid `object` fails", { }) test_that("invalid `method` fails", { + skip_if_no_setups(refmods) for (tstsetup in names(refmods)) { expect_error(cv_varsel(refmods[[tstsetup]], method = "k-fold"), "^Unexpected value for argument `method`\\.$", @@ -1235,6 +1227,7 @@ test_that("invalid `method` fails", { }) test_that("invalid `cv_method` fails", { + skip_if_no_setups(refmods) for (tstsetup in names(refmods)) { expect_error(cv_varsel(refmods[[tstsetup]], cv_method = "k-fold"), "^Unknown `cv_method`\\.$", @@ -1340,7 +1333,7 @@ if (run_more) { test_that("the message when cutting off the search is thrown correctly", { skip_if_not(run_vs) skip_if_not_installed("rstanarm") - mssg_cut_search_orig <- options(projpred.mssg_cut_search = NULL) + withr::local_options(list(projpred.mssg_cut_search = NULL)) dat_gauss <- data.frame(y = df_gaussian$y, df_gaussian$x) stopifnot(sum(grepl("^X", names(dat_gauss))) > 19) fit_exceed <- suppressWarnings(rstanarm::stan_glm( @@ -1376,7 +1369,6 @@ if (run_more) { info = paste("fit_not_exceed, nterms_max =", nterms_max_i %||% "NULL") ) } - options(mssg_cut_search_orig) }) } @@ -1619,6 +1611,9 @@ test_that(paste( } tstsetups <- tstsetups_tmp } + # Test setups for which rstanarm::kfold() fails (the skip at the end of this + # test lists them): + kfold_failed <- character() for (tstsetup in tstsetups) { args_cvvs_i <- args_cvvs[[tstsetup]] tstsetup_fit <- args_cvvs_i$tstsetup_fit @@ -1638,13 +1633,10 @@ test_that(paste( # belonging to the same level of a variable with group-level effects are # in the same fold, so prediction is performed for new levels (see, e.g., # brms's GitHub issue #1286): - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } # Make the construction of the CV folds reproducible: - set.seed(seed2_tst * 3L) - folds_vec <- loo::kfold_split_grouped(K = K_crr, x = dat$z.1) - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) + folds_vec <- withr::with_seed(seed2_tst * 3L, { + loo::kfold_split_grouped(K = K_crr, x = dat$z.1) + }) } else { folds_vec <- cv_folds(nobsv, K = K_crr, seed = seed2_tst) } @@ -1659,9 +1651,9 @@ test_that(paste( cores = 1)), silent = TRUE) if (inherits(kfold_obj, "try-error")) { - message("Could not test `tstsetup = \"", tstsetup, "\"` in the rstanarm ", - "`cvfits` test. Error message: \"", - attr(kfold_obj, "condition")$message, "\"") + kfold_failed <- c(kfold_failed, paste0( + tstsetup, " (", attr(kfold_obj, "condition")$message, ")" + )) next } kfold_obj <- structure(kfold_obj$fits[, "fit"], folds = folds_vec) @@ -1718,6 +1710,9 @@ test_that(paste( ) } } + skip_if(length(kfold_failed) > 0, + paste("rstanarm::kfold() failed for:", + paste(kfold_failed, collapse = "; "))) }) test_that(paste( @@ -1752,13 +1747,10 @@ test_that(paste( # belonging to the same level of a variable with group-level effects are # in the same fold, so prediction is performed for new levels (see, e.g., # brms's GitHub issue #1286): - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } # Make the construction of the CV folds reproducible: - set.seed(seed2_tst + 10L) - folds_vec <- loo::kfold_split_grouped(K = K_crr, x = dat$z.1) - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) + folds_vec <- withr::with_seed(seed2_tst + 10L, { + loo::kfold_split_grouped(K = K_crr, x = dat$z.1) + }) } else if (grepl("\\.gam\\.", tstsetup)) { folds_vec <- cv_folds(nobsv, K = K_crr, seed = seed2_tst + 10L) } else { @@ -2638,9 +2630,7 @@ test_that("argument `folds` of run_cvfun() works", { if (!run_more) { tstsetups <- head(tstsetups, 1) } - if (exists(".Random.seed", envir = .GlobalEnv)) { - rng_old <- get(".Random.seed", envir = .GlobalEnv) - } + withr::local_preserve_seed() for (tstsetup in tstsetups) { set.seed(seed3_tst) folds_sep <- cv_folds(nobsv, K = K_tst) @@ -2648,5 +2638,4 @@ test_that("argument `folds` of run_cvfun() works", { expect_identical(lapply(cvfits_sep, as.matrix), lapply(cvfitss[[tstsetup]], as.matrix), info = tstsetup) } - if (exists("rng_old")) assign(".Random.seed", rng_old, envir = .GlobalEnv) })