Skip to content
This repository was archived by the owner on Jan 30, 2025. It is now read-only.

Commit

Permalink
Allow empty/null values in checks
Browse files Browse the repository at this point in the history
  • Loading branch information
nfrerebeau committed Nov 8, 2024
1 parent bd4ae05 commit 7bc3b64
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 8 deletions.
10 changes: 6 additions & 4 deletions R/assert.R
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,16 @@ needs <- assert_package
#' @param x An object to be checked.
#' @param expected An appropriate expected value.
#' @param allow_empty A [`logical`] scalar: should [empty][is_empty()] object be
#' allowed?
#' @param empty Deprecated.
#' ignored?
#' @param allow_null A [`logical`] scalar: should `NULL` object be ignored?
#' @return
#' Throws an error, if any, and returns `x` invisibly otherwise.
#' @author N. Frerebeau
#' @family checking methods
#' @export
assert_length <- function(x, expected, allow_empty = empty, empty = FALSE) {
assert_length <- function(x, expected, allow_empty = FALSE, allow_null = FALSE) {
if (is.null(x) && isTRUE(allow_null)) return(invisible(NULL))

arg <- deparse(substitute(x))
if (!(allow_empty && is_empty(x)) && !has_length(x, n = expected)) {
txt <- tr_("%s must be of length %d; not %d.")
Expand Down Expand Up @@ -312,7 +314,7 @@ assert_unique <- function(x) {
#' "`integer`", "`double`", "`character`" or "`logical`".
#' @param allow_empty A [`logical`] scalar: should [empty][is_empty()] object be
#' allowed?
#' @param allow_null A [`logical`] scalar: should `NULL` object be allowed?
#' @param allow_null A [`logical`] scalar: should `NULL` object be ignored?
#' @return
#' Throws an error, if any, and returns `x` invisibly otherwise.
#' @author N. Frerebeau
Expand Down
1 change: 1 addition & 0 deletions inst/tinytest/test_assert.R
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ expect_inherits(cnd[[1]], "error_bad_length")

expect_identical(assert_length(numeric(), expected = 10, allow_empty = TRUE), numeric())
expect_identical(assert_length(LETTERS, expected = 26), LETTERS)
expect_null(assert_length(NULL, expected = 10, allow_null = TRUE))

## Lengths ---------------------------------------------------------------------
k <- list(1:10, 1:20)
Expand Down
6 changes: 3 additions & 3 deletions man/assert_length.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion man/assert_type.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 7bc3b64

Please sign in to comment.