]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
Handle default ports in WSGITransport (#1469)
authorAber <me@abersheeran.com>
Tue, 16 Feb 2021 12:33:17 +0000 (20:33 +0800)
committerGitHub <noreply@github.com>
Tue, 16 Feb 2021 12:33:17 +0000 (13:33 +0100)
* 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 <florimond.manca@gmail.com>
httpx/_transports/wsgi.py
tests/test_wsgi.py

index 953e1908c23bb500a352b0f48963be29d9a71151..67b44bde42f3f717637cc1e674ad15afb3fb99f2 100644 (file)
@@ -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"),
index 7bf11a0c34b71b32c59b056b87335535c691c6df..b130e53c40db3c428aa1cd0d383c55b7c32b26c0 100644 (file)
@@ -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