From c34203d56c6fb08a83fdd2a971de4bdd83ea7124 Mon Sep 17 00:00:00 2001 From: JSap0914 Date: Wed, 17 Jun 2026 16:29:03 +0900 Subject: [PATCH] fix(init): validate Python version constraint in interactive prompt The interactive Python version prompt in `poetry init` accepted arbitrary strings without validation, silently writing invalid constraints like `invalid-python` verbatim into `pyproject.toml`. This inconsistency existed because PR #10909 added `_validate_version_constraint` to the dependency-version prompt but left the Python-version prompt unguarded. Apply the same validator (`_validate_version_constraint`) and the same `set_max_attempts(3)` to the Compatible Python versions question. Invalid constraints now raise a clear error and re-prompt the user, consistent with the dependency version and author validators in the same command. Verification: pytest tests/console/commands/test_init.py \ -k test_python_version_constraint_validated_in_interactive_prompt --- src/poetry/console/commands/init.py | 2 ++ tests/console/commands/test_init.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/poetry/console/commands/init.py b/src/poetry/console/commands/init.py index a0921fdd1eb..2f9cdccca8b 100644 --- a/src/poetry/console/commands/init.py +++ b/src/poetry/console/commands/init.py @@ -181,6 +181,8 @@ def _init_pyproject( f"Compatible Python versions [{python}]: ", default=python, ) + question.set_validator(self._validate_version_constraint) + question.set_max_attempts(3) python = self.ask(question) if is_interactive: diff --git a/tests/console/commands/test_init.py b/tests/console/commands/test_init.py index 935f6d1d9cb..c6d5d1dc91a 100644 --- a/tests/console/commands/test_init.py +++ b/tests/console/commands/test_init.py @@ -1048,6 +1048,29 @@ def test_validate_version_constraint_rejects_invalid_inputs(invalid: str) -> Non InitCommand._validate_version_constraint(invalid) +def test_python_version_constraint_validated_in_interactive_prompt( + tester: CommandTester, +) -> None: + """Invalid Python version constraints should be rejected and re-prompted.""" + inputs = [ + "my-package", # Package name + "1.2.3", # Version + "", # Description + "n", # Author + "", # License + "invalid-python", # Python version -- INVALID, gets rejected + ">=3.8", # Python version -- VALID on retry + "n", # Interactive packages + "n", # Interactive dev packages + "\n", # Generate + ] + tester.execute(inputs="\n".join(inputs)) + output = tester.io.fetch_output() + + assert 'requires-python = ">=3.8"' in output + assert 'requires-python = "invalid-python"' not in output + + @pytest.mark.parametrize( "author", [