Skip to content

Commit

Permalink
fix: adds tests and better protects against problematic names
Browse files Browse the repository at this point in the history
  • Loading branch information
averissimo committed Oct 24, 2024
1 parent 25a5d96 commit b3f6dad
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 2 additions & 2 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ make_c_call <- function(choices) {
#'
#' @keywords internal
sanitize_id <- function(id) {
id <- as.character(as.name(id))
id_converted <- make.names(id)
if (identical(make.names(id), id)) {
return(id)
Expand All @@ -82,8 +83,7 @@ sanitize_id <- function(id) {
if (!grepl("^X", id)) {
id_converted <- gsub("^X", "", id_converted)
}

paste0(substr(rlang::hash(id), 1, 4), "_", id_converted)
paste0(substr(rlang::hash(as.character(id)), 1, 4), "_", id_converted)
}

#' `NS` wrapper to sanitize ids for shiny
Expand Down
29 changes: 29 additions & 0 deletions tests/testthat/test-utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,32 @@ testthat::test_that("make_c_call", {
testthat::expect_identical(make_c_call(1:3), quote(c(1L, 2L, 3L)))
testthat::expect_identical(make_c_call(1), 1)
})

testthat::describe("sanitize_id", {
testthat::it("should replace non-ASCII characters in middle of id with `_`", {
testthat::expect_identical(NS("app", "a$b"), paste0("app-", substr(rlang::hash("a$b"), 1, 4), "_a_b"))
})

testthat::it("should replace non-ASCII characters in the start/end of id with `_`", {
testthat::expect_identical(NS("app", "%a.b%c$"), paste0("app-", substr(rlang::hash("%a.b%c$"), 1, 4), "__a_b_c_"))
})

testthat::it("should replace all quotes characters with `_`", {
testthat::expect_identical(NS("app", " a.b.c\"d`e'j"), paste0("app-", substr(rlang::hash(" a.b.c\"d`e'j"), 1, 4), "__a_b_c_d_e_j"))

Check warning on line 17 in tests/testthat/test-utils.R

View workflow job for this annotation

GitHub Actions / SuperLinter 🦸‍♀️ / Lint R code 🧶

file=tests/testthat/test-utils.R,line=17,col=121,[line_length_linter] Lines should not be more than 120 characters. This line is 135 characters.
})

testthat::it("should replace UTF-8 special characters with `_`", {
testthat::expect_identical(
NS("app", "a\U1F643"),
paste0("app-", substr(rlang::hash("a\U1F643"), 1, 4), "_a_")
)
})

testthat::it("should replace all escape characters from JQuery selectors", {
forbidden <- " !\"#$%&'()*+,./:;<=>?@[\\]^`{|}~]"
testthat::expect_identical(
NS("app", forbidden),
paste0("app-", substr(rlang::hash(forbidden), 1, 4), paste(rep("_", nchar(forbidden) + 1), collapse = ""))
)
})
})

0 comments on commit b3f6dad

Please sign in to comment.