Skip to content
Myr

test_asgi.py

This file

Path

tests/test_asgi.py

216 lines · 7.1 KiB · Python

Last changed by

Ensure that ASGI 'raw_path' does not include query component of URL. (#2999)Tom Christiebefore adoption90538a3

History of this file

Take it

1import json23import pytest45import httpx6from httpx import ASGITransport789async def hello_world(scope, receive, send):10    status = 20011    output = b"Hello, World!"12    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]1314    await send({"type": "http.response.start", "status": status, "headers": headers})15    await send({"type": "http.response.body", "body": output})161718async def echo_path(scope, receive, send):19    status = 20020    output = json.dumps({"path": scope["path"]}).encode("utf-8")21    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]2223    await send({"type": "http.response.start", "status": status, "headers": headers})24    await send({"type": "http.response.body", "body": output})252627async def echo_raw_path(scope, receive, send):28    status = 20029    output = json.dumps({"raw_path": scope["raw_path"].decode("ascii")}).encode("utf-8")30    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]3132    await send({"type": "http.response.start", "status": status, "headers": headers})33    await send({"type": "http.response.body", "body": output})343536async def echo_body(scope, receive, send):37    status = 20038    headers = [(b"content-type", "text/plain")]3940    await send({"type": "http.response.start", "status": status, "headers": headers})41    more_body = True42    while more_body:43        message = await receive()44        body = message.get("body", b"")45        more_body = message.get("more_body", False)46        await send({"type": "http.response.body", "body": body, "more_body": more_body})474849async def echo_headers(scope, receive, send):50    status = 20051    output = json.dumps(52        {"headers": [[k.decode(), v.decode()] for k, v in scope["headers"]]}53    ).encode("utf-8")54    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]5556    await send({"type": "http.response.start", "status": status, "headers": headers})57    await send({"type": "http.response.body", "body": output})585960async def raise_exc(scope, receive, send):61    raise RuntimeError()626364async def raise_exc_after_response(scope, receive, send):65    status = 20066    output = b"Hello, World!"67    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]6869    await send({"type": "http.response.start", "status": status, "headers": headers})70    await send({"type": "http.response.body", "body": output})71    raise RuntimeError()727374@pytest.mark.anyio75async def test_asgi_transport():76    async with httpx.ASGITransport(app=hello_world) as transport:77        request = httpx.Request("GET", "http://www.example.com/")78        response = await transport.handle_async_request(request)79        await response.aread()80        assert response.status_code == 20081        assert response.content == b"Hello, World!"828384@pytest.mark.anyio85async def test_asgi_transport_no_body():86    async with httpx.ASGITransport(app=echo_body) as transport:87        request = httpx.Request("GET", "http://www.example.com/")88        response = await transport.handle_async_request(request)89        await response.aread()90        assert response.status_code == 20091        assert response.content == b""929394@pytest.mark.anyio95async def test_asgi():96    async with httpx.AsyncClient(app=hello_world) as client:97        response = await client.get("http://www.example.org/")9899    assert response.status_code == 200100    assert response.text == "Hello, World!"101102103@pytest.mark.anyio104async def test_asgi_urlencoded_path():105    async with httpx.AsyncClient(app=echo_path) as client:106        url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")107        response = await client.get(url)108109    assert response.status_code == 200110    assert response.json() == {"path": "/user@example.org"}111112113@pytest.mark.anyio114async def test_asgi_raw_path():115    async with httpx.AsyncClient(app=echo_raw_path) as client:116        url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")117        response = await client.get(url)118119    assert response.status_code == 200120    assert response.json() == {"raw_path": "/user@example.org"}121122123@pytest.mark.anyio124async def test_asgi_raw_path_should_not_include_querystring_portion():125    """126    See https://github.com/encode/httpx/issues/2810127    """128    async with httpx.AsyncClient(app=echo_raw_path) as client:129        url = httpx.URL("http://www.example.org/path?query")130        response = await client.get(url)131132    assert response.status_code == 200133    assert response.json() == {"raw_path": "/path"}134135136@pytest.mark.anyio137async def test_asgi_upload():138    async with httpx.AsyncClient(app=echo_body) as client:139        response = await client.post("http://www.example.org/", content=b"example")140141    assert response.status_code == 200142    assert response.text == "example"143144145@pytest.mark.anyio146async def test_asgi_headers():147    async with httpx.AsyncClient(app=echo_headers) as client:148        response = await client.get("http://www.example.org/")149150    assert response.status_code == 200151    assert response.json() == {152        "headers": [153            ["host", "www.example.org"],154            ["accept", "*/*"],155            ["accept-encoding", "gzip, deflate, br"],156            ["connection", "keep-alive"],157            ["user-agent", f"python-httpx/{httpx.__version__}"],158        ]159    }160161162@pytest.mark.anyio163async def test_asgi_exc():164    async with httpx.AsyncClient(app=raise_exc) as client:165        with pytest.raises(RuntimeError):166            await client.get("http://www.example.org/")167168169@pytest.mark.anyio170async def test_asgi_exc_after_response():171    async with httpx.AsyncClient(app=raise_exc_after_response) as client:172        with pytest.raises(RuntimeError):173            await client.get("http://www.example.org/")174175176@pytest.mark.anyio177async def test_asgi_disconnect_after_response_complete():178    disconnect = False179180    async def read_body(scope, receive, send):181        nonlocal disconnect182183        status = 200184        headers = [(b"content-type", "text/plain")]185186        await send(187            {"type": "http.response.start", "status": status, "headers": headers}188        )189        more_body = True190        while more_body:191            message = await receive()192            more_body = message.get("more_body", False)193194        await send({"type": "http.response.body", "body": b"", "more_body": False})195196        # The ASGI spec says of the Disconnect message:197        # "Sent to the application when a HTTP connection is closed or if receive is198        # called after a response has been sent."199        # So if receive() is called again, the disconnect message should be received200        message = await receive()201        disconnect = message.get("type") == "http.disconnect"202203    async with httpx.AsyncClient(app=read_body) as client:204        response = await client.post("http://www.example.org/", content=b"example")205206    assert response.status_code == 200207    assert disconnect208209210@pytest.mark.anyio211async def test_asgi_exc_no_raise():212    transport = ASGITransport(app=raise_exc, raise_app_exceptions=False)213    async with httpx.AsyncClient(transport=transport) as client:214        response = await client.get("http://www.example.org/")215216        assert response.status_code == 500