Skip to content
Myr

test_wsgi.py

This file

Path

tests/test_wsgi.py

194 lines · 5.4 KiB · Python

Last changed by

Use `__future__.annotations` (#3068)Kar Petrosyanbefore adoption371b6e9

History of this file

Take it

1from __future__ import annotations23import sys4import typing5import wsgiref.validate6from functools import partial7from io import StringIO89import pytest1011import httpx1213if typing.TYPE_CHECKING:  # pragma: no cover14    from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment151617def application_factory(output: typing.Iterable[bytes]) -> WSGIApplication:18    def application(environ, start_response):19        status = "200 OK"2021        response_headers = [22            ("Content-type", "text/plain"),23        ]2425        start_response(status, response_headers)2627        for item in output:28            yield item2930    return wsgiref.validate.validator(application)313233def echo_body(34    environ: WSGIEnvironment, start_response: StartResponse35) -> typing.Iterable[bytes]:36    status = "200 OK"37    output = environ["wsgi.input"].read()3839    response_headers = [40        ("Content-type", "text/plain"),41    ]4243    start_response(status, response_headers)4445    return [output]464748def echo_body_with_response_stream(49    environ: WSGIEnvironment, start_response: StartResponse50) -> typing.Iterable[bytes]:51    status = "200 OK"5253    response_headers = [("Content-Type", "text/plain")]5455    start_response(status, response_headers)5657    def output_generator(f: typing.IO[bytes]) -> typing.Iterator[bytes]:58        while True:59            output = f.read(2)60            if not output:61                break62            yield output6364    return output_generator(f=environ["wsgi.input"])656667def raise_exc(68    environ: WSGIEnvironment,69    start_response: StartResponse,70    exc: type[Exception] = ValueError,71) -> typing.Iterable[bytes]:72    status = "500 Server Error"73    output = b"Nope!"7475    response_headers = [76        ("Content-type", "text/plain"),77    ]7879    try:80        raise exc()81    except exc:82        exc_info = sys.exc_info()83        start_response(status, response_headers, exc_info)8485    return [output]868788def log_to_wsgi_log_buffer(environ, start_response):89    print("test1", file=environ["wsgi.errors"])90    environ["wsgi.errors"].write("test2")91    return echo_body(environ, start_response)929394def test_wsgi():95    client = httpx.Client(app=application_factory([b"Hello, World!"]))96    response = client.get("http://www.example.org/")97    assert response.status_code == 20098    assert response.text == "Hello, World!"99100101def test_wsgi_upload():102    client = httpx.Client(app=echo_body)103    response = client.post("http://www.example.org/", content=b"example")104    assert response.status_code == 200105    assert response.text == "example"106107108def test_wsgi_upload_with_response_stream():109    client = httpx.Client(app=echo_body_with_response_stream)110    response = client.post("http://www.example.org/", content=b"example")111    assert response.status_code == 200112    assert response.text == "example"113114115def test_wsgi_exc():116    client = httpx.Client(app=raise_exc)117    with pytest.raises(ValueError):118        client.get("http://www.example.org/")119120121def test_wsgi_http_error():122    client = httpx.Client(app=partial(raise_exc, exc=RuntimeError))123    with pytest.raises(RuntimeError):124        client.get("http://www.example.org/")125126127def test_wsgi_generator():128    output = [b"", b"", b"Some content", b" and more content"]129    client = httpx.Client(app=application_factory(output))130    response = client.get("http://www.example.org/")131    assert response.status_code == 200132    assert response.text == "Some content and more content"133134135def test_wsgi_generator_empty():136    output = [b"", b"", b"", b""]137    client = httpx.Client(app=application_factory(output))138    response = client.get("http://www.example.org/")139    assert response.status_code == 200140    assert response.text == ""141142143def test_logging():144    buffer = StringIO()145    transport = httpx.WSGITransport(app=log_to_wsgi_log_buffer, wsgi_errors=buffer)146    client = httpx.Client(transport=transport)147    response = client.post("http://www.example.org/", content=b"example")148    assert response.status_code == 200  # no errors149    buffer.seek(0)150    assert buffer.read() == "test1\ntest2"151152153@pytest.mark.parametrize(154    "url, expected_server_port",155    [156        pytest.param("http://www.example.org", "80", id="auto-http"),157        pytest.param("https://www.example.org", "443", id="auto-https"),158        pytest.param("http://www.example.org:8000", "8000", id="explicit-port"),159    ],160)161def test_wsgi_server_port(url: str, expected_server_port: str) -> None:162    """163    SERVER_PORT is populated correctly from the requested URL.164    """165    hello_world_app = application_factory([b"Hello, World!"])166    server_port: str | None = None167168    def app(environ, start_response):169        nonlocal server_port170        server_port = environ["SERVER_PORT"]171        return hello_world_app(environ, start_response)172173    client = httpx.Client(app=app)174    response = client.get(url)175    assert response.status_code == 200176    assert response.text == "Hello, World!"177    assert server_port == expected_server_port178179180def test_wsgi_server_protocol():181    server_protocol = None182183    def app(environ, start_response):184        nonlocal server_protocol185        server_protocol = environ["SERVER_PROTOCOL"]186        start_response("200 OK", [("Content-Type", "text/plain")])187        return [b"success"]188189    with httpx.Client(app=app, base_url="http://testserver") as client:190        response = client.get("/")191192    assert response.status_code == 200193    assert response.text == "success"194    assert server_protocol == "HTTP/1.1"