-
Notifications
You must be signed in to change notification settings - Fork 316
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
Re-enter the mocking game #1739
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cool!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
incorporating what we've learned from mockr and mockery
So what did we learn? I'm curious as I have never used these packages.
Co-authored-by: Gábor Csárdi <csardi.gabor@gmail.com> Co-authored-by: Lionel Henry <lionel.hry@gmail.com>
What we learned:
|
Note that this doesn't appear to work to mock S3 methods. # In package
mockable_generic <- function(x) {
UseMethod("mockable_generic")
}
#' @export
mockable_generic.integer <- function(x) {
x + 1
}
# In test
test_that("local_mocked_bindings affects S3 methods", {
local_mocked_bindings(mockable_generic.integer = function(x) 100)
expect_equal(mockable_generic(1L), 100)
}) I tried also binding in the S3 methods table: method_env <- ns_env[[".__S3MethodsTable__."]]
methods <- names(bindings) %in% names(method_env)
local_bindings(!!!bindings[methods], .env = method_env, .frame = .env)
bindings <- bindings[!methods] But while that works when called interactively, it doesn't work in tests. |
For S3 methods it is usually sufficient to bind them in the global environment. Edit: Though the S3 table might have precedence if existing methods are registered. |
@lionel- yeah, that only works for new methods, I think. But maybe my attempt didn't work because of something to do with the way that testthat sets up environments. It certainly looks like pkgload modifies the same place when unloading packages: https://github.com/r-lib/pkgload/blob/main/R/unload.R#L157-L164. (However, that does suggest that, in general, I need to look in the namespace of the generic, not just the namespace of the current package.) |
Oooooh, I wonder if it's because |
No description provided.