Skip to content
Myr

test_asgi.py

This file

Path

tests/test_asgi.py

203 lines · 6.7 KiB · Python

Last changed by

Fix exception suppression in asgi transport (#2669)Nikbefore adoptiona682f6f

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_upload():125    async with httpx.AsyncClient(app=echo_body) as client:126        response = await client.post("http://www.example.org/", content=b"example")127128    assert response.status_code == 200129    assert response.text == "example"130131132@pytest.mark.anyio133async def test_asgi_headers():134    async with httpx.AsyncClient(app=echo_headers) as client:135        response = await client.get("http://www.example.org/")136137    assert response.status_code == 200138    assert response.json() == {139        "headers": [140            ["host", "www.example.org"],141            ["accept", "*/*"],142            ["accept-encoding", "gzip, deflate, br"],143            ["connection", "keep-alive"],144            ["user-agent", f"python-httpx/{httpx.__version__}"],145        ]146    }147148149@pytest.mark.anyio150async def test_asgi_exc():151    async with httpx.AsyncClient(app=raise_exc) as client:152        with pytest.raises(RuntimeError):153            await client.get("http://www.example.org/")154155156@pytest.mark.anyio157async def test_asgi_exc_after_response():158    async with httpx.AsyncClient(app=raise_exc_after_response) as client:159        with pytest.raises(RuntimeError):160            await client.get("http://www.example.org/")161162163@pytest.mark.anyio164async def test_asgi_disconnect_after_response_complete():165    disconnect = False166167    async def read_body(scope, receive, send):168        nonlocal disconnect169170        status = 200171        headers = [(b"content-type", "text/plain")]172173        await send(174            {"type": "http.response.start", "status": status, "headers": headers}175        )176        more_body = True177        while more_body:178            message = await receive()179            more_body = message.get("more_body", False)180181        await send({"type": "http.response.body", "body": b"", "more_body": False})182183        # The ASGI spec says of the Disconnect message:184        # "Sent to the application when a HTTP connection is closed or if receive is185        # called after a response has been sent."186        # So if receive() is called again, the disconnect message should be received187        message = await receive()188        disconnect = message.get("type") == "http.disconnect"189190    async with httpx.AsyncClient(app=read_body) as client:191        response = await client.post("http://www.example.org/", content=b"example")192193    assert response.status_code == 200194    assert disconnect195196197@pytest.mark.anyio198async def test_asgi_exc_no_raise():199    transport = ASGITransport(app=raise_exc, raise_app_exceptions=False)200    async with httpx.AsyncClient(transport=transport) as client:201        response = await client.get("http://www.example.org/")202203        assert response.status_code == 500