Skip to content
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
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export(assert_file_has_extension)
export(assert_finite)
export(assert_flag)
export(assert_function)
export(assert_function_expects)
export(assert_function_expects_n_arguments)
export(assert_greater_than)
export(assert_greater_than_or_equal_to)
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# assertions 0.2.0

* Added `assert_function_expects()` for checking required argument names in functions

* Added `assert_all_strings_contain()` and `assert_string_contains()` for checking character inputs against regular expressions

* Added `assert_packages_installed()`
Expand Down
52 changes: 52 additions & 0 deletions R/assert_functions.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,33 @@ function_expects_n_arguments_advanced <- function(x, n, dots = c("throw_error","
}


# Expect function has arguments
# @param
# @param required the names of parameters the function must support (character)
#
# @returns TRUE if the function contains the expected parameters, otherwise returns a string (the error message)
#
function_expects_advanced <- function(x, required){
if(!is.function(x)) {
value_class <- toString(class(x))
return(paste0("{.strong '{arg_name}'} must be a function, not a ", value_class))
}

declared_args <- setdiff(func_arg_names(x), "...")
if(!is_subset(required, declared_args)){
missing_args <- setopts_exlusive_to_first(required, declared_args)
missing_count <- length(missing_args)
missing_args <- paste0("`", paste(missing_args, collapse = "`, `"), "`")
return(paste0("Function '{arg_name}' is missing the following parameter",
if(missing_count == 1) "" else "s",
" in its signature: {.strong ", missing_args, "}"
))
}

return(TRUE)
}


# Assertions --------------------------------------------------------------

#' Assert function expects n arguments
Expand All @@ -42,3 +69,28 @@ function_expects_n_arguments_advanced <- function(x, n, dots = c("throw_error","
#'
#' @export
assert_function_expects_n_arguments <- assert_create(func = function_expects_n_arguments_advanced)

#' Assert function expects specific parameter names
#'
#' Assert that a function signature includes required set of parameter names in its
#' formal argument list, regardless of whether those parameters have default
#' values. The `...` argument is ignored.
#'
#' @param x a function to check for required parameter names
#' @param required a character vector of parameter names that must appear in
#' the function signature (order does not matter)
#' @inheritParams common_roxygen_params
#'
#' @return invisible(TRUE) if function `x` declares all required parameters,
#' otherwise aborts with the error message specified by `msg`
#'
#' @examples
#' my_fun <- function(x, y = 1, ...) x + y
#' assert_function_expects(my_fun, c("x", "y"))
#'
#' try({
#' assert_function_expects(my_fun, c("x", "z"))
#' })
#'
#' @export
assert_function_expects <- assert_create(func = function_expects_advanced)
10 changes: 10 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ func_supports_variable_arguments <- function(func){
func_args_as_pairlist <- function(func){
formals(args(func))
}

func_required_arg_names <- function(func){
args <- formals(args(func))
if(length(args) == 0){
return(character(0))
}
required_args <- args[vapply(args, is.symbol, FUN.VALUE = TRUE)]
required_args <- names(required_args)
Comment on lines +72 to +78

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fix required-arg detection for symbol defaults

func_required_arg_names() uses is.symbol to decide which formals are “required.” In R, a default like x = mean or x = y is stored as a symbol too, so this logic treats those defaulted args as required and assert_function_expects() will incorrectly report them missing when callers omit them. This only shows up for functions whose defaults are symbols, but it makes the new assertion reject valid functions. Consider checking for a missing default (e.g., identical(arg, quote(expr=))) rather than is.symbol.

Useful? React with 👍 / 👎.

setdiff(required_args, "...")
}
#
# func_args_as_alist <- function(func){
# a= unlist(func_args_as_pairlist(func))
Expand Down
43 changes: 43 additions & 0 deletions man/assert_function_expects.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

68 changes: 68 additions & 0 deletions tests/testthat/test-assert_functions.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ fn_1_arg <- function(a) {}
fn_2_args <- function(a, b) {}
fn_1_arg_with_dots <- function(a, ...) {}
fn_2_args_with_dots <- function(a, b, ...) {}
fn_with_required_args <- function(x, y, z = 1, ...) {}
fn_with_defaults <- function(x = 1, y = 2) {}
fn_with_no_required <- function(...) {}

# Unit tests for `function_expects_n_arguments_advanced`
test_that("function_expects_n_arguments_advanced behaves correctly for exact argument count", {
Expand Down Expand Up @@ -69,6 +72,21 @@ test_that("function_expects_n_arguments_advanced handles `dots` parameter correc
expect_true(function_expects_n_arguments_advanced(fn_2_args_with_dots, Inf, dots = "count_as_inf"))
})

test_that("function_expects_advanced validates required argument names", {
expect_true(function_expects_advanced(fn_2_args, c("a", "b")))
expect_true(function_expects_advanced(fn_with_required_args, c("x", "y")))

expect_match(function_expects_advanced(fn_2_args, "c"),
"missing the following parameter", fixed = TRUE)
expect_match(function_expects_advanced(fn_2_args, c("b", "c")),
"missing the following parameter", fixed = TRUE)
expect_match(function_expects_advanced(fn_with_no_required, "x"),
"missing the following parameter", fixed = TRUE)
expect_true(function_expects_advanced(fn_with_defaults, "x"))
expect_match(function_expects_advanced(1, "x"),
"must be a function, not a", fixed = TRUE)
})




Expand Down Expand Up @@ -105,3 +123,53 @@ cli::test_that_cli("assert_function_expects_n_arguments() works", config = "plai
# Custom error messages work
expect_error(assert_function_expects_n_arguments(my_func, 3, msg = "Custom error message"), "Custom error message")
})

cli::test_that_cli("assert_function_expects() works", config = "plain", {

# Function with required args and one defaulted argument
my_func <- function(a, b, c = 1) { a + b + c }

# Function that accepts additional arguments via ...
my_func_dots <- function(a, b, ...) { a + b }

# Succeeds when required parameters are present (ignores defaults)
expect_true(assert_function_expects(my_func, c("a", "b")))

# Succeeds when required parameters are present and ... is ignored
expect_true(assert_function_expects(my_func_dots, c("a", "b")))

# Succeeds when checking for a parameter with a default value
expect_true(assert_function_expects(my_func, c("c")))

# Function missing one of the required parameters
my_func2 <- function(a, c) { a + c }

# Errors when a required parameter is absent from the signature
expect_error(
assert_function_expects(my_func2, c("a", "b")),
"Function 'my_func2' is missing the following parameter in its signature: `b`"
)

# Errors when input is not a function
expect_error(
assert_function_expects(123, "a"),
"'123' must be a function, not a numeric"
)

# Errors when function has no matching required parameters
expect_error(
assert_function_expects(fn_with_no_required, "a"),
"Function 'fn_with_no_required' is missing the following parameter in its signature: `a`"
)

# Succeeds when required parameter exists even if it has a default
expect_true(assert_function_expects(fn_with_defaults, "x"))

# Uses custom error message when provided
expect_error(
assert_function_expects(my_func, c("a", "d"), msg = "Custom error message"),
"Custom error message"
)

})