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
3 changes: 2 additions & 1 deletion src/python_picnic_api2/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from .client import PicnicAPI
from .exceptions import PicnicParseError
from .exceptions import PicnicAPIError, PicnicParseError
from .models import (
Address,
Article,
Expand All @@ -26,6 +26,7 @@
"PicnicAuthError",
"Picnic2FAError",
"Picnic2FARequired",
"PicnicAPIError",
"PicnicParseError",
"PicnicModel",
"Article",
Expand Down
39 changes: 30 additions & 9 deletions src/python_picnic_api2/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import typing_extensions

from .exceptions import PicnicParseError
from .exceptions import PicnicAPIError, PicnicParseError
from .helper import _url_generator
from .models import (
Article,
Expand Down Expand Up @@ -51,17 +51,37 @@ def __init__(
if not self.session.authenticated and username and password:
self.login(username, password)

@staticmethod
def _parse_json(response, url: str):
"""Decode a response body, raising a descriptive error if it is not JSON.

Picnic's edge can answer with an HTML or plain-text page instead of the
expected JSON (e.g. an HTTP 403 on ``/cart``). Without this the body
error surfaces as a bare ``JSONDecodeError`` that hides the status code.
"""
try:
return response.json()
except ValueError as error:
body = response.text[:200]
raise PicnicAPIError(
"Picnic API returned a non-JSON response "
f"(HTTP {response.status_code}) for {url}: {body!r}",
status_code=response.status_code,
body=body,
) from error

def _get(self, path: str, add_picnic_headers=False):
url = self._base_url + path

# Make the request, add special picnic headers if needed
headers = _HEADERS if add_picnic_headers else None
response = self.session.get(url, headers=headers).json()
response = self.session.get(url, headers=headers)
body = self._parse_json(response, url)

if self._contains_auth_error(response):
if self._contains_auth_error(body):
raise PicnicAuthError("Picnic authentication error")

return response
return body

def _post(
self, path: str, data=None, base_url_override=None, add_picnic_headers=False
Expand All @@ -70,14 +90,15 @@ def _post(
kwargs = {"json": data}
if add_picnic_headers:
kwargs["headers"] = _HEADERS
response = self.session.post(url, **kwargs).json()
response = self.session.post(url, **kwargs)
body = self._parse_json(response, url)

if self._contains_auth_error(response):
if self._contains_auth_error(body):
raise PicnicAuthError(
f"Picnic authentication error: {response['error'].get('message')}"
f"Picnic authentication error: {body['error'].get('message')}"
)

return response
return body

@staticmethod
def _contains_auth_error(response):
Expand Down Expand Up @@ -120,7 +141,7 @@ def _post_2fa(self, path: str, data=None):
if response.status_code == 204 or not response.content:
return None

json_body = response.json()
json_body = self._parse_json(response, url)

# This should not happen because password auth is already done
# at this point, but just in case.
Expand Down
27 changes: 27 additions & 0 deletions src/python_picnic_api2/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,32 @@
from .session import Picnic2FAError, Picnic2FARequired, PicnicAuthError


class PicnicAPIError(ValueError):
"""Raised when the Picnic API returns a body that is not JSON.

Picnic normally returns JSON, including for errors, but its edge/WAF can
answer with an HTML or plain-text page (e.g. a 403 on ``/cart``). Raised
instead of a bare ``JSONDecodeError`` so the HTTP status and the start of
the body end up in the message.

Subclasses :class:`ValueError` because callers treat an undecodable body as
a transient response error: Home Assistant's Picnic coordinator maps
``ValueError`` to ``UpdateFailed`` and suppresses it for endpoints that
legitimately return an empty body.
"""

def __init__(
self,
message: str,
*,
status_code: int | None = None,
body: str | None = None,
):
super().__init__(message)
self.status_code = status_code
self.body = body


class PicnicParseError(Exception):
"""Raised when a Picnic PML ("layout") response cannot be parsed into a model.

Expand All @@ -25,6 +51,7 @@ def __init__(self, message: str, *, endpoint: str | None = None):


__all__ = [
"PicnicAPIError",
"PicnicParseError",
"PicnicAuthError",
"Picnic2FARequired",
Expand Down
39 changes: 38 additions & 1 deletion tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import pytest

from python_picnic_api2 import Category, PicnicAPI
from python_picnic_api2 import Category, PicnicAPI, PicnicAPIError
from python_picnic_api2.client import DEFAULT_URL
from python_picnic_api2.session import (
Picnic2FAError,
Expand All @@ -24,7 +24,13 @@ def __init__(self, json_data, status_code, content=b"data"):
self.status_code = status_code
self.content = content

@property
def text(self):
return self.content.decode("utf-8", errors="replace")

def json(self):
if isinstance(self.json_data, Exception):
raise self.json_data
return self.json_data

def setUp(self) -> None:
Expand Down Expand Up @@ -394,6 +400,37 @@ def test_get_category_by_ids(self):
self.assertEqual(category.l2_id, 1000)
self.assertEqual(category.l3_id, 22193)

def test_get_non_json_response(self):
body = b"<html><body>403 Forbidden</body></html>"
self.session_mock().get.return_value = self.MockResponse(
ValueError("Expecting value: line 1 column 1 (char 0)"), 403, content=body
)

with self.assertRaises(PicnicAPIError) as ctx:
self.client.get_cart()

self.assertEqual(str(ctx.exception), (
"Picnic API returned a non-JSON response (HTTP 403) for "
f"{self.expected_base_url}/cart: {body.decode()!r}"
))
self.assertEqual(ctx.exception.status_code, 403)
self.assertEqual(ctx.exception.body, body.decode())
# Callers rely on ValueError handling for transient body errors
self.assertIsInstance(ctx.exception, ValueError)

def test_post_non_json_response(self):
body = b"Rate limited"
self.session_mock().post.return_value = self.MockResponse(
ValueError("Expecting value: line 1 column 1 (char 0)"), 429,
content=body,
)

with self.assertRaises(PicnicAPIError) as ctx:
self.client.clear_cart()

self.assertEqual(ctx.exception.status_code, 429)
self.assertEqual(ctx.exception.body, body.decode())

def test_get_auth_exception(self):
self.session_mock().get.return_value = self.MockResponse(
{"error": {"code": "AUTH_ERROR"}}, 400
Expand Down