Skip to content

Commit dc0fc1a

Browse files
authored
Fix API connection error handling (#13)
Fixes #12 Fixes home-assistant/core/issues/61687
1 parent 2e45203 commit dc0fc1a

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

luftdaten/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ async def get_data(self):
2929
response = await client.get(str(url))
3030
except httpx.ConnectError:
3131
raise exceptions.LuftdatenConnectionError(f"Connection to {url} failed")
32+
except httpx.ConnectTimeout:
33+
raise exceptions.LuftdatenConnectionError(f"Connection to {url} timed out")
34+
except httpx.ReadTimeout:
35+
raise exceptions.LuftdatenConnectionError(f"Read timeout from {url}")
3236

3337
if response.status_code == httpx.codes.OK:
3438
try:

tests/test_timeout.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,29 @@
44
from pytest_httpx import HTTPXMock
55

66
from luftdaten import Luftdaten
7+
from luftdaten.exceptions import LuftdatenConnectionError
78

89
SENSOR_ID = 1
910

1011
@pytest.mark.asyncio
11-
async def test_timeout(httpx_mock: HTTPXMock):
12-
"""Test if the connection is hitting the timeout."""
12+
async def test_connect_timeout(httpx_mock: HTTPXMock):
13+
"""Test if the connection is hitting the timeout during connect."""
14+
15+
def raise_timeout(request):
16+
"""Set the timeout for the requests."""
17+
raise httpx.ConnectTimeout(
18+
f"Unable to connect within {request.extensions['timeout']}", request=request
19+
)
20+
21+
httpx_mock.add_callback(raise_timeout)
22+
23+
with pytest.raises(LuftdatenConnectionError):
24+
client = Luftdaten(SENSOR_ID)
25+
await client.get_data()
26+
27+
@pytest.mark.asyncio
28+
async def test_read_timeout(httpx_mock: HTTPXMock):
29+
"""Test if the connection is hitting the timeout during data reading."""
1330

1431
def raise_timeout(request):
1532
"""Set the timeout for the requests."""
@@ -19,6 +36,6 @@ def raise_timeout(request):
1936

2037
httpx_mock.add_callback(raise_timeout)
2138

22-
with pytest.raises(httpx.ReadTimeout):
39+
with pytest.raises(LuftdatenConnectionError):
2340
client = Luftdaten(SENSOR_ID)
2441
await client.get_data()

0 commit comments

Comments
 (0)