Skip to content

Commit 0b4a832

Browse files
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 <tom@tomchristie.com>
1 parent c24bbb8 commit 0b4a832

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

httpx/_transports/wsgi.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import io
22
import itertools
3+
import sys
34
import typing
45
from urllib.parse import unquote
56

@@ -67,11 +68,13 @@ def __init__(
6768
raise_app_exceptions: bool = True,
6869
script_name: str = "",
6970
remote_addr: str = "127.0.0.1",
71+
wsgi_errors: typing.Optional[typing.TextIO] = None,
7072
) -> None:
7173
self.app = app
7274
self.raise_app_exceptions = raise_app_exceptions
7375
self.script_name = script_name
7476
self.remote_addr = remote_addr
77+
self.wsgi_errors = wsgi_errors
7578

7679
def handle_request(
7780
self,
@@ -94,7 +97,7 @@ def handle_request(
9497
"wsgi.version": (1, 0),
9598
"wsgi.url_scheme": scheme.decode("ascii"),
9699
"wsgi.input": wsgi_input,
97-
"wsgi.errors": io.BytesIO(),
100+
"wsgi.errors": self.wsgi_errors or sys.stderr,
98101
"wsgi.multithread": True,
99102
"wsgi.multiprocess": False,
100103
"wsgi.run_once": False,

tests/test_wsgi.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import sys
22
import wsgiref.validate
33
from functools import partial
4+
from io import StringIO
45

56
import pytest
67

@@ -70,6 +71,12 @@ def raise_exc(environ, start_response, exc=ValueError):
7071
return [output]
7172

7273

74+
def log_to_wsgi_log_buffer(environ, start_response):
75+
print("test1", file=environ["wsgi.errors"])
76+
environ["wsgi.errors"].write("test2")
77+
return echo_body(environ, start_response)
78+
79+
7380
def test_wsgi():
7481
client = httpx.Client(app=application_factory([b"Hello, World!"]))
7582
response = client.get("http://www.example.org/")
@@ -119,6 +126,16 @@ def test_wsgi_generator_empty():
119126
assert response.text == ""
120127

121128

129+
def test_logging():
130+
buffer = StringIO()
131+
transport = httpx.WSGITransport(app=log_to_wsgi_log_buffer, wsgi_errors=buffer)
132+
client = httpx.Client(transport=transport)
133+
response = client.post("http://www.example.org/", content=b"example")
134+
assert response.status_code == 200 # no errors
135+
buffer.seek(0)
136+
assert buffer.read() == "test1\ntest2"
137+
138+
122139
@pytest.mark.parametrize(
123140
"url, expected_server_port",
124141
[

0 commit comments

Comments
 (0)