Skip to content
Myr

test_wsgi.py

This file

Path

tests/test_wsgi.py

175 lines · 4.8 KiB · Python

Last changed by

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

History of this file

Take it

1import sys2import typing3import wsgiref.validate4from functools import partial5from io import StringIO67import pytest89import httpx1011if typing.TYPE_CHECKING:  # pragma: no cover12    from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment131415def application_factory(output: typing.Iterable[bytes]) -> "WSGIApplication":16    def application(environ, start_response):17        status = "200 OK"1819        response_headers = [20            ("Content-type", "text/plain"),21        ]2223        start_response(status, response_headers)2425        for item in output:26            yield item2728    return wsgiref.validate.validator(application)293031def echo_body(32    environ: "WSGIEnvironment", start_response: "StartResponse"33) -> typing.Iterable[bytes]:34    status = "200 OK"35    output = environ["wsgi.input"].read()3637    response_headers = [38        ("Content-type", "text/plain"),39    ]4041    start_response(status, response_headers)4243    return [output]444546def echo_body_with_response_stream(47    environ: "WSGIEnvironment", start_response: "StartResponse"48) -> typing.Iterable[bytes]:49    status = "200 OK"5051    response_headers = [("Content-Type", "text/plain")]5253    start_response(status, response_headers)5455    def output_generator(f: typing.IO[bytes]) -> typing.Iterator[bytes]:56        while True:57            output = f.read(2)58            if not output:59                break60            yield output6162    return output_generator(f=environ["wsgi.input"])636465def raise_exc(66    environ: "WSGIEnvironment",67    start_response: "StartResponse",68    exc: typing.Type[Exception] = ValueError,69) -> typing.Iterable[bytes]:70    status = "500 Server Error"71    output = b"Nope!"7273    response_headers = [74        ("Content-type", "text/plain"),75    ]7677    try:78        raise exc()79    except exc:80        exc_info = sys.exc_info()81        start_response(status, response_headers, exc_info)8283    return [output]848586def log_to_wsgi_log_buffer(environ, start_response):87    print("test1", file=environ["wsgi.errors"])88    environ["wsgi.errors"].write("test2")89    return echo_body(environ, start_response)909192def test_wsgi():93    client = httpx.Client(app=application_factory([b"Hello, World!"]))94    response = client.get("http://www.example.org/")95    assert response.status_code == 20096    assert response.text == "Hello, World!"979899def test_wsgi_upload():100    client = httpx.Client(app=echo_body)101    response = client.post("http://www.example.org/", content=b"example")102    assert response.status_code == 200103    assert response.text == "example"104105106def test_wsgi_upload_with_response_stream():107    client = httpx.Client(app=echo_body_with_response_stream)108    response = client.post("http://www.example.org/", content=b"example")109    assert response.status_code == 200110    assert response.text == "example"111112113def test_wsgi_exc():114    client = httpx.Client(app=raise_exc)115    with pytest.raises(ValueError):116        client.get("http://www.example.org/")117118119def test_wsgi_http_error():120    client = httpx.Client(app=partial(raise_exc, exc=RuntimeError))121    with pytest.raises(RuntimeError):122        client.get("http://www.example.org/")123124125def test_wsgi_generator():126    output = [b"", b"", b"Some content", b" and more content"]127    client = httpx.Client(app=application_factory(output))128    response = client.get("http://www.example.org/")129    assert response.status_code == 200130    assert response.text == "Some content and more content"131132133def test_wsgi_generator_empty():134    output = [b"", b"", b"", b""]135    client = httpx.Client(app=application_factory(output))136    response = client.get("http://www.example.org/")137    assert response.status_code == 200138    assert response.text == ""139140141def test_logging():142    buffer = StringIO()143    transport = httpx.WSGITransport(app=log_to_wsgi_log_buffer, wsgi_errors=buffer)144    client = httpx.Client(transport=transport)145    response = client.post("http://www.example.org/", content=b"example")146    assert response.status_code == 200  # no errors147    buffer.seek(0)148    assert buffer.read() == "test1\ntest2"149150151@pytest.mark.parametrize(152    "url, expected_server_port",153    [154        pytest.param("http://www.example.org", "80", id="auto-http"),155        pytest.param("https://www.example.org", "443", id="auto-https"),156        pytest.param("http://www.example.org:8000", "8000", id="explicit-port"),157    ],158)159def test_wsgi_server_port(url: str, expected_server_port: str) -> None:160    """161    SERVER_PORT is populated correctly from the requested URL.162    """163    hello_world_app = application_factory([b"Hello, World!"])164    server_port: str165166    def app(environ, start_response):167        nonlocal server_port168        server_port = environ["SERVER_PORT"]169        return hello_world_app(environ, start_response)170171    client = httpx.Client(app=app)172    response = client.get(url)173    assert response.status_code == 200174    assert response.text == "Hello, World!"175    assert server_port == expected_server_port