Skip to content

Commit

Permalink
Enable more pylint checks
Browse files Browse the repository at this point in the history
  • Loading branch information
Andre0512 committed Jul 16, 2023
1 parent e1c8bc5 commit 5a77837
Show file tree
Hide file tree
Showing 15 changed files with 58 additions and 43 deletions.
4 changes: 3 additions & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
[MESSAGES CONTROL]

disable=C,R
disable=missing-docstring

[FORMAT]

max-args=6
max-attributes=8
max-line-length=88
7 changes: 3 additions & 4 deletions pyhon/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
if __name__ == "__main__":
sys.path.insert(0, str(Path(__file__).parent.parent))

# pylint: disable=wrong-import-position
from pyhon import Hon, HonAPI, diagnose, printer

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -91,11 +92,9 @@ async def main() -> None:
data = device.data.copy()
attr = "get" if args.get("all") else "pop"
print(
printer.key_print(
data["attributes"].__getattribute__(attr)("parameters")
)
printer.key_print(getattr(data["attributes"], attr)("parameters"))
)
print(printer.key_print(data.__getattribute__(attr)("appliance")))
print(printer.key_print(getattr(data, attr)("appliance")))
print(printer.key_print(data))
print(
printer.pretty_print(
Expand Down
1 change: 1 addition & 0 deletions pyhon/appliance.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
_LOGGER = logging.getLogger(__name__)


# pylint: disable=too-many-public-methods,too-many-instance-attributes
class HonAppliance:
_MINIMAL_UPDATE_INTERVAL = 5 # seconds

Expand Down
1 change: 1 addition & 0 deletions pyhon/appliances/dw.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=duplicate-code
from typing import Any, Dict

from pyhon.appliances.base import ApplianceBase
Expand Down
1 change: 1 addition & 0 deletions pyhon/appliances/td.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=duplicate-code
from typing import Any, Dict

from pyhon.appliances.base import ApplianceBase
Expand Down
1 change: 1 addition & 0 deletions pyhon/appliances/wd.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=duplicate-code
from typing import Dict, Any

from pyhon.appliances.base import ApplianceBase
Expand Down
1 change: 1 addition & 0 deletions pyhon/appliances/wm.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=duplicate-code
from typing import Any, Dict

from pyhon.appliances.base import ApplianceBase
Expand Down
4 changes: 2 additions & 2 deletions pyhon/command_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ class HonCommandLoader:
"""Loads and parses hOn command data"""

def __init__(self, api: "HonAPI", appliance: "HonAppliance") -> None:
self._api: "HonAPI" = api
self._appliance: "HonAppliance" = appliance
self._api_commands: Dict[str, Any] = {}
self._favourites: List[Dict[str, Any]] = []
self._command_history: List[Dict[str, Any]] = []
self._commands: Dict[str, HonCommand] = {}
self._api: "HonAPI" = api
self._appliance: "HonAppliance" = appliance
self._appliance_data: Dict[str, Any] = {}
self._additional_data: Dict[str, Any] = {}

Expand Down
9 changes: 4 additions & 5 deletions pyhon/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,16 @@ def __init__(
categories: Optional[Dict[str, "HonCommand"]] = None,
category_name: str = "",
):
self._name: str = name
self._api: Optional[HonAPI] = appliance.api
self._appliance: "HonAppliance" = appliance
self._name: str = name
self._categories: Optional[Dict[str, "HonCommand"]] = categories
self._category_name: str = category_name
self._description: str = attributes.pop("description", "")
self._protocol_type: str = attributes.pop("protocolType", "")
self._parameters: Dict[str, HonParameter] = {}
self._parameters: Dict[str, Parameter] = {}
self._data: Dict[str, Any] = {}
self._available_settings: Dict[str, HonParameter] = {}
self._rules: List[HonRuleSet] = []
attributes.pop("description", "")
attributes.pop("protocolType", "")
self._load_parameters(attributes)

def __repr__(self) -> str:
Expand Down
49 changes: 27 additions & 22 deletions pyhon/connection/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ class HonLoginData:
loaded: Optional[Dict[str, Any]] = None


@dataclass
class HonAuthData:
access_token: str = ""
refresh_token: str = ""
cognito_token: str = ""
id_token: str = ""


class HonAuth:
_TOKEN_EXPIRES_AFTER_HOURS = 8
_TOKEN_EXPIRE_WARNING_HOURS = 7
Expand All @@ -46,28 +54,25 @@ def __init__(
self._login_data = HonLoginData()
self._login_data.email = email
self._login_data.password = password
self._access_token = ""
self._refresh_token = ""
self._cognito_token = ""
self._id_token = ""
self._device = device
self._expires: datetime = datetime.utcnow()
self._auth = HonAuthData()

@property
def cognito_token(self) -> str:
return self._cognito_token
return self._auth.cognito_token

@property
def id_token(self) -> str:
return self._id_token
return self._auth.id_token

@property
def access_token(self) -> str:
return self._access_token
return self._auth.access_token

@property
def refresh_token(self) -> str:
return self._refresh_token
return self._auth.refresh_token

def _check_token_expiration(self, hours: int) -> bool:
return datetime.utcnow() >= self._expires + timedelta(hours=hours)
Expand Down Expand Up @@ -192,12 +197,12 @@ async def _login(self) -> str:

def _parse_token_data(self, text: str) -> bool:
if access_token := re.findall("access_token=(.*?)&", text):
self._access_token = access_token[0]
self._auth.access_token = access_token[0]
if refresh_token := re.findall("refresh_token=(.*?)&", text):
self._refresh_token = refresh_token[0]
self._auth.refresh_token = refresh_token[0]
if id_token := re.findall("id_token=(.*?)&", text):
self._id_token = id_token[0]
return True if access_token and refresh_token and id_token else False
self._auth.id_token = id_token[0]
return bool(access_token and refresh_token and id_token)

async def _get_token(self, url: str) -> bool:
async with self._request.get(url) as response:
Expand Down Expand Up @@ -229,7 +234,7 @@ async def _get_token(self, url: str) -> bool:
return True

async def _api_auth(self) -> bool:
post_headers = {"id-token": self._id_token}
post_headers = {"id-token": self._auth.id_token}
data = self._device.get()
async with self._request.post(
f"{const.API_URL}/auth/v1/login", headers=post_headers, json=data
Expand All @@ -239,8 +244,8 @@ async def _api_auth(self) -> bool:
except json.JSONDecodeError:
await self._error_logger(response)
return False
self._cognito_token = json_data.get("cognitoUser", {}).get("Token", "")
if not self._cognito_token:
self._auth.cognito_token = json_data.get("cognitoUser", {}).get("Token", "")
if not self._auth.cognito_token:
_LOGGER.error(json_data)
raise exceptions.HonAuthenticationError()
return True
Expand All @@ -262,7 +267,7 @@ async def authenticate(self) -> None:
async def refresh(self) -> bool:
params = {
"client_id": const.CLIENT_ID,
"refresh_token": self._refresh_token,
"refresh_token": self._auth.refresh_token,
"grant_type": "refresh_token",
}
async with self._request.post(
Expand All @@ -273,14 +278,14 @@ async def refresh(self) -> bool:
return False
data = await response.json()
self._expires = datetime.utcnow()
self._id_token = data["id_token"]
self._access_token = data["access_token"]
self._auth.id_token = data["id_token"]
self._auth.access_token = data["access_token"]
return await self._api_auth()

def clear(self) -> None:
self._session.cookie_jar.clear_domain(const.AUTH_API.split("/")[-2])
self._request.called_urls = []
self._cognito_token = ""
self._id_token = ""
self._access_token = ""
self._refresh_token = ""
self._auth.cognito_token = ""
self._auth.id_token = ""
self._auth.access_token = ""
self._auth.refresh_token = ""
5 changes: 3 additions & 2 deletions pyhon/hon.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
from aiohttp import ClientSession
from typing_extensions import Self

from pyhon import HonAPI, exceptions
from pyhon.appliance import HonAppliance
from pyhon.connection.api import HonAPI
from pyhon.connection.api import TestAPI
from pyhon.exceptions import NoAuthenticationException

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -43,7 +44,7 @@ async def __aexit__(
@property
def api(self) -> HonAPI:
if self._api is None:
raise exceptions.NoAuthenticationException
raise NoAuthenticationException
return self._api

@property
Expand Down
6 changes: 3 additions & 3 deletions pyhon/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def pretty_print(
) -> str:
result = ""
space = whitespace * intend
if (isinstance(data, list) or isinstance(data, dict)) and key:
if isinstance(data, (dict, list)) and key:
result += f"{space}{'- ' if is_list else ''}{key}:\n"
intend += 1
if isinstance(data, list):
Expand All @@ -39,10 +39,10 @@ def pretty_print(
value, intend=intend, is_list=True, whitespace=whitespace
)
elif isinstance(data, dict):
for i, (key, value) in enumerate(sorted(data.items())):
for i, (list_key, value) in enumerate(sorted(data.items())):
result += pretty_print(
value,
key=key,
key=list_key,
intend=intend + (is_list if i else 0),
is_list=is_list and not i,
whitespace=whitespace,
Expand Down
4 changes: 4 additions & 0 deletions pyhon/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ def __init__(self, command: "HonCommand", rule: Dict[str, Any]):
self._rules: Dict[str, List[HonRule]] = {}
self._parse_rule(rule)

@property
def rules(self) -> Dict[str, List[HonRule]]:
return self._rules

def _parse_rule(self, rule: Dict[str, Any]) -> None:
for param_key, params in rule.items():
param_key = self._command.appliance.options.get(param_key, param_key)
Expand Down
2 changes: 1 addition & 1 deletion pyhon/typedefs.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from pyhon.parameter.range import HonParameterRange


class Callback(Protocol):
class Callback(Protocol): # pylint: disable=too-few-public-methods
def __call__(
self, url: str | URL, *args: Any, **kwargs: Any
) -> aiohttp.client._RequestContextManager:
Expand Down
6 changes: 3 additions & 3 deletions requirements_dev.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
black==23.3.0
black==23.7.0
flake8==6.0.0
mypy==1.2.0
pylint==2.17.2
mypy==1.4.1
pylint==2.17.4

0 comments on commit 5a77837

Please sign in to comment.