| 1 |
test_that("local_vars() restores previous state", { |
| 2 |
vars <- c("a", "b", "c") |
| 3 |
local_vars(vars) |
| 4 |
|
| 5 |
fn <- function() { |
| 6 |
local_vars(c("d", "e", "f")) |
| 7 |
starts_with("e") |
| 8 |
} |
| 9 |
expect_identical(fn(), 2L) |
| 10 |
|
| 11 |
expect_identical(peek_vars(), vars) |
| 12 |
}) |
| 13 |
|
| 14 |
test_that("with_vars() works", { |
| 15 |
vars <- c("a", "b", "c") |
| 16 |
local_vars(vars) |
| 17 |
|
| 18 |
fn <- function(expr) { |
| 19 |
with_vars(c("rose", "blue", "red"), expr) |
| 20 |
} |
| 21 |
expect_identical(fn(starts_with("r")), c(1L, 3L)) |
| 22 |
|
| 23 |
expect_identical(peek_vars(), vars) |
| 24 |
}) |
| 25 |
|
| 26 |
test_that("has_vars() detects variables", { |
| 27 |
expect_false(has_vars()) |
| 28 |
|
| 29 |
local_vars(letters) |
| 30 |
expect_true(has_vars()) |
| 31 |
}) |
| 32 |
|
| 33 |
test_that("Missing names are kept", { |
| 34 |
local_vars(c("foo", NA)) |
| 35 |
expect_identical(peek_vars(), c("foo", NA)) |
| 36 |
|
| 37 |
local_vars(c(NA, "foo")) |
| 38 |
expect_identical(peek_vars(), c(NA, "foo")) |
| 39 |
|
| 40 |
local_vars(c("bar", "")) |
| 41 |
expect_identical(peek_vars(), c("bar", "")) |
| 42 |
|
| 43 |
local_vars(c("", "bar")) |
| 44 |
expect_identical(peek_vars(), c("", "bar")) |
| 45 |
}) |
| 46 |
|
| 47 |
test_that("full data is in scope", { |
| 48 |
x <- structure(set_names(letters), class = c("foo", "character")) |
| 49 |
|
| 50 |
identical <- FALSE |
| 51 |
helper <- function(data = peek_data()) { |
| 52 |
identical <<- identical(data, x) |
| 53 |
1 |
| 54 |
} |
| 55 |
|
| 56 |
select_loc(x, helper()) |
| 57 |
expect_true(identical) |
| 58 |
}) |
| 59 |
|
| 60 |
test_that("peek_data() fails informatively", { |
| 61 |
expect_error(peek_data(), "must be used within") |
| 62 |
}) |
| 63 |
|
| 64 |
test_that("generic error message is thrown if `fn` is not supplied", { |
| 65 |
expect_snapshot(peek_vars(), error = TRUE) |
| 66 |
|
| 67 |
withr::local_options(cli.hyperlink = TRUE, rlang_interactive = TRUE) |
| 68 |
expect_snapshot(peek_vars(), error = TRUE) |
| 69 |
}) |
| 70 |
|
| 71 |
test_that("custom error message is thrown if `fn` is supplied", { |
| 72 |
expect_error(peek_vars(fn = "z"), "`z()` must be used", fixed = TRUE) |
| 73 |
}) |