Skip to content
Myr

test_redirects.py

This file

Path

tests/client/test_redirects.py

447 lines · 17.1 KiB · Python

Last changed by

Enabling `ruff` C416 (#3001)James Brazabefore adoption2318fd8

History of this file

Take it

1import typing23import pytest45import httpx678def redirects(request: httpx.Request) -> httpx.Response:9    if request.url.scheme not in ("http", "https"):10        raise httpx.UnsupportedProtocol(f"Scheme {request.url.scheme!r} not supported.")1112    if request.url.path == "/redirect_301":13        status_code = httpx.codes.MOVED_PERMANENTLY14        content = b"<a href='https://example.org/'>here</a>"15        headers = {"location": "https://example.org/"}16        return httpx.Response(status_code, headers=headers, content=content)1718    elif request.url.path == "/redirect_302":19        status_code = httpx.codes.FOUND20        headers = {"location": "https://example.org/"}21        return httpx.Response(status_code, headers=headers)2223    elif request.url.path == "/redirect_303":24        status_code = httpx.codes.SEE_OTHER25        headers = {"location": "https://example.org/"}26        return httpx.Response(status_code, headers=headers)2728    elif request.url.path == "/relative_redirect":29        status_code = httpx.codes.SEE_OTHER30        headers = {"location": "/"}31        return httpx.Response(status_code, headers=headers)3233    elif request.url.path == "/malformed_redirect":34        status_code = httpx.codes.SEE_OTHER35        headers = {"location": "https://:443/"}36        return httpx.Response(status_code, headers=headers)3738    elif request.url.path == "/invalid_redirect":39        status_code = httpx.codes.SEE_OTHER40        raw_headers = [(b"location", "https://😇/".encode("utf-8"))]41        return httpx.Response(status_code, headers=raw_headers)4243    elif request.url.path == "/no_scheme_redirect":44        status_code = httpx.codes.SEE_OTHER45        headers = {"location": "//example.org/"}46        return httpx.Response(status_code, headers=headers)4748    elif request.url.path == "/multiple_redirects":49        params = httpx.QueryParams(request.url.query)50        count = int(params.get("count", "0"))51        redirect_count = count - 152        status_code = httpx.codes.SEE_OTHER if count else httpx.codes.OK53        if count:54            location = "/multiple_redirects"55            if redirect_count:56                location += f"?count={redirect_count}"57            headers = {"location": location}58        else:59            headers = {}60        return httpx.Response(status_code, headers=headers)6162    if request.url.path == "/redirect_loop":63        status_code = httpx.codes.SEE_OTHER64        headers = {"location": "/redirect_loop"}65        return httpx.Response(status_code, headers=headers)6667    elif request.url.path == "/cross_domain":68        status_code = httpx.codes.SEE_OTHER69        headers = {"location": "https://example.org/cross_domain_target"}70        return httpx.Response(status_code, headers=headers)7172    elif request.url.path == "/cross_domain_target":73        status_code = httpx.codes.OK74        data = {75            "body": request.content.decode("ascii"),76            "headers": dict(request.headers),77        }78        return httpx.Response(status_code, json=data)7980    elif request.url.path == "/redirect_body":81        status_code = httpx.codes.PERMANENT_REDIRECT82        headers = {"location": "/redirect_body_target"}83        return httpx.Response(status_code, headers=headers)8485    elif request.url.path == "/redirect_no_body":86        status_code = httpx.codes.SEE_OTHER87        headers = {"location": "/redirect_body_target"}88        return httpx.Response(status_code, headers=headers)8990    elif request.url.path == "/redirect_body_target":91        data = {92            "body": request.content.decode("ascii"),93            "headers": dict(request.headers),94        }95        return httpx.Response(200, json=data)9697    elif request.url.path == "/cross_subdomain":98        if request.headers["Host"] != "www.example.org":99            status_code = httpx.codes.PERMANENT_REDIRECT100            headers = {"location": "https://www.example.org/cross_subdomain"}101            return httpx.Response(status_code, headers=headers)102        else:103            return httpx.Response(200, text="Hello, world!")104105    elif request.url.path == "/redirect_custom_scheme":106        status_code = httpx.codes.MOVED_PERMANENTLY107        headers = {"location": "market://details?id=42"}108        return httpx.Response(status_code, headers=headers)109110    if request.method == "HEAD":111        return httpx.Response(200)112113    return httpx.Response(200, html="<html><body>Hello, world!</body></html>")114115116def test_redirect_301():117    client = httpx.Client(transport=httpx.MockTransport(redirects))118    response = client.post("https://example.org/redirect_301", follow_redirects=True)119    assert response.status_code == httpx.codes.OK120    assert response.url == "https://example.org/"121    assert len(response.history) == 1122123124def test_redirect_302():125    client = httpx.Client(transport=httpx.MockTransport(redirects))126    response = client.post("https://example.org/redirect_302", follow_redirects=True)127    assert response.status_code == httpx.codes.OK128    assert response.url == "https://example.org/"129    assert len(response.history) == 1130131132def test_redirect_303():133    client = httpx.Client(transport=httpx.MockTransport(redirects))134    response = client.get("https://example.org/redirect_303", follow_redirects=True)135    assert response.status_code == httpx.codes.OK136    assert response.url == "https://example.org/"137    assert len(response.history) == 1138139140def test_next_request():141    client = httpx.Client(transport=httpx.MockTransport(redirects))142    request = client.build_request("POST", "https://example.org/redirect_303")143    response = client.send(request, follow_redirects=False)144    assert response.status_code == httpx.codes.SEE_OTHER145    assert response.url == "https://example.org/redirect_303"146    assert response.next_request is not None147148    response = client.send(response.next_request, follow_redirects=False)149    assert response.status_code == httpx.codes.OK150    assert response.url == "https://example.org/"151    assert response.next_request is None152153154@pytest.mark.anyio155async def test_async_next_request():156    async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:157        request = client.build_request("POST", "https://example.org/redirect_303")158        response = await client.send(request, follow_redirects=False)159        assert response.status_code == httpx.codes.SEE_OTHER160        assert response.url == "https://example.org/redirect_303"161        assert response.next_request is not None162163        response = await client.send(response.next_request, follow_redirects=False)164        assert response.status_code == httpx.codes.OK165        assert response.url == "https://example.org/"166        assert response.next_request is None167168169def test_head_redirect():170    """171    Contrary to Requests, redirects remain enabled by default for HEAD requests.172    """173    client = httpx.Client(transport=httpx.MockTransport(redirects))174    response = client.head("https://example.org/redirect_302", follow_redirects=True)175    assert response.status_code == httpx.codes.OK176    assert response.url == "https://example.org/"177    assert response.request.method == "HEAD"178    assert len(response.history) == 1179    assert response.text == ""180181182def test_relative_redirect():183    client = httpx.Client(transport=httpx.MockTransport(redirects))184    response = client.get(185        "https://example.org/relative_redirect", follow_redirects=True186    )187    assert response.status_code == httpx.codes.OK188    assert response.url == "https://example.org/"189    assert len(response.history) == 1190191192def test_malformed_redirect():193    # https://github.com/encode/httpx/issues/771194    client = httpx.Client(transport=httpx.MockTransport(redirects))195    response = client.get(196        "http://example.org/malformed_redirect", follow_redirects=True197    )198    assert response.status_code == httpx.codes.OK199    assert response.url == "https://example.org:443/"200    assert len(response.history) == 1201202203def test_invalid_redirect():204    client = httpx.Client(transport=httpx.MockTransport(redirects))205    with pytest.raises(httpx.RemoteProtocolError):206        client.get("http://example.org/invalid_redirect", follow_redirects=True)207208209def test_no_scheme_redirect():210    client = httpx.Client(transport=httpx.MockTransport(redirects))211    response = client.get(212        "https://example.org/no_scheme_redirect", follow_redirects=True213    )214    assert response.status_code == httpx.codes.OK215    assert response.url == "https://example.org/"216    assert len(response.history) == 1217218219def test_fragment_redirect():220    client = httpx.Client(transport=httpx.MockTransport(redirects))221    response = client.get(222        "https://example.org/relative_redirect#fragment", follow_redirects=True223    )224    assert response.status_code == httpx.codes.OK225    assert response.url == "https://example.org/#fragment"226    assert len(response.history) == 1227228229def test_multiple_redirects():230    client = httpx.Client(transport=httpx.MockTransport(redirects))231    response = client.get(232        "https://example.org/multiple_redirects?count=20", follow_redirects=True233    )234    assert response.status_code == httpx.codes.OK235    assert response.url == "https://example.org/multiple_redirects"236    assert len(response.history) == 20237    assert response.history[0].url == "https://example.org/multiple_redirects?count=20"238    assert response.history[1].url == "https://example.org/multiple_redirects?count=19"239    assert len(response.history[0].history) == 0240    assert len(response.history[1].history) == 1241242243@pytest.mark.anyio244async def test_async_too_many_redirects():245    async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:246        with pytest.raises(httpx.TooManyRedirects):247            await client.get(248                "https://example.org/multiple_redirects?count=21", follow_redirects=True249            )250251252def test_sync_too_many_redirects():253    client = httpx.Client(transport=httpx.MockTransport(redirects))254    with pytest.raises(httpx.TooManyRedirects):255        client.get(256            "https://example.org/multiple_redirects?count=21", follow_redirects=True257        )258259260def test_redirect_loop():261    client = httpx.Client(transport=httpx.MockTransport(redirects))262    with pytest.raises(httpx.TooManyRedirects):263        client.get("https://example.org/redirect_loop", follow_redirects=True)264265266def test_cross_domain_redirect_with_auth_header():267    client = httpx.Client(transport=httpx.MockTransport(redirects))268    url = "https://example.com/cross_domain"269    headers = {"Authorization": "abc"}270    response = client.get(url, headers=headers, follow_redirects=True)271    assert response.url == "https://example.org/cross_domain_target"272    assert "authorization" not in response.json()["headers"]273274275def test_cross_domain_https_redirect_with_auth_header():276    client = httpx.Client(transport=httpx.MockTransport(redirects))277    url = "http://example.com/cross_domain"278    headers = {"Authorization": "abc"}279    response = client.get(url, headers=headers, follow_redirects=True)280    assert response.url == "https://example.org/cross_domain_target"281    assert "authorization" not in response.json()["headers"]282283284def test_cross_domain_redirect_with_auth():285    client = httpx.Client(transport=httpx.MockTransport(redirects))286    url = "https://example.com/cross_domain"287    response = client.get(url, auth=("user", "pass"), follow_redirects=True)288    assert response.url == "https://example.org/cross_domain_target"289    assert "authorization" not in response.json()["headers"]290291292def test_same_domain_redirect():293    client = httpx.Client(transport=httpx.MockTransport(redirects))294    url = "https://example.org/cross_domain"295    headers = {"Authorization": "abc"}296    response = client.get(url, headers=headers, follow_redirects=True)297    assert response.url == "https://example.org/cross_domain_target"298    assert response.json()["headers"]["authorization"] == "abc"299300301def test_same_domain_https_redirect_with_auth_header():302    client = httpx.Client(transport=httpx.MockTransport(redirects))303    url = "http://example.org/cross_domain"304    headers = {"Authorization": "abc"}305    response = client.get(url, headers=headers, follow_redirects=True)306    assert response.url == "https://example.org/cross_domain_target"307    assert response.json()["headers"]["authorization"] == "abc"308309310def test_body_redirect():311    """312    A 308 redirect should preserve the request body.313    """314    client = httpx.Client(transport=httpx.MockTransport(redirects))315    url = "https://example.org/redirect_body"316    content = b"Example request body"317    response = client.post(url, content=content, follow_redirects=True)318    assert response.url == "https://example.org/redirect_body_target"319    assert response.json()["body"] == "Example request body"320    assert "content-length" in response.json()["headers"]321322323def test_no_body_redirect():324    """325    A 303 redirect should remove the request body.326    """327    client = httpx.Client(transport=httpx.MockTransport(redirects))328    url = "https://example.org/redirect_no_body"329    content = b"Example request body"330    response = client.post(url, content=content, follow_redirects=True)331    assert response.url == "https://example.org/redirect_body_target"332    assert response.json()["body"] == ""333    assert "content-length" not in response.json()["headers"]334335336def test_can_stream_if_no_redirect():337    client = httpx.Client(transport=httpx.MockTransport(redirects))338    url = "https://example.org/redirect_301"339    with client.stream("GET", url, follow_redirects=False) as response:340        pass341    assert response.status_code == httpx.codes.MOVED_PERMANENTLY342    assert response.headers["location"] == "https://example.org/"343344345class ConsumeBodyTransport(httpx.MockTransport):346    def handle_request(self, request: httpx.Request) -> httpx.Response:347        assert isinstance(request.stream, httpx.SyncByteStream)348        list(request.stream)349        return self.handler(request)  # type: ignore[return-value]350351352def test_cannot_redirect_streaming_body():353    client = httpx.Client(transport=ConsumeBodyTransport(redirects))354    url = "https://example.org/redirect_body"355356    def streaming_body() -> typing.Iterator[bytes]:357        yield b"Example request body"  # pragma: no cover358359    with pytest.raises(httpx.StreamConsumed):360        client.post(url, content=streaming_body(), follow_redirects=True)361362363def test_cross_subdomain_redirect():364    client = httpx.Client(transport=httpx.MockTransport(redirects))365    url = "https://example.com/cross_subdomain"366    response = client.get(url, follow_redirects=True)367    assert response.url == "https://www.example.org/cross_subdomain"368369370def cookie_sessions(request: httpx.Request) -> httpx.Response:371    if request.url.path == "/":372        cookie = request.headers.get("Cookie")373        if cookie is not None:374            content = b"Logged in"375        else:376            content = b"Not logged in"377        return httpx.Response(200, content=content)378379    elif request.url.path == "/login":380        status_code = httpx.codes.SEE_OTHER381        headers = {382            "location": "/",383            "set-cookie": (384                "session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "385                "httponly; samesite=lax"386            ),387        }388        return httpx.Response(status_code, headers=headers)389390    else:391        assert request.url.path == "/logout"392        status_code = httpx.codes.SEE_OTHER393        headers = {394            "location": "/",395            "set-cookie": (396                "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "397                "httponly; samesite=lax"398            ),399        }400        return httpx.Response(status_code, headers=headers)401402403def test_redirect_cookie_behavior():404    client = httpx.Client(405        transport=httpx.MockTransport(cookie_sessions), follow_redirects=True406    )407408    # The client is not logged in.409    response = client.get("https://example.com/")410    assert response.url == "https://example.com/"411    assert response.text == "Not logged in"412413    # Login redirects to the homepage, setting a session cookie.414    response = client.post("https://example.com/login")415    assert response.url == "https://example.com/"416    assert response.text == "Logged in"417418    # The client is logged in.419    response = client.get("https://example.com/")420    assert response.url == "https://example.com/"421    assert response.text == "Logged in"422423    # Logout redirects to the homepage, expiring the session cookie.424    response = client.post("https://example.com/logout")425    assert response.url == "https://example.com/"426    assert response.text == "Not logged in"427428    # The client is not logged in.429    response = client.get("https://example.com/")430    assert response.url == "https://example.com/"431    assert response.text == "Not logged in"432433434def test_redirect_custom_scheme():435    client = httpx.Client(transport=httpx.MockTransport(redirects))436    with pytest.raises(httpx.UnsupportedProtocol) as e:437        client.post("https://example.org/redirect_custom_scheme", follow_redirects=True)438    assert str(e.value) == "Scheme 'market' not supported."439440441@pytest.mark.anyio442async def test_async_invalid_redirect():443    async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:444        with pytest.raises(httpx.RemoteProtocolError):445            await client.get(446                "http://example.org/invalid_redirect", follow_redirects=True447            )