From 02a692aba574a8e1ea7abd6fdfbfa77258ad8e6e Mon Sep 17 00:00:00 2001 From: Aber Date: Tue, 16 Feb 2021 20:33:17 +0800 Subject: [PATCH] Handle default ports in WSGITransport (#1469) * Maybe port is `None` https://www.python.org/dev/peps/pep-3333/#environ-variables > SERVER_NAME, SERVER_PORT > When HTTP_HOST is not set, these variables can be combined to determine a default. See the URL Reconstruction section below for more detail. SERVER_NAME and SERVER_PORT are required strings and must never be empty. * Add unit test * Compute default port Co-authored-by: Florimond Manca --- httpx/_transports/wsgi.py | 3 +++ tests/test_wsgi.py | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/httpx/_transports/wsgi.py b/httpx/_transports/wsgi.py index 953e1908..67b44bde 100644 --- a/httpx/_transports/wsgi.py +++ b/httpx/_transports/wsgi.py @@ -74,6 +74,9 @@ class WSGITransport(httpcore.SyncHTTPTransport): scheme, host, port, full_path = url path, _, query = full_path.partition(b"?") + if port is None: + port = {b"http": 80, b"https": 443}[scheme] + environ = { "wsgi.version": (1, 0), "wsgi.url_scheme": scheme.decode("ascii"), diff --git a/tests/test_wsgi.py b/tests/test_wsgi.py index 7bf11a0c..b130e53c 100644 --- a/tests/test_wsgi.py +++ b/tests/test_wsgi.py @@ -116,3 +116,30 @@ def test_wsgi_generator_empty(): response = client.get("http://www.example.org/") assert response.status_code == 200 assert response.text == "" + + +@pytest.mark.parametrize( + "url, expected_server_port", + [ + pytest.param("http://www.example.org", "80", id="auto-http"), + pytest.param("https://www.example.org", "443", id="auto-https"), + pytest.param("http://www.example.org:8000", "8000", id="explicit-port"), + ], +) +def test_wsgi_server_port(url: str, expected_server_port: int): + """ + SERVER_PORT is populated correctly from the requested URL. + """ + hello_world_app = application_factory([b"Hello, World!"]) + server_port: str + + def app(environ, start_response): + nonlocal server_port + server_port = environ["SERVER_PORT"] + return hello_world_app(environ, start_response) + + client = httpx.Client(app=app) + response = client.get(url) + assert response.status_code == 200 + assert response.text == "Hello, World!" + assert server_port == expected_server_port -- 2.47.3