Skip to content

Commit 45966c2

Browse files
authored
Add missing type hints and some code cleanup (#29)
1 parent 9b24a8d commit 45966c2

4 files changed

Lines changed: 35 additions & 36 deletions

File tree

glances_api/__init__.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def __init__(
3535
self.url = f"{schema}://{host}:{port}/api/{version}"
3636
self.data: dict[str, Any] = {}
3737
self.plugins: list[str] = []
38-
self.values: Any | None = None
38+
self.values: dict[str, Any] | None = None
3939
self.username = username
4040
self.password = password
4141
self.verify_ssl = verify_ssl
@@ -45,7 +45,7 @@ async def get_data(self, endpoint: str) -> None:
4545
"""Retrieve the data."""
4646
url = f"{self.url}/{endpoint}"
4747

48-
httpx_client: Any = (
48+
httpx_client = (
4949
self.httpx_client
5050
if self.httpx_client
5151
else httpx.AsyncClient(verify=self.verify_ssl)
@@ -55,12 +55,16 @@ async def get_data(self, endpoint: str) -> None:
5555
async with httpx_client as client:
5656
if self.password is None:
5757
response = await client.get(url)
58-
else:
58+
elif self.username is not None:
5959
response = await client.get(
6060
url, auth=(self.username, self.password)
6161
)
62-
except (httpx.ConnectError, httpx.TimeoutException):
63-
raise exceptions.GlancesApiConnectionError(f"Connection to {url} failed")
62+
else:
63+
raise ValueError("username and password must be provided.")
64+
except (httpx.ConnectError, httpx.TimeoutException) as err:
65+
raise exceptions.GlancesApiConnectionError(
66+
f"Connection to {url} failed"
67+
) from err
6468

6569
if response.status_code == httpx.codes.UNAUTHORIZED:
6670
raise exceptions.GlancesApiAuthorizationError(
@@ -77,11 +81,11 @@ async def get_data(self, endpoint: str) -> None:
7781
self.data = response.json()
7882
elif endpoint == "pluginslist":
7983
self.plugins = response.json()
80-
except TypeError:
84+
except TypeError as err:
8185
_LOGGER.error("Can not load data from Glances")
8286
raise exceptions.GlancesApiConnectionError(
8387
"Unable to get the data from Glances"
84-
)
88+
) from err
8589

8690
async def get_metrics(self, element: str) -> None:
8791
"""Get all the metrics for a monitored element."""

glances_api/exceptions.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,14 @@
44
class GlancesApiError(Exception):
55
"""General GlancesApiError exception occurred."""
66

7-
pass
8-
97

108
class GlancesApiConnectionError(GlancesApiError):
119
"""When a connection error is encountered."""
1210

13-
pass
14-
1511

1612
class GlancesApiAuthorizationError(GlancesApiError):
1713
"""When a connection error is encountered."""
1814

19-
pass
20-
2115

2216
class GlancesApiNoDataAvailable(GlancesApiError):
2317
"""When no data is available."""
24-
25-
pass

tests/test_responses.py

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
"""Test the interaction with the Glances API."""
2+
from typing import Any
3+
24
import pytest
5+
from pytest_httpx import HTTPXMock
6+
37
from glances_api import Glances
48
from glances_api.exceptions import GlancesApiNoDataAvailable
5-
from pytest_httpx import HTTPXMock
69

710
PLUGINS_LIST_RESPONSE = [
811
"alert",
@@ -17,7 +20,7 @@
1720
"fs",
1821
]
1922

20-
RESPONSE = {
23+
RESPONSE: dict[str, Any] = {
2124
"cpu": {
2225
"total": 10.6,
2326
"user": 7.6,
@@ -241,7 +244,7 @@
241244
"uptime": "3 days, 10:25:20",
242245
}
243246

244-
HA_SENSOR_DATA = {
247+
HA_SENSOR_DATA: dict[str, Any] = {
245248
"fs": {
246249
"/ssl": {"disk_use": 30.7, "disk_use_percent": 6.7, "disk_free": 426.5},
247250
"/media": {"disk_use": 30.7, "disk_use_percent": 6.7, "disk_free": 426.5},
@@ -267,7 +270,7 @@
267270

268271

269272
@pytest.mark.asyncio
270-
async def test_non_existing_endpoint(httpx_mock: HTTPXMock):
273+
async def test_non_existing_endpoint(httpx_mock: HTTPXMock) -> None:
271274
"""Test a non-exisiting endpoint."""
272275
httpx_mock.add_response(status_code=400)
273276

@@ -279,7 +282,7 @@ async def test_non_existing_endpoint(httpx_mock: HTTPXMock):
279282

280283

281284
@pytest.mark.asyncio
282-
async def test_plugins_list(httpx_mock: HTTPXMock):
285+
async def test_plugins_list(httpx_mock: HTTPXMock) -> None:
283286
"""Test the plugins list response."""
284287
httpx_mock.add_response(json=PLUGINS_LIST_RESPONSE)
285288

@@ -290,19 +293,19 @@ async def test_plugins_list(httpx_mock: HTTPXMock):
290293

291294

292295
@pytest.mark.asyncio
293-
async def test_exisiting_endpoint(httpx_mock: HTTPXMock):
296+
async def test_exisiting_endpoint(httpx_mock: HTTPXMock) -> None:
294297
"""Test the a valid endpoint."""
295298
httpx_mock.add_response(json=RESPONSE)
296299

297300
client = Glances()
298301
await client.get_metrics("cpu")
299-
302+
assert client.values
300303
assert client.values["total"] == 10.6
301304
assert client.values["system"] == 2.1
302305

303306

304307
@pytest.mark.asyncio
305-
async def test_ha_sensor_data(httpx_mock: HTTPXMock):
308+
async def test_ha_sensor_data(httpx_mock: HTTPXMock) -> None:
306309
"""Test the return value for ha sensors."""
307310
httpx_mock.add_response(json=RESPONSE)
308311

@@ -315,21 +318,21 @@ async def test_ha_sensor_data(httpx_mock: HTTPXMock):
315318
@pytest.mark.asyncio
316319
async def test_ha_sensor_data_with_incomplete_container_information(
317320
httpx_mock: HTTPXMock,
318-
):
319-
"""Test the return value for ha sensors when container memory and cpu data is not exposed by glances."""
320-
TEST_RESPONSE = RESPONSE
321-
del TEST_RESPONSE["containers"]["containers"][0]["memory"]["usage"]
322-
del TEST_RESPONSE["containers"]["containers"][0]["cpu"]["total"]
323-
del TEST_RESPONSE["containers"]["containers"][1]["memory"]["usage"]
324-
del TEST_RESPONSE["containers"]["containers"][1]["cpu"]["total"]
321+
) -> None:
322+
"""Test the return value for ha sensors when some data is not exposed."""
323+
response = RESPONSE.copy()
324+
del response["containers"]["containers"][0]["memory"]["usage"]
325+
del response["containers"]["containers"][0]["cpu"]["total"]
326+
del response["containers"]["containers"][1]["memory"]["usage"]
327+
del response["containers"]["containers"][1]["cpu"]["total"]
325328

326-
TEST_HA_SENSOR_DATA = HA_SENSOR_DATA
327-
TEST_HA_SENSOR_DATA["docker"]["docker_memory_use"] = 0
328-
TEST_HA_SENSOR_DATA["docker"]["docker_cpu_use"] = 0
329+
ha_sensor_data = HA_SENSOR_DATA.copy()
330+
ha_sensor_data["docker"]["docker_memory_use"] = 0
331+
ha_sensor_data["docker"]["docker_cpu_use"] = 0
329332

330-
httpx_mock.add_response(json=TEST_RESPONSE)
333+
httpx_mock.add_response(json=response)
331334

332335
client = Glances()
333336
result = await client.get_ha_sensor_data()
334337

335-
assert result == TEST_HA_SENSOR_DATA
338+
assert result == ha_sensor_data

tests/test_timeout.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88

99
@pytest.mark.asyncio
10-
async def test_timeout(httpx_mock: HTTPXMock):
10+
async def test_timeout(httpx_mock: HTTPXMock) -> None:
1111
"""Test if the connection is hitting the timeout."""
1212

1313
def raise_timeout(request):

0 commit comments

Comments
 (0)