From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 7 Sep 2021 14:44:35 +0000 (-0500) Subject: BUG: wsgi.error should be TextIO, not BytesIO in WSGI transport (#1828) X-Git-Tag: 1.0.0.beta0~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=0b4a83257bef85559d91b466e4ac94a216a25485;p=thirdparty%2Fhttpx.git BUG: wsgi.error should be TextIO, not BytesIO in WSGI transport (#1828) * wsgi.error should be StringIO, not BytesIO Based on the documentation at https://modwsgi.readthedocs.io/en/master/user-guides/debugging-techniques.html#apache-error-log-files * Default to sys.stderr and add test * rename log_file param to wsgi_errors Co-authored-by: Tom Christie --- diff --git a/httpx/_transports/wsgi.py b/httpx/_transports/wsgi.py index e71f1604..e8bdfd3f 100644 --- a/httpx/_transports/wsgi.py +++ b/httpx/_transports/wsgi.py @@ -1,5 +1,6 @@ import io import itertools +import sys import typing from urllib.parse import unquote @@ -67,11 +68,13 @@ class WSGITransport(BaseTransport): raise_app_exceptions: bool = True, script_name: str = "", remote_addr: str = "127.0.0.1", + wsgi_errors: typing.Optional[typing.TextIO] = None, ) -> None: self.app = app self.raise_app_exceptions = raise_app_exceptions self.script_name = script_name self.remote_addr = remote_addr + self.wsgi_errors = wsgi_errors def handle_request( self, @@ -94,7 +97,7 @@ class WSGITransport(BaseTransport): "wsgi.version": (1, 0), "wsgi.url_scheme": scheme.decode("ascii"), "wsgi.input": wsgi_input, - "wsgi.errors": io.BytesIO(), + "wsgi.errors": self.wsgi_errors or sys.stderr, "wsgi.multithread": True, "wsgi.multiprocess": False, "wsgi.run_once": False, diff --git a/tests/test_wsgi.py b/tests/test_wsgi.py index 164899b5..0eeb32d1 100644 --- a/tests/test_wsgi.py +++ b/tests/test_wsgi.py @@ -1,6 +1,7 @@ import sys import wsgiref.validate from functools import partial +from io import StringIO import pytest @@ -70,6 +71,12 @@ def raise_exc(environ, start_response, exc=ValueError): return [output] +def log_to_wsgi_log_buffer(environ, start_response): + print("test1", file=environ["wsgi.errors"]) + environ["wsgi.errors"].write("test2") + return echo_body(environ, start_response) + + def test_wsgi(): client = httpx.Client(app=application_factory([b"Hello, World!"])) response = client.get("http://www.example.org/") @@ -119,6 +126,16 @@ def test_wsgi_generator_empty(): assert response.text == "" +def test_logging(): + buffer = StringIO() + transport = httpx.WSGITransport(app=log_to_wsgi_log_buffer, wsgi_errors=buffer) + client = httpx.Client(transport=transport) + response = client.post("http://www.example.org/", content=b"example") + assert response.status_code == 200 # no errors + buffer.seek(0) + assert buffer.read() == "test1\ntest2" + + @pytest.mark.parametrize( "url, expected_server_port", [