Skip to content

Commit

Permalink
Throw errors from mocked responses (#271)
Browse files Browse the repository at this point in the history
Fixes #252
  • Loading branch information
hadley authored Aug 11, 2023
1 parent fe38a8f commit d789827
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 4 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# httr2 (development version)

* `with_mock()` and `local_mock()` now correctly trigger errors when the
mocked response represents an HTTP failure (#252).

* New `req_progress()` adds a progress bar to long download or uploads (#20).

* @mgirlich is now a httr2 contributor in recognition of many small contributions.
Expand Down
2 changes: 1 addition & 1 deletion R/req-mock.R
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
#' my_mock <- function(req) {
#' response(status_code = 403)
#' }
#' with_mock(my_mock, google())
#' try(with_mock(my_mock, google()))
with_mock <- function(mock, code) {
withr::with_options(list(httr2_mock = mock), code)
}
Expand Down
8 changes: 6 additions & 2 deletions R/req-perform.R
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ req_perform <- function(
mock <- as_function(mock)
mock_resp <- mock(req)
if (!is.null(mock_resp)) {
return(mock_resp)
return(handle_resp(req, mock_resp, error_call = error_call))
}
}

Expand Down Expand Up @@ -115,11 +115,15 @@ req_perform <- function(
signal("", "httr2_fetch", n = n, tries = tries, reauth = reauth)

resp <- cache_post_fetch(req, resp, path = path)
handle_resp(req, resp, error_call = error_call)
}

handle_resp <- function(req, resp, error_call = caller_env()) {
if (is_error(resp)) {
cnd_signal(resp)
} else if (error_is_error(req, resp)) {
resp_abort(resp, error_body(req, resp), call = error_call)
body <- error_body(req, resp, error_call)
resp_abort(resp, body, call = error_call)
} else {
resp
}
Expand Down
2 changes: 1 addition & 1 deletion man/with_mock.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions tests/testthat/test-req-mock.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,10 @@ test_that("can override requests through mocking", {
local_mock(~ resp)
expect_equal(req_perform(req), resp)
})

test_that("can generate errors with mocking", {
local_mock(~ response(404))

req <- request("https://google.com")
expect_error(req_perform(req), class = "httr2_http_404")
})

0 comments on commit d789827

Please sign in to comment.