test_wsgi.py
This file
Path
tests/test_wsgi.py
111 lines · 2.7 KiB · Python
Last changed by
Fix support for generator-based WSGI apps (#887)Ed Singletonbefore adoption94323f9
History of this fileTake it
1import sys23import pytest45import httpx678def application_factory(output):9 def application(environ, start_response):10 status = "200 OK"1112 response_headers = [13 ("Content-type", "text/plain"),14 ]1516 start_response(status, response_headers)1718 for item in output:19 yield item2021 return application222324def echo_body(environ, start_response):25 status = "200 OK"26 output = environ["wsgi.input"].read()2728 response_headers = [29 ("Content-type", "text/plain"),30 ]3132 start_response(status, response_headers)3334 return [output]353637def echo_body_with_response_stream(environ, start_response):38 status = "200 OK"3940 response_headers = [("Content-Type", "text/plain")]4142 start_response(status, response_headers)4344 def output_generator(f):45 while True:46 output = f.read(2)47 if not output:48 break49 yield output5051 return output_generator(f=environ["wsgi.input"])525354def raise_exc(environ, start_response):55 status = "500 Server Error"56 output = b"Nope!"5758 response_headers = [59 ("Content-type", "text/plain"),60 ]6162 try:63 raise ValueError()64 except ValueError:65 exc_info = sys.exc_info()66 start_response(status, response_headers, exc_info=exc_info)6768 return [output]697071def test_wsgi():72 client = httpx.Client(app=application_factory([b"Hello, World!"]))73 response = client.get("http://www.example.org/")74 assert response.status_code == 20075 assert response.text == "Hello, World!"767778def test_wsgi_upload():79 client = httpx.Client(app=echo_body)80 response = client.post("http://www.example.org/", data=b"example")81 assert response.status_code == 20082 assert response.text == "example"838485def test_wsgi_upload_with_response_stream():86 client = httpx.Client(app=echo_body_with_response_stream)87 response = client.post("http://www.example.org/", data=b"example")88 assert response.status_code == 20089 assert response.text == "example"909192def test_wsgi_exc():93 client = httpx.Client(app=raise_exc)94 with pytest.raises(ValueError):95 client.get("http://www.example.org/")969798def test_wsgi_generator():99 output = [b"", b"", b"Some content", b" and more content"]100 client = httpx.Client(app=application_factory(output))101 response = client.get("http://www.example.org/")102 assert response.status_code == 200103 assert response.text == "Some content and more content"104105106def test_wsgi_generator_empty():107 output = [b"", b"", b"", b""]108 client = httpx.Client(app=application_factory(output))109 response = client.get("http://www.example.org/")110 assert response.status_code == 200111 assert response.text == ""