| 1 |
|
| 2 |
test_that("one_of gives useful errors", { |
| 3 |
expect_snapshot({ |
| 4 |
(expect_error( |
| 5 |
one_of(1L, .vars = c("x", "y")), |
| 6 |
class = "vctrs_error_incompatible_index_type" |
| 7 |
)) |
| 8 |
}) |
| 9 |
}) |
| 10 |
|
| 11 |
test_that("one_of tolerates but warns for unknown columns", { |
| 12 |
vars <- c("x", "y") |
| 13 |
|
| 14 |
expect_warning(res <- one_of("z", .vars = vars), "Unknown columns: `z`") |
| 15 |
expect_equal(res, integer(0)) |
| 16 |
expect_warning(res <- one_of(c("x", "z"), .vars = vars), "Unknown columns: `z`") |
| 17 |
expect_equal(res, 1L) |
| 18 |
}) |
| 19 |
|
| 20 |
test_that("one_of converts names to locations", { |
| 21 |
expect_equal(one_of("a", "z", .vars = letters), c(1L, 26L)) |
| 22 |
}) |
| 23 |
|
| 24 |
test_that("one_of works with variables", { |
| 25 |
var <- "x" |
| 26 |
expect_equal(select_loc(letters2, one_of(var)), c(x = 24L)) |
| 27 |
# error messages from rlang |
| 28 |
expect_error(select_loc(letters2, one_of(`_x`)), "not found") |
| 29 |
expect_error(select_loc(letters2, one_of(`_y`)), "not found") |
| 30 |
}) |
| 31 |
|
| 32 |
test_that("one_of works when passed variable name matches the column name (#2266)", { |
| 33 |
x <- "x" |
| 34 |
y <- "x" |
| 35 |
expect_equal(select_loc(letters2, one_of(!!x)), c(x = 24L)) |
| 36 |
expect_equal(select_loc(letters2, one_of(!!y)), c(x = 24L)) |
| 37 |
expect_equal(select_loc(letters2, one_of(y)), c(x = 24L)) |
| 38 |
}) |
| 39 |
|
| 40 |
test_that("one_of() supports S3 vectors", { |
| 41 |
expect_identical(select_loc(letters2, one_of(factor(c("a", "c")))), c(a = 1L, c = 3L)) |
| 42 |
}) |
| 43 |
|
| 44 |
test_that("one_of() compacts inputs (#110)", { |
| 45 |
letters_seq <- set_names(seq_along(letters2), letters2) |
| 46 |
expect_identical( |
| 47 |
select_loc(letters2, -one_of()), |
| 48 |
letters_seq |
| 49 |
) |
| 50 |
expect_identical( |
| 51 |
select_loc(letters2, -one_of(NULL)), |
| 52 |
letters_seq |
| 53 |
) |
| 54 |
}) |
| 55 |
|
| 56 |
test_that("no set variables throws error", { |
| 57 |
expect_error(one_of("z"), "`one_of()` must be used within a *selecting* function", fixed = TRUE) |
| 58 |
}) |
| 59 |
|
| 60 |
|
| 61 |
test_that("no set variables throws error from the correct function", { |
| 62 |
expect_error(one_of(starts_with("z")), "`one_of()` must be used within a *selecting* function", fixed = TRUE) |
| 63 |
}) |