Skip to content

Commit 69659c4

Browse files
authored
Add allow_na argument to check_character() (#1742)
1 parent d2829e2 commit 69659c4

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

R/standalone-types-check.R

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
#
1010
# ## Changelog
1111
#
12+
# 2024-08-15:
13+
# - `check_character()` gains an `allow_na` argument (@martaalcalde, #1724)
14+
#
1215
# 2023-03-13:
1316
# - Improved error messages of number checkers (@teunbrand)
1417
# - Added `allow_infinite` argument to `check_number_whole()` (@mgirlich).
@@ -457,15 +460,28 @@ check_formula <- function(x,
457460

458461
# Vectors -----------------------------------------------------------------
459462

463+
# TODO: Figure out what to do with logical `NA` and `allow_na = TRUE`
464+
460465
check_character <- function(x,
461466
...,
467+
allow_na = TRUE,
462468
allow_null = FALSE,
463469
arg = caller_arg(x),
464470
call = caller_env()) {
471+
465472
if (!missing(x)) {
466473
if (is_character(x)) {
474+
if (!allow_na && any(is.na(x))) {
475+
abort(
476+
sprintf("`%s` can't contain NA values.", arg),
477+
arg = arg,
478+
call = call
479+
)
480+
}
481+
467482
return(invisible(NULL))
468483
}
484+
469485
if (allow_null && is_null(x)) {
470486
return(invisible(NULL))
471487
}
@@ -475,7 +491,6 @@ check_character <- function(x,
475491
x,
476492
"a character vector",
477493
...,
478-
allow_na = FALSE,
479494
allow_null = allow_null,
480495
arg = arg,
481496
call = call

tests/testthat/_snaps/standalone-types-check.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,12 @@
450450
<error/rlang_error>
451451
Error in `checker()`:
452452
! `foo` must be a character vector or `NULL`, not a list.
453+
Code
454+
err(checker(c("a", NA), check_character, allow_na = FALSE))
455+
Output
456+
<error/rlang_error>
457+
Error in `checker()`:
458+
! `foo` can't contain NA values.
453459

454460
# `check_logical()` checks
455461

tests/testthat/test-standalone-types-check.R

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ test_that("`check_environment()` checks", {
153153
test_that("`check_character()` checks", {
154154
expect_null(check_character(""))
155155
expect_null(check_character(na_chr))
156+
expect_null(check_character(c("a", NA)))
156157
expect_null(check_character(chr()))
157158
expect_null(check_character("foo"))
158159
expect_null(check_character(letters))
@@ -164,6 +165,7 @@ test_that("`check_character()` checks", {
164165
err(checker(NA, check_character))
165166
err(checker(1, check_character))
166167
err(checker(list("foo", "bar"), check_character, allow_null = TRUE))
168+
err(checker(c("a", NA), check_character, allow_na = FALSE))
167169
})
168170
})
169171

0 commit comments

Comments
 (0)