Skip to content

Commit

Permalink
improve assert_class()
Browse files Browse the repository at this point in the history
  • Loading branch information
JanMarvin committed Aug 25, 2023
1 parent 2265f42 commit e6bbd8c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
6 changes: 5 additions & 1 deletion R/asserts.R
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
# Use arg_nm to override the default name of the argument in case of an error message.
assert_class <- function(x, class, or_null = FALSE, all = FALSE, package = NULL, envir = parent.frame(), arg_nm = NULL) {

sx <- as.character(substitute(x, envir))
if (length(sx) == 0 || !is.null(arg_nm)) {
sx <- arg_nm %||% "argument"
}

if (missing(x)) {
stop("input ", sx, " is missing", call. = FALSE)
}

ok <- if (all) {
all(vapply(class, function(i) inherits(x, i), NA))
} else {
Expand All @@ -28,7 +33,6 @@ assert_class <- function(x, class, or_null = FALSE, all = FALSE, package = NULL,
invisible(NULL)
}


assert_chart_sheet <- function(x) assert_class(x, c("wbChartSheet", "R6"), all = TRUE)
assert_comment <- function(x) assert_class(x, c("wbComment", "R6"), all = TRUE)
assert_color <- function(x) assert_class(x, c("wbColour"), all = TRUE)
Expand Down
11 changes: 11 additions & 0 deletions tests/testthat/test-asserts.R
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ test_that("class assertions work", {
# nolint end
})

test_that("missing check works", {
wb <- wb_workbook()
expect_silent(assert_workbook(wb))

wb <- substitute()
expect_error(assert_workbook(wb), "input wb is missing")

wb <- "Not_a_workbook"
expect_error(assert_workbook(wb), "wb must be class wbWorkbook or R6")
})

test_that("match_oneof() works", {
expect_identical(match_oneof(1:4, 3:4), 3L)
expect_identical(match_oneof(1:4, 3:4, several = TRUE), 3:4)
Expand Down

0 comments on commit e6bbd8c

Please sign in to comment.