From 7f2190e2bc2765f6b22a9ab076b707d7b3809023 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rasmus=20Skytte=20Randl=C3=B8v?= Date: Fri, 4 Oct 2024 10:01:13 +0200 Subject: [PATCH] feat(helper-setup): Add the checkmate_err_msg helper --- testthat/helper-setup.R | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/testthat/helper-setup.R b/testthat/helper-setup.R index 74ee44a..153566d 100644 --- a/testthat/helper-setup.R +++ b/testthat/helper-setup.R @@ -125,3 +125,30 @@ get_test_conns <- function() { return(test_conns) } + + +#' Parse checkmate assertions for testthat compatibility +#' @description +#' The error messages generated by `checkmate` are formatted to look nicely in the console by the +#' addition of `*` and `\n` characters. +#' +#' This means that checking these errors with `testthat::expect_error()` will often fail or will be harder to read +#' in the test since we need to manually insert `*` and `\n` to the comparison pattern to match the error message. +#' +#' This helper function intercepts the `checkmate` error message and removes the `*` and `\n` characters to allow for +#' human readable error checking. +#' @return +#' The checkmate error without `*` and `\n` characters. +#' @noRd +checkmate_err_msg <- function(expr) { + tryCatch( + expr, + error = \(e) { + e$message |> + stringr::str_remove_all(stringr::fixed("\n *")) |> + stringr::str_remove_all(stringr::fixed("* ")) |> + simpleError(message = _) |> + stop() + } + ) +}