Skip to content

Commit

Permalink
Merge pull request #3 from edknock/assert-scalar-positive-integer
Browse files Browse the repository at this point in the history
Add assert_scalar_positive_integer
  • Loading branch information
richfitz authored Sep 6, 2024
2 parents 4d90647 + 21b0f65 commit 97ff376
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
13 changes: 13 additions & 0 deletions R/standalone-utils-assert.R
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,19 @@ assert_scalar_positive_numeric <- function(x, allow_zero = TRUE,
}


assert_scalar_positive_integer <- function(x, allow_zero = TRUE,
name = deparse(substitute(x)),
tolerance = NULL, arg = name,
call = parent.frame()) {
assert_scalar_integer(x, name, tolerance = tolerance, arg = arg, call = call)
min <- if (allow_zero) 0 else 1
if (x < min) {
cli::cli_abort("'{name}' must be at least {min}", arg = arg, call = call)
}
invisible(x)
}


assert_raw <- function(x, len = NULL, name = deparse(substitute(x)),
arg = name, call = parent.frame()) {
if (!is.raw(x)) {
Expand Down
18 changes: 18 additions & 0 deletions tests/testthat/test-util-assert.R
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,21 @@ test_that("assert_scalar_positive numeric", {
expect_error(assert_scalar_positive_numeric(x, allow_zero = FALSE),
"'x' must be greater than 0")
})


test_that("assert_scalar_positive integer", {
x <- 1
expect_silent(assert_scalar_positive_integer(x))
expect_silent(assert_scalar_positive_integer(x, allow_zero = FALSE))
x <- 0
expect_silent(assert_scalar_positive_integer(x))
expect_error(assert_scalar_positive_integer(x, allow_zero = FALSE),
"'x' must be at least 1")
x <- -2
expect_error(assert_scalar_positive_integer(x),
"'x' must be at least 0")
expect_error(assert_scalar_positive_integer(x, allow_zero = FALSE),
"'x' must be at least 1")
x <- 1.1
expect_error(assert_scalar_positive_integer(x), "Expected 'x' to be integer")
})

0 comments on commit 97ff376

Please sign in to comment.