From e1cc16f8bea15f11f63eacaa6089cd6e6b8b1965 Mon Sep 17 00:00:00 2001 From: vorelq Date: Sat, 29 Sep 2018 18:38:32 +0200 Subject: [PATCH] Fix 0 port value being overriden by default By explicitly comparing port value with None, instead of using its bool() value. --- CHANGES.rst | 2 ++ flask/app.py | 3 ++- tests/test_basic.py | 17 ++++++++++------- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 45fe3651..3a9597a3 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -42,6 +42,8 @@ Unreleased :pr:`3195` - Allow customizing the :attr:`Flask.url_map_class` used for routing. :pr:`3069` +- The development server port can be set to 0, which tells the OS to + pick an available port. :issue:`2926` .. _#2935: https://github.com/pallets/flask/issues/2935 .. _#2957: https://github.com/pallets/flask/issues/2957 diff --git a/flask/app.py b/flask/app.py index acbc00e7..50775ce4 100644 --- a/flask/app.py +++ b/flask/app.py @@ -972,7 +972,8 @@ class Flask(_PackageBoundObject): sn_host, _, sn_port = server_name.partition(":") host = host or sn_host or _host - port = int(port or sn_port or _port) + # pick the first value that's not None (0 is allowed) + port = int(next((p for p in (port, sn_port) if p is not None), _port)) options.setdefault("use_reloader", self.debug) options.setdefault("use_debugger", self.debug) diff --git a/tests/test_basic.py b/tests/test_basic.py index 86beeb12..b759098f 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -1916,21 +1916,24 @@ def test_run_server_port(monkeypatch, app): @pytest.mark.parametrize( - "host,port,expect_host,expect_port", + "host,port,server_name,expect_host,expect_port", ( - (None, None, "pocoo.org", 8080), - ("localhost", None, "localhost", 8080), - (None, 80, "pocoo.org", 80), - ("localhost", 80, "localhost", 80), + (None, None, "pocoo.org:8080", "pocoo.org", 8080), + ("localhost", None, "pocoo.org:8080", "localhost", 8080), + (None, 80, "pocoo.org:8080", "pocoo.org", 80), + ("localhost", 80, "pocoo.org:8080", "localhost", 80), + ("localhost", 0, "localhost:8080", "localhost", 0), + (None, None, "localhost:8080", "localhost", 8080), + (None, None, "localhost:0", "localhost", 0), ), ) -def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app): +def test_run_from_config(monkeypatch, host, port, server_name, expect_host, expect_port, app): def run_simple_mock(hostname, port, *args, **kwargs): assert hostname == expect_host assert port == expect_port monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock) - app.config["SERVER_NAME"] = "pocoo.org:8080" + app.config["SERVER_NAME"] = server_name app.run(host, port)