]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
BUG: wsgi.error should be TextIO, not BytesIO in WSGI transport (#1828)
authorAdrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>
Tue, 7 Sep 2021 14:44:35 +0000 (09:44 -0500)
committerGitHub <noreply@github.com>
Tue, 7 Sep 2021 14:44:35 +0000 (15:44 +0100)
* 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 <tom@tomchristie.com>
httpx/_transports/wsgi.py
tests/test_wsgi.py

index e71f1604d8c747171cbc45c1630c846f3920220b..e8bdfd3f687c1e3bbfcb617191d558bbd1bc2b24 100644 (file)
@@ -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,
index 164899b57f0fa8b80d09635ea512a8877a0f2461..0eeb32d145a09574cde20766200161a784972ad2 100644 (file)
@@ -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",
     [