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

fix: assertions now provide informative errors when mandatory argumen… #103

Merged
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
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