Skip to content

Comments

feat: check requires-poetry before any validation#10593

Merged
finswimmer merged 1 commit intopython-poetry:mainfrom
finswimmer:i10582-requires-poetry
Oct 22, 2025
Merged

feat: check requires-poetry before any validation#10593
finswimmer merged 1 commit intopython-poetry:mainfrom
finswimmer:i10582-requires-poetry

Conversation

@finswimmer
Copy link
Member

@finswimmer finswimmer commented Oct 21, 2025

Pull Request Check List

Resolves: #10582

  • Added tests for changed code.
  • Updated documentation for changed code.

Summary by Sourcery

Ensure that the project’s requires-poetry constraint is validated immediately when creating a Poetry instance, raising an error early if the running Poetry version does not satisfy the requirement.

Enhancements:

  • Extract the version constraint check into a shared _ensure_valid_poetry_version helper and invoke it before any other validation.
  • Remove duplicated version-check logic from Factory.create_poetry.

Tests:

  • Add a test and fixture to verify that an invalid requires-poetry setting triggers an error before other validations.

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 21, 2025

Reviewer's Guide

This PR centralizes the requires-poetry version constraint check into a new helper method and ensures it runs before any other project validation, simplifying the factory logic and adding a test for early enforcement.

Sequence diagram for early requires-poetry version check in create_poetry

sequenceDiagram
    participant Caller
    participant Factory
    participant "_ensure_valid_poetry_version()"
    participant "super().create_poetry()"
    Caller->>Factory: create_poetry(cwd, with_groups, io)
    Factory->>"_ensure_valid_poetry_version()": Check version constraint
    "_ensure_valid_poetry_version()"-->>Factory: Raise error if not allowed
    Factory->>"super().create_poetry()": Create Poetry object
    "super().create_poetry()"-->>Factory: Poetry object
    Factory-->>Caller: Poetry object
Loading

Class diagram for updated Factory class (requires-poetry check centralization)

classDiagram
    class Factory {
        +_ensure_valid_poetry_version(cwd: Path | None) void
        +create_poetry(cwd: Path | None = None, with_groups: bool = True, io: IO | None = None) Poetry
    }
    Factory --|> BaseFactory
    class BaseFactory {
        +create_poetry(cwd: Path | None = None, with_groups: bool = True) Poetry
    }
Loading

File-Level Changes

Change Details Files
Extract and run the requires-poetry check before validation
  • Introduced _ensure_valid_poetry_version to load and enforce the version constraint from pyproject
  • Called the new helper at the start of create_poetry
  • Removed the old inline version check block after super()
  • Used parse_constraint and Version.parse to validate and raise PoetryError
src/poetry/factory.py
Add test and fixture for early version enforcement
  • Added test_create_poetry_check_version_before_validation to assert errors raised before other checks
  • Created a fixture directory self_version_not_ok_invalid_config with an invalid requires-poetry entry
tests/test_factory.py
tests/fixtures/self_version_not_ok_invalid_config/pyproject.toml

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/poetry/factory.py:55-62` </location>
<code_context>
     Factory class to create various elements needed by Poetry.
     """

+    def _ensure_valid_poetry_version(self, cwd: Path | None) -> None:
+        poetry_file = self.locate(cwd)
+        pyproject = PyProjectTOML(path=poetry_file)
+        poetry_config = pyproject.data.get("tool", {}).get("poetry", {})
+
+        if version_str := poetry_config.get("requires-poetry"):
+            version_constraint = parse_constraint(version_str)
+            version = Version.parse(__version__)
+            if not version_constraint.allows(version):
+                raise PoetryError(
+                    f"This project requires Poetry {version_constraint},"
+                    f" but you are using Poetry {version}"
+                )
+
     def create_poetry(
</code_context>

<issue_to_address>
**suggestion:** Consider handling missing or malformed 'requires-poetry' values more robustly.

If 'requires-poetry' is malformed, parse_constraint may throw an uncaught exception. Consider catching parsing errors and raising a clear PoetryError, or validating the format before parsing.

```suggestion
        if version_str := poetry_config.get("requires-poetry"):
            if not isinstance(version_str, str):
                raise PoetryError(
                    f"Invalid 'requires-poetry' value in pyproject.toml: expected a string, got {type(version_str).__name__}"
                )
            try:
                version_constraint = parse_constraint(version_str)
            except Exception as exc:
                raise PoetryError(
                    f"Malformed 'requires-poetry' value in pyproject.toml: '{version_str}'. Error: {exc}"
                ) from exc
            version = Version.parse(__version__)
            if not version_constraint.allows(version):
                raise PoetryError(
                    f"This project requires Poetry {version_constraint},"
                    f" but you are using Poetry {version}"
                )
```
</issue_to_address>

### Comment 2
<location> `tests/test_factory.py:259-256` </location>
<code_context>
     )


+def test_create_poetry_check_version_before_validation(
+    fixture_dir: FixtureDirGetter,
+) -> None:
+    with pytest.raises(PoetryError) as e:
+        Factory().create_poetry(fixture_dir("self_version_not_ok_invalid_config"))
+    assert (
+        str(e.value)
+        == f"This project requires Poetry <1.2, but you are using Poetry {__version__}"
+    )
+
+
</code_context>

<issue_to_address>
**suggestion (testing):** Consider adding a test for the case where 'requires-poetry' is missing or malformed.

Adding tests for missing, empty, or invalid 'requires-poetry' fields will improve error handling and test coverage for configuration edge cases.

Suggested implementation:

```python
def test_create_poetry_check_version_before_validation(
    fixture_dir: FixtureDirGetter,
) -> None:
    with pytest.raises(PoetryError) as e:
        Factory().create_poetry(fixture_dir("self_version_not_ok_invalid_config"))
    assert (
        str(e.value)
        == f"This project requires Poetry <1.2, but you are using Poetry {__version__}"
    )


def test_create_poetry_missing_requires_poetry(
    fixture_dir: FixtureDirGetter,
) -> None:
    with pytest.raises(PoetryError) as e:
        Factory().create_poetry(fixture_dir("missing_requires_poetry"))
    assert "requires-poetry" in str(e.value)


def test_create_poetry_empty_requires_poetry(
    fixture_dir: FixtureDirGetter,
) -> None:
    with pytest.raises(PoetryError) as e:
        Factory().create_poetry(fixture_dir("empty_requires_poetry"))
    assert "requires-poetry" in str(e.value)


def test_create_poetry_invalid_requires_poetry(
    fixture_dir: FixtureDirGetter,
) -> None:
    with pytest.raises(PoetryError) as e:
        Factory().create_poetry(fixture_dir("invalid_requires_poetry"))
    assert "requires-poetry" in str(e.value)

```

You will need to add the corresponding fixture directories:
- `missing_requires_poetry`
- `empty_requires_poetry`
- `invalid_requires_poetry`

Each should contain a `pyproject.toml` file with the appropriate configuration for the test case:
- Missing: no `requires-poetry` field.
- Empty: `requires-poetry = ""`
- Invalid: `requires-poetry = "not_a_version_specifier"`
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@finswimmer finswimmer requested a review from a team October 21, 2025 16:55
@finswimmer finswimmer force-pushed the i10582-requires-poetry branch from 5981c2e to 5c20f15 Compare October 21, 2025 17:22
@finswimmer finswimmer merged commit 21ac342 into python-poetry:main Oct 22, 2025
63 checks passed
@github-actions
Copy link

This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Nov 22, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

requires-poetry should run before validating the pyproject.toml schema

2 participants