Skip to content

Commit

Permalink
warn about skipped names
Browse files Browse the repository at this point in the history
  • Loading branch information
m7pr committed Oct 30, 2024
1 parent d3eb395 commit 5839f0d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
13 changes: 12 additions & 1 deletion R/teal_data-extract.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,23 @@
#' @export
`[.teal_data` <- function(x, names) {
checkmate::assert_character(names)
names <- intersect(names, ls(get_env(x)))
possible_names <- ls(get_env(x))
names_warn <- setdiff(names, possible_names)
names <- intersect(names, possible_names)
if (!length(names)) {
warning("None of `names` elements exist in `teal_data`. Returning empty `teal_data`.")
return(teal_data())
}

if (length(names_warn)) {
warning(
sprintf(
"Some elements of `names` do not exist in `teal_data`. Skipping those: %s.",
paste(names_warn, collapse = ", ")
)
)
}

x <- NextMethod("`[`", x) # takes 'names' from function's environment
x@join_keys <- x@join_keys[names]

Expand Down
17 changes: 13 additions & 4 deletions tests/testthat/test-extract.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
testthat::test_that("`[.` returns empty teal_data for improper names", {
testthat::test_that("`[.` returns empty teal_data for names not in teal_data", {
data <- teal_data(x = 1, a = 2)
testthat::expect_warning(
testthat::expect_equal(data["y"], teal_data())
testthat::expect_equal(data["y"], teal_data()),
"None of `names` elements exist in `teal_data`. Returning empty `teal_data`."
)
})

testthat::test_that("`[.` returns limited teal_data for some names not in teal_data", {
data <- teal_data(x = 1, a = 2)
testthat::expect_warning(
testthat::expect_equal(data[c("y", "a")], data["a"]),
"Some elements of `names` do not exist in `teal_data`. Skipping those: y."
)
})

Expand All @@ -21,12 +30,12 @@ testthat::test_that("`[.` handles names as NA_character_", {

testthat::test_that("`[.` throws warning if names is NULL", {
data <- teal_data(x = 1, a = 2)
testthat::expect_error(data[NULL], "Assertion on 'names' failed: Must inherit from class 'character'")
testthat::expect_error(data[NULL], "Assertion on 'names' failed: Must be of type 'character', not 'NULL'.")
})

testthat::test_that("`[.` thorws warnings if names is numeric", {
data <- teal_data(x = 1, a = 2)
testthat::expect_error(data[1], "Assertion on 'names' failed: Must inherit from class 'character'")
testthat::expect_error(data[1], "Assertion on 'names' failed: Must be of type 'character', not 'double'.")
})

testthat::test_that("`[.` returns limited join_keys", {
Expand Down

0 comments on commit 5839f0d

Please sign in to comment.