Skip to content

Commit

Permalink
make skip if not functions
Browse files Browse the repository at this point in the history
  • Loading branch information
maxheld83 committed Sep 12, 2024
1 parent 49ae266 commit 14dd118
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
44 changes: 43 additions & 1 deletion R/tests.R
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
}
}
}
9 changes: 9 additions & 0 deletions tests/testthat/test-tests.R
Original file line number Diff line number Diff line change
@@ -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.
})

0 comments on commit 14dd118

Please sign in to comment.