Skip to content

Commit

Permalink
Improve error message parsing (#298)
Browse files Browse the repository at this point in the history
* Improve error message parsing

* Reformat line

* Update CI as parts are broken (#299)

* Update deps

* Change coverage generation

---------

Co-authored-by: tb1337 <[email protected]>
  • Loading branch information
tb1337 and tb1337 authored Sep 15, 2024
1 parent 21df02c commit f8032e9
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 21 deletions.
10 changes: 3 additions & 7 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ jobs:
- name: 🏗 Install Python dependencies
run: poetry install --no-interaction
- name: 🚀 Run pytest
run: poetry run pytest --cov pypaperless tests
run: poetry run pytest -v --cov-report xml:coverage.xml --cov src tests
- name: ⬆️ Upload coverage artifact
uses: actions/[email protected]
with:
name: coverage-${{ matrix.python }}
path: .coverage
path: coverage.xml

coverage:
runs-on: ubuntu-latest
Expand All @@ -68,12 +68,8 @@ jobs:
poetry config virtualenvs.in-project true
- name: 🏗 Install dependencies
run: poetry install --no-interaction
- name: 🚀 Process coverage results
run: |
poetry run coverage combine coverage*/.coverage*
poetry run coverage xml -i
- name: 🚀 Upload coverage report
uses: codecov/[email protected]
with:
fail_ci_if_error: true
token: ${{ secrets.CODECOV_TOKEN }}
fail_ci_if_error: true
6 changes: 3 additions & 3 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ yamllint = "^1.35.1"

[tool.coverage.run]
plugins = ["covdefaults"]
source = ["pypaperless"]

[tool.coverage.report]
fail_under = 95
Expand Down
33 changes: 25 additions & 8 deletions src/pypaperless/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,33 @@ class JsonResponseWithError(PaperlessError):

def __init__(self, payload: Any) -> None:
"""Initialize a `JsonResponseWithError` instance."""
key: str = "error"
message: Any = "unknown error"

if isinstance(payload, dict):
key = "error" if "error" in payload else set(payload.keys()).pop()
message = payload[key]
if isinstance(message, list):
message = message.pop()
def _parse_payload(payload: Any, key: list[str] | None = None) -> tuple[list[str], str]:
"""Parse first suitable error from payload."""
if key is None:
key = []

super().__init__(f"Paperless: {key} - {message}")
if isinstance(payload, list):
return _parse_payload(payload.pop(0), key)
if isinstance(payload, dict):
if "error" in payload:
key.append("error")
return _parse_payload(payload["error"], key)

new_key = next(iter(payload))
key.append(new_key)

return _parse_payload(payload[new_key], key)

return key, payload

key, message = _parse_payload(payload)

if len(key) == 0:
key.append("error")
key_chain = " -> ".join(key)

super().__init__(f"Paperless [{key_chain}]: {message}")


# Models
Expand Down
12 changes: 9 additions & 3 deletions tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,19 +111,25 @@ async def test_jsonresponsewitherror(self) -> None:
payload = "sample string"
raise JsonResponseWithError(payload) # noqa: TRY301
except JsonResponseWithError as exc:
assert exc.args[0] == "Paperless: error - unknown error" # noqa: PT017
assert exc.args[0] == "Paperless [error]: sample string" # noqa: PT017

try:
payload = {"failure": "something failed"}
raise JsonResponseWithError(payload) # noqa: TRY301
except JsonResponseWithError as exc:
assert exc.args[0] == "Paperless: failure - something failed" # noqa: PT017
assert exc.args[0] == "Paperless [failure]: something failed" # noqa: PT017

try:
payload = {"error": ["that", "should", "have", "been", "never", "happened"]}
raise JsonResponseWithError(payload) # noqa: TRY301
except JsonResponseWithError as exc:
assert exc.args[0] == "Paperless: error - happened" # noqa: PT017
assert exc.args[0] == "Paperless [error]: that" # noqa: PT017

try:
payload = [{"some": [[{"weird": {"error": ["occurred"]}}]]}]
raise JsonResponseWithError(payload) # noqa: TRY301
except JsonResponseWithError as exc:
assert exc.args[0] == "Paperless [some -> weird -> error]: occurred" # noqa: PT017

async def test_request(self, resp: aioresponses) -> None:
"""Test generate request."""
Expand Down

0 comments on commit f8032e9

Please sign in to comment.