Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/poetry/console/commands/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ def _determine_requirements(
"(or leave blank to use the latest version):"
)
question.set_max_attempts(3)
question.set_validator(lambda x: (x or "").strip() or None)
question.set_validator(self._validate_version_constraint)

package_constraint = self.ask(question)

Expand Down Expand Up @@ -521,6 +521,21 @@ def _validate_package(package: str | None) -> str | None:

return package

@staticmethod
def _validate_version_constraint(constraint: str | None) -> str | None:
from poetry.core.constraints.version import parse_constraint

constraint = (constraint or "").strip()
if not constraint:
return None

try:
parse_constraint(constraint)
except ValueError as e:
raise ValueError(f"Invalid version constraint: {constraint}") from e

return constraint

def _get_pool(self) -> RepositoryPool:
from poetry.config.config import Config
from poetry.repositories import RepositoryPool
Expand Down
32 changes: 32 additions & 0 deletions tests/console/commands/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -1016,6 +1016,38 @@ def test_validate_package_invalid(name: str) -> None:
assert InitCommand._validate_package(name)


@pytest.mark.parametrize(
("constraint", "expected"),
[
("^1.0", "^1.0"),
(" ^1.0 ", "^1.0"),
("==1.2.3", "==1.2.3"),
(">=1,<2", ">=1,<2"),
("", None),
(None, None),
(" ", None),
],
)
def test_validate_version_constraint_accepts_valid_inputs(
constraint: str | None, expected: str | None
) -> None:
assert InitCommand._validate_version_constraint(constraint) == expected


@pytest.mark.parametrize(
"invalid",
[
"latest",
"isort",
"==1.,",
"not-a-version",
],
)
def test_validate_version_constraint_rejects_invalid_inputs(invalid: str) -> None:
with pytest.raises(ValueError, match="Invalid version constraint"):
InitCommand._validate_version_constraint(invalid)


@pytest.mark.parametrize(
"author",
[
Expand Down
Loading