Skip to content
Myr

test_asgi.py

This file

Path

tests/test_asgi.py

173 lines · 5.9 KiB · Python

Last changed by

Add raw_path to scope in ASGITransport (#1357)Simon Willisonbefore adoptionca5f524

History of this file

Take it

1import json23import pytest45import httpx678async def hello_world(scope, receive, send):9    status = 20010    output = b"Hello, World!"11    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]1213    await send({"type": "http.response.start", "status": status, "headers": headers})14    await send({"type": "http.response.body", "body": output})151617async def echo_path(scope, receive, send):18    status = 20019    output = json.dumps({"path": scope["path"]}).encode("utf-8")20    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]2122    await send({"type": "http.response.start", "status": status, "headers": headers})23    await send({"type": "http.response.body", "body": output})242526async def echo_raw_path(scope, receive, send):27    status = 20028    output = json.dumps({"raw_path": scope["raw_path"].decode("ascii")}).encode("utf-8")29    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]3031    await send({"type": "http.response.start", "status": status, "headers": headers})32    await send({"type": "http.response.body", "body": output})333435async def echo_body(scope, receive, send):36    status = 20037    headers = [(b"content-type", "text/plain")]3839    await send({"type": "http.response.start", "status": status, "headers": headers})40    more_body = True41    while more_body:42        message = await receive()43        body = message.get("body", b"")44        more_body = message.get("more_body", False)45        await send({"type": "http.response.body", "body": body, "more_body": more_body})464748async def echo_headers(scope, receive, send):49    status = 20050    output = json.dumps(51        {"headers": [[k.decode(), v.decode()] for k, v in scope["headers"]]}52    ).encode("utf-8")53    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]5455    await send({"type": "http.response.start", "status": status, "headers": headers})56    await send({"type": "http.response.body", "body": output})575859async def raise_exc(scope, receive, send):60    raise RuntimeError()616263async def raise_exc_after_response(scope, receive, send):64    status = 20065    output = b"Hello, World!"66    headers = [(b"content-type", "text/plain"), (b"content-length", str(len(output)))]6768    await send({"type": "http.response.start", "status": status, "headers": headers})69    await send({"type": "http.response.body", "body": output})70    raise RuntimeError()717273@pytest.mark.usefixtures("async_environment")74async def test_asgi():75    async with httpx.AsyncClient(app=hello_world) as client:76        response = await client.get("http://www.example.org/")7778    assert response.status_code == 20079    assert response.text == "Hello, World!"808182@pytest.mark.usefixtures("async_environment")83async def test_asgi_urlencoded_path():84    async with httpx.AsyncClient(app=echo_path) as client:85        url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")86        response = await client.get(url)8788    assert response.status_code == 20089    assert response.json() == {"path": "/user@example.org"}909192@pytest.mark.usefixtures("async_environment")93async def test_asgi_raw_path():94    async with httpx.AsyncClient(app=echo_raw_path) as client:95        url = httpx.URL("http://www.example.org/").copy_with(path="/user@example.org")96        response = await client.get(url)9798    assert response.status_code == 20099    assert response.json() == {"raw_path": "/user%40example.org"}100101102@pytest.mark.usefixtures("async_environment")103async def test_asgi_upload():104    async with httpx.AsyncClient(app=echo_body) as client:105        response = await client.post("http://www.example.org/", content=b"example")106107    assert response.status_code == 200108    assert response.text == "example"109110111@pytest.mark.usefixtures("async_environment")112async def test_asgi_headers():113    async with httpx.AsyncClient(app=echo_headers) as client:114        response = await client.get("http://www.example.org/")115116    assert response.status_code == 200117    assert response.json() == {118        "headers": [119            ["host", "www.example.org"],120            ["accept", "*/*"],121            ["accept-encoding", "gzip, deflate, br"],122            ["connection", "keep-alive"],123            ["user-agent", f"python-httpx/{httpx.__version__}"],124        ]125    }126127128@pytest.mark.usefixtures("async_environment")129async def test_asgi_exc():130    async with httpx.AsyncClient(app=raise_exc) as client:131        with pytest.raises(RuntimeError):132            await client.get("http://www.example.org/")133134135@pytest.mark.usefixtures("async_environment")136async def test_asgi_exc_after_response():137    async with httpx.AsyncClient(app=raise_exc_after_response) as client:138        with pytest.raises(RuntimeError):139            await client.get("http://www.example.org/")140141142@pytest.mark.usefixtures("async_environment")143async def test_asgi_disconnect_after_response_complete():144    disconnect = False145146    async def read_body(scope, receive, send):147        nonlocal disconnect148149        status = 200150        headers = [(b"content-type", "text/plain")]151152        await send(153            {"type": "http.response.start", "status": status, "headers": headers}154        )155        more_body = True156        while more_body:157            message = await receive()158            more_body = message.get("more_body", False)159160        await send({"type": "http.response.body", "body": b"", "more_body": False})161162        # The ASGI spec says of the Disconnect message:163        # "Sent to the application when a HTTP connection is closed or if receive is164        # called after a response has been sent."165        # So if receive() is called again, the disconnect message should be received166        message = await receive()167        disconnect = message.get("type") == "http.disconnect"168169    async with httpx.AsyncClient(app=read_body) as client:170        response = await client.post("http://www.example.org/", content=b"example")171172    assert response.status_code == 200173    assert disconnect