Skip to content

Commit e4b98d5

Browse files
authored
Also handle errors in try_again() (#2265)
And improve docs to correctly calculate failure probabiltiies
1 parent fc95be8 commit e4b98d5

File tree

4 files changed

+40
-6
lines changed

4 files changed

+40
-6
lines changed

R/try-again.R

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#' Evaluate an expression multiple times until it succeeds
1+
#' Evaluate an expectation multiple times until it succeeds
22
#'
33
#' If you have a flaky test, you can use `try_again()` to run it a few times
44
#' until it succeeds. In most cases, you are better fixing the underlying
@@ -17,7 +17,10 @@
1717
#' expect_equal(usually_return_1(), 1)
1818
#'
1919
#' # 1% chance of failure:
20-
#' try_again(3, expect_equal(usually_return_1(), 1))
20+
#' try_again(1, expect_equal(usually_return_1(), 1))
21+
#'
22+
#' # 0.1% chance of failure:
23+
#' try_again(2, expect_equal(usually_return_1(), 1))
2124
#' }
2225
try_again <- function(times, code) {
2326
check_number_whole(times, min = 1)
@@ -28,9 +31,16 @@ try_again <- function(times, code) {
2831
while (i <= times) {
2932
tryCatch(
3033
return(eval(get_expr(code), get_env(code))),
31-
expectation_failure = function(cnd) NULL
34+
expectation_failure = function(cnd) {
35+
cli::cli_inform(c(i = "Expectation failed; trying again ({i})..."))
36+
NULL
37+
},
38+
error = function(cnd) {
39+
cli::cli_inform(c(i = "Expectation errored; trying again ({i})..."))
40+
NULL
41+
}
3242
)
33-
cli::cli_inform(c(i = "Expectation failed; trying again ({i})..."))
43+
3444
i <- i + 1
3545
}
3646

man/try_again.Rd

Lines changed: 5 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/testthat/_snaps/try-again.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,11 @@
1919
`actual`: 1.0
2020
`expected`: 0.0
2121

22+
# handles errors
23+
24+
Code
25+
result <- try_again(3, expect_equal(fails_twice(), 1))
26+
Message
27+
i Expectation errored; trying again (1)...
28+
i Expectation errored; trying again (2)...
29+

tests/testthat/test-try-again.R

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,16 @@ test_that("tries multiple times", {
1313
third_try <- succeed_after(3)
1414
expect_snapshot(try_again(1, third_try()), error = TRUE)
1515
})
16+
17+
test_that("handles errors", {
18+
fails_twice <- local({
19+
i <- 0
20+
function() {
21+
i <<- i + 1
22+
if (i <= 2) stop("fail") else 1
23+
}
24+
})
25+
26+
expect_snapshot(result <- try_again(3, expect_equal(fails_twice(), 1)))
27+
expect_equal(result, 1)
28+
})

0 commit comments

Comments
 (0)