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 <florimond.manca@gmail.com>
This commit is contained in:
Aber 2021-02-16 20:33:17 +08:00 committed by GitHub
parent d964343fa1
commit 02a692aba5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 0 deletions

View 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"),

View 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