Skip to content
Myr

test_redirects.py

This file

Path

tests/client/test_redirects.py

445 lines · 17.1 KiB · Python

Last changed by

Preserve Authorization header on HTTPS redirect (#1850) (#2074)waterfountain1996before adoption4401d55

History of this file

Take it

1import pytest23import httpx456def redirects(request: httpx.Request) -> httpx.Response:7    if request.url.scheme not in ("http", "https"):8        raise httpx.UnsupportedProtocol(f"Scheme {request.url.scheme!r} not supported.")910    if request.url.path == "/redirect_301":11        status_code = httpx.codes.MOVED_PERMANENTLY12        content = b"<a href='https://example.org/'>here</a>"13        headers = {"location": "https://example.org/"}14        return httpx.Response(status_code, headers=headers, content=content)1516    elif request.url.path == "/redirect_302":17        status_code = httpx.codes.FOUND18        headers = {"location": "https://example.org/"}19        return httpx.Response(status_code, headers=headers)2021    elif request.url.path == "/redirect_303":22        status_code = httpx.codes.SEE_OTHER23        headers = {"location": "https://example.org/"}24        return httpx.Response(status_code, headers=headers)2526    elif request.url.path == "/relative_redirect":27        status_code = httpx.codes.SEE_OTHER28        headers = {"location": "/"}29        return httpx.Response(status_code, headers=headers)3031    elif request.url.path == "/malformed_redirect":32        status_code = httpx.codes.SEE_OTHER33        headers = {"location": "https://:443/"}34        return httpx.Response(status_code, headers=headers)3536    elif request.url.path == "/invalid_redirect":37        status_code = httpx.codes.SEE_OTHER38        raw_headers = [(b"location", "https://😇/".encode("utf-8"))]39        return httpx.Response(status_code, headers=raw_headers)4041    elif request.url.path == "/no_scheme_redirect":42        status_code = httpx.codes.SEE_OTHER43        headers = {"location": "//example.org/"}44        return httpx.Response(status_code, headers=headers)4546    elif request.url.path == "/multiple_redirects":47        params = httpx.QueryParams(request.url.query)48        count = int(params.get("count", "0"))49        redirect_count = count - 150        status_code = httpx.codes.SEE_OTHER if count else httpx.codes.OK51        if count:52            location = "/multiple_redirects"53            if redirect_count:54                location += f"?count={redirect_count}"55            headers = {"location": location}56        else:57            headers = {}58        return httpx.Response(status_code, headers=headers)5960    if request.url.path == "/redirect_loop":61        status_code = httpx.codes.SEE_OTHER62        headers = {"location": "/redirect_loop"}63        return httpx.Response(status_code, headers=headers)6465    elif request.url.path == "/cross_domain":66        status_code = httpx.codes.SEE_OTHER67        headers = {"location": "https://example.org/cross_domain_target"}68        return httpx.Response(status_code, headers=headers)6970    elif request.url.path == "/cross_domain_target":71        status_code = httpx.codes.OK72        data = {73            "body": request.content.decode("ascii"),74            "headers": dict(request.headers),75        }76        return httpx.Response(status_code, json=data)7778    elif request.url.path == "/redirect_body":79        status_code = httpx.codes.PERMANENT_REDIRECT80        headers = {"location": "/redirect_body_target"}81        return httpx.Response(status_code, headers=headers)8283    elif request.url.path == "/redirect_no_body":84        status_code = httpx.codes.SEE_OTHER85        headers = {"location": "/redirect_body_target"}86        return httpx.Response(status_code, headers=headers)8788    elif request.url.path == "/redirect_body_target":89        data = {90            "body": request.content.decode("ascii"),91            "headers": dict(request.headers),92        }93        return httpx.Response(200, json=data)9495    elif request.url.path == "/cross_subdomain":96        if request.headers["Host"] != "www.example.org":97            status_code = httpx.codes.PERMANENT_REDIRECT98            headers = {"location": "https://www.example.org/cross_subdomain"}99            return httpx.Response(status_code, headers=headers)100        else:101            return httpx.Response(200, text="Hello, world!")102103    elif request.url.path == "/redirect_custom_scheme":104        status_code = httpx.codes.MOVED_PERMANENTLY105        headers = {"location": "market://details?id=42"}106        return httpx.Response(status_code, headers=headers)107108    if request.method == "HEAD":109        return httpx.Response(200)110111    return httpx.Response(200, html="<html><body>Hello, world!</body></html>")112113114def test_redirect_301():115    client = httpx.Client(transport=httpx.MockTransport(redirects))116    response = client.post("https://example.org/redirect_301", follow_redirects=True)117    assert response.status_code == httpx.codes.OK118    assert response.url == "https://example.org/"119    assert len(response.history) == 1120121122def test_redirect_302():123    client = httpx.Client(transport=httpx.MockTransport(redirects))124    response = client.post("https://example.org/redirect_302", follow_redirects=True)125    assert response.status_code == httpx.codes.OK126    assert response.url == "https://example.org/"127    assert len(response.history) == 1128129130def test_redirect_303():131    client = httpx.Client(transport=httpx.MockTransport(redirects))132    response = client.get("https://example.org/redirect_303", follow_redirects=True)133    assert response.status_code == httpx.codes.OK134    assert response.url == "https://example.org/"135    assert len(response.history) == 1136137138def test_next_request():139    client = httpx.Client(transport=httpx.MockTransport(redirects))140    request = client.build_request("POST", "https://example.org/redirect_303")141    response = client.send(request, follow_redirects=False)142    assert response.status_code == httpx.codes.SEE_OTHER143    assert response.url == "https://example.org/redirect_303"144    assert response.next_request is not None145146    response = client.send(response.next_request, follow_redirects=False)147    assert response.status_code == httpx.codes.OK148    assert response.url == "https://example.org/"149    assert response.next_request is None150151152@pytest.mark.usefixtures("async_environment")153async def test_async_next_request():154    async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:155        request = client.build_request("POST", "https://example.org/redirect_303")156        response = await client.send(request, follow_redirects=False)157        assert response.status_code == httpx.codes.SEE_OTHER158        assert response.url == "https://example.org/redirect_303"159        assert response.next_request is not None160161        response = await client.send(response.next_request, follow_redirects=False)162        assert response.status_code == httpx.codes.OK163        assert response.url == "https://example.org/"164        assert response.next_request is None165166167def test_head_redirect():168    """169    Contrary to Requests, redirects remain enabled by default for HEAD requests.170    """171    client = httpx.Client(transport=httpx.MockTransport(redirects))172    response = client.head("https://example.org/redirect_302", follow_redirects=True)173    assert response.status_code == httpx.codes.OK174    assert response.url == "https://example.org/"175    assert response.request.method == "HEAD"176    assert len(response.history) == 1177    assert response.text == ""178179180def test_relative_redirect():181    client = httpx.Client(transport=httpx.MockTransport(redirects))182    response = client.get(183        "https://example.org/relative_redirect", follow_redirects=True184    )185    assert response.status_code == httpx.codes.OK186    assert response.url == "https://example.org/"187    assert len(response.history) == 1188189190def test_malformed_redirect():191    # https://github.com/encode/httpx/issues/771192    client = httpx.Client(transport=httpx.MockTransport(redirects))193    response = client.get(194        "http://example.org/malformed_redirect", follow_redirects=True195    )196    assert response.status_code == httpx.codes.OK197    assert response.url == "https://example.org:443/"198    assert len(response.history) == 1199200201def test_invalid_redirect():202    client = httpx.Client(transport=httpx.MockTransport(redirects))203    with pytest.raises(httpx.RemoteProtocolError):204        client.get("http://example.org/invalid_redirect", follow_redirects=True)205206207def test_no_scheme_redirect():208    client = httpx.Client(transport=httpx.MockTransport(redirects))209    response = client.get(210        "https://example.org/no_scheme_redirect", follow_redirects=True211    )212    assert response.status_code == httpx.codes.OK213    assert response.url == "https://example.org/"214    assert len(response.history) == 1215216217def test_fragment_redirect():218    client = httpx.Client(transport=httpx.MockTransport(redirects))219    response = client.get(220        "https://example.org/relative_redirect#fragment", follow_redirects=True221    )222    assert response.status_code == httpx.codes.OK223    assert response.url == "https://example.org/#fragment"224    assert len(response.history) == 1225226227def test_multiple_redirects():228    client = httpx.Client(transport=httpx.MockTransport(redirects))229    response = client.get(230        "https://example.org/multiple_redirects?count=20", follow_redirects=True231    )232    assert response.status_code == httpx.codes.OK233    assert response.url == "https://example.org/multiple_redirects"234    assert len(response.history) == 20235    assert response.history[0].url == "https://example.org/multiple_redirects?count=20"236    assert response.history[1].url == "https://example.org/multiple_redirects?count=19"237    assert len(response.history[0].history) == 0238    assert len(response.history[1].history) == 1239240241@pytest.mark.usefixtures("async_environment")242async def test_async_too_many_redirects():243    async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:244        with pytest.raises(httpx.TooManyRedirects):245            await client.get(246                "https://example.org/multiple_redirects?count=21", follow_redirects=True247            )248249250def test_sync_too_many_redirects():251    client = httpx.Client(transport=httpx.MockTransport(redirects))252    with pytest.raises(httpx.TooManyRedirects):253        client.get(254            "https://example.org/multiple_redirects?count=21", follow_redirects=True255        )256257258def test_redirect_loop():259    client = httpx.Client(transport=httpx.MockTransport(redirects))260    with pytest.raises(httpx.TooManyRedirects):261        client.get("https://example.org/redirect_loop", follow_redirects=True)262263264def test_cross_domain_redirect_with_auth_header():265    client = httpx.Client(transport=httpx.MockTransport(redirects))266    url = "https://example.com/cross_domain"267    headers = {"Authorization": "abc"}268    response = client.get(url, headers=headers, follow_redirects=True)269    assert response.url == "https://example.org/cross_domain_target"270    assert "authorization" not in response.json()["headers"]271272273def test_cross_domain_https_redirect_with_auth_header():274    client = httpx.Client(transport=httpx.MockTransport(redirects))275    url = "http://example.com/cross_domain"276    headers = {"Authorization": "abc"}277    response = client.get(url, headers=headers, follow_redirects=True)278    assert response.url == "https://example.org/cross_domain_target"279    assert "authorization" not in response.json()["headers"]280281282def test_cross_domain_redirect_with_auth():283    client = httpx.Client(transport=httpx.MockTransport(redirects))284    url = "https://example.com/cross_domain"285    response = client.get(url, auth=("user", "pass"), follow_redirects=True)286    assert response.url == "https://example.org/cross_domain_target"287    assert "authorization" not in response.json()["headers"]288289290def test_same_domain_redirect():291    client = httpx.Client(transport=httpx.MockTransport(redirects))292    url = "https://example.org/cross_domain"293    headers = {"Authorization": "abc"}294    response = client.get(url, headers=headers, follow_redirects=True)295    assert response.url == "https://example.org/cross_domain_target"296    assert response.json()["headers"]["authorization"] == "abc"297298299def test_same_domain_https_redirect_with_auth_header():300    client = httpx.Client(transport=httpx.MockTransport(redirects))301    url = "http://example.org/cross_domain"302    headers = {"Authorization": "abc"}303    response = client.get(url, headers=headers, follow_redirects=True)304    assert response.url == "https://example.org/cross_domain_target"305    assert response.json()["headers"]["authorization"] == "abc"306307308def test_body_redirect():309    """310    A 308 redirect should preserve the request body.311    """312    client = httpx.Client(transport=httpx.MockTransport(redirects))313    url = "https://example.org/redirect_body"314    content = b"Example request body"315    response = client.post(url, content=content, follow_redirects=True)316    assert response.url == "https://example.org/redirect_body_target"317    assert response.json()["body"] == "Example request body"318    assert "content-length" in response.json()["headers"]319320321def test_no_body_redirect():322    """323    A 303 redirect should remove the request body.324    """325    client = httpx.Client(transport=httpx.MockTransport(redirects))326    url = "https://example.org/redirect_no_body"327    content = b"Example request body"328    response = client.post(url, content=content, follow_redirects=True)329    assert response.url == "https://example.org/redirect_body_target"330    assert response.json()["body"] == ""331    assert "content-length" not in response.json()["headers"]332333334def test_can_stream_if_no_redirect():335    client = httpx.Client(transport=httpx.MockTransport(redirects))336    url = "https://example.org/redirect_301"337    with client.stream("GET", url, follow_redirects=False) as response:338        pass339    assert response.status_code == httpx.codes.MOVED_PERMANENTLY340    assert response.headers["location"] == "https://example.org/"341342343class ConsumeBodyTransport(httpx.MockTransport):344    def handle_request(self, request: httpx.Request) -> httpx.Response:345        assert isinstance(request.stream, httpx.SyncByteStream)346        [_ for _ in request.stream]347        return self.handler(request)348349350def test_cannot_redirect_streaming_body():351    client = httpx.Client(transport=ConsumeBodyTransport(redirects))352    url = "https://example.org/redirect_body"353354    def streaming_body():355        yield b"Example request body"  # pragma: nocover356357    with pytest.raises(httpx.StreamConsumed):358        client.post(url, content=streaming_body(), follow_redirects=True)359360361def test_cross_subdomain_redirect():362    client = httpx.Client(transport=httpx.MockTransport(redirects))363    url = "https://example.com/cross_subdomain"364    response = client.get(url, follow_redirects=True)365    assert response.url == "https://www.example.org/cross_subdomain"366367368def cookie_sessions(request: httpx.Request) -> httpx.Response:369    if request.url.path == "/":370        cookie = request.headers.get("Cookie")371        if cookie is not None:372            content = b"Logged in"373        else:374            content = b"Not logged in"375        return httpx.Response(200, content=content)376377    elif request.url.path == "/login":378        status_code = httpx.codes.SEE_OTHER379        headers = {380            "location": "/",381            "set-cookie": (382                "session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "383                "httponly; samesite=lax"384            ),385        }386        return httpx.Response(status_code, headers=headers)387388    else:389        assert request.url.path == "/logout"390        status_code = httpx.codes.SEE_OTHER391        headers = {392            "location": "/",393            "set-cookie": (394                "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "395                "httponly; samesite=lax"396            ),397        }398        return httpx.Response(status_code, headers=headers)399400401def test_redirect_cookie_behavior():402    client = httpx.Client(403        transport=httpx.MockTransport(cookie_sessions), follow_redirects=True404    )405406    # The client is not logged in.407    response = client.get("https://example.com/")408    assert response.url == "https://example.com/"409    assert response.text == "Not logged in"410411    # Login redirects to the homepage, setting a session cookie.412    response = client.post("https://example.com/login")413    assert response.url == "https://example.com/"414    assert response.text == "Logged in"415416    # The client is logged in.417    response = client.get("https://example.com/")418    assert response.url == "https://example.com/"419    assert response.text == "Logged in"420421    # Logout redirects to the homepage, expiring the session cookie.422    response = client.post("https://example.com/logout")423    assert response.url == "https://example.com/"424    assert response.text == "Not logged in"425426    # The client is not logged in.427    response = client.get("https://example.com/")428    assert response.url == "https://example.com/"429    assert response.text == "Not logged in"430431432def test_redirect_custom_scheme():433    client = httpx.Client(transport=httpx.MockTransport(redirects))434    with pytest.raises(httpx.UnsupportedProtocol) as e:435        client.post("https://example.org/redirect_custom_scheme", follow_redirects=True)436    assert str(e.value) == "Scheme 'market' not supported."437438439@pytest.mark.usefixtures("async_environment")440async def test_async_invalid_redirect():441    async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:442        with pytest.raises(httpx.RemoteProtocolError):443            await client.get(444                "http://example.org/invalid_redirect", follow_redirects=True445            )