Skip to content

Commit

Permalink
Merge pull request #103 from selkamand/99-calling-created-assertions-…
Browse files Browse the repository at this point in the history
…without-any-arguments-makes-i

fix: assertions now provide informative errors when mandatory argumen…
  • Loading branch information
selkamand committed Jan 11, 2024
2 parents 1d32c63 + 131c18a commit 2e635c4
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions R/assert_create.R
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ assert_create <- function(func, default_error_msg = NULL){
# Create body of assertion function
body = quote({

# Check mandatory arguments are all supplied
if(required_args_are_missing())
cli::cli_abort('mandatory argument/s were not supplied')

# Setup some variables ( these will be useful later)
if(is.null(arg_name))
arg_name <- deparse(match.call()[[2]])
Expand Down
11 changes: 11 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,14 @@ func_arg_count <- function(func, dots = c("throw_error", "count_as_0", "count_as
# lgl <- unlist(args) == substitute()
# return(lgl)
# }

required_args_are_missing <- function (fun = sys.function(-1), ncall = 3) {
f_args <- formals(fun)
f_args <- f_args[vapply(f_args, is.symbol, FUN.VALUE = TRUE)]
f_args <- names(f_args)
f_args <- setdiff(f_args, "...")
test <- vapply(f_args,
function(x) missingArg(as.name(x), envir = parent.frame(ncall), eval = TRUE),
FUN.VALUE = TRUE)
return(any(test))
}
7 changes: 7 additions & 0 deletions tests/testthat/test-assert_create.R
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,14 @@ cli::test_that_cli(configs = "plain", "assertion function works as expected with
expect_snapshot(assert_between_min_and_max(2, min = 3, max = 5), error = TRUE)
})

cli::test_that_cli(configs = "plain", "created assertion() functions throw informative error when mandatory arguments are not supplied", {
f1 <- function(bob, billy) { return(TRUE) }
assert_f1 <- assertions::assert_create(f1, default_error_msg = 'this is an error message')

expect_error(assert_f1(), regexp = "mandatory argument/s were not supplied", fixed=TRUE)
expect_error(assert_f1(bob = 'a'), regexp = "mandatory argument/s were not supplied", fixed=TRUE)
expect_true(assert_f1('a', 'b'))
})

# Test Creation of Assertion Chains -----------------------------------------------------
cli::test_that_cli(configs = "plain", "assertion chains can evaluate expressions part and not get confused if they contain variable names", {
Expand Down

0 comments on commit 2e635c4

Please sign in to comment.