Skip to content

Commit

Permalink
Adjust violations
Browse files Browse the repository at this point in the history
  • Loading branch information
epenet committed Sep 11, 2024
1 parent ba614a1 commit ef425a2
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 20 deletions.
34 changes: 25 additions & 9 deletions src/sfrbox_api/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@


def _with_error_wrapping(
func: Callable[_P, Awaitable[_R]]
func: Callable[_P, Awaitable[_R]],
) -> Callable[_P, Coroutine[Any, Any, _R]]:
"""Catch httpx errors."""

Expand Down Expand Up @@ -69,7 +69,9 @@ def __init__(self, *, ip: str, client: httpx.AsyncClient) -> None:
self._ip = ip
self._client = client

async def authenticate(self, *, username: str = "admin", password: str) -> None:
async def authenticate(
self, *, username: str = "admin", password: str
) -> None:
"""Initialise le token pour pouvoir accéder aux méthodes privées de l'API."""
self._username = username
self._password = password
Expand All @@ -95,7 +97,9 @@ async def _get_token(self) -> str:
)
token = element.get("token", "")
hash = compute_hash(token, self._username, self._password)
element = await self._send_get("auth", "checkToken", token=token, hash=hash)
element = await self._send_get(
"auth", "checkToken", token=token, hash=hash
)
assert element is not None # noqa: S101
return element.get("token", "")

