diff --git a/R/standalone-types-check.R b/R/standalone-types-check.R index 90a889f1b..22ea57ba8 100644 --- a/R/standalone-types-check.R +++ b/R/standalone-types-check.R @@ -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). @@ -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)) } @@ -475,7 +491,6 @@ check_character <- function(x, x, "a character vector", ..., - allow_na = FALSE, allow_null = allow_null, arg = arg, call = call diff --git a/tests/testthat/_snaps/standalone-types-check.md b/tests/testthat/_snaps/standalone-types-check.md index 16af3ed25..a54db03a6 100644 --- a/tests/testthat/_snaps/standalone-types-check.md +++ b/tests/testthat/_snaps/standalone-types-check.md @@ -450,6 +450,12 @@ 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 in `checker()`: + ! `foo` can't contain NA values. # `check_logical()` checks diff --git a/tests/testthat/test-standalone-types-check.R b/tests/testthat/test-standalone-types-check.R index ce0a3dc0a..a8a6e177c 100644 --- a/tests/testthat/test-standalone-types-check.R +++ b/tests/testthat/test-standalone-types-check.R @@ -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)) @@ -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)) }) })