test_wsgi.py
This file
Path
tests/test_wsgi.py
212 lines · 6.1 KiB · Python
Last changed by
Deprecate `app=...` in favor of explicit `WSGITransport`/`ASGITransport`. (#3050)Tom Christiebefore adoptioncabd1c0
History of this fileTake 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 transport = httpx.WSGITransport(app=application_factory([b"Hello, World!"]))96 client = httpx.Client(transport=transport)97 response = client.get("http://www.example.org/")98 assert response.status_code == 20099 assert response.text == "Hello, World!"100101102def test_wsgi_upload():103 transport = httpx.WSGITransport(app=echo_body)104 client = httpx.Client(transport=transport)105 response = client.post("http://www.example.org/", content=b"example")106 assert response.status_code == 200107 assert response.text == "example"108109110def test_wsgi_upload_with_response_stream():111 transport = httpx.WSGITransport(app=echo_body_with_response_stream)112 client = httpx.Client(transport=transport)113 response = client.post("http://www.example.org/", content=b"example")114 assert response.status_code == 200115 assert response.text == "example"116117118def test_wsgi_exc():119 transport = httpx.WSGITransport(app=raise_exc)120 client = httpx.Client(transport=transport)121 with pytest.raises(ValueError):122 client.get("http://www.example.org/")123124125def test_wsgi_http_error():126 transport = httpx.WSGITransport(app=partial(raise_exc, exc=RuntimeError))127 client = httpx.Client(transport=transport)128 with pytest.raises(RuntimeError):129 client.get("http://www.example.org/")130131132def test_wsgi_generator():133 output = [b"", b"", b"Some content", b" and more content"]134 transport = httpx.WSGITransport(app=application_factory(output))135 client = httpx.Client(transport=transport)136 response = client.get("http://www.example.org/")137 assert response.status_code == 200138 assert response.text == "Some content and more content"139140141def test_wsgi_generator_empty():142 output = [b"", b"", b"", b""]143 transport = httpx.WSGITransport(app=application_factory(output))144 client = httpx.Client(transport=transport)145 response = client.get("http://www.example.org/")146 assert response.status_code == 200147 assert response.text == ""148149150def test_logging():151 buffer = StringIO()152 transport = httpx.WSGITransport(app=log_to_wsgi_log_buffer, wsgi_errors=buffer)153 client = httpx.Client(transport=transport)154 response = client.post("http://www.example.org/", content=b"example")155 assert response.status_code == 200 # no errors156 buffer.seek(0)157 assert buffer.read() == "test1\ntest2"158159160@pytest.mark.parametrize(161 "url, expected_server_port",162 [163 pytest.param("http://www.example.org", "80", id="auto-http"),164 pytest.param("https://www.example.org", "443", id="auto-https"),165 pytest.param("http://www.example.org:8000", "8000", id="explicit-port"),166 ],167)168def test_wsgi_server_port(url: str, expected_server_port: str) -> None:169 """170 SERVER_PORT is populated correctly from the requested URL.171 """172 hello_world_app = application_factory([b"Hello, World!"])173 server_port: str | None = None174175 def app(environ, start_response):176 nonlocal server_port177 server_port = environ["SERVER_PORT"]178 return hello_world_app(environ, start_response)179180 transport = httpx.WSGITransport(app=app)181 client = httpx.Client(transport=transport)182 response = client.get(url)183 assert response.status_code == 200184 assert response.text == "Hello, World!"185 assert server_port == expected_server_port186187188def test_wsgi_server_protocol():189 server_protocol = None190191 def app(environ, start_response):192 nonlocal server_protocol193 server_protocol = environ["SERVER_PROTOCOL"]194 start_response("200 OK", [("Content-Type", "text/plain")])195 return [b"success"]196197 transport = httpx.WSGITransport(app=app)198 with httpx.Client(transport=transport, base_url="http://testserver") as client:199 response = client.get("/")200201 assert response.status_code == 200202 assert response.text == "success"203 assert server_protocol == "HTTP/1.1"204205206def test_deprecated_shortcut():207 """208 The `app=...` shortcut is now deprecated.209 Use the explicit transport style instead.210 """211 with pytest.warns(DeprecationWarning):212 httpx.Client(app=application_factory([b"Hello, World!"]))