Skip to content

Commit

Permalink
Add allow_na argument to check_character() (#1742)
Browse files Browse the repository at this point in the history
  • Loading branch information
martaalcalde authored Aug 16, 2024
1 parent d2829e2 commit 69659c4
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
17 changes: 16 additions & 1 deletion R/standalone-types-check.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
#
# ## Changelog
#
# 2024-08-15:
# - `check_character()` gains an `allow_na` argument (@martaalcalde, #1724)
#
# 2023-03-13:
# - Improved error messages of number checkers (@teunbrand)
# - Added `allow_infinite` argument to `check_number_whole()` (@mgirlich).
Expand Down Expand Up @@ -457,15 +460,28 @@ check_formula <- function(x,

# Vectors -----------------------------------------------------------------

# TODO: Figure out what to do with logical `NA` and `allow_na = TRUE`

check_character <- function(x,
...,
allow_na = TRUE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {

if (!missing(x)) {
if (is_character(x)) {
if (!allow_na && any(is.na(x))) {
abort(
sprintf("`%s` can't contain NA values.", arg),
arg = arg,
call = call
)
}

return(invisible(NULL))
}

if (allow_null && is_null(x)) {
return(invisible(NULL))
}
Expand All @@ -475,7 +491,6 @@ check_character <- function(x,
x,
"a character vector",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
Expand Down
6 changes: 6 additions & 0 deletions tests/testthat/_snaps/standalone-types-check.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,12 @@
<error/rlang_error>
Error in `checker()`:
! `foo` must be a character vector or `NULL`, not a list.
Code
err(checker(c("a", NA), check_character, allow_na = FALSE))
Output
<error/rlang_error>
Error in `checker()`:
! `foo` can't contain NA values.

# `check_logical()` checks

Expand Down
2 changes: 2 additions & 0 deletions tests/testthat/test-standalone-types-check.R
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ test_that("`check_environment()` checks", {
test_that("`check_character()` checks", {
expect_null(check_character(""))
expect_null(check_character(na_chr))
expect_null(check_character(c("a", NA)))
expect_null(check_character(chr()))
expect_null(check_character("foo"))
expect_null(check_character(letters))
Expand All @@ -164,6 +165,7 @@ test_that("`check_character()` checks", {
err(checker(NA, check_character))
err(checker(1, check_character))
err(checker(list("foo", "bar"), check_character, allow_null = TRUE))
err(checker(c("a", NA), check_character, allow_na = FALSE))
})
})

Expand Down

0 comments on commit 69659c4

Please sign in to comment.