Skip to content

Commit

Permalink
Add guard against non-200 HTTP responses (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
jpbede authored Feb 2, 2024
1 parent df3bd36 commit 6cb740b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
15 changes: 13 additions & 2 deletions aiotankerkoenig/aiotankerkoenig.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@
import asyncio
from dataclasses import dataclass
from importlib import metadata
import socket
from typing import Any, Self

from aiohttp import ClientSession
from aiohttp import ClientError, ClientSession
from yarl import URL

from .const import GasType, Sort
from .exceptions import TankerkoenigConnectionTimeoutError, TankerkoenigError
from .exceptions import (
TankerkoenigConnectionError,
TankerkoenigConnectionTimeoutError,
TankerkoenigError,
)
from .models import (
PriceInfo,
PriceInfoResponse,
Expand Down Expand Up @@ -66,6 +71,12 @@ async def _request(self, path: str, params: dict[str, Any]) -> str:
raise TankerkoenigConnectionTimeoutError(
msg,
) from exception
except (
ClientError,
socket.gaierror,
) as exception:
msg = "Error occurred while communicating with the tankerkoenig.de API"
raise TankerkoenigConnectionError(msg) from exception

content_type = response.headers.get("Content-Type", "")
text = await response.text()
Expand Down
16 changes: 16 additions & 0 deletions tests/test_aiotankerkoenig.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
GasType,
Sort,
Tankerkoenig,
TankerkoenigConnectionError,
TankerkoenigConnectionTimeoutError,
TankerkoenigError,
TankerkoenigInvalidKeyError,
Expand Down Expand Up @@ -57,6 +58,21 @@ async def test_unexpected_server_response(
await tankerkoenig_client.station_details(station_id="1")


async def test_non_200_response(
responses: aioresponses,
tankerkoenig_client: Tankerkoenig,
) -> None:
"""Test handling unexpected response."""
responses.get(
f"{TANKERKOENIG_ENDPOINT}/json/detail.php?apikey=abc123&id=1",
status=500,
headers={"Content-Type": "plain/text"},
body="Yes",
)
with pytest.raises(TankerkoenigConnectionError):
await tankerkoenig_client.station_details(station_id="1")


@pytest.mark.parametrize(
"message",
[
Expand Down

0 comments on commit 6cb740b

Please sign in to comment.