Skip to content
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

Validate data arguments #34

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* Fixed an issue where disabling line statement could raise an error during template parsing. Since line statements are disabled by default, this error could be encountered quite easily (#31).
* `quote_sql()` now escapes single-quotes using an additional single-quote (#30).
* Fixed edge case in how error messages are formatted (#32).
* `render()` now validates data variables are supported (#25).


# jinjar 0.3.0
Expand Down
12 changes: 12 additions & 0 deletions R/encode.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ encode <- function(...) {
))
}

for (name in names(data)) {
x <- data[[name]]
if (!(is_null(x) || is_logical(x) || is_integer(x) || is_double(x) || is_character(x)
|| is_bare_list(x) || inherits_any(x, "data.frame"))) {
cli::cli_abort(c(
"Data variable {.arg {name}} is unsupported.",
"x" = "{.arg {name}} is {.obj_type_friendly {x}}.",
"i" = "Choices: NULL, logical, integer, double, character, list, dataframe."
))
}
}

jsonlite::toJSON(
data,
auto_unbox = TRUE, # length-1 vectors output as scalars
Expand Down
10 changes: 10 additions & 0 deletions tests/testthat/_snaps/encode.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,13 @@
! All data variables must be named.
x Unnamed variables: `b` and `mtcars`

# data validation works

Code
encode(a = mean)
Condition
Error in `encode()`:
! Data variable `a` is unsupported.
x `a` is a function.
i Choices: NULL, logical, integer, double, character, list, dataframe.

4 changes: 4 additions & 0 deletions tests/testthat/test-encode.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ test_that("dynamic dots work", {
expect_equal(encode(a = 1), res)
expect_equal(encode(!!!list(a = 1)), res)
})

test_that("data validation works", {
expect_snapshot(encode(a = mean), error = TRUE)
})
Loading