Skip to content

Commit

Permalink
Merge pull request #207 from krlmlr/193-mock-local
Browse files Browse the repository at this point in the history
Fix evaluation environments for mock definition
  • Loading branch information
hadley committed Jan 7, 2015
2 parents 82819b8 + 4649688 commit 5d319b6
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Expand Up @@ -29,6 +29,8 @@

* `colourise()` was removed. (Colour is still supported, via the `crayon` package.)

* Mocks can now access values local to the call of `with_mock` (#193, @krlmlr).

* All equality expectations are now documented together (#173); all
matching expectations are also documented together.

Expand Down
6 changes: 3 additions & 3 deletions R/mock.r
Expand Up @@ -43,7 +43,7 @@ with_mock <- function(..., .env = topenv()) {
}
code <- new_values[code_pos]

mocks <- extract_mocks(new_values = new_values[!code_pos], .env = .env)
mocks <- extract_mocks(new_values = new_values[!code_pos], .env = .env, eval_env = parent.frame())

on.exit(lapply(mocks, reset_mock), add = TRUE)
lapply(mocks, set_mock)
Expand All @@ -61,7 +61,7 @@ colons_rx <- "::(?:[:]?)"
name_rx <- ".*"
pkg_and_name_rx <- sprintf("^(?:(%s)%s)?(%s)$", pkg_rx, colons_rx, name_rx)

extract_mocks <- function(new_values, .env) {
extract_mocks <- function(new_values, .env, eval_env = parent.frame()) {
if (is.environment(.env))
.env <- environmentName(.env)
mock_qual_names <- names(new_values)
Expand All @@ -81,7 +81,7 @@ extract_mocks <- function(new_values, .env) {
if (!exists(name, envir = env, mode = "function"))
stop("Function ", name, " not found in environment ",
environmentName(env), ".")
mock(name = name, env = env, new = eval(new_values[[qual_name]]))
mock(name = name, env = env, new = eval(new_values[[qual_name]], eval_env, eval_env))
}
)
}
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-mock.r
Expand Up @@ -150,3 +150,12 @@ test_that("mock extraction", {
expect_identical(extract_mocks(list(acf = identity), "stats")[[1]]$new_value, identity)
expect_equal(length(extract_mocks(list(not = identity, `base::!` = identity), "testthat")), 2)
})

test_that("mocks can access local variables", {
value <- TRUE

with_mock(
expect_equal(2 * 3, 4),
all.equal = function(x, y, ...) {value}
)
})

0 comments on commit 5d319b6

Please sign in to comment.