diff --git a/.Rbuildignore b/.Rbuildignore index 38d225ec8..c0b2e00e3 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -20,3 +20,5 @@ ^\.github/workflows/R\.yaml$ ^\.github/workflows/pr-commands\.yaml$ ^CRAN-SUBMISSION$ +^[\.]?air\.toml$ +^\.vscode$ diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..344f76eba --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,5 @@ +{ + "recommendations": [ + "Posit.air-vscode" + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..f2d0b79d6 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "[r]": { + "editor.formatOnSave": true, + "editor.defaultFormatter": "Posit.air-vscode" + } +} diff --git a/R/auto-test.R b/R/auto-test.R index 8630ff46e..d45113580 100644 --- a/R/auto-test.R +++ b/R/auto-test.R @@ -28,9 +28,13 @@ #' @param hash Passed on to [watch()]. When FALSE, uses less accurate #' modification time stamps, but those are faster for large files. #' @keywords debugging -auto_test <- function(code_path, test_path, reporter = default_reporter(), - env = test_env(), - hash = TRUE) { +auto_test <- function( + code_path, + test_path, + reporter = default_reporter(), + env = test_env(), + hash = TRUE +) { reporter <- find_reporter(reporter) code_path <- normalizePath(code_path) test_path <- normalizePath(test_path) @@ -72,7 +76,11 @@ auto_test <- function(code_path, test_path, reporter = default_reporter(), #' modification time stamps, but those are faster for large files. #' @keywords debugging #' @seealso [auto_test()] for details on how method works -auto_test_package <- function(pkg = ".", reporter = default_reporter(), hash = TRUE) { +auto_test_package <- function( + pkg = ".", + reporter = default_reporter(), + hash = TRUE +) { reporter <- find_reporter(reporter) path <- pkgload::pkg_path(pkg) @@ -86,7 +94,12 @@ auto_test_package <- function(pkg = ".", reporter = default_reporter(), hash = T # Start by loading all code and running all tests withr::local_envvar("NOT_CRAN" = "true") pkgload::load_all(path) - test_dir(test_path, package = package, reporter = reporter$clone(deep = TRUE), stop_on_failure = FALSE) + test_dir( + test_path, + package = package, + reporter = reporter$clone(deep = TRUE), + stop_on_failure = FALSE + ) # Next set up watcher to monitor changes watcher <- function(added, deleted, modified) { @@ -106,7 +119,11 @@ auto_test_package <- function(pkg = ".", reporter = default_reporter(), hash = T cat("Changed code: ", paste0(basename(code), collapse = ", "), "\n") cat("Rerunning all tests\n") pkgload::load_all(path, quiet = TRUE) - test_dir(test_path, package = package, reporter = reporter$clone(deep = TRUE)) + test_dir( + test_path, + package = package, + reporter = reporter$clone(deep = TRUE) + ) } else if (length(tests) > 0) { # If test changes, rerun just that test cat("Rerunning tests: ", paste0(basename(tests), collapse = ", "), "\n") @@ -115,7 +132,7 @@ auto_test_package <- function(pkg = ".", reporter = default_reporter(), hash = T test_dir = test_path, test_package = package, test_paths = tests, - env = env, + env = env, reporter = reporter$clone(deep = TRUE) ) } diff --git a/R/colour-text.R b/R/colour-text.R index fcceaa16b..1bf3ea93d 100644 --- a/R/colour-text.R +++ b/R/colour-text.R @@ -1,4 +1,7 @@ -colourise <- function(text, as = c("success", "skip", "warning", "failure", "error")) { +colourise <- function( + text, + as = c("success", "skip", "warning", "failure", "error") +) { if (has_colour()) { unclass(cli::make_ansi_style(testthat_style(as))(text)) } else { @@ -11,7 +14,9 @@ has_colour <- function() { cli::num_ansi_colors() > 1 } -testthat_style <- function(type = c("success", "skip", "warning", "failure", "error")) { +testthat_style <- function( + type = c("success", "skip", "warning", "failure", "error") +) { type <- match.arg(type) c( diff --git a/R/compare.R b/R/compare.R index 2739cfce9..906e0caa6 100644 --- a/R/compare.R +++ b/R/compare.R @@ -64,10 +64,14 @@ print_out <- function(x, ...) { # Common helpers --------------------------------------------------------------- same_length <- function(x, y) length(x) == length(y) -diff_length <- function(x, y) difference(fmt = "Lengths differ: %i is not %i", length(x), length(y)) +diff_length <- function(x, y) { + difference(fmt = "Lengths differ: %i is not %i", length(x), length(y)) +} same_type <- function(x, y) identical(typeof(x), typeof(y)) -diff_type <- function(x, y) difference(fmt = "Types not compatible: %s is not %s", typeof(x), typeof(y)) +diff_type <- function(x, y) { + difference(fmt = "Types not compatible: %s is not %s", typeof(x), typeof(y)) +} same_class <- function(x, y) { if (!is.object(x) && !is.object(y)) { @@ -76,7 +80,11 @@ same_class <- function(x, y) { identical(class(x), class(y)) } diff_class <- function(x, y) { - difference(fmt = "Classes differ: %s is not %s", format_class(class(x)), format_class(class(y))) + difference( + fmt = "Classes differ: %s is not %s", + format_class(class(x)), + format_class(class(y)) + ) } same_attr <- function(x, y) { @@ -91,10 +99,9 @@ vector_equal <- function(x, y) { (is.na(x) & is.na(y)) | (!is.na(x) & !is.na(y) & x == y) } -vector_equal_tol <- function(x, y, tolerance = .Machine$double.eps ^ 0.5) { +vector_equal_tol <- function(x, y, tolerance = .Machine$double.eps^0.5) { (is.na(x) & is.na(y)) | (!is.na(x) & !is.na(y)) & (x == y | abs(x - y) < tolerance) - } @@ -125,9 +132,15 @@ vector_equal_tol <- function(x, y, tolerance = .Machine$double.eps ^ 0.5) { #' compare(x, y) #' compare(c(x, x), c(y, y)) #' -compare.character <- function(x, y, check.attributes = TRUE, ..., - max_diffs = 5, max_lines = 5, - width = cli::console_width()) { +compare.character <- function( + x, + y, + check.attributes = TRUE, + ..., + max_diffs = 5, + max_lines = 5, + width = cli::console_width() +) { if (identical(x, y)) { return(no_difference()) } @@ -174,10 +187,13 @@ mismatch_character <- function(x, y, diff = !vector_equal(x, y)) { } #' @export -format.mismatch_character <- function(x, ..., - max_diffs = 5, - max_lines = 5, - width = cli::console_width()) { +format.mismatch_character <- function( + x, + ..., + max_diffs = 5, + max_lines = 5, + width = cli::console_width() +) { width <- width - 6 # allocate space for labels n_show <- seq_len(min(x$n_diff, max_diffs)) @@ -186,11 +202,16 @@ format.mismatch_character <- function(x, ..., show_y <- str_trunc(encode(x$y[n_show]), width * max_lines) show_i <- x$i[n_show] - sidebyside <- Map(function(x, y, pos) { - x <- paste0("x[", pos, "]: ", str_chunk(x, width)) - y <- paste0("y[", pos, "]: ", str_chunk(y, width)) - paste(c(x, y), collapse = "\n") - }, show_x, show_y, show_i) + sidebyside <- Map( + function(x, y, pos) { + x <- paste0("x[", pos, "]: ", str_chunk(x, width)) + y <- paste0("y[", pos, "]: ", str_chunk(y, width)) + paste(c(x, y), collapse = "\n") + }, + show_x, + show_y, + show_i + ) summary <- paste0(x$n_diff, "/", x$n, " mismatches") paste0(summary, "\n", paste0(sidebyside, collapse = "\n\n")) @@ -238,13 +259,20 @@ str_chunk <- function(x, length) { #' # Compare ignores minor numeric differences in the same way #' # as all.equal. #' compare(x, x + 1e-9) -compare.numeric <- function(x, y, - tolerance = testthat_tolerance(), - check.attributes = TRUE, - ..., max_diffs = 9) { +compare.numeric <- function( + x, + y, + tolerance = testthat_tolerance(), + check.attributes = TRUE, + ..., + max_diffs = 9 +) { all_equal <- all.equal( - x, y, tolerance = tolerance, - check.attributes = check.attributes, ... + x, + y, + tolerance = tolerance, + check.attributes = check.attributes, + ... ) if (isTRUE(all_equal)) { return(no_difference()) @@ -284,7 +312,7 @@ testthat_tolerance <- function() { skip("Long doubles not available and `tolerance` not supplied") } - .Machine$double.eps ^ 0.5 + .Machine$double.eps^0.5 } mismatch_numeric <- function(x, y, diff = !vector_equal(x, y)) { @@ -312,7 +340,8 @@ format.mismatch_numeric <- function(x, ..., max_diffs = 9, digits = 3) { n_show <- seq_len(min(x$n_diff, max_diffs)) diffs <- paste0( - format(paste0("[", x$i[n_show], "]")), " ", + format(paste0("[", x$i[n_show], "]")), + " ", format(x$x[n_show], digits = digits), " - ", format(x$y[n_show], digits = digits), @@ -362,10 +391,11 @@ compare.POSIXt <- function(x, y, tolerance = 0.001, ..., max_diffs = 9) { } standardise_tzone <- function(x) { - if (is.null(attr(x, "tzone")) || identical(attr(x, "tzone"), Sys.timezone())) { + if ( + is.null(attr(x, "tzone")) || identical(attr(x, "tzone"), Sys.timezone()) + ) { attr(x, "tzone") <- "" } x } - diff --git a/R/deprec-condition.R b/R/deprec-condition.R index 15d6f8c28..e72953abf 100644 --- a/R/deprec-condition.R +++ b/R/deprec-condition.R @@ -1,13 +1,15 @@ - new_capture <- function(class) { exiting_handlers <- rep_named(class, list(identity)) - calling_handlers <- rep_named(class, alist(function(cnd) { - if (can_entrace(cnd)) { - cnd <- cnd_entrace(cnd) - } - return_from(env, cnd) - })) + calling_handlers <- rep_named( + class, + alist(function(cnd) { + if (can_entrace(cnd)) { + cnd <- cnd_entrace(cnd) + } + return_from(env, cnd) + }) + ) formals <- pairlist2(code = , entrace = FALSE) @@ -16,11 +18,23 @@ new_capture <- function(class) { body <- expr({ if (!entrace) { - return(tryCatch({ code; NULL }, !!!exiting_handlers)) + return(tryCatch( + { + code + NULL + }, + !!!exiting_handlers + )) } env <- environment() - withCallingHandlers({ code; NULL }, !!!calling_handlers) + withCallingHandlers( + { + code + NULL + }, + !!!calling_handlers + ) }) new_function(formals, body, ns_env("testthat")) diff --git a/R/edition.R b/R/edition.R index c2bf9c9dd..aef968bd0 100644 --- a/R/edition.R +++ b/R/edition.R @@ -34,7 +34,9 @@ edition_deprecate <- function(in_edition, what, instead = NULL) { } edition_require <- function(in_edition, what) { - if (edition_get() >= in_edition || isTRUE(getOption("testthat.edition_ignore"))) { + if ( + edition_get() >= in_edition || isTRUE(getOption("testthat.edition_ignore")) + ) { return() } diff --git a/R/example.R b/R/example.R index cf93689a5..725418c61 100644 --- a/R/example.R +++ b/R/example.R @@ -17,7 +17,8 @@ testthat_examples <- function() { #' @rdname testthat_examples testthat_example <- function(filename) { system.file( - "examples", paste0("test-", filename, ".R"), + "examples", + paste0("test-", filename, ".R"), package = "testthat", mustWork = TRUE ) diff --git a/R/expect-comparison.R b/R/expect-comparison.R index 1927ae9ee..458eb7c9a 100644 --- a/R/expect-comparison.R +++ b/R/expect-comparison.R @@ -24,9 +24,9 @@ expect_compare <- function(operator = c("<", "<=", ">", ">="), act, exp) { op <- match.fun(operator) msg <- c( - "<" = "not strictly less than", + "<" = "not strictly less than", "<=" = "not less than", - ">" = "not strictly more than", + ">" = "not strictly more than", ">=" = "not more than" )[[operator]] @@ -36,7 +36,13 @@ expect_compare <- function(operator = c("<", "<=", ">", ">="), act, exp) { } expect( if (!is.na(cmp)) cmp else FALSE, - sprintf("%s is %s %s. Difference: %.3g", act$lab, msg, exp$lab, act$val - exp$val), + sprintf( + "%s is %s %s. Difference: %.3g", + act$lab, + msg, + exp$lab, + act$val - exp$val + ), trace_env = caller_env() ) invisible(act$val) diff --git a/R/expect-condition.R b/R/expect-condition.R index f032b5573..6929944aa 100644 --- a/R/expect-condition.R +++ b/R/expect-condition.R @@ -105,16 +105,19 @@ #' expect_message(f(-1)) #' expect_message(f(-1), "already negative") #' expect_message(f(1), NA) -expect_error <- function(object, - regexp = NULL, - class = NULL, - ..., - inherit = TRUE, - info = NULL, - label = NULL) { - +expect_error <- function( + object, + regexp = NULL, + class = NULL, + ..., + inherit = TRUE, + info = NULL, + label = NULL +) { if (edition_get() >= 3) { - expect_condition_matching("error", {{ object }}, + expect_condition_matching( + "error", + {{ object }}, regexp = regexp, class = class, ..., @@ -143,21 +146,24 @@ expect_error <- function(object, #' @export #' @rdname expect_error -expect_warning <- function(object, - regexp = NULL, - class = NULL, - ..., - inherit = TRUE, - all = FALSE, - info = NULL, - label = NULL) { - +expect_warning <- function( + object, + regexp = NULL, + class = NULL, + ..., + inherit = TRUE, + all = FALSE, + info = NULL, + label = NULL +) { if (edition_get() >= 3) { if (!missing(all)) { warn("The `all` argument is deprecated") } - expect_condition_matching("warning", {{ object }}, + expect_condition_matching( + "warning", + {{ object }}, regexp = regexp, class = class, ..., @@ -166,9 +172,18 @@ expect_warning <- function(object, label = label ) } else { - act <- quasi_capture(enquo(object), label, capture_warnings, ignore_deprecation = identical(regexp, NA)) + act <- quasi_capture( + enquo(object), + label, + capture_warnings, + ignore_deprecation = identical(regexp, NA) + ) msg <- compare_messages( - act$cap, act$lab, regexp = regexp, all = all, ..., + act$cap, + act$lab, + regexp = regexp, + all = all, + ..., cond_type = "warnings" ) expect(is.null(msg), msg, info = info) @@ -179,17 +194,20 @@ expect_warning <- function(object, #' @export #' @rdname expect_error -expect_message <- function(object, - regexp = NULL, - class = NULL, - ..., - inherit = TRUE, - all = FALSE, - info = NULL, - label = NULL) { - +expect_message <- function( + object, + regexp = NULL, + class = NULL, + ..., + inherit = TRUE, + all = FALSE, + info = NULL, + label = NULL +) { if (edition_get() >= 3) { - expect_condition_matching("message", {{ object }}, + expect_condition_matching( + "message", + {{ object }}, regexp = regexp, class = class, ..., @@ -208,16 +226,19 @@ expect_message <- function(object, #' @export #' @rdname expect_error -expect_condition <- function(object, - regexp = NULL, - class = NULL, - ..., - inherit = TRUE, - info = NULL, - label = NULL) { - +expect_condition <- function( + object, + regexp = NULL, + class = NULL, + ..., + inherit = TRUE, + info = NULL, + label = NULL +) { if (edition_get() >= 3) { - expect_condition_matching("condition", {{ object }}, + expect_condition_matching( + "condition", + {{ object }}, regexp = regexp, class = class, ..., @@ -226,8 +247,12 @@ expect_condition <- function(object, label = label ) } else { - - act <- quasi_capture(enquo(object), label, capture_condition, entrace = TRUE) + act <- quasi_capture( + enquo(object), + label, + capture_condition, + entrace = TRUE + ) msg <- compare_condition_2e( act$cap, act$lab, @@ -243,16 +268,18 @@ expect_condition <- function(object, } } -expect_condition_matching <- function(base_class, - object, - regexp = NULL, - class = NULL, - ..., - inherit = TRUE, - info = NULL, - label = NULL, - trace_env = caller_env(), - error_call = caller_env()) { +expect_condition_matching <- function( + base_class, + object, + regexp = NULL, + class = NULL, + ..., + inherit = TRUE, + info = NULL, + label = NULL, + trace_env = caller_env(), + error_call = caller_env() +) { matcher <- cnd_matcher( base_class, class, @@ -275,7 +302,13 @@ expect_condition_matching <- function(base_class, # Access error fields with `[[` rather than `$` because the # `$.Throwable` from the rJava package throws with unknown fields - expect(is.null(msg), msg, info = info, trace = act$cap[["trace"]], trace_env = trace_env) + expect( + is.null(msg), + msg, + info = info, + trace = act$cap[["trace"]], + trace_env = trace_env + ) # If a condition was expected, return it. Otherwise return the value # of the expression. @@ -284,13 +317,15 @@ expect_condition_matching <- function(base_class, # ------------------------------------------------------------------------- -cnd_matcher <- function(base_class, - class = NULL, - pattern = NULL, - ..., - inherit = TRUE, - ignore_deprecation = FALSE, - error_call = caller_env()) { +cnd_matcher <- function( + base_class, + class = NULL, + pattern = NULL, + ..., + inherit = TRUE, + ignore_deprecation = FALSE, + error_call = caller_env() +) { check_string(class, allow_null = TRUE, call = error_call) check_string(pattern, allow_null = TRUE, allow_na = TRUE, call = error_call) @@ -328,7 +363,6 @@ cnd_matcher <- function(base_class, ) } ) - } else { TRUE } @@ -391,7 +425,12 @@ compare_condition_3e <- function(cond_type, cond_class, cond, lab, expected) { if (is.null(cond_class)) { sprintf("%s did not throw the expected %s.", lab, cond_type) } else { - sprintf("%s did not throw a %s with class <%s>.", lab, cond_type, cond_class) + sprintf( + "%s did not throw a %s with class <%s>.", + lab, + cond_type, + cond_class + ) } } else { NULL @@ -411,14 +450,15 @@ compare_condition_3e <- function(cond_type, cond_class, cond, lab, expected) { } } -compare_condition_2e <- function(cond, - lab, - regexp = NULL, - class = NULL, - ..., - inherit = TRUE, - cond_type = "error") { - +compare_condition_2e <- function( + cond, + lab, + regexp = NULL, + class = NULL, + ..., + inherit = TRUE, + cond_type = "error" +) { # Expecting no condition if (identical(regexp, NA)) { if (!is.null(cond)) { @@ -484,19 +524,23 @@ cnd_matches_2e <- function(cnd, class, regexp, inherit, ...) { } ok_class <- is.null(class) || cnd_inherits(cnd, class) - ok_msg <- is.null(regexp) || cnd_some(cnd, function(x) { - any(grepl(regexp, cnd_message(x), ...)) - }) + ok_msg <- is.null(regexp) || + cnd_some(cnd, function(x) { + any(grepl(regexp, cnd_message(x), ...)) + }) c(class = ok_class, msg = ok_msg) } -compare_messages <- function(messages, - lab, - regexp = NA, ..., - all = FALSE, - cond_type = "messages") { +compare_messages <- function( + messages, + lab, + regexp = NA, + ..., + all = FALSE, + cond_type = "messages" +) { bullets <- paste0("* ", messages, collapse = "\n") # Expecting no messages if (identical(regexp, NA)) { diff --git a/R/expect-constant.R b/R/expect-constant.R index d391ed00c..5fad3e4ee 100644 --- a/R/expect-constant.R +++ b/R/expect-constant.R @@ -76,7 +76,8 @@ expect_waldo_constant <- function(act, constant, info, ...) { length(comp) == 0, sprintf( "%s is not %s\n\n%s", - act$lab, deparse(constant), + act$lab, + deparse(constant), paste0(comp, collapse = "\n\n") ), info = info, diff --git a/R/expect-equality.R b/R/expect-equality.R index 9ac01a36c..94e644e95 100644 --- a/R/expect-equality.R +++ b/R/expect-equality.R @@ -54,11 +54,15 @@ NULL #' @export #' @rdname equality-expectations -expect_equal <- function(object, expected, ..., - tolerance = if (edition_get() >= 3) testthat_tolerance(), - info = NULL, label = NULL, - expected.label = NULL) { - +expect_equal <- function( + object, + expected, + ..., + tolerance = if (edition_get() >= 3) testthat_tolerance(), + info = NULL, + label = NULL, + expected.label = NULL +) { act <- quasi_label(enquo(object), label, arg = "object") exp <- quasi_label(enquo(expected), expected.label, arg = "expected") @@ -82,8 +86,14 @@ expect_equal <- function(object, expected, ..., #' @export #' @rdname equality-expectations -expect_identical <- function(object, expected, info = NULL, label = NULL, - expected.label = NULL, ...) { +expect_identical <- function( + object, + expected, + info = NULL, + label = NULL, + expected.label = NULL, + ... +) { act <- quasi_label(enquo(object), label, arg = "object") exp <- quasi_label(enquo(expected), expected.label, arg = "expected") @@ -112,14 +122,22 @@ expect_identical <- function(object, expected, info = NULL, label = NULL, } expect_waldo_equal <- function(type, act, exp, info, ...) { - comp <- waldo_compare(act$val, exp$val, ..., x_arg = "actual", y_arg = "expected") + comp <- waldo_compare( + act$val, + exp$val, + ..., + x_arg = "actual", + y_arg = "expected" + ) expect( length(comp) == 0, sprintf( "%s (%s) not %s to %s (%s).\n\n%s", - act$lab, "`actual`", + act$lab, + "`actual`", type, - exp$lab, "`expected`", + exp$lab, + "`expected`", paste0(comp, collapse = "\n\n") ), info = info, @@ -152,12 +170,20 @@ expect_waldo_equal <- function(type, act, exp, info, ...) { #' expect_equal(a, b) #' } #' expect_equivalent(a, b) -expect_equivalent <- function(object, expected, ..., info = NULL, label = NULL, - expected.label = NULL) { +expect_equivalent <- function( + object, + expected, + ..., + info = NULL, + label = NULL, + expected.label = NULL +) { act <- quasi_label(enquo(object), label, arg = "object") exp <- quasi_label(enquo(expected), expected.label, arg = "expected") - edition_deprecate(3, "expect_equivalent()", + edition_deprecate( + 3, + "expect_equivalent()", "Use expect_equal(ignore_attr = TRUE)" ) @@ -187,9 +213,13 @@ expect_equivalent <- function(object, expected, ..., info = NULL, label = NULL, #' @family expectations #' @keywords internal #' @export -expect_reference <- function(object, expected, info = NULL, label = NULL, - expected.label = NULL) { - +expect_reference <- function( + object, + expected, + info = NULL, + label = NULL, + expected.label = NULL +) { edition_deprecate(3, "expect_reference()") act <- quasi_label(enquo(object), label, arg = "object") diff --git a/R/expect-inheritance.R b/R/expect-inheritance.R index 199b32d3c..64b2229d7 100644 --- a/R/expect-inheritance.R +++ b/R/expect-inheritance.R @@ -53,7 +53,12 @@ expect_type <- function(object, type) { expect( identical(act_type, type), - sprintf("%s has type %s, not %s.", act$lab, format_class(act_type), format_class(type)) + sprintf( + "%s has type %s, not %s.", + act$lab, + format_class(act_type), + format_class(type) + ) ) invisible(act$val) } @@ -112,7 +117,12 @@ expect_s7_class <- function(object, class) { sprintf( "%s inherits from %s not <%s>.", act$lab, - paste0("<", setdiff(base::class(object), "S7_object"), ">", collapse = "/"), + paste0( + "<", + setdiff(base::class(object), "S7_object"), + ">", + collapse = "/" + ), attr(class, "name", TRUE) ) ) @@ -171,11 +181,12 @@ isS3 <- function(x) is.object(x) && !isS4(x) #' @export expect_is <- function(object, class, info = NULL, label = NULL) { stopifnot(is.character(class)) - edition_deprecate(3, "expect_is()", + edition_deprecate( + 3, + "expect_is()", "Use `expect_type()`, `expect_s3_class()`, or `expect_s4_class()` instead" ) - act <- quasi_label(enquo(object), label, arg = "object") act$class <- format_class(class(act$val)) exp_lab <- format_class(class(class)) diff --git a/R/expect-known.R b/R/expect-known.R index 31a780d4b..f48cbb871 100644 --- a/R/expect-known.R +++ b/R/expect-known.R @@ -48,15 +48,19 @@ #' # This will fail #' expect_known_output(mtcars[1:9, ], tmp, print = TRUE) #' } -expect_known_output <- function(object, file, - update = TRUE, - ..., - info = NULL, - label = NULL, - print = FALSE, - width = 80) { - - edition_deprecate(3, "expect_known_output()", +expect_known_output <- function( + object, + file, + update = TRUE, + ..., + info = NULL, + label = NULL, + print = FALSE, + width = 80 +) { + edition_deprecate( + 3, + "expect_known_output()", "Please use `expect_snapshot_output()` instead" ) @@ -89,15 +93,18 @@ compare_file <- function(path, lines, ..., update = TRUE, info = NULL) { } comp <- waldo_compare( - x = old_lines, x_arg = "old", - y = lines, y_arg = "new", + x = old_lines, + x_arg = "old", + y = lines, + y_arg = "new", ... ) expect( length(comp) == 0, sprintf( "Results have changed from known value recorded in %s.\n\n%s", - encodeString(path, quote = "'"), paste0(comp, collapse = "\n\n") + encodeString(path, quote = "'"), + paste0(comp, collapse = "\n\n") ), info = info, trace_env = caller_env() @@ -116,17 +123,21 @@ compare_file <- function(path, lines, ..., update = TRUE, info = NULL) { #' #' @export #' @keywords internal -expect_output_file <- function(object, file, - update = TRUE, - ..., - info = NULL, - label = NULL, - print = FALSE, - width = 80) { - +expect_output_file <- function( + object, + file, + update = TRUE, + ..., + info = NULL, + label = NULL, + print = FALSE, + width = 80 +) { # Code is a copy of expect_known_output() - edition_deprecate(3, "expect_output_file()", - "Please use `expect_snapshot_output()` instead" + edition_deprecate( + 3, + "expect_output_file()", + "Please use `expect_snapshot_output()` instead" ) act <- list() @@ -140,13 +151,18 @@ expect_output_file <- function(object, file, #' @export #' @rdname expect_known_output -expect_known_value <- function(object, file, - update = TRUE, - ..., - info = NULL, - label = NULL, - version = 2) { - edition_deprecate(3, "expect_known_value()", +expect_known_value <- function( + object, + file, + update = TRUE, + ..., + info = NULL, + label = NULL, + version = 2 +) { + edition_deprecate( + 3, + "expect_known_value()", "Please use `expect_snapshot_value()` instead" ) @@ -167,7 +183,9 @@ expect_known_value <- function(object, file, comp$equal, sprintf( "%s has changed from known value recorded in %s.\n%s", - act$lab, encodeString(file, quote = "'"), comp$message + act$lab, + encodeString(file, quote = "'"), + comp$message ), info = info ) @@ -180,7 +198,9 @@ expect_known_value <- function(object, file, #' @rdname expect_known_output #' @usage NULL expect_equal_to_reference <- function(..., update = FALSE) { - edition_deprecate(3, "expect_equal_to_reference()", + edition_deprecate( + 3, + "expect_equal_to_reference()", "Please use `expect_snapshot_value()` instead" ) expect_known_value(..., update = update) @@ -192,7 +212,9 @@ expect_equal_to_reference <- function(..., update = FALSE) { #' to use in the test output. expect_known_hash <- function(object, hash = NULL) { check_installed("digest") - edition_deprecate(3, "expect_known_hash()", + edition_deprecate( + 3, + "expect_known_hash()", "Please use `expect_snapshot_value()` instead" ) diff --git a/R/expect-named.R b/R/expect-named.R index 79174312c..0c90c56f1 100644 --- a/R/expect-named.R +++ b/R/expect-named.R @@ -24,9 +24,14 @@ #' # Can also check for the absence of names with NULL #' z <- 1:4 #' expect_named(z, NULL) -expect_named <- function(object, expected, ignore.order = FALSE, - ignore.case = FALSE, info = NULL, - label = NULL) { +expect_named <- function( + object, + expected, + ignore.order = FALSE, + ignore.case = FALSE, + info = NULL, + label = NULL +) { act <- quasi_label(enquo(object), label, arg = "object") act$names <- names(act$val) @@ -54,10 +59,16 @@ expect_named <- function(object, expected, ignore.order = FALSE, } normalise_names <- function(x, ignore.order = FALSE, ignore.case = FALSE) { - if (is.null(x)) return() + if (is.null(x)) { + return() + } - if (ignore.order) x <- sort(x) - if (ignore.case) x <- tolower(x) + if (ignore.order) { + x <- sort(x) + } + if (ignore.case) { + x <- tolower(x) + } x } diff --git a/R/expect-no-condition.R b/R/expect-no-condition.R index 02c42796e..ee35e9eed 100644 --- a/R/expect-no-condition.R +++ b/R/expect-no-condition.R @@ -38,10 +38,7 @@ #' #' # warning does match so causes a failure: #' try(expect_no_warning(foo(), message = "problem")) -expect_no_error <- function(object, - ..., - message = NULL, - class = NULL) { +expect_no_error <- function(object, ..., message = NULL, class = NULL) { check_dots_empty() expect_no_("error", {{ object }}, regexp = message, class = class) } @@ -49,49 +46,40 @@ expect_no_error <- function(object, #' @export #' @rdname expect_no_error -expect_no_warning <- function(object, - ..., - message = NULL, - class = NULL - ) { +expect_no_warning <- function(object, ..., message = NULL, class = NULL) { check_dots_empty() expect_no_("warning", {{ object }}, regexp = message, class = class) } #' @export #' @rdname expect_no_error -expect_no_message <- function(object, - ..., - message = NULL, - class = NULL - ) { +expect_no_message <- function(object, ..., message = NULL, class = NULL) { check_dots_empty() expect_no_("message", {{ object }}, regexp = message, class = class) } #' @export #' @rdname expect_no_error -expect_no_condition <- function(object, - ..., - message = NULL, - class = NULL - ) { +expect_no_condition <- function(object, ..., message = NULL, class = NULL) { check_dots_empty() expect_no_("condition", {{ object }}, regexp = message, class = class) } -expect_no_ <- function(base_class, - object, - regexp = NULL, - class = NULL, - trace_env = caller_env()) { - +expect_no_ <- function( + base_class, + object, + regexp = NULL, + class = NULL, + trace_env = caller_env() +) { matcher <- cnd_matcher( base_class, class, pattern = regexp, - ignore_deprecation = base_class == "warning" && is.null(regexp) && is.null(class) + ignore_deprecation = base_class == "warning" && + is.null(regexp) && + is.null(class) ) capture <- function(code) { @@ -108,13 +96,19 @@ expect_no_ <- function(base_class, } expected <- paste0( - "Expected ", quo_label(enquo(object)), " to run without any ", base_class, "s", + "Expected ", + quo_label(enquo(object)), + " to run without any ", + base_class, + "s", if (!is.null(class)) paste0(" of class '", class, "'"), if (!is.null(regexp)) paste0(" matching pattern '", regexp, "'"), "." ) actual <- paste0( - "Actually got a <", class(cnd)[[1]], "> with text:\n", + "Actually got a <", + class(cnd)[[1]], + "> with text:\n", indent_lines(rlang::cnd_message(cnd)) ) message <- format_error_bullets(c(expected, i = actual)) diff --git a/R/expect-output.R b/R/expect-output.R index 951d388c1..fd4cf1e74 100644 --- a/R/expect-output.R +++ b/R/expect-output.R @@ -22,13 +22,14 @@ #' # You can use the arguments of grepl to control the matching #' expect_output(str(mtcars), "11 VARIABLES", ignore.case = TRUE) #' expect_output(str(mtcars), "$ mpg", fixed = TRUE) -expect_output <- function(object, - regexp = NULL, - ..., - info = NULL, - label = NULL, - width = 80 - ) { +expect_output <- function( + object, + regexp = NULL, + ..., + info = NULL, + label = NULL, + width = 80 +) { act <- quasi_capture(enquo(object), label, capture_output, width = width) if (identical(regexp, NA)) { @@ -49,4 +50,3 @@ expect_output <- function(object, invisible(act$val) } - diff --git a/R/expect-self-test.R b/R/expect-self-test.R index 74e220e9d..09bfb2b87 100644 --- a/R/expect-self-test.R +++ b/R/expect-self-test.R @@ -115,7 +115,10 @@ show_failure <- function(expr) { invisible() } -expect_snapshot_reporter <- function(reporter, paths = test_path("reporters/tests.R")) { +expect_snapshot_reporter <- function( + reporter, + paths = test_path("reporters/tests.R") +) { local_options(rlang_trace_format_srcrefs = FALSE) local_rng_version("3.3") set.seed(1014) @@ -123,7 +126,9 @@ expect_snapshot_reporter <- function(reporter, paths = test_path("reporters/test expect_snapshot_output( with_reporter(reporter, { - for (path in paths) test_one_file(path) + for (path in paths) { + test_one_file(path) + } }) ) } @@ -136,8 +141,12 @@ local_rng_version <- function(version, .local_envir = parent.frame()) { # Use specifically for testthat tests in order to override the # defaults found when starting the reporter -local_output_override <- function(width = 80, crayon = TRUE, unicode = TRUE, - .env = parent.frame()) { +local_output_override <- function( + width = 80, + crayon = TRUE, + unicode = TRUE, + .env = parent.frame() +) { reporter <- get_reporter() if (is.null(reporter)) { return() @@ -151,9 +160,12 @@ local_output_override <- function(width = 80, crayon = TRUE, unicode = TRUE, reporter$crayon <- crayon reporter$unicode <- unicode - withr::defer({ - reporter$width <- old_width - reporter$crayon <- old_crayon - reporter$unicode <- old_unicode - }, .env) + withr::defer( + { + reporter$width <- old_width + reporter$crayon <- old_crayon + reporter$unicode <- old_unicode + }, + .env + ) } diff --git a/R/expect-setequal.R b/R/expect-setequal.R index 54d95143a..3d46d11f8 100644 --- a/R/expect-setequal.R +++ b/R/expect-setequal.R @@ -40,11 +40,16 @@ expect_setequal <- function(object, expected) { if (length(exp_miss) || length(act_miss)) { fail(paste0( - act$lab, " (`actual`) and ", exp$lab, " (`expected`) don't have the same values.\n", - if (length(act_miss)) - paste0("* Only in `actual`: ", values(act_miss), "\n"), - if (length(exp_miss)) + act$lab, + " (`actual`) and ", + exp$lab, + " (`expected`) don't have the same values.\n", + if (length(act_miss)) { + paste0("* Only in `actual`: ", values(act_miss), "\n") + }, + if (length(exp_miss)) { paste0("* Only in `expected`: ", values(exp_miss), "\n") + } )) } else { succeed() @@ -136,9 +141,12 @@ expect_contains <- function(object, expected) { if (any(exp_miss)) { fail(paste0( - act$lab, " (`actual`) doesn't fully contain all the values in ", exp$lab, " (`expected`).\n", - paste0("* Missing from `actual`: ", values(exp$val[exp_miss]), "\n"), - paste0("* Present in `actual`: ", values(act$val), "\n") + act$lab, + " (`actual`) doesn't fully contain all the values in ", + exp$lab, + " (`expected`).\n", + paste0("* Missing from `actual`: ", values(exp$val[exp_miss]), "\n"), + paste0("* Present in `actual`: ", values(act$val), "\n") )) } else { succeed() @@ -161,9 +169,12 @@ expect_in <- function(object, expected) { if (any(act_miss)) { fail(paste0( - act$lab, " (`actual`) isn't fully contained within ", exp$lab, " (`expected`).\n", - paste0("* Missing from `expected`: ", values(act$val[act_miss]), "\n"), - paste0("* Present in `expected`: ", values(exp$val), "\n") + act$lab, + " (`actual`) isn't fully contained within ", + exp$lab, + " (`expected`).\n", + paste0("* Missing from `expected`: ", values(act$val[act_miss]), "\n"), + paste0("* Present in `expected`: ", values(exp$val), "\n") )) } else { succeed() diff --git a/R/expect-shape.R b/R/expect-shape.R index 4f35d1156..d4d18853d 100644 --- a/R/expect-shape.R +++ b/R/expect-shape.R @@ -49,26 +49,37 @@ expect_shape = function(object, ..., length, nrow, ncol, dim) { if (length(dim_object) == 1L) { fail(sprintf("%s has only one dimension.", act$lab)) } - + act$ncol <- dim_object[2L] expect( identical(as.integer(act$ncol), as.integer(ncol)), sprintf("%s has %i columns, not %i.", act$lab, act$ncol, ncol) ) - } else { # !missing(dim) + } else { + # !missing(dim) if (!is.numeric(dim) && !is.integer(dim)) { stop_input_type(dim, "a numeric vector") } act$dim <- dim_object if (length(act$dim) != length(dim)) { - fail(sprintf("%s has %i dimensions, not %i.", act$lab, length(act$dim), length(dim))) + fail(sprintf( + "%s has %i dimensions, not %i.", + act$lab, + length(act$dim), + length(dim) + )) } expect( identical(as.integer(act$dim), as.integer(dim)), - sprintf("%s has dim (%s), not (%s).", act$lab, toString(act$dim), toString(dim)) + sprintf( + "%s has dim (%s), not (%s).", + act$lab, + toString(act$dim), + toString(dim) + ) ) } diff --git a/R/expect-that.R b/R/expect-that.R index 6e6a84e7d..eefe836e9 100644 --- a/R/expect-that.R +++ b/R/expect-that.R @@ -50,7 +50,11 @@ expect_that <- function(object, condition, info = NULL, label = NULL) { #' test_that("this test fails", fail()) #' test_that("this test succeeds", succeed()) #' } -fail <- function(message = "Failure has been forced", info = NULL, trace_env = caller_env()) { +fail <- function( + message = "Failure has been forced", + info = NULL, + trace_env = caller_env() +) { expect(FALSE, message, info = info, trace_env = trace_env) } diff --git a/R/expectation.R b/R/expectation.R index 57febc222..6c48e5dbe 100644 --- a/R/expectation.R +++ b/R/expectation.R @@ -35,11 +35,14 @@ #' #' @seealso [exp_signal()] #' @export -expect <- function(ok, failure_message, - info = NULL, - srcref = NULL, - trace = NULL, - trace_env = caller_env()) { +expect <- function( + ok, + failure_message, + info = NULL, + srcref = NULL, + trace = NULL, + trace_env = caller_env() +) { type <- if (ok) "success" else "failure" # Preserve existing API which appear to be used in package test code @@ -97,12 +100,14 @@ expectation <- function(type, message, srcref = NULL, trace = NULL) { #' @param ... Additional attributes for the expectation object. #' @param .subclass An optional subclass for the expectation object. #' @export -new_expectation <- function(type, - message, - ..., - srcref = NULL, - trace = NULL, - .subclass = NULL) { +new_expectation <- function( + type, + message, + ..., + srcref = NULL, + trace = NULL, + .subclass = NULL +) { type <- match.arg(type, c("success", "failure", "error", "skip", "warning")) structure( @@ -147,7 +152,11 @@ is.expectation <- function(x) inherits(x, "expectation") #' @export print.expectation <- function(x, ...) { - cat(cli::style_bold("<", paste0(class(x), collapse = "/"), ">"), "\n", sep = "") + cat( + cli::style_bold("<", paste0(class(x), collapse = "/"), ">"), + "\n", + sep = "" + ) cat(format(x), "\n", sep = "") invisible(x) } @@ -184,7 +193,6 @@ as.expectation.expectation <- function(x, srcref = NULL) { #' @export as.expectation.error <- function(x, srcref = NULL) { - if (is.null(x$call)) { header <- paste0("Error: ") } else { @@ -192,8 +200,11 @@ as.expectation.error <- function(x, srcref = NULL) { } msg <- paste0( - if (!is_simple_error(x)) paste0("<", paste(class(x), collapse = "/"), ">\n"), - header, cnd_message(x) + if (!is_simple_error(x)) { + paste0("<", paste(class(x), collapse = "/"), ">\n") + }, + header, + cnd_message(x) ) expectation("error", msg, srcref, trace = x[["trace"]]) @@ -217,8 +228,10 @@ as.expectation.skip <- function(x, ..., srcref = NULL) { #' @export as.expectation.default <- function(x, srcref = NULL) { stop( - "Don't know how to convert '", paste(class(x), collapse = "', '"), - "' to expectation.", call. = FALSE + "Don't know how to convert '", + paste(class(x), collapse = "', '"), + "' to expectation.", + call. = FALSE ) } @@ -231,17 +244,22 @@ expectation_type <- function(exp) { expectation_success <- function(exp) expectation_type(exp) == "success" expectation_failure <- function(exp) expectation_type(exp) == "failure" -expectation_error <- function(exp) expectation_type(exp) == "error" -expectation_skip <- function(exp) expectation_type(exp) == "skip" +expectation_error <- function(exp) expectation_type(exp) == "error" +expectation_skip <- function(exp) expectation_type(exp) == "skip" expectation_warning <- function(exp) expectation_type(exp) == "warning" -expectation_broken <- function(exp) expectation_failure(exp) || expectation_error(exp) -expectation_ok <- function(exp) expectation_type(exp) %in% c("success", "warning") +expectation_broken <- function(exp) { + expectation_failure(exp) || expectation_error(exp) +} +expectation_ok <- function(exp) { + expectation_type(exp) %in% c("success", "warning") +} single_letter_summary <- function(x) { - switch(expectation_type(x), - skip = colourise("S", "skip"), + switch( + expectation_type(x), + skip = colourise("S", "skip"), success = colourise(".", "success"), - error = colourise("E", "error"), + error = colourise("E", "error"), failure = colourise("F", "failure"), warning = colourise("W", "warning"), "?" @@ -255,5 +273,7 @@ expectation_location <- function(x, prefix = "", suffix = "") { } filename <- attr(srcref, "srcfile")$filename - cli::format_inline("{prefix}{.file {filename}:{srcref[1]}:{srcref[2]}}{suffix}") + cli::format_inline( + "{prefix}{.file {filename}:{srcref[1]}:{srcref[2]}}{suffix}" + ) } diff --git a/R/expectations-matches.R b/R/expectations-matches.R index 0f4e679be..f9ff6de17 100644 --- a/R/expectations-matches.R +++ b/R/expectations-matches.R @@ -27,8 +27,16 @@ #' # Zero-length inputs always fail #' expect_match(character(), ".") #' } -expect_match <- function(object, regexp, perl = FALSE, fixed = FALSE, ..., all = TRUE, - info = NULL, label = NULL) { +expect_match <- function( + object, + regexp, + perl = FALSE, + fixed = FALSE, + ..., + all = TRUE, + info = NULL, + label = NULL +) { # Capture here to avoid environment-related messiness act <- quasi_label(enquo(object), label, arg = "object") stopifnot(is.character(regexp), length(regexp) == 1) @@ -54,8 +62,16 @@ expect_match <- function(object, regexp, perl = FALSE, fixed = FALSE, ..., all = #' @describeIn expect_match Check that a string doesn't match a regular #' expression. #' @export -expect_no_match <- function(object, regexp, perl = FALSE, fixed = FALSE, ..., all = TRUE, - info = NULL, label = NULL) { +expect_no_match <- function( + object, + regexp, + perl = FALSE, + fixed = FALSE, + ..., + all = TRUE, + info = NULL, + label = NULL +) { # Capture here to avoid environment-related messiness act <- quasi_label(enquo(object), label, arg = "object") stopifnot(is.character(regexp), length(regexp) == 1) @@ -78,9 +94,17 @@ expect_no_match <- function(object, regexp, perl = FALSE, fixed = FALSE, ..., al ) } -expect_match_ <- function(act, regexp, perl = FALSE, fixed = FALSE, ..., all = TRUE, - info = NULL, label = NULL, negate = FALSE) { - +expect_match_ <- function( + act, + regexp, + perl = FALSE, + fixed = FALSE, + ..., + all = TRUE, + info = NULL, + label = NULL, + negate = FALSE +) { matches <- grepl(regexp, act$val, perl = perl, fixed = fixed, ...) condition <- if (negate) !matches else matches escape <- if (fixed) identity else escape_regex diff --git a/R/local.R b/R/local.R index b8693bab0..dc1af8136 100644 --- a/R/local.R +++ b/R/local.R @@ -65,7 +65,11 @@ #' cat("\n") #' }) local_test_context <- function(.env = parent.frame()) { - withr::local_envvar("_R_CHECK_BROWSER_NONINTERACTIVE_" = "true", TESTTHAT = "true", .local_envir = .env) + withr::local_envvar( + "_R_CHECK_BROWSER_NONINTERACTIVE_" = "true", + TESTTHAT = "true", + .local_envir = .env + ) if (edition_get() >= 3) { local_reproducible_output(.env = .env) } @@ -93,14 +97,15 @@ local_test_context <- function(.env = parent.frame()) { #' local_reproducible_output(unicode = TRUE) #' expect_equal(cli::symbol$ellipsis, "\u2026") #' }) -local_reproducible_output <- function(width = 80, - crayon = FALSE, - unicode = FALSE, - rstudio = FALSE, - hyperlinks = FALSE, - lang = "C", - .env = parent.frame()) { - +local_reproducible_output <- function( + width = 80, + crayon = FALSE, + unicode = FALSE, + rstudio = FALSE, + hyperlinks = FALSE, + lang = "C", + .env = parent.frame() +) { if (unicode) { # If you force unicode display, you _must_ skip the test on non-utf8 # locales; otherwise it's guaranteed to fail @@ -150,7 +155,7 @@ waldo_compare <- function(x, y, ..., x_arg = "x", y_arg = "y") { # up through calling handlers, which are run before on.exit() local_reporter_output() - waldo::compare(x, y,..., x_arg = x_arg, y_arg = y_arg) + waldo::compare(x, y, ..., x_arg = x_arg, y_arg = y_arg) } local_width <- function(width = 80, .env = parent.frame()) { diff --git a/R/mock.R b/R/mock.R index c81ba7a2d..737acc558 100644 --- a/R/mock.R +++ b/R/mock.R @@ -86,7 +86,9 @@ extract_mocks <- function(funs, .env) { if (is_base_pkg(pkg_name)) { stop( - "Can't mock functions in base packages (", pkg_name, ")", + "Can't mock functions in base packages (", + pkg_name, + ")", call. = FALSE ) } @@ -100,8 +102,12 @@ extract_mocks <- function(funs, .env) { env <- asNamespace(pkg_name) if (!exists(name, envir = env, mode = "function")) { - stop("Function ", name, " not found in environment ", - environmentName(env), ".", + stop( + "Function ", + name, + " not found in environment ", + environmentName(env), + ".", call. = FALSE ) } @@ -116,7 +122,8 @@ mock <- function(name, env, new) { list( env = env, name = as.name(name), - orig_value = .Call(duplicate_, target_value), target_value = target_value, + orig_value = .Call(duplicate_, target_value), + target_value = target_value, new_value = new ), class = "mock" @@ -124,11 +131,23 @@ mock <- function(name, env, new) { } set_mock <- function(mock) { - .Call(reassign_function, mock$name, mock$env, mock$target_value, mock$new_value) + .Call( + reassign_function, + mock$name, + mock$env, + mock$target_value, + mock$new_value + ) } reset_mock <- function(mock) { - .Call(reassign_function, mock$name, mock$env, mock$target_value, mock$orig_value) + .Call( + reassign_function, + mock$name, + mock$env, + mock$target_value, + mock$orig_value + ) } is_base_pkg <- function(x) { diff --git a/R/old-school.R b/R/old-school.R index 30e664699..c8cd38ad5 100644 --- a/R/old-school.R +++ b/R/old-school.R @@ -58,7 +58,12 @@ is_false <- function() { #' @rdname oldskool has_names <- function(expected, ignore.order = FALSE, ignore.case = FALSE) { function(x) { - expect_named(x, expected = expected, ignore.order = ignore.order, ignore.case = ignore.case) + expect_named( + x, + expected = expected, + ignore.order = ignore.order, + ignore.case = ignore.case + ) } } diff --git a/R/parallel-config.R b/R/parallel-config.R index 8f81cb0d7..1082e4c54 100644 --- a/R/parallel-config.R +++ b/R/parallel-config.R @@ -2,13 +2,19 @@ find_parallel <- function(path, load_package = "source", package = NULL) { # If env var is set, then use that parenv <- Sys.getenv("TESTTHAT_PARALLEL", NA_character_) if (!is.na(parenv)) { - if (toupper(parenv) == "TRUE") return(TRUE) - if (toupper(parenv) == "FALSE") return(FALSE) + if (toupper(parenv) == "TRUE") { + return(TRUE) + } + if (toupper(parenv) == "FALSE") { + return(FALSE) + } abort("`TESTTHAT_PARALLEL` must be `TRUE` or `FALSE`") } # Make sure we get the local package package if not "installed" - if (load_package != "installed") package <- NULL + if (load_package != "installed") { + package <- NULL + } desc <- find_description(path, package) if (is.null(desc)) { return(FALSE) diff --git a/R/parallel-taskq.R b/R/parallel-taskq.R index b5f6d36f7..61d488ae4 100644 --- a/R/parallel-taskq.R +++ b/R/parallel-taskq.R @@ -1,4 +1,3 @@ - # See https://www.tidyverse.org/blog/2019/09/callr-task-q/ # for a detailed explanation on how the task queue works. # @@ -10,12 +9,12 @@ # * We do not need a pop() method, because poll() will just return # every message. -PROCESS_DONE <- 200L +PROCESS_DONE <- 200L PROCESS_STARTED <- 201L -PROCESS_MSG <- 301L -PROCESS_EXITED <- 500L +PROCESS_MSG <- 301L +PROCESS_EXITED <- 500L PROCESS_CRASHED <- 501L -PROCESS_CLOSED <- 502L +PROCESS_CLOSED <- 502L PROCESS_FAILURES <- c(PROCESS_EXITED, PROCESS_CRASHED, PROCESS_CLOSED) task_q <- R6::R6Class( @@ -26,20 +25,32 @@ task_q <- R6::R6Class( invisible(self) }, list_tasks = function() private$tasks, - get_num_waiting = function() - sum(!private$tasks$idle & private$tasks$state == "waiting"), - get_num_running = function() - sum(!private$tasks$idle & private$tasks$state == "running"), + get_num_waiting = function() { + sum(!private$tasks$idle & private$tasks$state == "waiting") + }, + get_num_running = function() { + sum(!private$tasks$idle & private$tasks$state == "running") + }, get_num_done = function() sum(private$tasks$state == "done"), is_idle = function() sum(!private$tasks$idle) == 0, push = function(fun, args = list(), id = NULL) { - if (is.null(id)) id <- private$get_next_id() - if (id %in% private$tasks$id) stop("Duplicate task id") + if (is.null(id)) { + id <- private$get_next_id() + } + if (id %in% private$tasks$id) { + stop("Duplicate task id") + } before <- which(private$tasks$idle)[1] - private$tasks <- df_add_row(private$tasks, .before = before, - id = id, idle = FALSE, state = "waiting", fun = I(list(fun)), - args = I(list(args)), worker = I(list(NULL)) + private$tasks <- df_add_row( + private$tasks, + .before = before, + id = id, + idle = FALSE, + state = "waiting", + fun = I(list(fun)), + args = I(list(args)), + worker = I(list(NULL)) ) private$schedule() invisible(id) @@ -47,13 +58,15 @@ task_q <- R6::R6Class( poll = function(timeout = 0) { limit <- Sys.time() + timeout - as_ms <- function(x) - if (x==Inf) -1 else as.integer(as.double(x, "secs") * 1000) - repeat{ + as_ms <- function(x) { + if (x == Inf) -1 else as.integer(as.double(x, "secs") * 1000) + } + repeat { topoll <- which(private$tasks$state == "running") conns <- lapply( private$tasks$worker[topoll], - function(x) x$get_poll_connection()) + function(x) x$get_poll_connection() + ) pr <- processx::poll(conns, as_ms(timeout)) ready <- topoll[pr == "ready"] results <- lapply(ready, function(i) { @@ -71,8 +84,12 @@ task_q <- R6::R6Class( } else { file <- private$tasks$args[[i]][[1]] errmsg <- paste0( - "unknown message from testthat subprocess: ", msg$code, ", ", - "in file `", file, "`" + "unknown message from testthat subprocess: ", + msg$code, + ", ", + "in file `", + file, + "`" ) abort( errmsg, @@ -82,11 +99,13 @@ task_q <- R6::R6Class( } msg }) - results <- results[! vapply(results, is.null, logical(1))] + results <- results[!vapply(results, is.null, logical(1))] private$schedule() - if (is.finite(timeout)) timeout <- limit - Sys.time() - if (length(results) || timeout < 0) break; + if (is.finite(timeout)) { + timeout <- limit - Sys.time() + } + if (length(results) || timeout < 0) break } results } @@ -110,7 +129,8 @@ task_q <- R6::R6Class( state = "running", fun = nl, args = nl, - worker = nl) + worker = nl + ) rsopts <- callr::r_session_options(...) for (i in seq_len(concurrency)) { rs <- callr::r_session$new(rsopts, wait = FALSE) @@ -120,23 +140,29 @@ task_q <- R6::R6Class( schedule = function() { ready <- which(private$tasks$state == "ready") - if (!length(ready)) return() + if (!length(ready)) { + return() + } rss <- private$tasks$worker[ready] private$tasks$worker[ready] <- replicate(length(ready), NULL) private$tasks$state[ready] <- ifelse(private$tasks$idle[ready], "waiting", "done") done <- which(private$tasks$state == "done") - if (any(done)) private$tasks <- private$tasks[-done, ] + if (any(done)) { + private$tasks <- private$tasks[-done, ] + } waiting <- which(private$tasks$state == "waiting")[1:length(ready)] private$tasks$worker[waiting] <- rss private$tasks$state[waiting] <- ifelse(private$tasks$idle[waiting], "ready", "running") lapply(waiting, function(i) { - if (! private$tasks$idle[i]) { - private$tasks$worker[[i]]$call(private$tasks$fun[[i]], - private$tasks$args[[i]]) + if (!private$tasks$idle[i]) { + private$tasks$worker[[i]]$call( + private$tasks$fun[[i]], + private$tasks$args[[i]] + ) } }) }, @@ -177,7 +203,7 @@ df_add_row <- function(df, ..., .before = NULL) { } else if (before <= 1L) { rbind(row, df) } else { - rbind(df[1:(before-1), ], row, df[before:nrow(df), ]) + rbind(df[1:(before - 1), ], row, df[before:nrow(df), ]) } } diff --git a/R/parallel.R b/R/parallel.R index 6f039d64d..57221100f 100644 --- a/R/parallel.R +++ b/R/parallel.R @@ -1,4 +1,3 @@ - # +-----------------------------+ +-------------------------------+ # | Main R process | | Subprocess 1 | # | +------------------------+ | | +---------------------------+ | @@ -33,23 +32,24 @@ # runs an event loop. test_files_parallel <- function( - test_dir, - test_package, - test_paths, - load_helpers = TRUE, - reporter = default_parallel_reporter(), - env = NULL, - stop_on_failure = FALSE, - stop_on_warning = FALSE, - wrap = TRUE, # unused, to match test_files signature - load_package = c("none", "installed", "source") - ) { - + test_dir, + test_package, + test_paths, + load_helpers = TRUE, + reporter = default_parallel_reporter(), + env = NULL, + stop_on_failure = FALSE, + stop_on_warning = FALSE, + wrap = TRUE, # unused, to match test_files signature + load_package = c("none", "installed", "source") +) { # TODO: support timeouts. 20-30s for each file by default? num_workers <- min(default_num_cpus(), length(test_paths)) inform(paste0( - "Starting ", num_workers, " test process", + "Starting ", + num_workers, + " test process", if (num_workers != 1) "es" )) @@ -78,7 +78,8 @@ test_files_parallel <- function( } }) - test_files_check(reporters$list$get_results(), + test_files_check( + reporters$list$get_results(), stop_on_failure = stop_on_failure, stop_on_warning = stop_on_warning ) @@ -108,7 +109,9 @@ default_num_cpus <- function() { ncpus <- getOption("Ncpus", NULL) if (!is.null(ncpus)) { ncpus <- suppressWarnings(as.integer(ncpus)) - if (is.na(ncpus)) abort("`getOption(Ncpus)` must be an integer") + if (is.na(ncpus)) { + abort("`getOption(Ncpus)` must be an integer") + } return(ncpus) } @@ -116,7 +119,9 @@ default_num_cpus <- function() { ncpus <- Sys.getenv("TESTTHAT_CPUS", "") if (ncpus != "") { ncpus <- suppressWarnings(as.integer(ncpus)) - if (is.na(ncpus)) abort("TESTTHAT_CPUS must be an integer") + if (is.na(ncpus)) { + abort("TESTTHAT_CPUS must be an integer") + } return(ncpus) } @@ -207,16 +212,19 @@ replay_events <- function(reporter, events) { } } -queue_setup <- function(test_paths, - test_package, - test_dir, - num_workers, - load_helpers, - load_package) { - +queue_setup <- function( + test_paths, + test_package, + test_dir, + num_workers, + load_helpers, + load_package +) { # TODO: observe `load_package`, but the "none" default is not # OK for the subprocess, because it'll not have the tested package - if (load_package == "none") load_package <- "source" + if (load_package == "none") { + load_package <- "source" + } # TODO: similarly, load_helpers = FALSE, coming from devtools, # is not appropriate in the subprocess @@ -228,7 +236,8 @@ queue_setup <- function(test_paths, # First we load the package "manually", in case it is testthat itself load_hook <- expr({ - switch(!!load_package, + switch( + !!load_package, installed = library(!!test_package, character.only = TRUE), source = pkgload::load_all(!!test_dir, helpers = FALSE, quiet = TRUE) ) @@ -256,7 +265,12 @@ queue_setup <- function(test_paths, queue } -queue_process_setup <- function(test_package, test_dir, load_helpers, load_package) { +queue_process_setup <- function( + test_package, + test_dir, + load_helpers, + load_package +) { env <- asNamespace("testthat")$test_files_setup_env( test_package, test_dir, @@ -313,15 +327,22 @@ queue_teardown <- function(queue) { if (!is.null(tasks$worker[[i]])) { # The worker might have crashed or exited, so this might fail. # If it does then we'll just ignore that worker - tryCatch({ - tasks$worker[[i]]$call(clean_fn) - topoll <- c(topoll, tasks$worker[[i]]$get_poll_connection()) - }, error = function(e) tasks$worker[i] <- list(NULL)) + tryCatch( + { + tasks$worker[[i]]$call(clean_fn) + topoll <- c(topoll, tasks$worker[[i]]$get_poll_connection()) + }, + error = function(e) tasks$worker[i] <- list(NULL) + ) } } # Give covr time to write out the coverage files - if (in_covr()) grace <- 30L else grace <- 3L + if (in_covr()) { + grace <- 30L + } else { + grace <- 3L + } limit <- Sys.time() + grace while (length(topoll) > 0 && (timeout <- limit - Sys.time()) > 0) { timeout <- as.double(timeout, units = "secs") * 1000 @@ -351,7 +372,8 @@ queue_teardown <- function(queue) { # collect several of them and only emit a condition a couple of times # a second. End-of-test and end-of-file events would be transmitted # immediately. -SubprocessReporter <- R6::R6Class("SubprocessReporter", +SubprocessReporter <- R6::R6Class( + "SubprocessReporter", inherit = Reporter, public = list( start_file = function(filename) { diff --git a/R/quasi-label.R b/R/quasi-label.R index e3f34deef..bd41bb122 100644 --- a/R/quasi-label.R +++ b/R/quasi-label.R @@ -51,7 +51,10 @@ quasi_label <- function(quo, label = NULL, arg = "quo") { quasi_capture <- function(.quo, .label, .capture, ...) { act <- list() act$lab <- .label %||% quo_label(.quo) - act$cap <- .capture(act$val <- eval_bare(quo_get_expr(.quo), quo_get_env(.quo)), ...) + act$cap <- .capture( + act$val <- eval_bare(quo_get_expr(.quo), quo_get_env(.quo)), + ... + ) act } @@ -103,8 +106,30 @@ is_call_infix <- function(x) { name <- as_string(fn) base <- c( - ":", "::", ":::", "$", "@", "^", "*", "/", "+", "-", ">", ">=", - "<", "<=", "==", "!=", "!", "&", "&&", "|", "||", "~", "<-", "<<-" + ":", + "::", + ":::", + "$", + "@", + "^", + "*", + "/", + "+", + "-", + ">", + ">=", + "<", + "<=", + "==", + "!=", + "!", + "&", + "&&", + "|", + "||", + "~", + "<-", + "<<-" ) name %in% base || grepl("^%.*%$", name) } diff --git a/R/reporter-check.R b/R/reporter-check.R index 15c0a5320..da7fdfdb2 100644 --- a/R/reporter-check.R +++ b/R/reporter-check.R @@ -5,7 +5,8 @@ #' #' @export #' @family reporters -CheckReporter <- R6::R6Class("CheckReporter", +CheckReporter <- R6::R6Class( + "CheckReporter", inherit = Reporter, public = list( problems = NULL, @@ -86,10 +87,21 @@ summary_line <- function(n_fail, n_warn, n_skip, n_pass) { # Ordered from most important to least important paste0( "[ ", - colourise_if("FAIL", "failure", n_fail > 0), " ", n_fail, " | ", - colourise_if("WARN", "warn", n_warn > 0), " ", n_warn, " | ", - colourise_if("SKIP", "skip", n_skip > 0), " ", n_skip, " | ", - colourise_if("PASS", "success", n_fail == 0), " ", n_pass, + colourise_if("FAIL", "failure", n_fail > 0), + " ", + n_fail, + " | ", + colourise_if("WARN", "warn", n_warn > 0), + " ", + n_warn, + " | ", + colourise_if("SKIP", "skip", n_skip > 0), + " ", + n_skip, + " | ", + colourise_if("PASS", "success", n_fail == 0), + " ", + n_pass, " ]" ) } diff --git a/R/reporter-debug.R b/R/reporter-debug.R index a513a12c4..fd3575a62 100644 --- a/R/reporter-debug.R +++ b/R/reporter-debug.R @@ -5,7 +5,8 @@ #' #' @export #' @family reporters -DebugReporter <- R6::R6Class("DebugReporter", +DebugReporter <- R6::R6Class( + "DebugReporter", inherit = Reporter, public = list( add_result = function(context, test, result) { @@ -68,8 +69,7 @@ recover2 <- function(start_frame = 1L, end_frame = sys.nframe()) { if (which) { frame <- sys.frame(start_frame - 2 + which) browse_frame(frame, skip = 7 - which) - } - else { + } else { break } } diff --git a/R/reporter-fail.R b/R/reporter-fail.R index f224942b9..184f0c165 100644 --- a/R/reporter-fail.R +++ b/R/reporter-fail.R @@ -6,7 +6,8 @@ #' #' @export #' @family reporters -FailReporter <- R6::R6Class("FailReporter", +FailReporter <- R6::R6Class( + "FailReporter", inherit = Reporter, public = list( failed = FALSE, diff --git a/R/reporter-junit.R b/R/reporter-junit.R index f9cdb75b8..3b865f392 100644 --- a/R/reporter-junit.R +++ b/R/reporter-junit.R @@ -26,18 +26,19 @@ classnameOK <- function(text) { #' #' @export #' @family reporters -JunitReporter <- R6::R6Class("JunitReporter", +JunitReporter <- R6::R6Class( + "JunitReporter", inherit = Reporter, public = list( - results = NULL, - timer = NULL, - doc = NULL, - errors = NULL, + results = NULL, + timer = NULL, + doc = NULL, + errors = NULL, failures = NULL, - skipped = NULL, - tests = NULL, - root = NULL, - suite = NULL, + skipped = NULL, + tests = NULL, + root = NULL, + suite = NULL, suite_time = NULL, file_name = NULL, @@ -78,9 +79,9 @@ JunitReporter <- R6::R6Class("JunitReporter", self$suite <- xml2::xml_add_child( self$root, "testsuite", - name = context, + name = context, timestamp = private$timestamp(), - hostname = private$hostname() + hostname = private$hostname() ) }, @@ -92,7 +93,10 @@ JunitReporter <- R6::R6Class("JunitReporter", xml2::xml_attr(self$suite, "failures") <- as.character(self$failures) xml2::xml_attr(self$suite, "errors") <- as.character(self$errors) #jenkins junit plugin requires time has at most 3 digits - xml2::xml_attr(self$suite, "time") <- as.character(round(self$suite_time, 3)) + xml2::xml_attr(self$suite, "time") <- as.character(round( + self$suite_time, + 3 + )) self$reset_suite() }, @@ -107,7 +111,8 @@ JunitReporter <- R6::R6Class("JunitReporter", # XML node for test case name <- test %||% "(unnamed)" testcase <- xml2::xml_add_child( - self$suite, "testcase", + self$suite, + "testcase", time = toString(time), classname = classnameOK(context), name = classnameOK(name) @@ -121,12 +126,22 @@ JunitReporter <- R6::R6Class("JunitReporter", # add an extra XML child node if not a success if (expectation_error(result)) { # "type" in Java is the exception class - error <- xml2::xml_add_child(testcase, "error", type = "error", message = first_line(result)) + error <- xml2::xml_add_child( + testcase, + "error", + type = "error", + message = first_line(result) + ) xml2::xml_text(error) <- cli::ansi_strip(format(result)) self$errors <- self$errors + 1 } else if (expectation_failure(result)) { # "type" in Java is the type of assertion that failed - failure <- xml2::xml_add_child(testcase, "failure", type = "failure", message = first_line(result)) + failure <- xml2::xml_add_child( + testcase, + "failure", + type = "failure", + message = first_line(result) + ) xml2::xml_text(failure) <- cli::ansi_strip(format(result)) self$failures <- self$failures + 1 } else if (expectation_skip(result)) { @@ -169,9 +184,10 @@ JunitReporter <- R6::R6Class("JunitReporter", # - timestamp - originally wrapper for toString(Sys.time()) # - hostname - originally wrapper for Sys.info()[["nodename"]] # -JunitReporterMock <- R6::R6Class("JunitReporterMock", +JunitReporterMock <- R6::R6Class( + "JunitReporterMock", inherit = JunitReporter, - public = list(), + public = list(), private = list( proctime = function() { c(user = 0, system = 0, elapsed = 0) diff --git a/R/reporter-list.R b/R/reporter-list.R index 989a9ee78..27401a857 100644 --- a/R/reporter-list.R +++ b/R/reporter-list.R @@ -8,7 +8,8 @@ methods::setOldClass("proc_time") #' #' @export #' @family reporters -ListReporter <- R6::R6Class("ListReporter", +ListReporter <- R6::R6Class( + "ListReporter", inherit = Reporter, public = list( current_start_time = NA, @@ -25,8 +26,10 @@ ListReporter <- R6::R6Class("ListReporter", }, start_test = function(context, test) { - if (!identical(self$current_context, context) || - !identical(self$current_test, test)) { + if ( + !identical(self$current_context, context) || + !identical(self$current_test, test) + ) { self$current_context <- context self$current_test <- test self$current_expectations <- Stack$new() @@ -51,16 +54,17 @@ ListReporter <- R6::R6Class("ListReporter", elapsed <- as.double(proc.time() - self$current_start_time) results <- list() - if (!is.null(self$current_expectations)) + if (!is.null(self$current_expectations)) { results <- self$current_expectations$as_list() + } self$results$push(list( - file = self$current_file %||% NA_character_, + file = self$current_file %||% NA_character_, context = context, - test = test, - user = elapsed[1], - system = elapsed[2], - real = elapsed[3], + test = test, + user = elapsed[1], + system = elapsed[2], + real = elapsed[3], results = results )) @@ -87,23 +91,24 @@ ListReporter <- R6::R6Class("ListReporter", # look for exceptions raised outside of tests # they happened just before end_context since they interrupt the test_file execution results <- results$as_list() - if (length(results) == 0) return() + if (length(results) == 0) { + return() + } self$results$push(list( - file = self$current_file %||% NA_character_, + file = self$current_file %||% NA_character_, context = context, - test = NA_character_, - user = NA_real_, - system = NA_real_, - real = NA_real_, + test = NA_character_, + user = NA_real_, + system = NA_real_, + real = NA_real_, results = results - )) + )) }, get_results = function() { testthat_results(self$results$as_list()) } - ) ) @@ -144,11 +149,19 @@ as.data.frame.testthat_results <- function(x, ...) { if (length(x) == 0) { return( data.frame( - file = character(0), context = character(0), test = character(0), - nb = integer(0), failed = integer(0), skipped = logical(0), - error = logical(0), warning = integer(0), - user = numeric(0), system = numeric(0), real = numeric(0), - passed = integer(0), result = list(), + file = character(0), + context = character(0), + test = character(0), + nb = integer(0), + failed = integer(0), + skipped = logical(0), + error = logical(0), + warning = integer(0), + user = numeric(0), + system = numeric(0), + real = numeric(0), + passed = integer(0), + result = list(), stringsAsFactors = FALSE ) ) @@ -184,10 +197,17 @@ summarize_one_test_results <- function(test) { context <- if (length(test$context) > 0) test$context else "" res <- data.frame( - file = test$file, context = context, test = test$test, - nb = nb_tests, failed = nb_failed, skipped = as.logical(nb_skipped), - error = error, warning = nb_warning, - user = test$user, system = test$system, real = test$real, + file = test$file, + context = context, + test = test$test, + nb = nb_tests, + failed = nb_failed, + skipped = as.logical(nb_skipped), + error = error, + warning = nb_warning, + user = test$user, + system = test$system, + real = test$real, stringsAsFactors = FALSE ) diff --git a/R/reporter-location.R b/R/reporter-location.R index 5dc398984..5e5c384b5 100644 --- a/R/reporter-location.R +++ b/R/reporter-location.R @@ -6,7 +6,8 @@ #' #' @export #' @family reporters -LocationReporter <- R6::R6Class("LocationReporter", +LocationReporter <- R6::R6Class( + "LocationReporter", inherit = Reporter, public = list( start_test = function(context, test) { diff --git a/R/reporter-minimal.R b/R/reporter-minimal.R index dcd030933..f8f038d6c 100644 --- a/R/reporter-minimal.R +++ b/R/reporter-minimal.R @@ -7,7 +7,8 @@ #' #' @export #' @family reporters -MinimalReporter <- R6::R6Class("MinimalReporter", +MinimalReporter <- R6::R6Class( + "MinimalReporter", inherit = Reporter, public = list( initialize = function(...) { diff --git a/R/reporter-multi.R b/R/reporter-multi.R index aac1ff3aa..07157e29d 100644 --- a/R/reporter-multi.R +++ b/R/reporter-multi.R @@ -5,7 +5,8 @@ #' #' @export #' @family reporters -MultiReporter <- R6::R6Class("MultiReporter", +MultiReporter <- R6::R6Class( + "MultiReporter", inherit = Reporter, public = list( reporters = list(), @@ -29,7 +30,13 @@ MultiReporter <- R6::R6Class("MultiReporter", o_apply(self$reporters, "start_test", context, test) }, add_result = function(context, test, result) { - o_apply(self$reporters, "add_result", context = context, test = test, result = result) + o_apply( + self$reporters, + "add_result", + context = context, + test = test, + result = result + ) }, end_test = function(context, test) { o_apply(self$reporters, "end_test", context, test) @@ -51,9 +58,12 @@ MultiReporter <- R6::R6Class("MultiReporter", o_apply <- function(objects, method, ...) { x <- NULL # silence check note - f <- new_function(exprs(x = ), expr( - `$`(x, !!method)(...) - )) + f <- new_function( + exprs(x = ), + expr( + `$`(x, !!method)(...) + ) + ) lapply(objects, f) } diff --git a/R/reporter-progress.R b/R/reporter-progress.R index c34ed1649..a958c8e8b 100644 --- a/R/reporter-progress.R +++ b/R/reporter-progress.R @@ -15,7 +15,8 @@ #' #' @export #' @family reporters -ProgressReporter <- R6::R6Class("ProgressReporter", +ProgressReporter <- R6::R6Class( + "ProgressReporter", inherit = Reporter, public = list( show_praise = TRUE, @@ -46,11 +47,13 @@ ProgressReporter <- R6::R6Class("ProgressReporter", ctxt_name = "", file_name = "", - initialize = function(show_praise = TRUE, - max_failures = testthat_max_fails(), - min_time = 1, - update_interval = 0.1, - ...) { + initialize = function( + show_praise = TRUE, + max_failures = testthat_max_fails(), + min_time = 1, + update_interval = 0.1, + ... + ) { super$initialize(...) self$capabilities$parallel_support <- TRUE self$show_praise <- show_praise @@ -100,12 +103,17 @@ ProgressReporter <- R6::R6Class("ProgressReporter", show_header = function() { self$cat_line( - colourise(cli::symbol$tick, "success"), " | ", - colourise("F", "failure"), " ", - colourise("W", "warning"), " ", - colourise(" S", "skip"), " ", + colourise(cli::symbol$tick, "success"), + " | ", + colourise("F", "failure"), + " ", + colourise("W", "warning"), + " ", + colourise(" S", "skip"), + " ", colourise(" OK", "success"), - " | ", "Context" + " | ", + "Context" ) }, @@ -154,17 +162,21 @@ ProgressReporter <- R6::R6Class("ProgressReporter", } else { colourise(n, type) } - } } message <- paste0( - status, " | ", - col_format(data$n_fail, "fail"), " ", - col_format(data$n_warn, "warn"), " ", - col_format(data$n_skip, "skip"), " ", + status, + " | ", + col_format(data$n_fail, "fail"), + " ", + col_format(data$n_warn, "warn"), + " ", + col_format(data$n_skip, "skip"), + " ", sprintf("%3d", data$n_ok), - " | ", data$name + " | ", + data$name ) if (complete && time > self$min_time) { @@ -311,8 +323,10 @@ ProgressReporter <- R6::R6Class("ProgressReporter", } time <- proc.time()[[3]] - if (!is.null(self$last_update) && - (time - self$last_update) < self$update_interval) { + if ( + !is.null(self$last_update) && + (time - self$last_update) < self$update_interval + ) { return(FALSE) } self$last_update <- time @@ -333,7 +347,8 @@ testthat_max_fails <- function() { #' @export #' @rdname ProgressReporter -CompactProgressReporter <- R6::R6Class("CompactProgressReporter", +CompactProgressReporter <- R6::R6Class( + "CompactProgressReporter", inherit = ProgressReporter, public = list( initialize = function(min_time = Inf, ...) { @@ -348,8 +363,7 @@ CompactProgressReporter <- R6::R6Class("CompactProgressReporter", super$start_file(name) }, - start_reporter = function(context) { - }, + start_reporter = function(context) {}, end_context = function(context) { if (self$ctxt_issues$size() == 0) { @@ -360,7 +374,10 @@ CompactProgressReporter <- R6::R6Class("CompactProgressReporter", self$cat_line() issues <- self$ctxt_issues$as_list() - summary <- vapply(issues, issue_summary, rule = TRUE, + summary <- vapply( + issues, + issue_summary, + rule = TRUE, FUN.VALUE = character(1) ) self$cat_tight(paste(summary, collapse = "\n\n")) @@ -394,7 +411,6 @@ CompactProgressReporter <- R6::R6Class("CompactProgressReporter", status <- summary_line(self$n_fail, self$n_warn, self$n_skip, self$n_ok) self$cat_tight(self$cr(), status) } - ) ) @@ -403,10 +419,10 @@ CompactProgressReporter <- R6::R6Class("CompactProgressReporter", #' @export #' @rdname ProgressReporter -ParallelProgressReporter <- R6::R6Class("ParallelProgressReporter", +ParallelProgressReporter <- R6::R6Class( + "ParallelProgressReporter", inherit = ProgressReporter, public = list( - files = list(), spin_frame = 0L, is_rstudio = FALSE, @@ -419,8 +435,8 @@ ParallelProgressReporter <- R6::R6Class("ParallelProgressReporter", self$is_rstudio <- Sys.getenv("RSTUDIO", "") == "1" }, - start_file = function(file) { - if (! file %in% names(self$files)) { + start_file = function(file) { + if (!file %in% names(self$files)) { self$files[[file]] <- list( issues = Stack$new(), n_fail = 0L, @@ -494,7 +510,9 @@ ParallelProgressReporter <- R6::R6Class("ParallelProgressReporter", }, update = function(force = FALSE) { - if (!force && !self$should_update()) return() + if (!force && !self$should_update()) { + return() + } self$spin_frame <- self$spin_frame + 1L status <- spinner(self$frames, self$spin_frame) @@ -525,7 +543,7 @@ issue_header <- function(x, pad = FALSE) { type <- first_upper(type) } if (pad) { - type <- strpad(type, 7) + type <- strpad(type, 7) } paste0(type, expectation_location(x, " (", ")"), ": ", x$test) @@ -570,13 +588,18 @@ skip_bullets <- function(skips) { skip_summary <- map_chr(locs_by_skip, paste, collapse = ", ") bullets <- paste0( - cli::symbol$bullet, " ", names(locs_by_skip), " (", n, "): ", skip_summary + cli::symbol$bullet, + " ", + names(locs_by_skip), + " (", + n, + "): ", + skip_summary ) cli::ansi_strwrap(bullets, exdent = 2) } - #' Set maximum number of test failures allowed before aborting the run #' #' This sets the `TESTTHAT_MAX_FAILS` env var which will affect both the diff --git a/R/reporter-rstudio.R b/R/reporter-rstudio.R index 394cbb18a..280eff11c 100644 --- a/R/reporter-rstudio.R +++ b/R/reporter-rstudio.R @@ -5,7 +5,8 @@ #' #' @export #' @family reporters -RStudioReporter <- R6::R6Class("RStudioReporter", +RStudioReporter <- R6::R6Class( + "RStudioReporter", inherit = Reporter, public = list( initialize = function(...) { diff --git a/R/reporter-silent.R b/R/reporter-silent.R index c3f717f5b..e68c31c6d 100644 --- a/R/reporter-silent.R +++ b/R/reporter-silent.R @@ -7,7 +7,8 @@ #' #' @export #' @family reporters -SilentReporter <- R6::R6Class("SilentReporter", +SilentReporter <- R6::R6Class( + "SilentReporter", inherit = Reporter, public = list( .expectations = NULL, diff --git a/R/reporter-stop.R b/R/reporter-stop.R index c7e0a353c..2d2ae799d 100644 --- a/R/reporter-stop.R +++ b/R/reporter-stop.R @@ -10,7 +10,8 @@ #' #' @export #' @family reporters -StopReporter <- R6::R6Class("StopReporter", +StopReporter <- R6::R6Class( + "StopReporter", inherit = Reporter, public = list( failures = NULL, diff --git a/R/reporter-summary.R b/R/reporter-summary.R index efb9c6aa6..b59c275ff 100644 --- a/R/reporter-summary.R +++ b/R/reporter-summary.R @@ -13,7 +13,8 @@ #' #' @export #' @family reporters -SummaryReporter <- R6::R6Class("SummaryReporter", +SummaryReporter <- R6::R6Class( + "SummaryReporter", inherit = Reporter, public = list( failures = NULL, @@ -23,10 +24,12 @@ SummaryReporter <- R6::R6Class("SummaryReporter", show_praise = TRUE, omit_dots = FALSE, - initialize = function(show_praise = TRUE, - omit_dots = getOption("testthat.summary.omit_dots"), - max_reports = getOption("testthat.summary.max_reports", 10L), - ...) { + initialize = function( + show_praise = TRUE, + omit_dots = getOption("testthat.summary.omit_dots"), + max_reports = getOption("testthat.summary.max_reports", 10L), + ... + ) { super$initialize(...) self$capabilities$parallel_support <- TRUE self$failures <- Stack$new() @@ -81,7 +84,9 @@ SummaryReporter <- R6::R6Class("SummaryReporter", if (self$failures$size() >= self$max_reports) { self$cat_line( - "Maximum number of ", self$max_reports, " failures reached, ", + "Maximum number of ", + self$max_reports, + " failures reached, ", "some test results may be missing." ) self$cat_line() @@ -110,8 +115,13 @@ SummaryReporter <- R6::R6Class("SummaryReporter", single_letter_summary(result) }, - cat_reports = function(header, expectations, max_n, summary_fun, - collapse = "\n\n") { + cat_reports = function( + header, + expectations, + max_n, + summary_fun, + collapse = "\n\n" + ) { n <- length(expectations) if (n == 0L) { return() @@ -127,7 +137,11 @@ SummaryReporter <- R6::R6Class("SummaryReporter", exp_summary <- function(i) { summary_fun(expectations[[i]], labels[i]) } - report_summary <- vapply(seq_along(expectations), exp_summary, character(1)) + report_summary <- vapply( + seq_along(expectations), + exp_summary, + character(1) + ) self$cat_tight(paste(report_summary, collapse = collapse)) if (n > max_n) { @@ -147,7 +161,10 @@ skip_summary <- function(x, label) { header <- paste0(label, ". ", x$test) paste0( - colourise(header, "skip"), expectation_location(x, " (", ")"), " - ", x$message + colourise(header, "skip"), + expectation_location(x, " (", ")"), + " - ", + x$message ) } @@ -155,7 +172,8 @@ failure_summary <- function(x, label, width = cli::console_width()) { header <- paste0(label, ". ", issue_header(x)) paste0( - cli::rule(header, col = testthat_style("error")), "\n", + cli::rule(header, col = testthat_style("error")), + "\n", format(x) ) } diff --git a/R/reporter-tap.R b/R/reporter-tap.R index d1803f522..3e856a2bb 100644 --- a/R/reporter-tap.R +++ b/R/reporter-tap.R @@ -6,7 +6,8 @@ #' #' @export #' @family reporters -TapReporter <- R6::R6Class("TapReporter", +TapReporter <- R6::R6Class( + "TapReporter", inherit = Reporter, public = list( results = list(), @@ -48,7 +49,11 @@ TapReporter <- R6::R6Class("TapReporter", self$cat_line(msg) } else { self$cat_line( - "ok ", i, " # ", toupper(expectation_type(result)), " ", + "ok ", + i, + " # ", + toupper(expectation_type(result)), + " ", format(result) ) } diff --git a/R/reporter-teamcity.R b/R/reporter-teamcity.R index eaf5f03bf..aa98f2fd1 100644 --- a/R/reporter-teamcity.R +++ b/R/reporter-teamcity.R @@ -6,7 +6,8 @@ #' #' @export #' @family reporters -TeamcityReporter <- R6::R6Class("TeamcityReporter", +TeamcityReporter <- R6::R6Class( + "TeamcityReporter", inherit = Reporter, public = list( i = NA_integer_, @@ -51,7 +52,9 @@ TeamcityReporter <- R6::R6Class("TeamcityReporter", lines <- strsplit(format(result), "\n")[[1]] private$report_event( - "testFailed", testName, message = lines[1], + "testFailed", + testName, + message = lines[1], details = paste(lines[-1], collapse = "\n") ) } diff --git a/R/reporter-zzz.R b/R/reporter-zzz.R index e4adce07a..a0952f170 100644 --- a/R/reporter-zzz.R +++ b/R/reporter-zzz.R @@ -75,7 +75,9 @@ stop_reporter <- function(message) { #' @param reporter name of reporter(s), or reporter object(s) #' @keywords internal find_reporter <- function(reporter) { - if (is.null(reporter)) return(NULL) + if (is.null(reporter)) { + return(NULL) + } if (inherits(reporter, "R6ClassGenerator")) { reporter$new() diff --git a/R/reporter.R b/R/reporter.R index 78cfc55f6..dc7998255 100644 --- a/R/reporter.R +++ b/R/reporter.R @@ -23,20 +23,21 @@ #' test_file(path) #' # Override the default by supplying the name of a reporter #' test_file(path, reporter = "minimal") -Reporter <- R6::R6Class("Reporter", +Reporter <- R6::R6Class( + "Reporter", public = list( capabilities = list(parallel_support = FALSE, parallel_updates = FALSE), start_reporter = function() {}, - start_context = function(context) {}, - start_test = function(context, test) {}, - start_file = function(filename) {}, - add_result = function(context, test, result) {}, - end_test = function(context, test) {}, - end_context = function(context) {}, - end_reporter = function() {}, - end_file = function() {}, - is_full = function() FALSE, - update = function() {}, + start_context = function(context) {}, + start_test = function(context, test) {}, + start_file = function(filename) {}, + add_result = function(context, test, result) {}, + end_test = function(context, test) {}, + end_context = function(context) {}, + end_reporter = function() {}, + end_file = function() {}, + is_full = function() FALSE, + update = function() {}, width = 80, unicode = TRUE, diff --git a/R/skip.R b/R/skip.R index 894cf7377..e36b12b64 100644 --- a/R/skip.R +++ b/R/skip.R @@ -114,8 +114,14 @@ skip_if_not_installed <- function(pkg, minimum_version = NULL) { installed_version <- package_version(pkg) if (installed_version < minimum_version) { skip(paste0( - "Installed ", pkg, " is version ", installed_version, "; ", - "but ", minimum_version, " is required" + "Installed ", + pkg, + " is version ", + installed_version, + "; ", + "but ", + minimum_version, + " is required" )) } } @@ -133,7 +139,9 @@ package_version <- function(x) { skip_unless_r <- function(spec) { parts <- unlist(strsplit(spec, " ", fixed = TRUE)) if (length(parts) != 2L) { - cli::cli_abort("{.arg spec} should be a comparison like '>=' and an R version separated by a space.") + cli::cli_abort( + "{.arg spec} should be a comparison like '>=' and an R version separated by a space." + ) } comparator <- match.fun(parts[1L]) required_version <- numeric_version(parts[2L]) @@ -143,7 +151,9 @@ skip_unless_r <- function(spec) { comparator(current_version, required_version), sprintf( "Current R version (%s) does not satisfy requirement (%s %s)", - current_version, parts[1L], required_version + current_version, + parts[1L], + required_version ) ) } @@ -184,11 +194,12 @@ skip_on_os <- function(os, arch = NULL) { several.ok = TRUE ) - msg <- switch(system_os(), + msg <- switch( + system_os(), windows = if ("windows" %in% os) "On Windows", - darwin = if ("mac" %in% os) "On Mac", - linux = if ("linux" %in% os) "On Linux", - sunos = if ("solaris" %in% os) "On Solaris", + darwin = if ("mac" %in% os) "On Mac", + linux = if ("linux" %in% os) "On Linux", + sunos = if ("solaris" %in% os) "On Solaris", emscripten = if ("emscripten" %in% os) "On Emscripten" ) @@ -272,7 +283,7 @@ skip_on_appveyor <- function() { # helpers ----------------------------------------------------------------- on_ci <- function() { - env_var_is_true("CI") + env_var_is_true("CI") } in_covr <- function() { env_var_is_true("R_COVR") diff --git a/R/snapshot-cleanup.R b/R/snapshot-cleanup.R index 2c2077c5a..0dd92fdb0 100644 --- a/R/snapshot-cleanup.R +++ b/R/snapshot-cleanup.R @@ -1,4 +1,8 @@ -snapshot_cleanup <- function(path, test_files_seen = character(), snap_files_seen = character()) { +snapshot_cleanup <- function( + path, + test_files_seen = character(), + snap_files_seen = character() +) { outdated <- snapshot_outdated(path, test_files_seen, snap_files_seen) if (length(outdated) > 0) { @@ -13,8 +17,8 @@ snapshot_cleanup <- function(path, test_files_seen = character(), snap_files_see unlink(empty, recursive = TRUE) # Delete snapshot folder - if (is_dir_empty(path)) { - unlink(path, recursive = TRUE) + if (is_dir_empty(path)) { + unlink(path, recursive = TRUE) } rstudio_tickle() @@ -26,19 +30,26 @@ is_dir_empty <- function(x) { length(dir(x, recursive = TRUE)) == 0 } -snapshot_outdated <- function(path, test_files_seen = character(), snap_files_seen = character()) { +snapshot_outdated <- function( + path, + test_files_seen = character(), + snap_files_seen = character() +) { all_files <- dir(path, recursive = TRUE) expected <- snapshot_expected(path, test_files_seen, snap_files_seen) setdiff(all_files, expected) } snapshot_expected <- function( - snap_dir, - test_files_seen = character(), - snap_files_seen = character()) { - + snap_dir, + test_files_seen = character(), + snap_files_seen = character() +) { if (length(test_files_seen) > 0) { - snaps <- c(paste0(test_files_seen, ".md"), paste0(test_files_seen, ".new.md")) + snaps <- c( + paste0(test_files_seen, ".md"), + paste0(test_files_seen, ".new.md") + ) } else { snaps <- character() } @@ -50,7 +61,8 @@ snapshot_expected <- function( snap_files_seen_new <- paste0( tools::file_path_sans_ext(snap_files_seen), - ".new.", tools::file_ext(snap_files_seen) + ".new.", + tools::file_ext(snap_files_seen) ) sort(c( diff --git a/R/snapshot-file-snaps.R b/R/snapshot-file-snaps.R index 198ef261a..d7ac27465 100644 --- a/R/snapshot-file-snaps.R +++ b/R/snapshot-file-snaps.R @@ -1,101 +1,108 @@ # Manage a test files worth of snapshots - if the test file uses variants, this # will correspond to multiple output files. -FileSnaps <- R6::R6Class("FileSnaps", public = list( - snap_path = NULL, - file = NULL, - type = NULL, - snaps = NULL, - - initialize = function(snap_path, file, type = c("old", "cur", "new")) { - self$snap_path <- snap_path - self$file <- file - self$type <- arg_match(type) - - if (self$type == "old") { - # Find variants - variants <- c("_default", dirs(self$snap_path)) - paths <- set_names(self$path(variants), variants) - paths <- paths[file.exists(paths)] - - self$snaps <- lapply(paths, read_snaps) - } else { - self$snaps <- list(`_default` = list()) - } - }, - - get = function(test, variant, i) { - test_snaps <- self$snaps[[variant]][[test]] - if (i > length(test_snaps)) { - NULL - } else { - test_snaps[[i]] - } - }, - - set = function(test, variant, i, data) { - self$snaps[[variant]][[test]][[i]] <- data - }, - - append = function(test, variant, data) { - if (!has_name(self$snaps, variant)) { - # Needed for R < 3.6 - self$snaps[[variant]] <- list() - } +FileSnaps <- R6::R6Class( + "FileSnaps", + public = list( + snap_path = NULL, + file = NULL, + type = NULL, + snaps = NULL, + + initialize = function(snap_path, file, type = c("old", "cur", "new")) { + self$snap_path <- snap_path + self$file <- file + self$type <- arg_match(type) + + if (self$type == "old") { + # Find variants + variants <- c("_default", dirs(self$snap_path)) + paths <- set_names(self$path(variants), variants) + paths <- paths[file.exists(paths)] + + self$snaps <- lapply(paths, read_snaps) + } else { + self$snaps <- list(`_default` = list()) + } + }, + + get = function(test, variant, i) { + test_snaps <- self$snaps[[variant]][[test]] + if (i > length(test_snaps)) { + NULL + } else { + test_snaps[[i]] + } + }, - self$snaps[[variant]][[test]] <- c(self$snaps[[variant]][[test]], data) - length(self$snaps[[variant]][[test]]) - }, + set = function(test, variant, i, data) { + self$snaps[[variant]][[test]][[i]] <- data + }, - reset = function(test, old) { - for (variant in names(self$snaps)) { - cur_test <- self$snaps[[variant]][[test]] - old_test <- old$snaps[[variant]][[test]] + append = function(test, variant, data) { + if (!has_name(self$snaps, variant)) { + # Needed for R < 3.6 + self$snaps[[variant]] <- list() + } - if (length(cur_test) == 0) { - self$snaps[[variant]][[test]] <- old_test - } else if (length(old_test) > length(cur_test)) { - self$snaps[[variant]][[test]] <- c(cur_test, old_test[-seq_along(cur_test)]) + self$snaps[[variant]][[test]] <- c(self$snaps[[variant]][[test]], data) + length(self$snaps[[variant]][[test]]) + }, + + reset = function(test, old) { + for (variant in names(self$snaps)) { + cur_test <- self$snaps[[variant]][[test]] + old_test <- old$snaps[[variant]][[test]] + + if (length(cur_test) == 0) { + self$snaps[[variant]][[test]] <- old_test + } else if (length(old_test) > length(cur_test)) { + self$snaps[[variant]][[test]] <- c( + cur_test, + old_test[-seq_along(cur_test)] + ) + } } - } - invisible() - }, - - write = function(variants = names(self$snaps)) { - for (variant in variants) { - default <- variant == "_default" - if (!default) { - dir.create(file.path(self$snap_path, variant), showWarnings = FALSE) + invisible() + }, + + write = function(variants = names(self$snaps)) { + for (variant in variants) { + default <- variant == "_default" + if (!default) { + dir.create(file.path(self$snap_path, variant), showWarnings = FALSE) + } + + write_snaps( + self$snaps[[variant]], + self$path(variant), + delete = default + ) } - - write_snaps( - self$snaps[[variant]], - self$path(variant), - delete = default + invisible() + }, + + delete = function(variant = "_default") { + unlink(self$path(variant)) + invisible() + }, + + variants = function() { + names(self$snaps) + }, + + filename = function() { + paste0(self$file, if (self$type == "new") ".new", ".md") + }, + + path = function(variant = "_default") { + ifelse( + variant == "_default", + file.path(self$snap_path, self$filename()), + file.path(self$snap_path, variant, self$filename()) ) } - invisible() - }, - - delete = function(variant = "_default") { - unlink(self$path(variant)) - invisible() - }, - - variants = function() { - names(self$snaps) - }, - - filename = function() { - paste0(self$file, if (self$type == "new") ".new", ".md") - }, - - path = function(variant = "_default") { - ifelse(variant == "_default", - file.path(self$snap_path, self$filename()), - file.path(self$snap_path, variant, self$filename()) - ) - } -)) + ) +) dirs <- function(path) { list.dirs(path, recursive = FALSE, full.names = FALSE) diff --git a/R/snapshot-file.R b/R/snapshot-file.R index 52bea739f..f287de0d1 100644 --- a/R/snapshot-file.R +++ b/R/snapshot-file.R @@ -85,13 +85,15 @@ #' path <- save_png(code) #' expect_snapshot_file(path, name) #' } -expect_snapshot_file <- function(path, - name = basename(path), - binary = lifecycle::deprecated(), - cran = FALSE, - compare = NULL, - transform = NULL, - variant = NULL) { +expect_snapshot_file <- function( + path, + name = basename(path), + binary = lifecycle::deprecated(), + cran = FALSE, + compare = NULL, + transform = NULL, + variant = NULL +) { edition_require(3, "expect_snapshot_file()") if (!cran && !interactive() && on_cran()) { skip("On CRAN") @@ -126,7 +128,9 @@ expect_snapshot_file <- function(path, } lab <- quo_label(enquo(path)) - equal <- snapshotter$take_file_snapshot(name, path, + equal <- snapshotter$take_file_snapshot( + name, + path, file_equal = compare, variant = variant, trace_env = caller_env() @@ -137,7 +141,8 @@ expect_snapshot_file <- function(path, equal, sprintf( "Snapshot of %s to '%s' has changed\n%s", - lab, paste0(snapshotter$file, "/", name), + lab, + paste0(snapshotter$file, "/", name), hint ) ) @@ -154,16 +159,17 @@ announce_snapshot_file <- function(path, name = basename(path)) { } } -snapshot_review_hint <- function(test, - name, - ci = on_ci(), - check = in_rcmd_check(), - reset_output = TRUE) { +snapshot_review_hint <- function( + test, + name, + ci = on_ci(), + check = in_rcmd_check(), + reset_output = TRUE +) { if (reset_output) { local_reporter_output() } - path <- paste0("tests/testthat/_snaps/", test, "/", new_name(name)) paste0( @@ -171,11 +177,21 @@ snapshot_review_hint <- function(test, if (check && !ci) "* Locate check directory\n", if (check) paste0("* Copy '", path, "' to local test directory\n"), if (check) "* ", - cli::format_inline("Run {.run testthat::snapshot_review('{test}/')} to review changes") + cli::format_inline( + "Run {.run testthat::snapshot_review('{test}/')} to review changes" + ) ) } -snapshot_file_equal <- function(snap_test_dir, snap_name, snap_variant, path, file_equal = compare_file_binary, fail_on_new = FALSE, trace_env = NULL) { +snapshot_file_equal <- function( + snap_test_dir, + snap_name, + snap_variant, + path, + file_equal = compare_file_binary, + fail_on_new = FALSE, + trace_env = NULL +) { if (!file.exists(path)) { abort(paste0("`", path, "` not found")) } @@ -198,8 +214,10 @@ snapshot_file_equal <- function(snap_test_dir, snap_name, snap_variant, path, fi message <- paste0( "Adding new file snapshot: 'tests/testthat/_snaps/", - snap_variant, if (!is.null(snap_variant)) "/", - snap_name, "'" + snap_variant, + if (!is.null(snap_variant)) "/", + snap_name, + "'" ) if (fail_on_new) { fail(message, trace_env = trace_env) @@ -216,8 +234,11 @@ snapshot_file_equal <- function(snap_test_dir, snap_name, snap_variant, path, fi new_name <- function(x) { pieces <- split_path(x) paste0( - pieces$dir, ifelse(pieces$dir == "", "", "/"), - pieces$name, ".new.", pieces$ext + pieces$dir, + ifelse(pieces$dir == "", "", "/"), + pieces$name, + ".new.", + pieces$ext ) } @@ -239,7 +260,12 @@ split_path <- function(path) { ) } -write_tmp_lines <- function(lines, ext = ".txt", eol = "\n", envir = caller_env()) { +write_tmp_lines <- function( + lines, + ext = ".txt", + eol = "\n", + envir = caller_env() +) { path <- withr::local_tempfile(fileext = ext, .local_envir = envir) brio::write_lines(lines, path, eol = eol) path diff --git a/R/snapshot-manage.R b/R/snapshot-manage.R index afd1cbc29..aabbefdce 100644 --- a/R/snapshot-manage.R +++ b/R/snapshot-manage.R @@ -52,12 +52,17 @@ review_app <- function(name, old_path, new_path) { case_index <- stats::setNames(seq_along(name), name) handled <- rep(FALSE, n) - ui <- shiny::fluidPage(style = "margin: 0.5em", - shiny::fluidRow(style = "display: flex", - shiny::div(style = "flex: 1 1", + ui <- shiny::fluidPage( + style = "margin: 0.5em", + shiny::fluidRow( + style = "display: flex", + shiny::div( + style = "flex: 1 1", shiny::selectInput("cases", NULL, case_index, width = "100%") ), - shiny::div(class = "btn-group", style = "margin-left: 1em; flex: 0 0 auto", + shiny::div( + class = "btn-group", + style = "margin-left: 1em; flex: 0 0 auto", shiny::actionButton("skip", "Skip"), shiny::actionButton("accept", "Accept", class = "btn-success"), ) @@ -93,7 +98,9 @@ review_app <- function(name, old_path, new_path) { handled[[i()]] <<- TRUE i <- next_case() - shiny::updateSelectInput(session, "cases", + shiny::updateSelectInput( + session, + "cases", choices = case_index[!handled], selected = i ) @@ -108,7 +115,11 @@ review_app <- function(name, old_path, new_path) { # Find next case; remaining <- case_index[!handled] next_cases <- which(remaining > i()) - if (length(next_cases) == 0) remaining[[1]] else remaining[[next_cases[[1]]]] + if (length(next_cases) == 0) { + remaining[[1]] + } else { + remaining[[next_cases[[1]]]] + } } } @@ -131,7 +142,11 @@ snapshot_meta <- function(files = NULL, path = "tests/testthat") { cur <- all[!grepl("\\.new\\.", all)] snap_file <- basename(dirname(cur)) != "_snaps" - snap_test <- ifelse(snap_file, basename(dirname(cur)), gsub("\\.md$", "", basename(cur))) + snap_test <- ifelse( + snap_file, + basename(dirname(cur)), + gsub("\\.md$", "", basename(cur)) + ) if (length(cur) == 0) { new <- character() @@ -140,7 +155,8 @@ snapshot_meta <- function(files = NULL, path = "tests/testthat") { new[!file.exists(new)] <- NA } - snap_name <- ifelse(snap_file, + snap_name <- ifelse( + snap_file, file.path(snap_test, basename(cur)), basename(cur) ) diff --git a/R/snapshot-reporter-parallel.R b/R/snapshot-reporter-parallel.R index 43488d308..4306e48c6 100644 --- a/R/snapshot-reporter-parallel.R +++ b/R/snapshot-reporter-parallel.R @@ -1,5 +1,5 @@ - -MainprocessSnapshotReporter <- R6::R6Class("MainprocessSnapshotReporter", +MainprocessSnapshotReporter <- R6::R6Class( + "MainprocessSnapshotReporter", inherit = SnapshotReporter, public = list( end_file = function() { @@ -8,7 +8,8 @@ MainprocessSnapshotReporter <- R6::R6Class("MainprocessSnapshotReporter", ) ) -SubprocessSnapshotReporter <- R6::R6Class("SubprocessSnapshotReporter", +SubprocessSnapshotReporter <- R6::R6Class( + "SubprocessSnapshotReporter", inherit = SnapshotReporter, public = list( start_file = function(path, test = NULL) { diff --git a/R/snapshot-reporter.R b/R/snapshot-reporter.R index 32743b9d9..5bdb0b9be 100644 --- a/R/snapshot-reporter.R +++ b/R/snapshot-reporter.R @@ -1,5 +1,5 @@ - -SnapshotReporter <- R6::R6Class("SnapshotReporter", +SnapshotReporter <- R6::R6Class( + "SnapshotReporter", inherit = Reporter, public = list( snap_dir = character(), @@ -41,13 +41,15 @@ SnapshotReporter <- R6::R6Class("SnapshotReporter", }, # Called by expectation - take_snapshot = function(value, - save = identity, - load = identity, - ..., - tolerance = testthat_tolerance(), - variant = NULL, - trace_env = NULL) { + take_snapshot = function( + value, + save = identity, + load = identity, + ..., + tolerance = testthat_tolerance(), + variant = NULL, + trace_env = NULL + ) { check_string(self$test, allow_empty = FALSE) i <- self$new_snaps$append(self$test, variant, save(value)) @@ -57,8 +59,10 @@ SnapshotReporter <- R6::R6Class("SnapshotReporter", old <- load(old_raw) comp <- waldo_compare( - x = old, x_arg = "old", - y = value, y_arg = "new", + x = old, + x_arg = "old", + y = value, + y_arg = "new", ..., tolerance = tolerance, quote_strings = FALSE @@ -93,7 +97,13 @@ SnapshotReporter <- R6::R6Class("SnapshotReporter", } }, - take_file_snapshot = function(name, path, file_equal, variant = NULL, trace_env = NULL) { + take_file_snapshot = function( + name, + path, + file_equal, + variant = NULL, + trace_env = NULL + ) { self$announce_file_snapshot(name) if (is.null(variant)) { @@ -145,7 +155,8 @@ SnapshotReporter <- R6::R6Class("SnapshotReporter", # clean up if we've seen all files tests <- context_name(find_test_scripts(".", full.names = FALSE)) if (!on_ci() && all(tests %in% self$test_file_seen)) { - snapshot_cleanup(self$snap_dir, + snapshot_cleanup( + self$snap_dir, test_files_seen = self$test_file_seen, snap_files_seen = self$snap_file_seen ) @@ -184,9 +195,17 @@ get_snapshotter <- function() { #' #' @export #' @keywords internal -local_snapshotter <- function(snap_dir = NULL, cleanup = FALSE, fail_on_new = FALSE, .env = parent.frame()) { +local_snapshotter <- function( + snap_dir = NULL, + cleanup = FALSE, + fail_on_new = FALSE, + .env = parent.frame() +) { snap_dir <- snap_dir %||% withr::local_tempdir(.local_envir = .env) - reporter <- SnapshotReporter$new(snap_dir = snap_dir, fail_on_new = fail_on_new) + reporter <- SnapshotReporter$new( + snap_dir = snap_dir, + fail_on_new = fail_on_new + ) if (!identical(cleanup, FALSE)) { warn("`cleanup` is deprecated") } diff --git a/R/snapshot-value.R b/R/snapshot-value.R index bbfc8ec78..339e2e694 100644 --- a/R/snapshot-value.R +++ b/R/snapshot-value.R @@ -20,25 +20,31 @@ #' @inheritParams expect_snapshot #' @inheritParams compare #' @export -expect_snapshot_value <- function(x, - style = c("json", "json2", "deparse", "serialize"), - cran = FALSE, - tolerance = testthat_tolerance(), - ..., - variant = NULL) { +expect_snapshot_value <- function( + x, + style = c("json", "json2", "deparse", "serialize"), + cran = FALSE, + tolerance = testthat_tolerance(), + ..., + variant = NULL +) { edition_require(3, "expect_snapshot_value()") variant <- check_variant(variant) lab <- quo_label(enquo(x)) style <- arg_match(style) - save <- switch(style, + save <- switch( + style, json = function(x) jsonlite::toJSON(x, auto_unbox = TRUE, pretty = TRUE), json2 = function(x) jsonlite::serializeJSON(x, pretty = TRUE), deparse = function(x) paste0(deparse(x), collapse = "\n"), - serialize = function(x) jsonlite::base64_enc(serialize(x, NULL, version = 2)) + serialize = function(x) { + jsonlite::base64_enc(serialize(x, NULL, version = 2)) + } ) - load <- switch(style, + load <- switch( + style, json = function(x) jsonlite::fromJSON(x, simplifyVector = FALSE), json2 = function(x) jsonlite::unserializeJSON(x), deparse = function(x) reparse(x), @@ -55,7 +61,9 @@ expect_snapshot_value <- function(x, tolerance = tolerance ) - expect_snapshot_helper(lab, x, + expect_snapshot_helper( + lab, + x, save = save, load = load, cran = cran, @@ -69,7 +77,8 @@ expect_snapshot_value <- function(x, # Safe environment for evaluating deparsed objects, based on inspection of # https://github.com/wch/r-source/blob/5234fe7b40aad8d3929d240c83203fa97d8c79fc/src/main/deparse.c#L845 reparse <- function(x) { - env <- env(emptyenv(), + env <- env( + emptyenv(), `-` = `-`, c = c, list = list, @@ -90,7 +99,8 @@ reparse <- function(x) { # Safe environment for evaluating deparsed objects, based on inspection of # https://github.com/wch/r-source/blob/5234fe7b40aad8d3929d240c83203fa97d8c79fc/src/main/deparse.c#L845 reparse <- function(x) { - env <- env(emptyenv(), + env <- env( + emptyenv(), `-` = `-`, c = c, list = list, @@ -108,24 +118,41 @@ reparse <- function(x) { eval(parse(text = x), env) } -check_roundtrip <- function(x, - y, - label, - style, - ..., - tolerance = testthat_tolerance(), - error_call = caller_env()) { - check <- waldo_compare(x, y, x_arg = "original", y_arg = "new", ..., tolerance = tolerance) +check_roundtrip <- function( + x, + y, + label, + style, + ..., + tolerance = testthat_tolerance(), + error_call = caller_env() +) { + check <- waldo_compare( + x, + y, + x_arg = "original", + y_arg = "new", + ..., + tolerance = tolerance + ) if (length(check) > 0) { - abort(c( - paste0("`", label, "` could not be safely serialized with `style = \"", style, "\"`."), - " " = paste0( - "Serializing then deserializing the object returned something new:\n\n", - check, "\n" + abort( + c( + paste0( + "`", + label, + "` could not be safely serialized with `style = \"", + style, + "\"`." + ), + " " = paste0( + "Serializing then deserializing the object returned something new:\n\n", + check, + "\n" + ), + i = "You may need to try a different `style`." ), - i = "You may need to try a different `style`."), call = error_call ) } } - diff --git a/R/snapshot.R b/R/snapshot.R index 94ccbd1ad..6b5178a72 100644 --- a/R/snapshot.R +++ b/R/snapshot.R @@ -60,12 +60,14 @@ #' warnings, and errors in the snapshot. Only the most specific #' class is included, i.e. the first element of `class(cnd)`. #' @export -expect_snapshot <- function(x, - cran = FALSE, - error = FALSE, - transform = NULL, - variant = NULL, - cnd_class = FALSE) { +expect_snapshot <- function( + x, + cran = FALSE, + error = FALSE, + transform = NULL, + variant = NULL, + cnd_class = FALSE +) { edition_require(3, "expect_snapshot()") variant <- check_variant(variant) if (!is.null(transform)) { @@ -99,7 +101,9 @@ expect_snapshot <- function(x, return() } - expect_snapshot_helper("code", out, + expect_snapshot_helper( + "code", + out, cran = cran, save = function(x) paste0(x, collapse = "\n"), load = function(x) split_by_line(x)[[1]], @@ -120,12 +124,13 @@ snapshot_replay.source <- function(x, state, ..., transform = NULL) { c(snap_header(state, "Code"), snapshot_lines(x$src)) } #' @export -snapshot_replay.condition <- function(x, - state, - ..., - transform = NULL, - cnd_class = FALSE) { - +snapshot_replay.condition <- function( + x, + state, + ..., + transform = NULL, + cnd_class = FALSE +) { cnd_message <- env_get(ns_env("rlang"), "cnd_message") if (inherits(x, "message")) { @@ -197,7 +202,9 @@ expect_snapshot_output <- function(x, cran = FALSE, variant = NULL) { val <- capture_output_lines(x, print = TRUE, width = NULL) ) - expect_snapshot_helper(lab, val, + expect_snapshot_helper( + lab, + val, cran = cran, save = function(x) paste0(x, collapse = "\n"), load = function(x) split_by_line(x)[[1]], @@ -211,10 +218,16 @@ expect_snapshot_output <- function(x, cran = FALSE, variant = NULL) { #' when executing `x`. #' @export #' @rdname expect_snapshot_output -expect_snapshot_error <- function(x, class = "error", cran = FALSE, variant = NULL) { +expect_snapshot_error <- function( + x, + class = "error", + cran = FALSE, + variant = NULL +) { edition_require(3, "expect_snapshot_error()") expect_snapshot_condition( - "error", {{x}}, + "error", + {{ x }}, class = class, cran = cran, variant = variant @@ -223,17 +236,29 @@ expect_snapshot_error <- function(x, class = "error", cran = FALSE, variant = NU #' @export #' @rdname expect_snapshot_output -expect_snapshot_warning <- function(x, class = "warning", cran = FALSE, variant = NULL) { +expect_snapshot_warning <- function( + x, + class = "warning", + cran = FALSE, + variant = NULL +) { edition_require(3, "expect_snapshot_warning()") expect_snapshot_condition( - "warning", {{x}}, + "warning", + {{ x }}, class = class, cran = cran, variant = variant ) } -expect_snapshot_condition <- function(base_class, x, class, cran = FALSE, variant = NULL) { +expect_snapshot_condition <- function( + base_class, + x, + class, + cran = FALSE, + variant = NULL +) { variant <- check_variant(variant) lab <- quo_label(enquo(x)) @@ -244,7 +269,12 @@ expect_snapshot_condition <- function(base_class, x, class, cran = FALSE, varian if (base_class == class) { fail(sprintf("%s did not generate %s", lab, base_class)) } else { - fail(sprintf("%s did not generate %s with class '%s'", lab, base_class, class)) + fail(sprintf( + "%s did not generate %s with class '%s'", + lab, + base_class, + class + )) } } @@ -257,15 +287,17 @@ expect_snapshot_condition <- function(base_class, x, class, cran = FALSE, varian ) } -expect_snapshot_helper <- function(lab, val, - cran = FALSE, - save = identity, - load = identity, - ..., - tolerance = testthat_tolerance(), - variant = NULL, - trace_env = caller_env() - ) { +expect_snapshot_helper <- function( + lab, + val, + cran = FALSE, + save = identity, + load = identity, + ..., + tolerance = testthat_tolerance(), + variant = NULL, + trace_env = caller_env() +) { if (!cran && !interactive() && on_cran()) { skip("On CRAN") } @@ -276,7 +308,8 @@ expect_snapshot_helper <- function(lab, val, return(invisible()) } - comp <- snapshotter$take_snapshot(val, + comp <- snapshotter$take_snapshot( + val, save = save, load = load, ..., @@ -317,8 +350,13 @@ snapshot_accept_hint <- function(variant, file, reset_output = TRUE) { } paste0( - cli::format_inline("* Run {.run testthat::snapshot_accept('{name}')} to accept the change."), "\n", - cli::format_inline("* Run {.run testthat::snapshot_review('{name}')} to interactively review the change.") + cli::format_inline( + "* Run {.run testthat::snapshot_accept('{name}')} to accept the change." + ), + "\n", + cli::format_inline( + "* Run {.run testthat::snapshot_review('{name}')} to interactively review the change." + ) ) } @@ -339,7 +377,11 @@ local_snapshot_dir <- function(snap_names, .env = parent.frame()) { dirs <- setdiff(unique(dirname(snap_names)), ".") for (dir in dirs) { - dir.create(file.path(path, "_snaps", dir), recursive = TRUE, showWarnings = FALSE) + dir.create( + file.path(path, "_snaps", dir), + recursive = TRUE, + showWarnings = FALSE + ) } snap_paths <- file.path(path, "_snaps", snap_names) diff --git a/R/source.R b/R/source.R index 14a44f4c0..56c91f2bd 100644 --- a/R/source.R +++ b/R/source.R @@ -11,17 +11,24 @@ #' that all expectations are reported, even if outside a test block. #' @export #' @keywords internal -source_file <- function(path, - env = test_env(), - chdir = TRUE, - desc = NULL, - wrap = TRUE, - error_call = caller_env()) { +source_file <- function( + path, + env = test_env(), + chdir = TRUE, + desc = NULL, + wrap = TRUE, + error_call = caller_env() +) { stopifnot(file.exists(path)) stopifnot(is.environment(env)) lines <- brio::read_lines(path) - srcfile <- srcfilecopy(path, lines, file.info(path)[1, "mtime"], isFile = TRUE) + srcfile <- srcfilecopy( + path, + lines, + file.info(path)[1, "mtime"], + isFile = TRUE + ) ## We need to parse from a connection, because parse() has a bug, ## and converts the input to the native encoding, if the text arg is used @@ -31,7 +38,9 @@ source_file <- function(path, exprs <- filter_desc(exprs, desc, error_call = error_call) n <- length(exprs) - if (n == 0L) return(invisible()) + if (n == 0L) { + return(invisible()) + } if (chdir) { old_dir <- setwd(dirname(path)) @@ -76,15 +85,20 @@ filter_desc <- function(exprs, desc = NULL, error_call = caller_env()) { include[[i]] <- TRUE } } else { - if (!is_string(expr[[2]])) + if (!is_string(expr[[2]])) { next + } test_desc <- as.character(expr[[2]]) - if (test_desc != desc) + if (test_desc != desc) { next + } if (found) { - abort("Found multiple tests with specified description", call = error_call) + abort( + "Found multiple tests with specified description", + call = error_call + ) } include[[i]] <- TRUE found <- TRUE @@ -100,8 +114,13 @@ filter_desc <- function(exprs, desc = NULL, error_call = caller_env()) { #' @rdname source_file #' @export -source_dir <- function(path, pattern = "\\.[rR]$", env = test_env(), - chdir = TRUE, wrap = TRUE) { +source_dir <- function( + path, + pattern = "\\.[rR]$", + env = test_env(), + chdir = TRUE, + wrap = TRUE +) { files <- normalizePath(sort(dir(path, pattern, full.names = TRUE))) lapply(files, function(path) { source_file(path, env = env, chdir = chdir, wrap = wrap) diff --git a/R/srcrefs.R b/R/srcrefs.R index a7dc097be..82934b627 100644 --- a/R/srcrefs.R +++ b/R/srcrefs.R @@ -1,4 +1,7 @@ -find_expectation_srcref <- function(test_code_frame = NULL, top = caller_env()) { +find_expectation_srcref <- function( + test_code_frame = NULL, + top = caller_env() +) { # It's not possible to give useful srcrefs interactively so don't even try path <- getOption("testthat_path") if (is.null(path)) { @@ -26,10 +29,7 @@ find_expectation_srcref <- function(test_code_frame = NULL, top = caller_env()) call_srcref %||% testthat_srcref } -find_srcref <- function(bottom = NULL, - top = caller_env(), - container = NULL) { - +find_srcref <- function(bottom = NULL, top = caller_env(), container = NULL) { idx <- sys_index(bottom, top) calls <- sys.calls()[rev(idx)] diff --git a/R/stack.R b/R/stack.R index 920521f03..b94662e89 100644 --- a/R/stack.R +++ b/R/stack.R @@ -42,8 +42,8 @@ Stack <- R6Class( ), private = list( - stack = NULL, # A list that holds the items - count = 0L, # Current number of items in the stack - init = 20L # Initial and minimum size of the stack + stack = NULL, # A list that holds the items + count = 0L, # Current number of items in the stack + init = 20L # Initial and minimum size of the stack ) ) diff --git a/R/teardown.R b/R/teardown.R index 6b6d951a6..0c91d6ea4 100644 --- a/R/teardown.R +++ b/R/teardown.R @@ -38,7 +38,9 @@ file_teardown_env$queue <- list() #' } #' # Then call local_test_data() in your tests teardown <- function(code, env = parent.frame()) { - edition_deprecate(3, "teardown()", + edition_deprecate( + 3, + "teardown()", "Please use test fixtures instead see vignette('test-fixtures') for details" ) @@ -51,7 +53,9 @@ teardown <- function(code, env = parent.frame()) { #' @export #' @rdname teardown setup <- function(code, env = parent.frame()) { - edition_deprecate(3, "setup()", + edition_deprecate( + 3, + "setup()", "Please use test fixtures instead see vignette('test-fixtures') for details" ) @@ -64,8 +68,9 @@ teardown_reset <- function() { } teardown_run <- function(path = ".") { - if (length(file_teardown_env$queue) == 0) + if (length(file_teardown_env$queue) == 0) { return() + } old_dir <- setwd(path) on.exit(setwd(old_dir), add = TRUE) diff --git a/R/test-compiled-code.R b/R/test-compiled-code.R index 46f1350d8..744e18a51 100644 --- a/R/test-compiled-code.R +++ b/R/test-compiled-code.R @@ -8,9 +8,14 @@ expect_cpp_tests_pass <- function(package) { tests_passed <- TRUE tryCatch( - output <- capture_output_lines(tests_passed <- .Call(run_testthat_tests, FALSE)), + output <- capture_output_lines( + tests_passed <- .Call(run_testthat_tests, FALSE) + ), error = function(e) { - warning(sprintf("failed to call test entrypoint '%s'", run_testthat_tests)) + warning(sprintf( + "failed to call test entrypoint '%s'", + run_testthat_tests + )) } ) @@ -40,21 +45,27 @@ run_cpp_tests <- function(package) { tests_passed <- TRUE catch_error <- FALSE - tryCatch({ - output <- capture_output_lines(tests_passed <- .Call(run_testthat_tests, TRUE)) - }, + tryCatch( + { + output <- capture_output_lines( + tests_passed <- .Call(run_testthat_tests, TRUE) + ) + }, error = function(e) { catch_error <- TRUE reporter <- get_reporter() context_start("Catch") reporter$start_test(context = "Catch", test = "Catch") - reporter$add_result(context = "Catch", test = "Catch", result = expectation("failure", e$message)) + reporter$add_result( + context = "Catch", + test = "Catch", + result = expectation("failure", e$message) + ) reporter$end_test(context = "Catch", test = "Catch") } ) - if (catch_error) { return() } @@ -80,7 +91,11 @@ run_cpp_tests <- function(package) { for (i in seq_len(successes)) { exp <- expectation("success", "") exp$test <- test_name - get_reporter()$add_result(context = context_name, test = test_name, result = exp) + get_reporter()$add_result( + context = context_name, + test = test_name, + result = exp + ) } failures <- xml2::xml_find_all(test, "./Expression") @@ -91,7 +106,8 @@ run_cpp_tests <- function(package) { filename <- xml2::xml_attr(failure, "filename") type <- xml2::xml_attr(failure, "type") - type_msg <- switch(type, + type_msg <- switch( + type, "CATCH_CHECK_FALSE" = "isn't false.", "CATCH_CHECK_THROWS" = "did not throw an exception.", "CATCH_CHECK_THROWS_AS" = "threw an exception with unexpected type.", @@ -101,12 +117,19 @@ run_cpp_tests <- function(package) { org_text <- paste(org_text, type_msg) line <- xml2::xml_attr(failure, "line") - failure_srcref <- srcref(srcfile(file.path("src", filename)), c(line, line, 1, 1)) + failure_srcref <- srcref( + srcfile(file.path("src", filename)), + c(line, line, 1, 1) + ) exp <- expectation("failure", org_text, srcref = failure_srcref) exp$test <- test_name - get_reporter()$add_result(context = context_name, test = test_name, result = exp) + get_reporter()$add_result( + context = context_name, + test = test_name, + result = exp + ) } exceptions <- xml2::xml_find_all(test, "./Exception") @@ -115,12 +138,19 @@ run_cpp_tests <- function(package) { filename <- xml2::xml_attr(exception, "filename") line <- xml2::xml_attr(exception, "line") - exception_srcref <- srcref(srcfile(file.path("src", filename)), c(line, line, 1, 1)) + exception_srcref <- srcref( + srcfile(file.path("src", filename)), + c(line, line, 1, 1) + ) exp <- expectation("error", exception_text, srcref = exception_srcref) exp$test <- test_name - get_reporter()$add_result(context = context_name, test = test_name, result = exp) + get_reporter()$add_result( + context = context_name, + test = test_name, + result = exp + ) } get_reporter()$end_test(context = context_name, test = test_name) @@ -266,7 +296,12 @@ use_catch <- function(dir = getwd()) { desc <- read.dcf(desc_path, all = TRUE) pkg <- desc$Package if (!nzchar(pkg)) { - stop("no 'Package' field in DESCRIPTION file '", desc_path, "'", call. = FALSE) + stop( + "no 'Package' field in DESCRIPTION file '", + desc_path, + "'", + call. = FALSE + ) } src_dir <- file.path(dir, "src") @@ -301,7 +336,12 @@ use_catch <- function(dir = getwd()) { # Copy the 'test-cpp.R' file. test_dir <- file.path(dir, "tests", "testthat") if (!file.exists(test_dir) && !dir.create(test_dir, recursive = TRUE)) { - stop("failed to create 'tests/testthat/' directory '", test_dir, "'", call. = FALSE) + stop( + "failed to create 'tests/testthat/' directory '", + test_dir, + "'", + call. = FALSE + ) } template_file <- system.file(package = "testthat", "resources", "test-cpp.R") @@ -311,7 +351,11 @@ use_catch <- function(dir = getwd()) { cat(transformed, file = output_path) # Copy the 'test-runner.R file. - template_file <- system.file(package = "testthat", "resources", "catch-routine-registration.R") + template_file <- system.file( + package = "testthat", + "resources", + "catch-routine-registration.R" + ) contents <- readChar(template_file, file.info(template_file)$size, TRUE) transformed <- sprintf(contents, pkg) output_path <- file.path(dir, "R", "catch-routine-registration.R") @@ -320,11 +364,14 @@ use_catch <- function(dir = getwd()) { message("> Added C++ unit testing infrastructure.") message("> Please ensure you have 'LinkingTo: testthat' in your DESCRIPTION.") message("> Please ensure you have 'Suggests: xml2' in your DESCRIPTION.") - message("> Please ensure you have 'useDynLib(", pkg, ", .registration = TRUE)' in your NAMESPACE.") + message( + "> Please ensure you have 'useDynLib(", + pkg, + ", .registration = TRUE)' in your NAMESPACE." + ) } get_routine <- function(package, routine) { - # check to see if the package has explicitly exported # the associated routine (check common prefixes as we # don't necessarily have access to the NAMESPACE and diff --git a/R/test-example.R b/R/test-example.R index f8625bb71..9bc4e8d58 100644 --- a/R/test-example.R +++ b/R/test-example.R @@ -68,7 +68,9 @@ test_example <- function(path, title = path) { reporter = get_reporter() %||% StopReporter$new(), skip_on_empty = FALSE ) - if (ok) succeed(path) + if (ok) { + succeed(path) + } invisible(ok) } diff --git a/R/test-files.R b/R/test-files.R index db231a2d7..362174eb6 100644 --- a/R/test-files.R +++ b/R/test-files.R @@ -41,19 +41,19 @@ #' @inheritParams with_reporter #' @inheritParams source_file #' @export -test_dir <- function(path, - filter = NULL, - reporter = NULL, - env = NULL, - ..., - load_helpers = TRUE, - stop_on_failure = TRUE, - stop_on_warning = FALSE, - wrap = lifecycle::deprecated(), - package = NULL, - load_package = c("none", "installed", "source") - ) { - +test_dir <- function( + path, + filter = NULL, + reporter = NULL, + env = NULL, + ..., + load_helpers = TRUE, + stop_on_failure = TRUE, + stop_on_warning = FALSE, + wrap = lifecycle::deprecated(), + package = NULL, + load_package = c("none", "installed", "source") +) { load_package <- arg_match(load_package) start_first <- find_test_start_first(path, load_package, package) @@ -115,11 +115,13 @@ test_dir <- function(path, #' test_file(path) #' test_file(path, desc = "some tests have warnings") #' test_file(path, reporter = "minimal") -test_file <- function(path, - reporter = default_compact_reporter(), - desc = NULL, - package = NULL, - ...) { +test_file <- function( + path, + reporter = default_compact_reporter(), + desc = NULL, + package = NULL, + ... +) { if (!file.exists(path)) { stop("`path` does not exist", call. = FALSE) } @@ -134,20 +136,21 @@ test_file <- function(path, ) } -test_files <- function(test_dir, - test_package, - test_paths, - load_helpers = TRUE, - reporter = default_reporter(), - env = NULL, - stop_on_failure = FALSE, - stop_on_warning = FALSE, - desc = NULL, - wrap = TRUE, - load_package = c("none", "installed", "source"), - parallel = FALSE, - error_call = caller_env()) { - +test_files <- function( + test_dir, + test_package, + test_paths, + load_helpers = TRUE, + reporter = default_reporter(), + env = NULL, + stop_on_failure = FALSE, + stop_on_warning = FALSE, + desc = NULL, + wrap = TRUE, + load_package = c("none", "installed", "source"), + parallel = FALSE, + error_call = caller_env() +) { if (!isTRUE(wrap)) { lifecycle::deprecate_stop("3.0.0", "test_dir(wrap = )") } @@ -180,22 +183,22 @@ test_files <- function(test_dir, error_call = error_call ) } - } -test_files_serial <- function(test_dir, - test_package, - test_paths, - load_helpers = TRUE, - reporter = default_reporter(), - env = NULL, - stop_on_failure = FALSE, - stop_on_warning = FALSE, - desc = NULL, - wrap = TRUE, - load_package = c("none", "installed", "source"), - error_call = caller_env()) { - +test_files_serial <- function( + test_dir, + test_package, + test_paths, + load_helpers = TRUE, + reporter = default_reporter(), + env = NULL, + stop_on_failure = FALSE, + stop_on_warning = FALSE, + desc = NULL, + wrap = TRUE, + load_package = c("none", "installed", "source"), + error_call = caller_env() +) { # Because load_all() called by test_files_setup_env() will have already # loaded them. We don't want to rely on testthat's loading since that # only affects the test environment and we want to keep the helpers @@ -212,7 +215,8 @@ test_files_serial <- function(test_dir, test_files_setup_state(test_dir, test_package, load_helpers, env) reporters <- test_files_reporter(reporter) - with_reporter(reporters$multi, + with_reporter( + reporters$multi, lapply( test_paths, test_one_file, @@ -222,16 +226,19 @@ test_files_serial <- function(test_dir, ) ) - test_files_check(reporters$list$get_results(), + test_files_check( + reporters$list$get_results(), stop_on_failure = stop_on_failure, stop_on_warning = stop_on_warning ) } -test_files_setup_env <- function(test_package, - test_dir, - load_package = c("none", "installed", "source"), - env = NULL) { +test_files_setup_env <- function( + test_package, + test_dir, + load_package = c("none", "installed", "source"), + env = NULL +) { library(testthat) load_package <- arg_match(load_package) @@ -277,11 +284,11 @@ find_load_all_args <- function(path) { } test_files_setup_state <- function( - test_dir, - test_package, - load_helpers, - env, - frame = parent.frame() + test_dir, + test_package, + load_helpers, + env, + frame = parent.frame() ) { # Define testing environment local_test_directory(test_dir, test_package, .env = frame) @@ -296,7 +303,7 @@ test_files_setup_state <- function( source_test_helpers(".", env) } source_test_setup(".", env) - withr::defer(source_test_teardown(".", env), frame) # old school + withr::defer(source_test_teardown(".", env), frame) # old school } test_files_reporter <- function(reporter, .env = parent.frame()) { @@ -312,7 +319,11 @@ test_files_reporter <- function(reporter, .env = parent.frame()) { ) } -test_files_check <- function(results, stop_on_failure = TRUE, stop_on_warning = FALSE) { +test_files_check <- function( + results, + stop_on_failure = TRUE, + stop_on_warning = FALSE +) { if (stop_on_failure && !all_passed(results)) { stop("Test failures", call. = FALSE) } @@ -323,10 +334,12 @@ test_files_check <- function(results, stop_on_failure = TRUE, stop_on_warning = invisible(results) } -test_one_file <- function(path, - env = test_env(), - desc = NULL, - error_call = caller_env()) { +test_one_file <- function( + path, + env = test_env(), + desc = NULL, + error_call = caller_env() +) { reporter <- get_reporter() on.exit(teardown_run(), add = TRUE) @@ -379,7 +392,14 @@ local_teardown_env <- function(frame = parent.frame()) { #' @return A character vector of paths #' @keywords internal #' @export -find_test_scripts <- function(path, filter = NULL, invert = FALSE, ..., full.names = TRUE, start_first = NULL) { +find_test_scripts <- function( + path, + filter = NULL, + invert = FALSE, + ..., + full.names = TRUE, + start_first = NULL +) { files <- dir(path, "^test.*\\.[rR]$", full.names = full.names) files <- filter_test_scripts(files, filter, invert, ...) order_test_scripts(files, start_first) @@ -399,7 +419,9 @@ filter_test_scripts <- function(files, filter = NULL, invert = FALSE, ...) { find_test_start_first <- function(path, load_package, package) { # Make sure we get the local package package if not "installed" - if (load_package != "installed") package <- NULL + if (load_package != "installed") { + package <- NULL + } desc <- find_description(path, package) if (is.null(desc)) { return(NULL) @@ -414,7 +436,9 @@ find_test_start_first <- function(path, load_package, package) { } order_test_scripts <- function(paths, start_first) { - if (is.null(start_first)) return(paths) + if (is.null(start_first)) { + return(paths) + } filemap <- data.frame( stringsAsFactors = FALSE, base = sub("\\.[rR]$", "", sub("^test[-_\\.]?", "", basename(paths))), diff --git a/R/test-package.R b/R/test-package.R index fd25d1e05..90154a6c5 100644 --- a/R/test-package.R +++ b/R/test-package.R @@ -59,7 +59,12 @@ test_check <- function(package, reporter = check_reporter(), ...) { #' @export #' @rdname test_package -test_local <- function(path = ".", reporter = NULL, ..., load_package = "source") { +test_local <- function( + path = ".", + reporter = NULL, + ..., + load_package = "source" +) { package <- pkgload::pkg_name(path) test_path <- file.path(pkgload::pkg_path(path), "tests", "testthat") diff --git a/R/test-state.R b/R/test-state.R index ed56e892b..1721f2485 100644 --- a/R/test-state.R +++ b/R/test-state.R @@ -43,8 +43,10 @@ #' @param callback Either a zero-argument function that returns an object #' capturing global state that you're interested in, or `NULL`. set_state_inspector <- function(callback) { - - if (!is.null(callback) && !(is.function(callback) && length(formals(callback)) == 0)) { + if ( + !is.null(callback) && + !(is.function(callback) && length(formals(callback)) == 0) + ) { cli::cli_abort("{.arg callback} must be a zero-arg function, or NULL") } @@ -53,7 +55,6 @@ set_state_inspector <- function(callback) { } testthat_state_condition <- function(before, after, call) { - diffs <- waldo_compare(before, after, x_arg = "before", y_arg = "after") if (length(diffs) == 0) { diff --git a/R/test-that.R b/R/test-that.R index 8b3ab2fc7..c20068da9 100644 --- a/R/test-that.R +++ b/R/test-that.R @@ -61,7 +61,6 @@ test_that <- function(desc, code) { # Access error fields with `[[` rather than `$` because the # `$.Throwable` from the rJava package throws with unknown fields test_code <- function(test, code, env, reporter, skip_on_empty = TRUE) { - frame <- caller_env() if (!is.null(test)) { @@ -167,7 +166,7 @@ test_code <- function(test, code, env, reporter, skip_on_empty = TRUE) { } handle_message <- function(e) { if (edition_get() < 3) { - maybe_restart("muffleMessage") + maybe_restart("muffleMessage") } } handle_skip <- function(e) { @@ -194,15 +193,15 @@ test_code <- function(test, code, env, reporter, skip_on_empty = TRUE) { } }, expectation = handle_expectation, - skip = handle_skip, - warning = handle_warning, - message = handle_message, - error = handle_error + skip = handle_skip, + warning = handle_warning, + message = handle_message, + error = handle_error ), # some errors may need handling here, e.g., stack overflow error = handle_fatal, # skip silently terminate code - skip = function(e) {} + skip = function(e) {} ) after <- inspect_state() diff --git a/R/try-again.R b/R/try-again.R index 6df4e4898..df68f1d89 100644 --- a/R/try-again.R +++ b/R/try-again.R @@ -22,7 +22,9 @@ try_again <- function(times, code) { NULL }, warning = function(e) { - if (identical(e$message, "restarting interrupted promise evaluation")) { + if ( + identical(e$message, "restarting interrupted promise evaluation") + ) { maybe_restart("muffleWarning") } } diff --git a/R/utils.R b/R/utils.R index d9df540eb..3df1308de 100644 --- a/R/utils.R +++ b/R/utils.R @@ -5,8 +5,28 @@ magrittr::`%>%` null <- function(...) invisible() escape_regex <- function(x) { - chars <- c("*", ".", "?", "^", "+", "$", "|", "(", ")", "[", "]", "{", "}", "\\") - gsub(paste0("([\\", paste0(collapse = "\\", chars), "])"), "\\\\\\1", x, perl = TRUE) + chars <- c( + "*", + ".", + "?", + "^", + "+", + "$", + "|", + "(", + ")", + "[", + "]", + "{", + "}", + "\\" + ) + gsub( + paste0("([\\", paste0(collapse = "\\", chars), "])"), + "\\\\\\1", + x, + perl = TRUE + ) } maybe_restart <- function(restart) { diff --git a/R/verify-output.R b/R/verify-output.R index f8d8dfe79..2e3aa3327 100644 --- a/R/verify-output.R +++ b/R/verify-output.R @@ -48,9 +48,14 @@ #' @param env The environment to evaluate `code` in. #' @export #' @keywords internal -verify_output <- function(path, code, width = 80, crayon = FALSE, - unicode = FALSE, env = caller_env()) { - +verify_output <- function( + path, + code, + width = 80, + crayon = FALSE, + unicode = FALSE, + env = caller_env() +) { local_reproducible_output(width = width, crayon = crayon, unicode = unicode) expr <- substitute(code) @@ -64,7 +69,6 @@ verify_output <- function(path, code, width = 80, crayon = FALSE, } verify_exec <- function(expr, env = caller_env(), replay = output_replay) { - if (is_call(expr, "{")) { exprs <- as.list(expr[-1]) } else { @@ -75,11 +79,15 @@ verify_exec <- function(expr, env = caller_env(), replay = output_replay) { withr::local_pdf(device_path) grDevices::dev.control(displaylist = "enable") - exprs <- lapply(exprs, function(x) if (is.character(x)) paste0("# ", x) else expr_deparse(x)) + exprs <- lapply(exprs, function(x) { + if (is.character(x)) paste0("# ", x) else expr_deparse(x) + }) source <- unlist(exprs, recursive = FALSE) handler <- evaluate::new_output_handler(value = testthat_print) - results <- evaluate::evaluate(source, envir = env, + results <- evaluate::evaluate( + source, + envir = env, new_device = FALSE, output_handler = handler ) diff --git a/R/watcher.R b/R/watcher.R index e48d0c864..27d765ad5 100644 --- a/R/watcher.R +++ b/R/watcher.R @@ -28,7 +28,9 @@ watch <- function(path, callback, pattern = NULL, hash = TRUE) { if (changes$n > 0) { # cat("C") keep_going <- TRUE - try(keep_going <- callback(changes$added, changes$deleted, changes$modified)) + try( + keep_going <- callback(changes$added, changes$deleted, changes$modified) + ) if (!isTRUE(keep_going)) return(invisible()) } else { @@ -40,9 +42,15 @@ watch <- function(path, callback, pattern = NULL, hash = TRUE) { } safe_digest <- function(path) { - if (!file.exists(path)) return(NA_character_) - if (is_directory(path)) return(NA_character_) - if (!is_readable(path)) return(NA_character_) + if (!file.exists(path)) { + return(NA_character_) + } + if (is_directory(path)) { + return(NA_character_) + } + if (!is_readable(path)) { + return(NA_character_) + } rlang::hash_file(path) } diff --git a/air.toml b/air.toml new file mode 100644 index 000000000..e69de29bb diff --git a/tests/testthat/_snaps/reporter-check.md b/tests/testthat/_snaps/reporter-check.md index 975349a5a..ba787c173 100644 --- a/tests/testthat/_snaps/reporter-check.md +++ b/tests/testthat/_snaps/reporter-check.md @@ -3,11 +3,11 @@ [ FAIL 4 | WARN 1 | SKIP 3 | PASS 1 ] == Skipped tests (3) =========================================================== - * empty test (2): 'reporters/tests.R:40:1', 'reporters/tests.R:45:1' + * empty test (2): 'reporters/tests.R:40:1', 'reporters/tests.R:44:1' * skip (1): 'reporters/tests.R:37:3' == Warnings ==================================================================== - -- Warning ('reporters/tests.R:47:5'): warnings get backtraces ----------------- + -- Warning ('reporters/tests.R:46:5'): warnings get backtraces ----------------- def Backtrace: x @@ -59,11 +59,11 @@ [ FAIL 4 | WARN 1 | SKIP 3 | PASS 1 ] == Skipped tests (3) =========================================================== - * empty test (2): 'reporters/tests.R:40:1', 'reporters/tests.R:45:1' + * empty test (2): 'reporters/tests.R:40:1', 'reporters/tests.R:44:1' * skip (1): 'reporters/tests.R:37:3' == Warnings ==================================================================== - -- Warning ('reporters/tests.R:47:5'): warnings get backtraces ----------------- + -- Warning ('reporters/tests.R:46:5'): warnings get backtraces ----------------- def Backtrace: x diff --git a/tests/testthat/_snaps/reporter-junit.md b/tests/testthat/_snaps/reporter-junit.md index 22d2cc782..9f373c60d 100644 --- a/tests/testthat/_snaps/reporter-junit.md +++ b/tests/testthat/_snaps/reporter-junit.md @@ -47,7 +47,7 @@ - + diff --git a/tests/testthat/_snaps/reporter-location.md b/tests/testthat/_snaps/reporter-location.md index 777058ad1..4da674543 100644 --- a/tests/testthat/_snaps/reporter-location.md +++ b/tests/testthat/_snaps/reporter-location.md @@ -29,8 +29,8 @@ End test: empty tests are implicitly skipped Start test: warnings get backtraces - 'reporters/tests.R:47:5' [warning] - 'reporters/tests.R:45:1' [skip] + 'reporters/tests.R:46:5' [warning] + 'reporters/tests.R:44:1' [skip] End test: warnings get backtraces diff --git a/tests/testthat/_snaps/reporter-progress.md b/tests/testthat/_snaps/reporter-progress.md index ebbad779a..1f9e857a3 100644 --- a/tests/testthat/_snaps/reporter-progress.md +++ b/tests/testthat/_snaps/reporter-progress.md @@ -255,14 +255,14 @@ | | 9 1 1 | reporters/backtraces x | 9 1 1 | reporters/backtraces -------------------------------------------------------------------------------- - Error ('reporters/backtraces.R:5:8'): errors thrown at block level are entraced + Error ('reporters/backtraces.R:3:8'): errors thrown at block level are entraced Error in `g()`: foo Backtrace: x 1. \-f() 2. \-g() - Error ('reporters/backtraces.R:10:10'): errors thrown from a quasi-labelled argument are entraced + Error ('reporters/backtraces.R:8:10'): errors thrown from a quasi-labelled argument are entraced Error in `foo()`: foo Backtrace: x @@ -271,7 +271,7 @@ 3. | \-rlang::eval_bare(expr, quo_get_env(quo)) 4. \-foo() - Error ('reporters/backtraces.R:15:10'): errors thrown from a quasi-labelled argument are entraced (deep case) + Error ('reporters/backtraces.R:13:10'): errors thrown from a quasi-labelled argument are entraced (deep case) Error in `foo()`: foo Backtrace: x @@ -285,7 +285,7 @@ 8. | \-rlang::eval_bare(expr, quo_get_env(quo)) 9. \-foo() - Error ('reporters/backtraces.R:23:10'): errors thrown from a quasi-labelled argument are entraced (deep deep case) + Error ('reporters/backtraces.R:21:10'): errors thrown from a quasi-labelled argument are entraced (deep deep case) Error in `bar()`: foobar Backtrace: x @@ -297,7 +297,7 @@ 6. \-foo() 7. \-bar() - Error ('reporters/backtraces.R:34:16'): failed expect_error() prints a backtrace + Error ('reporters/backtraces.R:32:16'): failed expect_error() prints a backtrace Error in `signaller()`: bar Backtrace: x @@ -310,21 +310,21 @@ 7. \-f() 8. \-signaller() - Error ('reporters/backtraces.R:43:3'): Errors are inspected with `conditionMessage()` + Error ('reporters/backtraces.R:41:3'): Errors are inspected with `conditionMessage()` Error in `eval(code, test_env)`: dispatched Backtrace: x 1. \-rlang::abort("Wrong message", "foobar") - Warning ('reporters/backtraces.R:48:10'): also get backtraces for warnings + Warning ('reporters/backtraces.R:46:10'): also get backtraces for warnings foobar Backtrace: x 1. \-foo() 2. \-bar() - Error ('reporters/backtraces.R:56:5'): deep stacks are shown + Error ('reporters/backtraces.R:54:5'): deep stacks are shown Error in `f(x - 1)`: This is deep Backtrace: x @@ -355,7 +355,7 @@ 25. \-f(x - 1) 26. \-f(x - 1) - Failure ('reporters/backtraces.R:64:6'): (code run outside of `test_that()`) + Failure ('reporters/backtraces.R:62:6'): (code run outside of `test_that()`) FALSE is not TRUE `actual`: FALSE @@ -367,7 +367,7 @@ 3. \-h() 4. \-testthat::expect_true(FALSE) - Failure ('reporters/backtraces.R:69:3'): nested expectations get backtraces + Failure ('reporters/backtraces.R:67:3'): nested expectations get backtraces FALSE is not TRUE `actual`: FALSE @@ -382,14 +382,14 @@ == Results ===================================================================== -- Failed tests ---------------------------------------------------------------- - Error ('reporters/backtraces.R:5:8'): errors thrown at block level are entraced + Error ('reporters/backtraces.R:3:8'): errors thrown at block level are entraced Error in `g()`: foo Backtrace: x 1. \-f() 2. \-g() - Error ('reporters/backtraces.R:10:10'): errors thrown from a quasi-labelled argument are entraced + Error ('reporters/backtraces.R:8:10'): errors thrown from a quasi-labelled argument are entraced Error in `foo()`: foo Backtrace: x @@ -398,7 +398,7 @@ 3. | \-rlang::eval_bare(expr, quo_get_env(quo)) 4. \-foo() - Error ('reporters/backtraces.R:15:10'): errors thrown from a quasi-labelled argument are entraced (deep case) + Error ('reporters/backtraces.R:13:10'): errors thrown from a quasi-labelled argument are entraced (deep case) Error in `foo()`: foo Backtrace: x @@ -412,7 +412,7 @@ 8. | \-rlang::eval_bare(expr, quo_get_env(quo)) 9. \-foo() - Error ('reporters/backtraces.R:23:10'): errors thrown from a quasi-labelled argument are entraced (deep deep case) + Error ('reporters/backtraces.R:21:10'): errors thrown from a quasi-labelled argument are entraced (deep deep case) Error in `bar()`: foobar Backtrace: x @@ -424,7 +424,7 @@ 6. \-foo() 7. \-bar() - Error ('reporters/backtraces.R:34:16'): failed expect_error() prints a backtrace + Error ('reporters/backtraces.R:32:16'): failed expect_error() prints a backtrace Error in `signaller()`: bar Backtrace: x @@ -437,14 +437,14 @@ 7. \-f() 8. \-signaller() - Error ('reporters/backtraces.R:43:3'): Errors are inspected with `conditionMessage()` + Error ('reporters/backtraces.R:41:3'): Errors are inspected with `conditionMessage()` Error in `eval(code, test_env)`: dispatched Backtrace: x 1. \-rlang::abort("Wrong message", "foobar") - Error ('reporters/backtraces.R:56:5'): deep stacks are shown + Error ('reporters/backtraces.R:54:5'): deep stacks are shown Error in `f(x - 1)`: This is deep Backtrace: x @@ -475,7 +475,7 @@ 25. \-f(x - 1) 26. \-f(x - 1) - Failure ('reporters/backtraces.R:64:6'): (code run outside of `test_that()`) + Failure ('reporters/backtraces.R:62:6'): (code run outside of `test_that()`) FALSE is not TRUE `actual`: FALSE @@ -487,7 +487,7 @@ 3. \-h() 4. \-testthat::expect_true(FALSE) - Failure ('reporters/backtraces.R:69:3'): nested expectations get backtraces + Failure ('reporters/backtraces.R:67:3'): nested expectations get backtraces FALSE is not TRUE `actual`: FALSE @@ -571,14 +571,14 @@ [ FAIL 4 | WARN 1 | SKIP 2 | PASS 1 ] [ FAIL 4 | WARN 1 | SKIP 3 | PASS 1 ] - -- Warning ('reporters/tests.R:47:5'): warnings get backtraces ----------------- + -- Warning ('reporters/tests.R:46:5'): warnings get backtraces ----------------- def Backtrace: x 1. \-f() -- Skipped tests (3) ----------------------------------------------------------- - * empty test (2): 'reporters/tests.R:40:1', 'reporters/tests.R:45:1' + * empty test (2): 'reporters/tests.R:40:1', 'reporters/tests.R:44:1' * skip (1): 'reporters/tests.R:37:3' diff --git a/tests/testthat/_snaps/reporter-rstudio.md b/tests/testthat/_snaps/reporter-rstudio.md index 3f45d1378..0c9b6bb08 100644 --- a/tests/testthat/_snaps/reporter-rstudio.md +++ b/tests/testthat/_snaps/reporter-rstudio.md @@ -6,6 +6,6 @@ 'reporters/tests.R:29:8' [error] errors get tracebacks. Error in `h()`: ! 'reporters/tests.R:37:3' [skip] explicit skips are reported. Reason: skip 'reporters/tests.R:40:1' [skip] empty tests are implicitly skipped. Reason: empty test - 'reporters/tests.R:47:5' [warning] warnings get backtraces. def - 'reporters/tests.R:45:1' [skip] warnings get backtraces. Reason: empty test + 'reporters/tests.R:46:5' [warning] warnings get backtraces. def + 'reporters/tests.R:44:1' [skip] warnings get backtraces. Reason: empty test diff --git a/tests/testthat/_snaps/reporter-stop.md b/tests/testthat/_snaps/reporter-stop.md index ebfef1ec8..57385cc9b 100644 --- a/tests/testthat/_snaps/reporter-stop.md +++ b/tests/testthat/_snaps/reporter-stop.md @@ -34,13 +34,13 @@ -- Skip ('reporters/tests.R:40:1'): empty tests are implicitly skipped --------- Reason: empty test - -- Warning ('reporters/tests.R:47:5'): warnings get backtraces ----------------- + -- Warning ('reporters/tests.R:46:5'): warnings get backtraces ----------------- def Backtrace: x 1. \-f() - -- Skip ('reporters/tests.R:45:1'): warnings get backtraces -------------------- + -- Skip ('reporters/tests.R:44:1'): warnings get backtraces -------------------- Reason: empty test diff --git a/tests/testthat/_snaps/reporter-summary.md b/tests/testthat/_snaps/reporter-summary.md index 836c196e6..41f44e8c9 100644 --- a/tests/testthat/_snaps/reporter-summary.md +++ b/tests/testthat/_snaps/reporter-summary.md @@ -12,10 +12,10 @@ 2. empty tests are implicitly skipped ('reporters/tests.R:40:1') - Reason: empty test - 3. warnings get backtraces ('reporters/tests.R:45:1') - Reason: empty test + 3. warnings get backtraces ('reporters/tests.R:44:1') - Reason: empty test == Warnings ==================================================================== - 1. warnings get backtraces ('reporters/tests.R:47:5') - def + 1. warnings get backtraces ('reporters/tests.R:46:5') - def == Failed ====================================================================== -- 1. Failure ('reporters/tests.R:12:3'): Failure:1 ---------------------------- @@ -61,10 +61,10 @@ 2. empty tests are implicitly skipped ('reporters/tests.R:40:1') - Reason: empty test - 3. warnings get backtraces ('reporters/tests.R:45:1') - Reason: empty test + 3. warnings get backtraces ('reporters/tests.R:44:1') - Reason: empty test == Warnings ==================================================================== - 1. warnings get backtraces ('reporters/tests.R:47:5') - def + 1. warnings get backtraces ('reporters/tests.R:46:5') - def == Failed ====================================================================== -- 1. Failure ('reporters/tests.R:12:3'): Failure:1 ---------------------------- @@ -110,10 +110,10 @@ 2. empty tests are implicitly skipped ('reporters/tests.R:40:1') - Reason: empty test - 3. warnings get backtraces ('reporters/tests.R:45:1') - Reason: empty test + 3. warnings get backtraces ('reporters/tests.R:44:1') - Reason: empty test == Warnings ==================================================================== - 1. warnings get backtraces ('reporters/tests.R:47:5') - def + 1. warnings get backtraces ('reporters/tests.R:46:5') - def == Failed ====================================================================== -- 1. Failure ('reporters/tests.R:12:3'): Failure:1 ---------------------------- diff --git a/tests/testthat/reporters/backtraces.R b/tests/testthat/reporters/backtraces.R index fa0cf27fe..4305e2676 100644 --- a/tests/testthat/reporters/backtraces.R +++ b/tests/testthat/reporters/backtraces.R @@ -1,5 +1,3 @@ - - test_that("errors thrown at block level are entraced", { f <- function() g() g <- function() stop("foo") diff --git a/tests/testthat/reporters/fail.R b/tests/testthat/reporters/fail.R index 26b6143ae..8e3ab8310 100644 --- a/tests/testthat/reporters/fail.R +++ b/tests/testthat/reporters/fail.R @@ -1,5 +1,3 @@ - - test_that("two failures", { expect_true(FALSE) expect_false(TRUE) diff --git a/tests/testthat/reporters/tests.R b/tests/testthat/reporters/tests.R index f8c3e0de0..45c2e8b88 100644 --- a/tests/testthat/reporters/tests.R +++ b/tests/testthat/reporters/tests.R @@ -37,8 +37,7 @@ test_that("explicit skips are reported", { skip("skip") }) -test_that("empty tests are implicitly skipped", { -}) +test_that("empty tests are implicitly skipped", {}) context("Warnings") diff --git a/tests/testthat/test-browser.R b/tests/testthat/test-browser.R index 0b14b3b6b..507af7b58 100644 --- a/tests/testthat/test-browser.R +++ b/tests/testthat/test-browser.R @@ -1,6 +1,6 @@ - test_that("browser() usages are errors in tests", { skip_if(getRversion() < "4.3.0") - if (!interactive()) + if (!interactive()) { expect_error(browser()) + } }) diff --git a/tests/testthat/test-compare.R b/tests/testthat/test-compare.R index 1d9f237bb..bfa4f79a1 100644 --- a/tests/testthat/test-compare.R +++ b/tests/testthat/test-compare.R @@ -10,7 +10,7 @@ test_that("list comparison truncates to max_diffs", { }) test_that("no diff", { - expect_equal(compare(1,1), no_difference()) + expect_equal(compare(1, 1), no_difference()) }) test_that("vector_equal_tol handles infinity", { @@ -102,7 +102,6 @@ test_that("vectors longer than `max_diffs` (#513)", { # numeric ------------------------------------------------------------------ - test_that("numeric types are compatible", { expect_true(compare(1, 1L)$equal) expect_true(compare(1L, 1)$equal) @@ -183,7 +182,10 @@ test_that("both POSIXt classes are compatible", { }) test_that("other classes are not", { - expect_match(compare(Sys.time(), 1)$message, "'POSIXct'/'POSIXt' is not 'numeric'") + expect_match( + compare(Sys.time(), 1)$message, + "'POSIXct'/'POSIXt' is not 'numeric'" + ) }) test_that("base lengths must be identical", { diff --git a/tests/testthat/test-context.R b/tests/testthat/test-context.R index 375596963..239d9cb1c 100644 --- a/tests/testthat/test-context.R +++ b/tests/testthat/test-context.R @@ -1,4 +1,5 @@ -CountReporter <- R6::R6Class("CountReporter", +CountReporter <- R6::R6Class( + "CountReporter", inherit = Reporter, public = list( context_i = 0, @@ -37,8 +38,8 @@ test_that("contexts are opened, then closed", { }) test_that("context_name strips prefix and extensions correctly", { - expect_equal(context_name("test-metrics.R"), "metrics") # uppercase - expect_equal(context_name("test-metrics.r"), "metrics") # lowercase + expect_equal(context_name("test-metrics.R"), "metrics") # uppercase + expect_equal(context_name("test-metrics.r"), "metrics") # lowercase expect_equal(context_name("test-check.Rfile.R"), "check.Rfile") # suffix only expect_equal(context_name("test-test-test.R"), "test-test") # 1st prefix only expect_equal(context_name("test_metrics.R"), "metrics") diff --git a/tests/testthat/test-edition.R b/tests/testthat/test-edition.R index 9e3810fc2..24556f7e8 100644 --- a/tests/testthat/test-edition.R +++ b/tests/testthat/test-edition.R @@ -42,7 +42,7 @@ test_that("edition for non-package dir is 2", { test_that("can set the edition via an environment variable", { local_bindings(edition = zap(), .env = the) - + withr::local_envvar(TESTTHAT_EDITION = 2) expect_equal(edition_get(), 2) diff --git a/tests/testthat/test-expect-condition.R b/tests/testthat/test-expect-condition.R index 858528819..4ac6f83d0 100644 --- a/tests/testthat/test-expect-condition.R +++ b/tests/testthat/test-expect-condition.R @@ -186,14 +186,29 @@ test_that("cnd expectations consistently return condition (#1371)", { expect_s3_class(expect_error(f(NULL, stop(""))), "simpleError") # Used to behave differently with non-`NULL` values - expect_s3_class(expect_message(f("return value", message(""))), "simpleMessage") - expect_s3_class(expect_warning(f("return value", warning(""))), "simpleWarning") + expect_s3_class( + expect_message(f("return value", message(""))), + "simpleMessage" + ) + expect_s3_class( + expect_warning(f("return value", warning(""))), + "simpleWarning" + ) expect_s3_class(expect_error(f("return value", stop(""))), "simpleError") # If there is no condition expected we return the value - expect_equal(expect_message(f("return value", NULL), regexp = NA), "return value") - expect_equal(expect_warning(f("return value", NULL), regexp = NA), "return value") - expect_equal(expect_error(f("return value", NULL), regexp = NA), "return value") + expect_equal( + expect_message(f("return value", NULL), regexp = NA), + "return value" + ) + expect_equal( + expect_warning(f("return value", NULL), regexp = NA), + "return value" + ) + expect_equal( + expect_error(f("return value", NULL), regexp = NA), + "return value" + ) }) test_that("cli width wrapping doesn't affect text matching", { @@ -203,7 +218,9 @@ test_that("cli width wrapping doesn't affect text matching", { local_use_cli() expect_error( - abort("foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz"), + abort( + "foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz" + ), "foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz foobarbaz" ) }) @@ -237,7 +254,8 @@ test_that("other conditions are swallowed", { f <- function(...) { conds <- c(...) for (cond in conds) { - switch(cond, + switch( + cond, message = message("message"), warning = warning("warning"), error = stop("error"), diff --git a/tests/testthat/test-expect-equality.R b/tests/testthat/test-expect-equality.R index 1650f1ef4..2176a0b4b 100644 --- a/tests/testthat/test-expect-equality.R +++ b/tests/testthat/test-expect-equality.R @@ -42,7 +42,7 @@ test_that("can control numeric tolerance", { expect_failure(expect_equal(x1, x2)) expect_success(expect_equal(x1, x2, tolerance = 1e-5)) expect_success(expect_equivalent(x1, x2, tolerance = 1e-5)) - + # with partial matching withr::local_options(warnPartialMatchArgs = FALSE) expect_success(expect_equal(x1, x2, tol = 1e-5)) @@ -78,7 +78,7 @@ test_that("default labels use unquoting", { local_edition(2) x <- 2 - expect_failure(expect_equal(1, !! x), "1 not equal to 2", fixed = TRUE) + expect_failure(expect_equal(1, !!x), "1 not equal to 2", fixed = TRUE) }) test_that("% is not treated as sprintf format specifier (#445)", { @@ -90,17 +90,21 @@ test_that("% is not treated as sprintf format specifier (#445)", { test_that("is_call_infix() handles complex calls (#1472)", { expect_false(is_call_infix(quote( base::any( - c(veryyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy_long_name = TRUE), + c( + veryyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy_long_name = TRUE + ), na.rm = TRUE ) ))) withr::local_envvar( "_R_CHECK_LENGTH_1_LOGIC2_" = "TRUE", - ) + ) expect_true( base::any( - c(veryyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy_long_name = TRUE), + c( + veryyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy_long_name = TRUE + ), na.rm = TRUE ) ) diff --git a/tests/testthat/test-expect-inheritance.R b/tests/testthat/test-expect-inheritance.R index e3f114bc6..f24abc0c6 100644 --- a/tests/testthat/test-expect-inheritance.R +++ b/tests/testthat/test-expect-inheritance.R @@ -58,14 +58,14 @@ test_that("test_s3_class can request exact match", { test_that("expect_s3_class allows unquoting of first argument", { f <- factor("a") - expect_success(expect_s3_class(!! rlang::quo(f), "factor")) + expect_success(expect_s3_class(!!rlang::quo(f), "factor")) }) test_that("expect_s4_class allows unquoting of first argument", { cls <- methods::setClass("new_class", slots = c("a" = "numeric")) obj <- methods::new("new_class", a = 3) - expect_success(expect_s4_class(!! rlang::quo(obj), "new_class")) + expect_success(expect_s4_class(!!rlang::quo(obj), "new_class")) }) # expect_s7_class -------------------------------------------------------- diff --git a/tests/testthat/test-expect-invisible.R b/tests/testthat/test-expect-invisible.R index 5c105824d..b2b0a2c81 100644 --- a/tests/testthat/test-expect-invisible.R +++ b/tests/testthat/test-expect-invisible.R @@ -7,10 +7,8 @@ test_that("basic principles of visibility hold", { }) test_that("generates useful failure messages", { - expect_snapshot_failure(expect_visible(invisible(1))) expect_snapshot_failure(expect_invisible(1)) - }) test_that("invisibly returns evaluated value", { diff --git a/tests/testthat/test-expect-known.R b/tests/testthat/test-expect-known.R index e37e247bb..3f11e801e 100644 --- a/tests/testthat/test-expect-known.R +++ b/tests/testthat/test-expect-known.R @@ -67,7 +67,6 @@ test_that("Warning for non-UTF-8 reference files", { # expect_known_value ------------------------------------------------------ - test_that("correctly matches to a file", { x <- 1 expect_success(expect_known_value(x, "one.rds")) @@ -87,7 +86,7 @@ test_that("first run is successful", { }) test_that("equal_to_ref does not overwrite existing", { - tmp_rds <- tempfile(fileext=".rds") + tmp_rds <- tempfile(fileext = ".rds") on.exit(unlink(tmp_rds)) ref_obj1 <- 1:3 ref_obj2 <- 2:4 @@ -100,7 +99,7 @@ test_that("equal_to_ref does not overwrite existing", { expect_equal(readRDS(tmp_rds), ref_obj1) # Now failure does update object - expect_failure(expect_equal_to_reference(ref_obj2, tmp_rds, update=TRUE)) + expect_failure(expect_equal_to_reference(ref_obj2, tmp_rds, update = TRUE)) expect_success(expect_equal_to_reference(ref_obj2, tmp_rds)) }) diff --git a/tests/testthat/test-expect-match.R b/tests/testthat/test-expect-match.R index 1c930d212..2a28d3911 100644 --- a/tests/testthat/test-expect-match.R +++ b/tests/testthat/test-expect-match.R @@ -4,8 +4,14 @@ test_that("extra arguments to matches passed onto grepl", { }) test_that("special regex characters are escaped in output", { - error <- tryCatch(expect_match("f() test", "f() test"), expectation = function(e) e$message) - expect_equal(error, "\"f\\(\\) test\" does not match \"f() test\".\nActual value: \"f\\(\\) test\"") + error <- tryCatch( + expect_match("f() test", "f() test"), + expectation = function(e) e$message + ) + expect_equal( + error, + "\"f\\(\\) test\" does not match \"f() test\".\nActual value: \"f\\(\\) test\"" + ) }) test_that("correct reporting of expected label", { @@ -33,6 +39,9 @@ test_that("prints multiple unmatched values", { test_that("expect_no_match works", { expect_success(expect_no_match("[a]", "[b]")) expect_success(expect_no_match("[a]", "[b]", fixed = TRUE)) - expect_failure(expect_no_match("te*st", "e*", fixed = TRUE), escape_regex("te*st")) + expect_failure( + expect_no_match("te*st", "e*", fixed = TRUE), + escape_regex("te*st") + ) expect_failure(expect_no_match("test", "TEST", ignore.case = TRUE), "test") }) diff --git a/tests/testthat/test-expect-named.R b/tests/testthat/test-expect-named.R index 3b10b670e..68da9a63d 100644 --- a/tests/testthat/test-expect-named.R +++ b/tests/testthat/test-expect-named.R @@ -13,5 +13,9 @@ test_that("expected_named optionally ignores case", { }) test_that("expected_named optionally ignores order", { - expect_success(expect_named(c(a = 1, b = 2), c("b", "a"), ignore.order = TRUE)) + expect_success(expect_named( + c(a = 1, b = 2), + c("b", "a"), + ignore.order = TRUE + )) }) diff --git a/tests/testthat/test-expect-no-condition.R b/tests/testthat/test-expect-no-condition.R index 22a59fbbc..8d39676e9 100644 --- a/tests/testthat/test-expect-no-condition.R +++ b/tests/testthat/test-expect-no-condition.R @@ -1,6 +1,4 @@ - test_that("expect_no_* conditions behave as expected", { - # base R expect_snapshot_failure(expect_no_error(stop("error"))) expect_snapshot_failure(expect_no_warning(warning("warning"))) @@ -15,7 +13,7 @@ test_that("expect_no_* conditions behave as expected", { test_that("expect_no_* pass with pure code", { expect_success(out <- expect_no_error(1)) expect_equal(out, 1) - + expect_success(expect_no_warning(1)) expect_success(expect_no_message(1)) expect_success(expect_no_condition(1)) @@ -27,15 +25,30 @@ test_that("expect_no_* don't emit success when they fail", { test_that("capture correct trace_env (#1994)", { # This should fail, not error - expect_failure(expect_message({message("a"); warn("b")}) |> expect_no_warning()) - expect_failure(expect_no_message({message("a"); warn("b")}) |> expect_warning()) + expect_failure( + expect_message({ + message("a") + warn("b") + }) |> + expect_no_warning() + ) + expect_failure( + expect_no_message({ + message("a") + warn("b") + }) |> + expect_warning() + ) }) test_that("unmatched conditions bubble up", { expect_error(expect_no_error(abort("foo"), message = "bar"), "foo") expect_warning(expect_no_warning(warn("foo"), message = "bar"), "foo") expect_message(expect_no_message(inform("foo"), message = "bar"), "foo") - expect_condition(expect_no_condition(signal("foo", "x"), message = "bar"), "foo") + expect_condition( + expect_no_condition(signal("foo", "x"), message = "bar"), + "foo" + ) }) test_that("only matches conditions of specified type", { diff --git a/tests/testthat/test-expect-setequal.R b/tests/testthat/test-expect-setequal.R index 9def76c0e..96c8ae569 100644 --- a/tests/testthat/test-expect-setequal.R +++ b/tests/testthat/test-expect-setequal.R @@ -53,7 +53,10 @@ test_that("ignores order", { test_that("error if any names are duplicated", { expect_error(expect_mapequal(list(a = 1, b = 2, b = 3), list(b = 2, a = 1))) expect_error(expect_mapequal(list(a = 1, b = 2), list(b = 3, b = 2, a = 1))) - expect_error(expect_mapequal(list(a = 1, b = 2, b = 3), list(b = 3, b = 2, a = 1))) + expect_error(expect_mapequal( + list(a = 1, b = 2, b = 3), + list(b = 3, b = 2, a = 1) + )) }) test_that("handling NULLs", { diff --git a/tests/testthat/test-expectation.R b/tests/testthat/test-expectation.R index 00e4c3149..37c0976d8 100644 --- a/tests/testthat/test-expectation.R +++ b/tests/testthat/test-expectation.R @@ -12,8 +12,16 @@ test_that("info only evaluated on failure", { }) test_that("can subclass expectation", { - exp <- new_expectation("failure", "didn't work", .subclass = "foo", bar = "baz") - expect_true(inherits_all(exp, c("foo", "expectation_failure", "expectation", "error", "condition"))) + exp <- new_expectation( + "failure", + "didn't work", + .subclass = "foo", + bar = "baz" + ) + expect_true(inherits_all( + exp, + c("foo", "expectation_failure", "expectation", "error", "condition") + )) expect_identical(attr(exp, "bar"), "baz") }) @@ -22,7 +30,10 @@ test_that("`expect()` and `exp_signal()` signal expectations", { expect_error(expect(FALSE, ""), class = "expectation_failure") expect_error(exp_signal(new_expectation("success", "")), regexp = NA) - expect_error(exp_signal(new_expectation("failure", "")), class = "expectation_failure") + expect_error( + exp_signal(new_expectation("failure", "")), + class = "expectation_failure" + ) }) test_that("conditionMessage() is called during conversion", { diff --git a/tests/testthat/test-make-expectation.R b/tests/testthat/test-make-expectation.R index 1b35dd0c8..ad0469e01 100644 --- a/tests/testthat/test-make-expectation.R +++ b/tests/testthat/test-make-expectation.R @@ -1,5 +1,4 @@ test_that("make_expectation returns and prints expectation", { - x <- 1:5 out <- capture_output( expect_equal(make_expectation(x), bquote(expect_equal(x, .(1:5)))) diff --git a/tests/testthat/test-mock2-helpers.R b/tests/testthat/test-mock2-helpers.R index 342cf9de2..c14c8346c 100644 --- a/tests/testthat/test-mock2-helpers.R +++ b/tests/testthat/test-mock2-helpers.R @@ -16,7 +16,9 @@ test_that("mock_output_sequence() works -- list", { test_that("mock_output_sequence()'s recycling works", { mocked_sequence <- mock_output_sequence( - "3", "This is a note", "n", + "3", + "This is a note", + "n", recycle = TRUE ) expect_equal(mocked_sequence(), "3") @@ -26,4 +28,3 @@ test_that("mock_output_sequence()'s recycling works", { expect_equal(mocked_sequence(), "This is a note") expect_equal(mocked_sequence(), "n") }) - diff --git a/tests/testthat/test-old-school.R b/tests/testthat/test-old-school.R index f746a0a3e..445ed086e 100644 --- a/tests/testthat/test-old-school.R +++ b/tests/testthat/test-old-school.R @@ -1,14 +1,15 @@ - test_that("old school logical works", { local_edition(2L) expect_warning( expect_success(expect_that(TRUE, is_true())), - "deprecated") + "deprecated" + ) expect_warning( expect_success(expect_that(FALSE, is_false())), - "deprecated") + "deprecated" + ) }) test_that("old school types still work", { diff --git a/tests/testthat/test-parallel-crash.R b/tests/testthat/test-parallel-crash.R index d6a1f0268..5e9794c07 100644 --- a/tests/testthat/test-parallel-crash.R +++ b/tests/testthat/test-parallel-crash.R @@ -6,12 +6,19 @@ test_that("crash", { withr::local_envvar(TESTTHAT_PARALLEL = "TRUE") pkg <- test_path("test-parallel", "crash") - err <- callr::r(function() { - tryCatch( - testthat::test_local(".", reporter = "summary", stop_on_failure = FALSE), - error = function(e) e - ) - }, wd = pkg) + err <- callr::r( + function() { + tryCatch( + testthat::test_local( + ".", + reporter = "summary", + stop_on_failure = FALSE + ), + error = function(e) e + ) + }, + wd = pkg + ) expect_s3_class(err, "testthat_process_error") expect_equal(err$test_file, "test-crash-3.R") }) diff --git a/tests/testthat/test-parallel-outside.R b/tests/testthat/test-parallel-outside.R index a2b7c396c..180b25487 100644 --- a/tests/testthat/test-parallel-outside.R +++ b/tests/testthat/test-parallel-outside.R @@ -1,4 +1,3 @@ - test_that("error outside of test_that()", { withr::local_envvar(TESTTHAT_PARALLEL = "TRUE") err <- tryCatch( diff --git a/tests/testthat/test-parallel-setup.R b/tests/testthat/test-parallel-setup.R index 3136302a0..f8bfdefb6 100644 --- a/tests/testthat/test-parallel-setup.R +++ b/tests/testthat/test-parallel-setup.R @@ -1,4 +1,3 @@ - test_that("error in parallel setup code", { skip_on_covr() withr::local_envvar(TESTTHAT_PARALLEL = "TRUE") diff --git a/tests/testthat/test-parallel-startup.R b/tests/testthat/test-parallel-startup.R index 108bb6a77..b2ea8a8f6 100644 --- a/tests/testthat/test-parallel-startup.R +++ b/tests/testthat/test-parallel-startup.R @@ -1,4 +1,3 @@ - test_that("startup error", { skip_on_covr() withr::local_envvar(TESTTHAT_PARALLEL = "TRUE") diff --git a/tests/testthat/test-parallel-teardown.R b/tests/testthat/test-parallel-teardown.R index 0df0a8aee..b3a2dd765 100644 --- a/tests/testthat/test-parallel-teardown.R +++ b/tests/testthat/test-parallel-teardown.R @@ -1,4 +1,3 @@ - test_that("teardown error", { skip("teardown errors are ignored") withr::local_envvar(TESTTHAT_PARALLEL = "TRUE") diff --git a/tests/testthat/test-parallel.R b/tests/testthat/test-parallel.R index f9c1bf1cd..7b3c344f0 100644 --- a/tests/testthat/test-parallel.R +++ b/tests/testthat/test-parallel.R @@ -1,6 +1,4 @@ - test_that("detect number of cpus to use", { - withr::local_options(Ncpus = 100L) withr::local_envvar(TESTTHAT_CPUS = NA) expect_equal(default_num_cpus(), 100L) @@ -26,14 +24,16 @@ test_that("ok", { withr::local_envvar(c(TESTTHAT_PARALLEL = "TRUE")) # we cannot run these with the silent reporter, because it is not # parallel compatible, and they'll not run in parallel - capture.output(suppressMessages(ret <- test_local( - test_path("test-parallel", "ok"), - reporter = "summary", - stop_on_failure = FALSE - ))) + capture.output(suppressMessages( + ret <- test_local( + test_path("test-parallel", "ok"), + reporter = "summary", + stop_on_failure = FALSE + ) + )) tdf <- as.data.frame(ret) tdf <- tdf[order(tdf$file), ] - expect_equal(tdf$failed, c(0,1,0)) + expect_equal(tdf$failed, c(0, 1, 0)) expect_equal(tdf$skipped, c(FALSE, FALSE, TRUE)) }) @@ -41,11 +41,13 @@ test_that("fail", { withr::local_envvar(c(TESTTHAT_PARALLEL = "TRUE")) # we cannot run these with the silent reporter, because it is not # parallel compatible, and they'll not run in parallel - capture.output(suppressMessages(ret <- test_local( - test_path("test-parallel", "fail"), - reporter = "summary", - stop_on_failure = FALSE - ))) + capture.output(suppressMessages( + ret <- test_local( + test_path("test-parallel", "fail"), + reporter = "summary", + stop_on_failure = FALSE + ) + )) tdf <- as.data.frame(ret) tdf <- tdf[order(tdf$file), ] expect_equal(tdf$failed, c(1)) @@ -58,14 +60,16 @@ test_that("snapshots", { file.copy(test_path("test-parallel", "snap"), tmp, recursive = TRUE) # we cannot run these with the silent reporter, because it is not # parallel compatible, and they'll not run in parallel - capture.output(suppressMessages(ret <- test_local( - file.path(tmp, "snap"), - reporter = "summary", - stop_on_failure = FALSE - ))) + capture.output(suppressMessages( + ret <- test_local( + file.path(tmp, "snap"), + reporter = "summary", + stop_on_failure = FALSE + ) + )) tdf <- as.data.frame(ret) tdf <- tdf[order(tdf$file), ] - expect_equal(tdf$failed, c(0,0,1)) + expect_equal(tdf$failed, c(0, 0, 1)) snaps <- file.path(tmp, "snap", "tests", "testthat", "_snaps") expect_true(file.exists(file.path(snaps, "snap-1.md"))) expect_true(file.exists(file.path(snaps, "snap-2.md"))) @@ -80,14 +84,16 @@ test_that("new snapshots are added", { unlink(file.path(tmp, "snap", "tests", "testthat", "_snaps", "snap-2.md")) # we cannot run these with the silent reporter, because it is not # parallel compatible, and they'll not run in parallel - capture.output(suppressMessages(ret <- test_local( - file.path(tmp, "snap"), - reporter = "summary", - stop_on_failure = FALSE - ))) + capture.output(suppressMessages( + ret <- test_local( + file.path(tmp, "snap"), + reporter = "summary", + stop_on_failure = FALSE + ) + )) tdf <- as.data.frame(ret) tdf <- tdf[order(tdf$file), ] - expect_equal(tdf$failed, c(0,0,1)) + expect_equal(tdf$failed, c(0, 0, 1)) snaps <- file.path(tmp, "snap", "tests", "testthat", "_snaps") expect_true(file.exists(file.path(snaps, "snap-1.md"))) expect_true(file.exists(file.path(snaps, "snap-2.md"))) @@ -105,14 +111,16 @@ test_that("snapshots are removed if test file has no snapshots", { ) # we cannot run these with the silent reporter, because it is not # parallel compatible, and they'll not run in parallel - capture.output(suppressMessages(ret <- test_local( - file.path(tmp, "snap"), - reporter = "summary", - stop_on_failure = FALSE - ))) + capture.output(suppressMessages( + ret <- test_local( + file.path(tmp, "snap"), + reporter = "summary", + stop_on_failure = FALSE + ) + )) tdf <- as.data.frame(ret) tdf <- tdf[order(tdf$file), ] - expect_equal(tdf$failed, c(0,0,1)) + expect_equal(tdf$failed, c(0, 0, 1)) snaps <- file.path(tmp, "snap", "tests", "testthat", "_snaps") expect_true(file.exists(file.path(snaps, "snap-1.md"))) expect_false(file.exists(file.path(snaps, "snap-2.md"))) @@ -128,14 +136,16 @@ test_that("snapshots are removed if test file is removed", { withr::local_envvar(CI = NA_character_) # we cannot run these with the silent reporter, because it is not # parallel compatible, and they'll not run in parallel - capture.output(suppressMessages(ret <- test_local( - file.path(tmp, "snap"), - reporter = "summary", - stop_on_failure = FALSE - ))) + capture.output(suppressMessages( + ret <- test_local( + file.path(tmp, "snap"), + reporter = "summary", + stop_on_failure = FALSE + ) + )) tdf <- as.data.frame(ret) tdf <- tdf[order(tdf$file), ] - expect_equal(tdf$failed, c(0,1)) + expect_equal(tdf$failed, c(0, 1)) snaps <- file.path(tmp, "snap", "tests", "testthat", "_snaps") expect_true(file.exists(file.path(snaps, "snap-1.md"))) expect_false(file.exists(file.path(snaps, "snap-2.md"))) diff --git a/tests/testthat/test-parallel/fail/tests/testthat/test-bad.R b/tests/testthat/test-parallel/fail/tests/testthat/test-bad.R index 5a659b4de..de4a4a0a7 100644 --- a/tests/testthat/test-parallel/fail/tests/testthat/test-bad.R +++ b/tests/testthat/test-parallel/fail/tests/testthat/test-bad.R @@ -1,4 +1,3 @@ - test_that("bad test", { expect_true(FALSE) }) diff --git a/tests/testthat/test-parallel/outside/tests/testthat/test-outside-2.R b/tests/testthat/test-parallel/outside/tests/testthat/test-outside-2.R index cccfaaf83..e165bd18e 100644 --- a/tests/testthat/test-parallel/outside/tests/testthat/test-outside-2.R +++ b/tests/testthat/test-parallel/outside/tests/testthat/test-outside-2.R @@ -1,4 +1,3 @@ - stop("Error outside of test_that()") test_that("this fails", { diff --git a/tests/testthat/test-parallel/setup/tests/testthat/setup-bad.R b/tests/testthat/test-parallel/setup/tests/testthat/setup-bad.R index 7b91e28a0..6cb456265 100644 --- a/tests/testthat/test-parallel/setup/tests/testthat/setup-bad.R +++ b/tests/testthat/test-parallel/setup/tests/testthat/setup-bad.R @@ -1,2 +1 @@ - stop("Error in setup") diff --git a/tests/testthat/test-parallel/snap/tests/testthat/test-snap-1.R b/tests/testthat/test-parallel/snap/tests/testthat/test-snap-1.R index 83c4867e4..2e580ced5 100644 --- a/tests/testthat/test-parallel/snap/tests/testthat/test-snap-1.R +++ b/tests/testthat/test-parallel/snap/tests/testthat/test-snap-1.R @@ -1,4 +1,3 @@ - test_that("snapshot", { expect_snapshot(1:10) }) diff --git a/tests/testthat/test-parallel/snap/tests/testthat/test-snap-2.R b/tests/testthat/test-parallel/snap/tests/testthat/test-snap-2.R index 4ef3d00cf..ab91db72b 100644 --- a/tests/testthat/test-parallel/snap/tests/testthat/test-snap-2.R +++ b/tests/testthat/test-parallel/snap/tests/testthat/test-snap-2.R @@ -1,4 +1,3 @@ - test_that("snapshot", { expect_snapshot(11:20) }) diff --git a/tests/testthat/test-parallel/snap/tests/testthat/test-snap-3.R b/tests/testthat/test-parallel/snap/tests/testthat/test-snap-3.R index c041e9f47..f2c4a02b6 100644 --- a/tests/testthat/test-parallel/snap/tests/testthat/test-snap-3.R +++ b/tests/testthat/test-parallel/snap/tests/testthat/test-snap-3.R @@ -1,4 +1,3 @@ - test_that("snapshot", { expect_snapshot(21:30) }) diff --git a/tests/testthat/test-parallel/startup/R/fail.R b/tests/testthat/test-parallel/startup/R/fail.R index da10b7d7a..8f6684c3a 100644 --- a/tests/testthat/test-parallel/startup/R/fail.R +++ b/tests/testthat/test-parallel/startup/R/fail.R @@ -1,4 +1,3 @@ - .onLoad <- function(libname, pkgname) { stop("This will fail when loading the package") } diff --git a/tests/testthat/test-parallel/teardown/tests/testthat/teardown-bad.R b/tests/testthat/test-parallel/teardown/tests/testthat/teardown-bad.R index 119b95ac7..07c18ccd2 100644 --- a/tests/testthat/test-parallel/teardown/tests/testthat/teardown-bad.R +++ b/tests/testthat/test-parallel/teardown/tests/testthat/teardown-bad.R @@ -1,2 +1 @@ - stop("Error in teardown") diff --git a/tests/testthat/test-quasi-label.R b/tests/testthat/test-quasi-label.R index bb098ef7a..8a55c1f3a 100644 --- a/tests/testthat/test-quasi-label.R +++ b/tests/testthat/test-quasi-label.R @@ -33,8 +33,9 @@ test_that("produces useful summaries for long calls", { arg + (arg + arg + arg + arg + arg + arg + arg + arg + arg + arg + arg) )) - expr_label(quote(function(a, b, c) { a + b + c})) - + expr_label(quote(function(a, b, c) { + a + b + c + })) }) }) @@ -50,4 +51,3 @@ test_that("other inlined other objects are deparsed", { test_that("informative error for missing arg", { expect_snapshot(error = TRUE, expect_equal()) }) - diff --git a/tests/testthat/test-reporter-check.R b/tests/testthat/test-reporter-check.R index 5da651b50..b9c80a99b 100644 --- a/tests/testthat/test-reporter-check.R +++ b/tests/testthat/test-reporter-check.R @@ -9,13 +9,19 @@ test_that("basic report works", { test_that("doesn't truncate long lines", { on.exit(unlink(test_path("testthat-problems.rds"))) - expect_snapshot_reporter(CheckReporter$new(), test_path("reporters/long-test.R")) + expect_snapshot_reporter( + CheckReporter$new(), + test_path("reporters/long-test.R") + ) }) test_that("always shows summary", { file.create(test_path("testthat-problems.rds")) - expect_snapshot_reporter(CheckReporter$new(), test_path("reporters/successes.R")) + expect_snapshot_reporter( + CheckReporter$new(), + test_path("reporters/successes.R") + ) # and cleans up testthat-problems expect_false(file.exists(test_path("testthat-problems.rds"))) }) diff --git a/tests/testthat/test-reporter-debug.R b/tests/testthat/test-reporter-debug.R index 34aab7200..2c2cc706c 100644 --- a/tests/testthat/test-reporter-debug.R +++ b/tests/testthat/test-reporter-debug.R @@ -3,7 +3,11 @@ test_that("produces consistent output", { local_edition(2) local_mocked_bindings( show_menu = function(choices, title = NULL) { - cat(paste0(format(seq_along(choices)), ": ", choices, sep = "\n"), "\n", sep = "") + cat( + paste0(format(seq_along(choices)), ": ", choices, sep = "\n"), + "\n", + sep = "" + ) 0L }, sink_number = function() 0L @@ -35,7 +39,9 @@ get_frame_from_debug_reporter <- function(choice, fun, envir = parent.frame()) { sink_number = function() 0L, with_reporter( "debug", - test_that("debug_reporter_test", { fun() }) + test_that("debug_reporter_test", { + fun() + }) ) ) diff --git a/tests/testthat/test-reporter-list.R b/tests/testthat/test-reporter-list.R index 14dc35da5..e0bd3df3e 100644 --- a/tests/testthat/test-reporter-list.R +++ b/tests/testthat/test-reporter-list.R @@ -1,4 +1,3 @@ - # regression test: test_file() used to crash with a NULL reporter test_that("ListReporter with test_file and NULL reporter", { test_file_path <- 'test-list-reporter/test-exercise-list-reporter.R' @@ -25,7 +24,7 @@ test_that("ListReporter - exception outside of test_that()", { # the 2nd result should be the exception expect_true(is.na(df$test[2])) # no test name - expect_true(df$error[2]) # it was an error + expect_true(df$error[2]) # it was an error expect_match(res[[2]]$results[[1]]$message, "dying outside of tests") }) @@ -47,7 +46,10 @@ test_that("exercise ListReporter", { # we convert the results to data frame for convenience df <- as.data.frame(res) expect_equal(nrow(df), 5) - expect_equal(df$test, c("test1", "test2", "test-pass", "test-fail", "test-error")) + expect_equal( + df$test, + c("test1", "test2", "test-pass", "test-fail", "test-error") + ) # test "A failing test" is the only failing test expect_equal(df$failed, c(0, 0, 0, 1, 0)) @@ -68,4 +70,3 @@ test_that("ListReporter and bare expectations", { # 2 tests, "before" and "after". no result for the bare expectation expect_identical(df$test, c("before", "after")) }) - diff --git a/tests/testthat/test-reporter-stop.R b/tests/testthat/test-reporter-stop.R index 5ee8d0060..b5ca1ac07 100644 --- a/tests/testthat/test-reporter-stop.R +++ b/tests/testthat/test-reporter-stop.R @@ -9,7 +9,7 @@ test_that("can suppress praise", { ) }) -test_that("stop if needed errors when needed",{ +test_that("stop if needed errors when needed", { r <- StopReporter$new() expect_error(r$stop_if_needed(), NA) r$n_fail <- 1 diff --git a/tests/testthat/test-reporter-summary.R b/tests/testthat/test-reporter-summary.R index 7ca4218bd..b9c074ef5 100644 --- a/tests/testthat/test-reporter-summary.R +++ b/tests/testthat/test-reporter-summary.R @@ -1,8 +1,17 @@ test_that("can control appearance of dots", { - expect_snapshot_reporter(SummaryReporter$new(show_praise = FALSE, omit_dots = FALSE)) - expect_snapshot_reporter(SummaryReporter$new(show_praise = FALSE, omit_dots = TRUE)) + expect_snapshot_reporter(SummaryReporter$new( + show_praise = FALSE, + omit_dots = FALSE + )) + expect_snapshot_reporter(SummaryReporter$new( + show_praise = FALSE, + omit_dots = TRUE + )) }) test_that("can control maximum reports", { - expect_snapshot_reporter(SummaryReporter$new(show_praise = FALSE, max_reports = 2)) + expect_snapshot_reporter(SummaryReporter$new( + show_praise = FALSE, + max_reports = 2 + )) }) diff --git a/tests/testthat/test-skip.R b/tests/testthat/test-skip.R index b4661cd26..efb114eb9 100644 --- a/tests/testthat/test-skip.R +++ b/tests/testthat/test-skip.R @@ -15,19 +15,19 @@ test_that("autogenerated message is always single line", { cnd <- capture_condition(skip_if_not( a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name || - a_very_long_argument_name + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name || + a_very_long_argument_name )) expect_length(cnd$message, 1) @@ -146,7 +146,11 @@ test_that("skip_unless_r works as expected", { expect_skip(skip_unless_r("== 0.0.0")) expect_skip(skip_unless_r("<= 0.0.0")) - expect_error(skip_unless_r("idfjdij"), "should be a comparison like '>='", fixed = TRUE) + expect_error( + skip_unless_r("idfjdij"), + "should be a comparison like '>='", + fixed = TRUE + ) }) test_that("skip_unless_r gives the expected output", { diff --git a/tests/testthat/test-snapshot-file.R b/tests/testthat/test-snapshot-file.R index 663192eb0..85b4476ce 100644 --- a/tests/testthat/test-snapshot-file.R +++ b/tests/testthat/test-snapshot-file.R @@ -58,7 +58,10 @@ test_that("basic workflow", { # warns on first run snapper$start_file("snapshot-6", "test") - expect_warning(expect_snapshot_file(write_tmp_lines(letters), "letters.txt"), "Adding new") + expect_warning( + expect_snapshot_file(write_tmp_lines(letters), "letters.txt"), + "Adding new" + ) snapper$end_file() # succeeds if unchanged @@ -68,7 +71,10 @@ test_that("basic workflow", { # fails if changed snapper$start_file("snapshot-6", "test") - expect_failure(expect_snapshot_file(write_tmp_lines(letters[-1]), "letters.txt")) + expect_failure(expect_snapshot_file( + write_tmp_lines(letters[-1]), + "letters.txt" + )) snapper$end_file() }) @@ -100,11 +106,15 @@ test_that("warns on first creation", { # Errors on non-existing file expect_error( - expect_true(snapshot_file_equal(tempdir(), "test.txt", NULL, "doesnt-exist.txt")), + expect_true(snapshot_file_equal( + tempdir(), + "test.txt", + NULL, + "doesnt-exist.txt" + )), "`doesnt-exist.txt` not found" ) - # Unchanged returns TRUE expect_true(snapshot_file_equal(tempdir(), "test.txt", NULL, path)) expect_true(file.exists(file.path(tempdir(), "test.txt"))) @@ -156,7 +166,22 @@ test_that("snapshot_hint output differs in R CMD check", { testthat:::snapshot_review_hint(..., reset_output = FALSE) } - expect_snapshot(cat(snapshot_review_hint("lala", "foo.r", check = FALSE, ci = FALSE))) - expect_snapshot(cat(snapshot_review_hint("lala", "foo.r", check = TRUE, ci = FALSE))) - expect_snapshot(cat(snapshot_review_hint("lala", "foo.r", check = TRUE, ci = TRUE))) + expect_snapshot(cat(snapshot_review_hint( + "lala", + "foo.r", + check = FALSE, + ci = FALSE + ))) + expect_snapshot(cat(snapshot_review_hint( + "lala", + "foo.r", + check = TRUE, + ci = FALSE + ))) + expect_snapshot(cat(snapshot_review_hint( + "lala", + "foo.r", + check = TRUE, + ci = TRUE + ))) }) diff --git a/tests/testthat/test-snapshot-manage.R b/tests/testthat/test-snapshot-manage.R index 4c7930642..540db8fc4 100644 --- a/tests/testthat/test-snapshot-manage.R +++ b/tests/testthat/test-snapshot-manage.R @@ -20,7 +20,6 @@ test_that("can accept specific files", { path <- local_snapshot_dir(c("test/a.txt", "test/a.new.txt")) expect_snapshot(snapshot_accept("test/", path = path)) expect_equal(dir(file.path(path, "_snaps"), recursive = TRUE), "test/a.txt") - }) test_that("can work with variants", { diff --git a/tests/testthat/test-snapshot-reporter.R b/tests/testthat/test-snapshot-reporter.R index 1ff943af6..64efb36d8 100644 --- a/tests/testthat/test-snapshot-reporter.R +++ b/tests/testthat/test-snapshot-reporter.R @@ -1,4 +1,3 @@ - test_that("can establish local snapshotter for testing", { snapper <- local_snapshotter() diff --git a/tests/testthat/test-snapshot-serialize.R b/tests/testthat/test-snapshot-serialize.R index df7a9ff1d..d636e8b05 100644 --- a/tests/testthat/test-snapshot-serialize.R +++ b/tests/testthat/test-snapshot-serialize.R @@ -8,7 +8,7 @@ test_that("single test case can roundtrip", { }) test_that("multiple tests can roundtrip", { - x <- list(foo = c("a","b"), bar = "d", baz = letters[1:3]) + x <- list(foo = c("a", "b"), bar = "d", baz = letters[1:3]) x_snap <- snap_to_md(x) x_lines <- strsplit(x_snap, "\n")[[1]] @@ -18,7 +18,7 @@ test_that("multiple tests can roundtrip", { test_that("snapshots always use \n", { path <- withr::local_tempfile() - x <- list(foo = c("a","b"), bar = "d", baz = letters[1:3]) + x <- list(foo = c("a", "b"), bar = "d", baz = letters[1:3]) write_snaps(x, path) snap <- brio::read_file(path) diff --git a/tests/testthat/test-snapshot-value.R b/tests/testthat/test-snapshot-value.R index 6e22ac86a..96edbc06e 100644 --- a/tests/testthat/test-snapshot-value.R +++ b/tests/testthat/test-snapshot-value.R @@ -10,7 +10,7 @@ test_that("can control snapshot value details", { expect_snapshot_value(1.2, tolerance = 0.1) # including through ... - f <- ~ 1 + f <- ~1 expect_snapshot_value(f, style = "serialize", ignore_formula_env = TRUE) }) @@ -41,5 +41,8 @@ test_that("check_roundtrip() gives nice error", { local_bindings(crayon = FALSE, .env = get_reporter()) wrapper <- function(...) check_roundtrip(...) - expect_snapshot(wrapper(NULL, list(), label = "foo", style = "json"), error = TRUE) + expect_snapshot( + wrapper(NULL, list(), label = "foo", style = "json"), + error = TRUE + ) }) diff --git a/tests/testthat/test-snapshot.R b/tests/testthat/test-snapshot.R index cf19e464c..d8ee1aa0a 100644 --- a/tests/testthat/test-snapshot.R +++ b/tests/testthat/test-snapshot.R @@ -39,8 +39,14 @@ test_that("multiple outputs of same type are collapsed", { expect_snapshot({ x <- 1 y <- 1 - {message("a"); message("b")} - {warning("a"); warning("b")} + { + message("a") + message("b") + } + { + warning("a") + warning("b") + } }) }) @@ -169,9 +175,7 @@ test_that("hint is informative", { }) test_that("expect_snapshot requires a non-empty test label", { - test_that("", { expect_error(expect_snapshot(1 + 1)) }) - }) diff --git a/tests/testthat/test-source.R b/tests/testthat/test-source.R index 9332a5b52..55f902eb2 100644 --- a/tests/testthat/test-source.R +++ b/tests/testthat/test-source.R @@ -13,9 +13,37 @@ test_that("source_file always uses UTF-8 encoding", { tmp <- tempfile() on.exit(unlink(tmp), add = TRUE) utf8 <- as.raw(c( - 0xc3, 0xa1, 0x72, 0x76, 0xc3, 0xad, 0x7a, 0x74, 0xc5, 0xb1, 0x72, 0xc5, - 0x91, 0x20, 0x74, 0xc3, 0xbc, 0x6b, 0xc3, 0xb6, 0x72, 0x66, 0xc3, 0xba, - 0x72, 0xc3, 0xb3, 0x67, 0xc3, 0xa9, 0x70 + 0xc3, + 0xa1, + 0x72, + 0x76, + 0xc3, + 0xad, + 0x7a, + 0x74, + 0xc5, + 0xb1, + 0x72, + 0xc5, + 0x91, + 0x20, + 0x74, + 0xc3, + 0xbc, + 0x6b, + 0xc3, + 0xb6, + 0x72, + 0x66, + 0xc3, + 0xba, + 0x72, + 0xc3, + 0xb3, + 0x67, + 0xc3, + 0xa9, + 0x70 )) writeBin(c(charToRaw("x <- \""), utf8, charToRaw("\"\n")), tmp) @@ -63,11 +91,14 @@ test_that("can find only matching test", { }) test_that("preserve srcrefs", { - code <- parse(keep.source = TRUE, text = ' + code <- parse( + keep.source = TRUE, + text = ' test_that("foo", { # this is a comment }) - ') + ' + ) expect_snapshot(filter_desc(code, "foo")) }) diff --git a/tests/testthat/test-source_dir.R b/tests/testthat/test-source_dir.R index 96cb79dd3..4fe4c7abc 100644 --- a/tests/testthat/test-source_dir.R +++ b/tests/testthat/test-source_dir.R @@ -2,12 +2,22 @@ test_that("source_dir()", { res <- source_dir("test_dir", pattern = "hello", chdir = TRUE, wrap = FALSE) expect_equal(res[[1]](), "Hello World") - res <- source_dir(normalizePath("test_dir"), pattern = "hello", chdir = TRUE, wrap = FALSE) + res <- source_dir( + normalizePath("test_dir"), + pattern = "hello", + chdir = TRUE, + wrap = FALSE + ) expect_equal(res[[1]](), "Hello World") res <- source_dir("test_dir", pattern = "hello", chdir = FALSE, wrap = FALSE) expect_equal(res[[1]](), "Hello World") - res <- source_dir(normalizePath("test_dir"), pattern = "hello", chdir = FALSE, wrap = FALSE) + res <- source_dir( + normalizePath("test_dir"), + pattern = "hello", + chdir = FALSE, + wrap = FALSE + ) expect_equal(res[[1]](), "Hello World") }) diff --git a/tests/testthat/test-srcrefs.R b/tests/testthat/test-srcrefs.R index 24923032a..ccfde5b73 100644 --- a/tests/testthat/test-srcrefs.R +++ b/tests/testthat/test-srcrefs.R @@ -10,16 +10,18 @@ srcref_line <- function(code) { test_that("line numbers captured for expectations and warnings", { f <- function() warning("Uh oh") + # fmt: skip lines <- srcref_line({ test_that("simple", { # line 1 expect_true(FALSE) # line 2 f() # line 3 }) - }) +}) expect_equal(lines, c(2, 3)) }) test_that("line numbers captured when called indirectly", { + # fmt: skip lines <- srcref_line({ test_that("simple", { # line 1 f <- function() g() # line 2 @@ -31,6 +33,7 @@ test_that("line numbers captured when called indirectly", { }) expect_equal(lines, 4) + # fmt: skip lines <- srcref_line({ f <- function() g() # line 1 g <- function() h() # line 2 @@ -43,6 +46,7 @@ test_that("line numbers captured when called indirectly", { }) test_that("line numbers captured inside a loop", { + # fmt: skip lines <- srcref_line({ test_that("simple", { # line 1 for (i in 1:4) expect_true(TRUE) # line 2 @@ -52,6 +56,7 @@ test_that("line numbers captured inside a loop", { }) test_that("line numbers captured for skip()s and stops()", { + # fmt: skip lines <- srcref_line({ test_that("simple", { # line 1 skip("Not this time") # line 2 @@ -59,16 +64,17 @@ test_that("line numbers captured for skip()s and stops()", { }) expect_equal(lines, 2) + # fmt: skip lines <- srcref_line({ test_that("simple", { # line 1 stop("Not this time") # line 2 }) # line 3 }) expect_equal(lines, 2) - }) test_that("line numbers captured for on.exit()", { + # fmt: skip lines <- srcref_line({ test_that("simple", { # line 1 on.exit({stop("Error")}) # line 2 @@ -77,6 +83,7 @@ test_that("line numbers captured for on.exit()", { expect_equal(lines, 2) # Falls back to test if no srcrf + # fmt: skip lines <- srcref_line({ test_that("simple", { # line 1 on.exit(stop("Error")) # line 2 diff --git a/tests/testthat/test-teardown.R b/tests/testthat/test-teardown.R index 4ac0cf517..0103b1ecc 100644 --- a/tests/testthat/test-teardown.R +++ b/tests/testthat/test-teardown.R @@ -1,6 +1,8 @@ test_that("teardown adds to queue", { local_edition(2) - withr::defer({teardown_reset()}) + withr::defer({ + teardown_reset() + }) expect_length(file_teardown_env$queue, 0) diff --git a/tests/testthat/test-test-files.R b/tests/testthat/test-test-files.R index 42f51e076..b5f226bd2 100644 --- a/tests/testthat/test-test-files.R +++ b/tests/testthat/test-test-files.R @@ -9,7 +9,11 @@ test_that("stops on failure", { test_that("runs all tests and records output", { withr::local_envvar(TESTTHAT_PARALLEL = "FALSE") - res <- test_dir(test_path("test_dir"), reporter = "silent", stop_on_failure = FALSE) + res <- test_dir( + test_path("test_dir"), + reporter = "silent", + stop_on_failure = FALSE + ) df <- as.data.frame(res) df$user <- df$system <- df$real <- df$result <- NULL diff --git a/tests/testthat/test-test-path.R b/tests/testthat/test-test-path.R index 07a57c82e..bad010c5c 100644 --- a/tests/testthat/test-test-path.R +++ b/tests/testthat/test-test-path.R @@ -1,4 +1,4 @@ -test_that("always returns a path",{ +test_that("always returns a path", { withr::local_envvar(TESTTHAT = "true") withr::local_options(testthat_interactive = FALSE) diff --git a/tests/testthat/test-test-state.R b/tests/testthat/test-test-state.R index c4a798637..f61c69d72 100644 --- a/tests/testthat/test-test-state.R +++ b/tests/testthat/test-test-state.R @@ -7,5 +7,8 @@ test_that("can detect state changes", { set_state_inspector(function() list(x = getOption("x"))) withr::defer(set_state_inspector(NULL)) - expect_snapshot_reporter(CheckReporter$new(), test_path("reporters/state-change.R")) + expect_snapshot_reporter( + CheckReporter$new(), + test_path("reporters/state-change.R") + ) }) diff --git a/tests/testthat/test-test-that.R b/tests/testthat/test-test-that.R index 19262203d..ca2252310 100644 --- a/tests/testthat/test-test-that.R +++ b/tests/testthat/test-test-that.R @@ -17,14 +17,18 @@ test_that("errors are captured", { g <- function() stop("I made a mistake", call. = FALSE) reporter <- with_reporter("silent", { - test_that("", { f() } ) + test_that("", { + f() + }) }) expect_equal(length(reporter$expectations()), 1) }) test_that("errors captured even when looking for messages", { reporter <- with_reporter("silent", { - test_that("", { expect_message(stop("a")) } ) + test_that("", { + expect_message(stop("a")) + }) }) expect_equal(length(reporter$expectations()), 1) expect_true(expectation_error(reporter$expectations()[[1L]])) @@ -32,7 +36,9 @@ test_that("errors captured even when looking for messages", { test_that("errors captured even when looking for warnings", { reporter <- with_reporter("silent", { - test_that("", { expect_warning(stop()) } ) + test_that("", { + expect_warning(stop()) + }) }) expect_equal(length(reporter$expectations()), 1) expect_true(expectation_error(reporter$expectations()[[1L]])) @@ -54,29 +60,66 @@ test_that("infinite recursion is captured", { reporter <- with_reporter("silent", { withr::with_options( list(expressions = sys.nframe() + 100), - test_that("", { f() }) + test_that("", { + f() + }) ) }) expect_equal(length(reporter$expectations()), 1) }) test_that("return value from test_that", { - with_reporter("", success <- test_that("success", { succeed() } )) + with_reporter( + "", + success <- test_that("success", { + succeed() + }) + ) expect_true(success) - with_reporter("", success <- test_that("success", { expect(TRUE, "Yes!") })) + with_reporter( + "", + success <- test_that("success", { + expect(TRUE, "Yes!") + }) + ) expect_true(success) - with_reporter("", error <- test_that("error", { barf } )) + with_reporter( + "", + error <- test_that("error", { + barf + }) + ) expect_false(error) - with_reporter("", failure <- test_that("failure", { expect_true(FALSE) } )) + with_reporter( + "", + failure <- test_that("failure", { + expect_true(FALSE) + }) + ) expect_false(failure) - with_reporter("", failure <- test_that("failure", { fail() } )) + with_reporter( + "", + failure <- test_that("failure", { + fail() + }) + ) expect_false(failure) - with_reporter("", success <- test_that("failure", { expect(FALSE, "No!") } )) + with_reporter( + "", + success <- test_that("failure", { + expect(FALSE, "No!") + }) + ) expect_false(success) - with_reporter("", skip <- test_that("skip", { skip("skipping") } )) + with_reporter( + "", + skip <- test_that("skip", { + skip("skipping") + }) + ) expect_false(skip) # No tests = automatically generated skip with_reporter("", skip <- test_that("success", {})) diff --git a/tests/testthat/test-verify-output.R b/tests/testthat/test-verify-output.R index 4a3c5889d..577ca9cff 100644 --- a/tests/testthat/test-verify-output.R +++ b/tests/testthat/test-verify-output.R @@ -3,8 +3,17 @@ test_that("can record all types of output", { "Output" 1 + 2 invisible(1:10) - 12345678 + 12345678 + 12345678 + 12345678 + 12345678 + 12345678 + - 12345678 + 12345678 + 12345678 + 12345678 + 12345678 + 12345678 + + 12345678 + + 12345678 + + 12345678 + + 12345678 + + 12345678 + + 12345678 + + 12345678 + + 12345678 + + 12345678 + + 12345678 "# Header" "Other output" @@ -75,7 +84,8 @@ test_that("verify_output() doesn't use cli unicode by default", { unicode = TRUE, { cat(cli::symbol$info, cli::symbol$cross, "\n") - }) + } + ) }) test_that("verify_output() handles carriage return", {