From f387950486caaf4fcf60de79aa24c8870460e9ca Mon Sep 17 00:00:00 2001 From: Hernan Ezequiel Di Giorgi Date: Sat, 18 Jul 2020 20:23:35 -0300 Subject: [PATCH] support `allow_redirects` option --- tests/integration/test_httpx.py | 18 ++++++++++++++++++ vcr/stubs/httpx_stubs.py | 8 +++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/tests/integration/test_httpx.py b/tests/integration/test_httpx.py index 6e3d2fa4..f7839347 100644 --- a/tests/integration/test_httpx.py +++ b/tests/integration/test_httpx.py @@ -235,3 +235,21 @@ def test_relative_redirects(tmpdir, scheme, do_request): assert response.json()["url"].endswith("request") assert cassette.play_count == 3 + + +def test_redirect_wo_allow_redirects(do_request, yml): + url = "https://mockbin.org/redirect/308/5" + + with vcr.use_cassette(yml): + response = do_request()("GET", url, allow_redirects=False) + + assert str(response.url).endswith("308/5") + assert response.status_code == 308 + + with vcr.use_cassette(yml) as cassette: + response = do_request()("GET", url, allow_redirects=False) + + assert str(response.url).endswith("308/5") + assert response.status_code == 308 + + assert cassette.play_count == 1 diff --git a/vcr/stubs/httpx_stubs.py b/vcr/stubs/httpx_stubs.py index c809389e..a22502c5 100644 --- a/vcr/stubs/httpx_stubs.py +++ b/vcr/stubs/httpx_stubs.py @@ -70,10 +70,11 @@ def _make_vcr_request(httpx_request, **kwargs): def _shared_vcr_send(cassette, real_send, *args, **kwargs): real_request = args[1] + vcr_request = _make_vcr_request(real_request, **kwargs) if cassette.can_play_response_for(vcr_request): - return vcr_request, _play_responses(cassette, real_request, vcr_request, args[0]) + return vcr_request, _play_responses(cassette, real_request, vcr_request, args[0], kwargs) if cassette.write_protected and cassette.filter_request(vcr_request): raise CannotOverwriteExistingCassetteException(cassette=cassette, failed_request=vcr_request) @@ -96,12 +97,13 @@ def _record_responses(cassette, vcr_request, real_response): return real_response -def _play_responses(cassette, request, vcr_request, client): +def _play_responses(cassette, request, vcr_request, client, kwargs): history = [] + allow_redirects = kwargs.get("allow_redirects", True) vcr_response = cassette.play_response(vcr_request) response = _from_serialized_response(request, vcr_response) - while 300 <= response.status_code <= 399: + while allow_redirects and 300 <= response.status_code <= 399: next_url = response.headers.get("location") if not next_url: break