When writing tests, I sometimes want to check how R would react to conflicts.
For instance, my package contains a compact()
function that conflicts with purrr::compact()
, and I wrote some code so that this latter is still used on regular lists.
In my tests, I want to check that purrr::compact()
will still work on regular lists if my package is loaded.
Therefore, I wrote a unit-test that looks a bit like this:
test_that("Test A", {
library(purrr, include.only="compact", warn.conflicts=FALSE)
compact = crosstable::compact
x = list(a = "a", b = NULL, c = integer(0), d = NA, e = list())
expect_identical(compact(x), list(a="a",d=NA))
})
However, the library()
call has a global effect that kind of messes up with some other unrelated tests.
Is there a way to import a library locally?
I'm thinking about something like rlang::local_options()
.
My first idea is a great package
withr
which helps with all temp related problems. Take into account that namespace will be still there,loadedNamespaces()
.Example of usage from .GlobalEnv:
Created on 2021-06-21 by the reprex package (v2.0.0)
Another idea is usage of
utils::getFromNamespace
: