From 14dd1183116e4ed58884ce9a5ccef10f325192b7 Mon Sep 17 00:00:00 2001 From: Maximilian Held Date: Thu, 12 Sep 2024 17:18:45 +0200 Subject: [PATCH] make skip if not functions --- NAMESPACE | 1 + R/tests.R | 44 ++++++++++++++++++++++++++++++++++++- tests/testthat/test-tests.R | 9 ++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 tests/testthat/test-tests.R diff --git a/NAMESPACE b/NAMESPACE index c4af25c..ae2fe89 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,6 +1,7 @@ # Generated by roxygen2: do not edit by hand export(is_installed2) +export(make_skip_if_not_function) export(opt_set_local2) export(source_pef) export(transform_with_generated) diff --git a/R/tests.R b/R/tests.R index 2c0fee6..855d004 100644 --- a/R/tests.R +++ b/R/tests.R @@ -2,7 +2,7 @@ #' #' To be used as an argument for [testthat::expect_snapshot()]. #' @param x A character vector. -#' @keywords snapshot helpers +#' @keywords snapshot helpers, testing helpers #' @name transform_snap NULL @@ -16,3 +16,45 @@ transform_with_generated <- function(x = character()) { x ) } + +#' Make a [testthat::skip_if_not()] function +#' +#' Function operator to turn +#' [checkmate](https://mllg.github.io/checkmate/index.html)'s +#' `check_*()`-type functions into [testthat](https://testthat.r-lib.org)'s +#' `skip_if_not_*()` functions. +#' +#' @inheritParams checkmate::makeAssertionFunction +#' @details +#' Notice that `check_*()` are always formulated *positively*; +#' the message from `check_*()` is emitted, +#' when its condition is *not* met. +#' The [testthat](https://testthat.r-lib.org) equivalent is the opposite: +#' a `skip_if_not_*()` function would skip with the emitted message. +#' +#' You cannot generate `skip_if_*()` functions from `check_*()` functions, +#' because the negation of the emitted message may be wrong or confusing. +#' But you can create one manually: +#' +#' ```r +#' skip_if_cond <- function(x) { +#' testthat::skip_if( +#' my_pkg::check_cond(x), +#' # needs a custom message here +#' "Skipping because condition is true." +#' ) +#' } +#' ``` +#' @export +#' @keywords testing helpers +make_skip_if_not_function <- function(check.fun) { + force(check.fun) + function(...) { + res <- check.fun(...) + if (isTRUE(res)) { + return(invisible()) + } else { + testthat::skip(res) + } + } +} diff --git a/tests/testthat/test-tests.R b/tests/testthat/test-tests.R new file mode 100644 index 0000000..b681dc3 --- /dev/null +++ b/tests/testthat/test-tests.R @@ -0,0 +1,9 @@ +describe("make_skip_if_not_function", { + it("returns invisibly if success", { + expect_equal( + make_skip_if_not_function(checkmate::check_scalar)(1), + invisible() + ) + }) + # can't easily test for failure, because then it would, well, skip. +})