Skip to content

Commit

Permalink
Add a few more from dust2
Browse files Browse the repository at this point in the history
  • Loading branch information
richfitz committed Aug 30, 2024
1 parent d4f10cf commit 25caf4e
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
29 changes: 29 additions & 0 deletions R/standalone-utils-assert.R
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,35 @@ assert_list <- function(x, name = deparse(substitute(x)), arg = name,
}


assert_scalar_positive_numeric <- function(x, allow_zero = TRUE,
name = deparse(substitute(x)),
arg = name, call = parent.frame()) {
assert_scalar_numeric(x, name = name, call = call)
if (allow_zero) {
if (x < 0) {
cli::cli_abort("'{name}' must be at least 0", arg = arg, call = call)
}
} else {
if (x <= 0) {
cli::cli_abort("'{name}' must be greater than 0", 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)) {
cli::cli_abort("'{name}' must be a raw vector", arg = arg, call = call)
}
if (!is.null(len)) {
assert_length(x, len, name = name, call = call)
}
invisible(x)
}


assert_named <- function(x, unique = FALSE, name = deparse(substitute(x)),
arg = name, call = parent.frame()) {
nms <- names(x)
Expand Down
28 changes: 28 additions & 0 deletions tests/testthat/test-util-assert.R
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,31 @@ test_that("assert_list", {
x <- c(a = 1)
expect_error(assert_list(x), "Expected 'x' to be a list")
})


test_that("assert_raw", {
x <- raw(10)
expect_silent(assert_raw(x))
expect_silent(assert_raw(x, 10))
expect_error(assert_raw(x, 5),
"Expected 'x' to have length 5, but was length 10")
x <- NULL
expect_error(assert_raw(x, 5),
"'x' must be a raw vector")
})


test_that("assert_scalar_positive numeric", {
x <- 1
expect_silent(assert_scalar_positive_numeric(x))
expect_silent(assert_scalar_positive_numeric(x, allow_zero = FALSE))
x <- 0
expect_silent(assert_scalar_positive_numeric(x))
expect_error(assert_scalar_positive_numeric(x, allow_zero = FALSE),
"'x' must be greater than 0")
x <- -2
expect_error(assert_scalar_positive_numeric(x),
"'x' must be at least 0")
expect_error(assert_scalar_positive_numeric(x, allow_zero = FALSE),
"'x' must be greater than 0")
})

0 comments on commit 25caf4e

Please sign in to comment.