From 1a3d6de032a23e745c4e5e6a784907fe918efd1f Mon Sep 17 00:00:00 2001 From: Tom Elliott Date: Thu, 9 Jan 2025 12:58:49 +1300 Subject: [PATCH] test functions --- R/function.R | 13 ++++++++++++- tests/testthat/test-functions.R | 16 ++++++++-------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/R/function.R b/R/function.R index f769620..37fa9fb 100644 --- a/R/function.R +++ b/R/function.R @@ -8,7 +8,14 @@ parse_args <- function(x, mc) { ) } args <- lapply(names(fmls), function(n) { - fmls[[n]]$check(eval(mc[[n]])) + tryCatch( + { + fmls[[n]]$check(eval(mc[[n]])) + }, + error = function(e) { + stop("Invalid argument '", n, "': ", e$message, call. = FALSE) + } + ) }) names(args) <- names(fmls) args @@ -48,6 +55,10 @@ ts_function <- function(f, ..., result = NULL) { stop("Invalid return type") } + if (length(args) == 0) { + args <- lapply(formals(f), eval) + } + fn <- function(...) { mc <- match.call(f) x <- parse_args(args, mc) diff --git a/tests/testthat/test-functions.R b/tests/testthat/test-functions.R index dd1a15b..0560c45 100644 --- a/tests/testthat/test-functions.R +++ b/tests/testthat/test-functions.R @@ -1,12 +1,12 @@ # # optional, check arguments - useful for debugging/development # check_args(match.call(), formals()) -# test_that("function definitions", { -# add <- ts_fun( -# function(a = ts_numeric(1), b = ts_numeric(1)) a + b, -# result = ts_numeric(1) -# ) +test_that("function definitions", { + add <- ts_function( + function(a = ts_numeric(1), b = ts_numeric(1)) a + b, + result = ts_numeric(1) + ) -# expect_equal(add(1, 2), 3) -# expect_error(add("a", 2)) -# }) + expect_equal(add(1, 2), 3) + expect_error(add("a", 2)) +})