-
Notifications
You must be signed in to change notification settings - Fork 283
feat: errors.py #1071
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+225
−47
Merged
feat: errors.py #1071
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import contextlib | ||
| import dataclasses | ||
| import sys | ||
| import typing | ||
|
|
||
| __all__ = ["ExceptionGroup"] | ||
|
|
||
|
|
||
| def __dir__() -> list[str]: | ||
| return __all__ | ||
|
|
||
|
|
||
| if sys.version_info >= (3, 11): # pragma: no cover | ||
| from builtins import ExceptionGroup | ||
| else: # pragma: no cover | ||
|
|
||
| class ExceptionGroup(Exception): | ||
| """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11. | ||
|
|
||
| If :external:exc:`ExceptionGroup` is already defined by Python itself, | ||
| that version is used instead. | ||
| """ | ||
|
|
||
| message: str | ||
| exceptions: list[Exception] | ||
|
|
||
| def __init__(self, message: str, exceptions: list[Exception]) -> None: | ||
| self.message = message | ||
| self.exceptions = exceptions | ||
|
|
||
| def __repr__(self) -> str: | ||
| return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})" | ||
|
|
||
|
|
||
| @dataclasses.dataclass | ||
| class _ErrorCollector: | ||
| """ | ||
| Collect errors into ExceptionGroups. | ||
|
|
||
| Used like this: | ||
|
|
||
| collector = _ErrorCollector() | ||
| # Add a single exception | ||
| collector.error(ValueError("one")) | ||
|
|
||
| # Supports nesting, including combining ExceptionGroups | ||
| with collector.collect(): | ||
| raise ValueError("two") | ||
| collector.finalize("Found some errors") | ||
|
|
||
| Since making a collector and then calling finalize later is a common pattern, | ||
| a convenience method ``on_exit`` is provided. | ||
| """ | ||
|
|
||
| errors: list[Exception] = dataclasses.field(default_factory=list, init=False) | ||
|
|
||
| def finalize(self, msg: str) -> None: | ||
| """Raise a group exception if there are any errors.""" | ||
| if self.errors: | ||
| raise ExceptionGroup(msg, self.errors) | ||
|
|
||
| @contextlib.contextmanager | ||
| def on_exit(self, msg: str) -> typing.Generator[_ErrorCollector, None, None]: | ||
| """ | ||
| Calls finalize if no uncollected errors were present. | ||
|
|
||
| Uncollected errors are raised normally. | ||
| """ | ||
| yield self | ||
| self.finalize(msg) | ||
|
|
||
| @contextlib.contextmanager | ||
| def collect(self, *err_cls: type[Exception]) -> typing.Generator[None, None, None]: | ||
| """ | ||
| Context manager to collect errors into the error list. | ||
|
|
||
| Must be inside loops, as only one error can be collected at a time. | ||
| """ | ||
| error_classes = err_cls or (Exception,) | ||
| try: | ||
| yield | ||
| except ExceptionGroup as error: | ||
| self.errors.extend(error.exceptions) | ||
| except error_classes as error: | ||
| self.errors.append(error) | ||
|
|
||
| def error( | ||
| self, | ||
| error: Exception, | ||
| ) -> None: | ||
| """Add an error to the list.""" | ||
| self.errors.append(error) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import pytest | ||
|
|
||
| import packaging.errors | ||
|
|
||
|
|
||
| def test_error_collector_collect() -> None: | ||
| collector = packaging.errors._ErrorCollector() | ||
|
|
||
| with collector.collect(): | ||
| raise ValueError("first error") | ||
|
|
||
| with collector.collect(): | ||
| raise KeyError("second error") | ||
|
|
||
| collector.error(TypeError("third error")) | ||
|
|
||
| with pytest.raises(packaging.errors.ExceptionGroup) as exc_info: | ||
| collector.finalize("collected errors") | ||
|
|
||
| exception_group = exc_info.value | ||
| assert exception_group.message == "collected errors" | ||
| assert len(exception_group.exceptions) == 3 | ||
| assert isinstance(exception_group.exceptions[0], ValueError) | ||
| assert str(exception_group.exceptions[0]) == "first error" | ||
| assert isinstance(exception_group.exceptions[1], KeyError) | ||
| assert str(exception_group.exceptions[1]) == "'second error'" | ||
| assert isinstance(exception_group.exceptions[2], TypeError) | ||
| assert str(exception_group.exceptions[2]) == "third error" | ||
|
|
||
|
|
||
| def test_error_collector_no_errors() -> None: | ||
| collector = packaging.errors._ErrorCollector() | ||
|
|
||
| with collector.collect(): | ||
| pass # No error | ||
|
|
||
| collector.finalize("no errors") # Should not raise | ||
|
|
||
|
|
||
| def test_error_collector_exception_group() -> None: | ||
| collector = packaging.errors._ErrorCollector() | ||
|
|
||
| with collector.collect(): | ||
| raise packaging.errors.ExceptionGroup( | ||
| "inner group", | ||
| [ValueError("inner error 1"), KeyError("inner error 2")], | ||
| ) | ||
|
|
||
| with pytest.raises(packaging.errors.ExceptionGroup) as exc_info: | ||
| collector.finalize("outer group") | ||
|
|
||
| exception_group = exc_info.value | ||
| assert exception_group.message == "outer group" | ||
| assert len(exception_group.exceptions) == 2 | ||
| assert isinstance(exception_group.exceptions[0], ValueError) | ||
| assert str(exception_group.exceptions[0]) == "inner error 1" | ||
| assert isinstance(exception_group.exceptions[1], KeyError) | ||
| assert str(exception_group.exceptions[1]) == "'inner error 2'" | ||
|
|
||
|
|
||
| def test_error_collector_on_exit() -> None: | ||
| collector = packaging.errors._ErrorCollector() | ||
|
|
||
| with pytest.raises(packaging.errors.ExceptionGroup) as exc_info, collector.on_exit( | ||
| "exiting" | ||
| ): | ||
| collector.error(ValueError("an error")) | ||
|
|
||
| exception_group = exc_info.value | ||
| assert exception_group.message == "exiting" | ||
| assert len(exception_group.exceptions) == 1 | ||
| assert isinstance(exception_group.exceptions[0], ValueError) | ||
| assert str(exception_group.exceptions[0]) == "an error" | ||
|
|
||
|
|
||
| def test_error_collector_on_exit_no_errors() -> None: | ||
| collector = packaging.errors._ErrorCollector() | ||
|
|
||
| with collector.on_exit("exiting"): | ||
| pass # No errors added | ||
|
|
||
|
|
||
| def test_error_collector_collect_specific_exception() -> None: | ||
| collector = packaging.errors._ErrorCollector() | ||
|
|
||
| with collector.collect(KeyError): | ||
| raise KeyError("a key error") | ||
|
|
||
| with pytest.raises(packaging.errors.ExceptionGroup) as exc_info: | ||
| collector.finalize("collected errors") | ||
|
|
||
| exception_group = exc_info.value | ||
| assert exception_group.message == "collected errors" | ||
| assert len(exception_group.exceptions) == 1 | ||
| assert isinstance(exception_group.exceptions[0], KeyError) | ||
| assert str(exception_group.exceptions[0]) == "'a key error'" | ||
|
|
||
|
|
||
| def test_error_collector_collect_unmatched_exception() -> None: | ||
| collector = packaging.errors._ErrorCollector() | ||
|
|
||
| # Now test that other exceptions are not collected | ||
| with pytest.raises( | ||
| ValueError, match="a value error" | ||
| ) as exc_info, collector.collect(KeyError): | ||
| raise ValueError("a value error") | ||
|
|
||
| assert str(exc_info.value) == "a value error" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.