Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add assert_scalar_positive_integer #3

Merged
merged 2 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
})