Expand All @@ -118,7 +122,9 @@ def _check_response(self, response: httpx.Response) -> XmlElement:
try:
element: XmlElement = DefusedElementTree.fromstring(response_text)
except Exception as exc:
raise SFRBoxError(f"Failed to parse response: {response_text}") from exc
raise SFRBoxError(
f"Failed to parse response: {response_text}"
) from exc
stat = element.get("stat", "")
if (
stat == "fail"
Expand All @@ -129,7 +135,9 @@ def _check_response(self, response: httpx.Response) -> XmlElement:
if code in {"115", "204", "901"}:
# Reset token on auth failure
self._token = None
raise SFRBoxAuthenticationError(f"Api call failed: [{code}] {msg}")
raise SFRBoxAuthenticationError(
f"Api call failed: [{code}] {msg}"
)
raise SFRBoxApiError(f"Api call failed: [{code}] {msg}")
if stat != "ok":
raise SFRBoxError(f"Response was not ok: {response_text}")
Expand All @@ -140,7 +148,9 @@ async def _send_get_simple(
self, namespace: str, method: str, **kwargs: str
) -> XmlElement:
params = httpx.QueryParams(method=f"{namespace}.{method}", **kwargs)
response = await self._client.get(f"http://{self._ip}/api/1.0/", params=params)
response = await self._client.get(
f"http://{self._ip}/api/1.0/", params=params
)
element = self._check_response(response)
return element

Expand All @@ -149,7 +159,9 @@ async def _send_get(
self, namespace: str, method: str, **kwargs: str
) -> XmlElement | None:
params = httpx.QueryParams(method=f"{namespace}.{method}", **kwargs)
response = await self._client.get(f"http://{self._ip}/api/1.0/", params=params)
response = await self._client.get(
f"http://{self._ip}/api/1.0/", params=params
)
element = self._check_response(response)
if len(element) == 0:
return None
Expand Down Expand Up @@ -211,10 +223,14 @@ async def wan_get_info(self) -> WanInfo | None:
async def wlan_get_client_list(self) -> WlanClientList:
"""Liste des clients WiFi."""
token = await self._ensure_token()
xml_response = await self._send_get_simple("wlan", "getClientList", token=token)
xml_response = await self._send_get_simple(
"wlan", "getClientList", token=token
)
client_elements = xml_response.findall("client")
return WlanClientList(
clients=[WlanClient(**element.attrib) for element in client_elements]
clients=[
WlanClient(**element.attrib) for element in client_elements
]
)

async def wlan_get_info(self) -> WlanInfo:
Expand Down
1 change: 1 addition & 0 deletions src/sfrbox_api/cli/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Command-line interface."""

import click


Expand Down
1 change: 1 addition & 0 deletions src/sfrbox_api/helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""SFR Box helpers."""

import hashlib
import hmac

Expand Down
6 changes: 4 additions & 2 deletions src/sfrbox_api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@


def _empty_to_none(
v: Union[float, int, str, None]
v: Union[float, int, str, None],
) -> Optional[Union[float, int, str, None]]:
return None if v == "" else v

Expand All @@ -22,7 +22,9 @@ class DslInfo:
"""Informations sur le lien ADSL."""

# validators
_empty_to_none = validator("uptime", pre=True, allow_reuse=True)(_empty_to_none)
_empty_to_none = validator("uptime", pre=True, allow_reuse=True)(
_empty_to_none
)

linemode: str
"""Mode du lien.
Expand Down
1 change: 1 addition & 0 deletions tests/cli/test_main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Test cases for the __main__ module."""

import pytest
from click.testing import CliRunner

Expand Down
36 changes: 27 additions & 9 deletions tests/test_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@


def _load_fixture(filename: str) -> str:
return pathlib.Path(__file__).parent.joinpath("fixtures", filename).read_text()
return (
pathlib.Path(__file__).parent.joinpath("fixtures", filename).read_text()
)


@respx.mock
Expand Down Expand Up @@ -71,7 +73,9 @@ async def test_authenticate_invalid_password() -> None:
box._token = "previous_token" # noqa: S105
with pytest.raises(
SFRBoxAuthenticationError,
match=re.escape("Api call failed: [204] Invalid login and/or password"),
match=re.escape(
"Api call failed: [204] Invalid login and/or password"
),
):
await box.authenticate(password="invalid_password") # noqa: S106
assert box._username == "admin"
Expand All @@ -85,7 +89,9 @@ async def test_authenticate_no_credentials() -> None:
"""It exits with a status code of zero."""
async with httpx.AsyncClient() as client:
box = SFRBox(ip="192.168.0.1", client=client)
with pytest.raises(SFRBoxAuthenticationError, match="Credentials not set"):
with pytest.raises(
SFRBoxAuthenticationError, match="Credentials not set"
):
await box._ensure_token()


Expand Down Expand Up @@ -341,8 +347,12 @@ async def test_wlan_getclientlist() -> None:
info = await box.wlan_get_client_list()
assert info == WlanClientList(
clients=[
WlanClient(mac_addr="01:02:03:04:05:06", ip_addr="192.168.1.23"),
WlanClient(mac_addr="06:07:08:09:10:11", ip_addr="192.168.1.24"),
WlanClient(
mac_addr="01:02:03:04:05:06", ip_addr="192.168.1.23"
),
WlanClient(
mac_addr="06:07:08:09:10:11", ip_addr="192.168.1.24"
),
]
)

Expand Down Expand Up @@ -385,7 +395,9 @@ async def test_wan_getinfo_fail() -> None:
box = SFRBox(ip="192.168.0.1", client=client)
with pytest.raises(
SFRBoxApiError,
match=re.escape("Api call failed: [[code-erreur]] [message-erreur]"),
match=re.escape(
"Api call failed: [[code-erreur]] [message-erreur]"
),
):
await box.wan_get_info()

Expand All @@ -399,7 +411,9 @@ async def test_wan_getinfo_invalid_xml() -> None:
)
async with httpx.AsyncClient() as client:
box = SFRBox(ip="192.168.0.1", client=client)
with pytest.raises(SFRBoxError, match="Failed to parse response: Invalid XML"):
with pytest.raises(
SFRBoxError, match="Failed to parse response: Invalid XML"
):
await box.wan_get_info()


Expand All @@ -412,7 +426,9 @@ async def test_wan_getinfo_incorrect_xml() -> None:
)
async with httpx.AsyncClient() as client:
box = SFRBox(ip="192.168.0.1", client=client)
with pytest.raises(SFRBoxError, match="Response was not ok: <incorrect_xml />"):
with pytest.raises(
SFRBoxError, match="Response was not ok: <incorrect_xml />"
):
await box.wan_get_info()


Expand All @@ -425,7 +441,9 @@ async def test_wan_getinfo_incorrect_namespace() -> None:
)
async with httpx.AsyncClient() as client:
box = SFRBox(ip="192.168.0.1", client=client)
with pytest.raises(SFRBoxError, match="Namespace wan not found in response"):
with pytest.raises(
SFRBoxError, match="Namespace wan not found in response"
):
await box.wan_get_info()


Expand Down
1 change: 1 addition & 0 deletions tests/test_helper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Test cases for the __main__ module."""

from sfrbox_api.helpers import compute_hash


Expand Down

0 comments on commit ef425a2

Please sign in to comment.