Add stricter mypy rules

This commit is contained in:
Andre Basche 2023-07-01 14:59:09 +02:00
parent 0553e6c17d
commit a10ab4423e
4 changed files with 63 additions and 39 deletions

View file

@ -2,3 +2,8 @@
check_untyped_defs = True check_untyped_defs = True
disallow_any_generics = True disallow_any_generics = True
disallow_untyped_defs = True disallow_untyped_defs = True
disallow_any_unimported = True
no_implicit_optional = True
warn_return_any = True
show_error_codes = True
warn_unused_ignores = True

View file

@ -6,6 +6,7 @@ from pathlib import Path
from typing import Optional, Dict, Any, TYPE_CHECKING, List from typing import Optional, Dict, Any, TYPE_CHECKING, List
from pyhon import diagnose, exceptions from pyhon import diagnose, exceptions
from pyhon.appliances.base import ApplianceBase
from pyhon.attributes import HonAttribute from pyhon.attributes import HonAttribute
from pyhon.command_loader import HonCommandLoader from pyhon.command_loader import HonCommandLoader
from pyhon.commands import HonCommand from pyhon.commands import HonCommand
@ -40,7 +41,7 @@ class HonAppliance:
self._default_setting = HonParameter("", {}, "") self._default_setting = HonParameter("", {}, "")
try: try:
self._extra = importlib.import_module( self._extra: Optional[ApplianceBase] = importlib.import_module(
f"pyhon.appliances.{self.appliance_type.lower()}" f"pyhon.appliances.{self.appliance_type.lower()}"
).Appliance(self) ).Appliance(self)
except ModuleNotFoundError: except ModuleNotFoundError:
@ -71,7 +72,8 @@ class HonAppliance:
def _check_name_zone(self, name: str, frontend: bool = True) -> str: def _check_name_zone(self, name: str, frontend: bool = True) -> str:
zone = " Z" if frontend else "_z" zone = " Z" if frontend else "_z"
if (attribute := self._info.get(name, "")) and self._zone: attribute: str = self._info.get(name, "")
if attribute and self._zone:
return f"{attribute}{zone}{self._zone}" return f"{attribute}{zone}{self._zone}"
return attribute return attribute
@ -112,9 +114,10 @@ class HonAppliance:
@property @property
def code(self) -> str: def code(self) -> str:
if code := self.info.get("code"): code: str = self.info.get("code", "")
if code:
return code return code
serial_number = self.info.get("serialNumber", "") serial_number: str = self.info.get("serialNumber", "")
return serial_number[:8] if len(serial_number) < 18 else serial_number[:11] return serial_number[:8] if len(serial_number) < 18 else serial_number[:11]
@property @property
@ -198,7 +201,7 @@ class HonAppliance:
@property @property
def settings(self) -> Dict[str, Parameter]: def settings(self) -> Dict[str, Parameter]:
result = {} result: Dict[str, Parameter] = {}
for name, command in self._commands.items(): for name, command in self._commands.items():
for key in command.setting_keys: for key in command.setting_keys:
setting = command.settings.get(key, self._default_setting) setting = command.settings.get(key, self._default_setting)

View file

@ -75,8 +75,12 @@ class HonAPI:
async def load_appliances(self) -> List[Dict[str, Any]]: async def load_appliances(self) -> List[Dict[str, Any]]:
async with self._hon.get(f"{const.API_URL}/commands/v1/appliance") as resp: async with self._hon.get(f"{const.API_URL}/commands/v1/appliance") as resp:
if result := await resp.json(): result = await resp.json()
return result.get("payload", {}).get("appliances", {}) if result:
appliances: List[Dict[str, Any]] = result.get("payload", {}).get(
"appliances", {}
)
return appliances
return [] return []
async def load_commands(self, appliance: HonAppliance) -> Dict[str, Any]: async def load_commands(self, appliance: HonAppliance) -> Dict[str, Any]:
@ -110,9 +114,10 @@ class HonAPI:
) )
async with self._hon.get(url) as response: async with self._hon.get(url) as response:
result: Dict[str, Any] = await response.json() result: Dict[str, Any] = await response.json()
if not result or not result.get("payload"): if not result or not result.get("payload"):
return [] return []
return result["payload"]["history"] command_history: List[Dict[str, Any]] = result["payload"]["history"]
return command_history
async def load_favourites(self, appliance: HonAppliance) -> List[Dict[str, Any]]: async def load_favourites(self, appliance: HonAppliance) -> List[Dict[str, Any]]:
url: str = ( url: str = (
@ -120,17 +125,20 @@ class HonAPI:
) )
async with self._hon.get(url) as response: async with self._hon.get(url) as response:
result: Dict[str, Any] = await response.json() result: Dict[str, Any] = await response.json()
if not result or not result.get("payload"): if not result or not result.get("payload"):
return [] return []
return result["payload"]["favourites"] favourites: List[Dict[str, Any]] = result["payload"]["favourites"]
return favourites
async def load_last_activity(self, appliance: HonAppliance) -> Dict[str, Any]: async def load_last_activity(self, appliance: HonAppliance) -> Dict[str, Any]:
url: str = f"{const.API_URL}/commands/v1/retrieve-last-activity" url: str = f"{const.API_URL}/commands/v1/retrieve-last-activity"
params: Dict[str, str] = {"macAddress": appliance.mac_address} params: Dict[str, str] = {"macAddress": appliance.mac_address}
async with self._hon.get(url, params=params) as response: async with self._hon.get(url, params=params) as response:
result: Dict[str, Any] = await response.json() result: Dict[str, Any] = await response.json()
if result and (activity := result.get("attributes")): if result:
return activity activity: Dict[str, Any] = result.get("attributes", "")
if activity:
return activity
return {} return {}
async def load_appliance_data(self, appliance: HonAppliance) -> Dict[str, Any]: async def load_appliance_data(self, appliance: HonAppliance) -> Dict[str, Any]:
@ -142,7 +150,10 @@ class HonAPI:
async with self._hon.get(url, params=params) as response: async with self._hon.get(url, params=params) as response:
result: Dict[str, Any] = await response.json() result: Dict[str, Any] = await response.json()
if result: if result:
return result.get("payload", {}).get("applianceModel", {}) appliance_data: Dict[str, Any] = result.get("payload", {}).get(
"applianceModel", {}
)
return appliance_data
return {} return {}
async def load_attributes(self, appliance: HonAppliance) -> Dict[str, Any]: async def load_attributes(self, appliance: HonAppliance) -> Dict[str, Any]:
@ -153,7 +164,8 @@ class HonAPI:
} }
url: str = f"{const.API_URL}/commands/v1/context" url: str = f"{const.API_URL}/commands/v1/context"
async with self._hon.get(url, params=params) as response: async with self._hon.get(url, params=params) as response:
return (await response.json()).get("payload", {}) attributes: Dict[str, Any] = (await response.json()).get("payload", {})
return attributes
async def load_statistics(self, appliance: HonAppliance) -> Dict[str, Any]: async def load_statistics(self, appliance: HonAppliance) -> Dict[str, Any]:
params: Dict[str, str] = { params: Dict[str, str] = {
@ -162,13 +174,15 @@ class HonAPI:
} }
url: str = f"{const.API_URL}/commands/v1/statistics" url: str = f"{const.API_URL}/commands/v1/statistics"
async with self._hon.get(url, params=params) as response: async with self._hon.get(url, params=params) as response:
return (await response.json()).get("payload", {}) statistics: Dict[str, Any] = (await response.json()).get("payload", {})
return statistics
async def load_maintenance(self, appliance: HonAppliance) -> Dict[str, Any]: async def load_maintenance(self, appliance: HonAppliance) -> Dict[str, Any]:
url = f"{const.API_URL}/commands/v1/maintenance-cycle" url = f"{const.API_URL}/commands/v1/maintenance-cycle"
params = {"macAddress": appliance.mac_address} params = {"macAddress": appliance.mac_address}
async with self._hon.get(url, params=params) as response: async with self._hon.get(url, params=params) as response:
return (await response.json()).get("payload", {}) maintenance: Dict[str, Any] = (await response.json()).get("payload", {})
return maintenance
async def send_command( async def send_command(
self, self,
@ -207,9 +221,8 @@ class HonAPI:
url: str = f"{const.API_URL}/config/v1/program-list-rules" url: str = f"{const.API_URL}/config/v1/program-list-rules"
async with self._hon_anonymous.get(url) as response: async with self._hon_anonymous.get(url) as response:
result: Dict[str, Any] = await response.json() result: Dict[str, Any] = await response.json()
if result and (data := result.get("payload")): data: Dict[str, Any] = result.get("payload", {})
return data return data
return {}
async def app_config( async def app_config(
self, language: str = "en", beta: bool = True self, language: str = "en", beta: bool = True
@ -223,17 +236,17 @@ class HonAPI:
} }
payload: str = json.dumps(payload_data, separators=(",", ":")) payload: str = json.dumps(payload_data, separators=(",", ":"))
async with self._hon_anonymous.post(url, data=payload) as response: async with self._hon_anonymous.post(url, data=payload) as response:
if (result := await response.json()) and (data := result.get("payload")): result = await response.json()
return data data: Dict[str, Any] = result.get("payload", {})
return {} return data
async def translation_keys(self, language: str = "en") -> Dict[str, Any]: async def translation_keys(self, language: str = "en") -> Dict[str, Any]:
config = await self.app_config(language=language) config = await self.app_config(language=language)
if url := config.get("language", {}).get("jsonPath"): if not (url := config.get("language", {}).get("jsonPath")):
async with self._hon_anonymous.get(url) as response: return {}
if result := await response.json(): async with self._hon_anonymous.get(url) as response:
return result result: Dict[str, Any] = await response.json()
return {} return result
async def close(self) -> None: async def close(self) -> None:
if self._hon_handler is not None: if self._hon_handler is not None:
@ -250,11 +263,12 @@ class TestAPI(HonAPI):
def _load_json(self, appliance: HonAppliance, file: str) -> Dict[str, Any]: def _load_json(self, appliance: HonAppliance, file: str) -> Dict[str, Any]:
directory = f"{appliance.appliance_type}_{appliance.appliance_model_id}".lower() directory = f"{appliance.appliance_type}_{appliance.appliance_model_id}".lower()
if (path := self._path / directory / f"{file}.json").exists(): if not (path := self._path / directory / f"{file}.json").exists():
with open(path, "r", encoding="utf-8") as json_file: _LOGGER.warning("Can't open %s", str(path))
return json.loads(json_file.read()) return {}
_LOGGER.warning(f"Can't open {str(path)}") with open(path, "r", encoding="utf-8") as json_file:
return {} data: Dict[str, Any] = json.loads(json_file.read())
return data
async def load_appliances(self) -> List[Dict[str, Any]]: async def load_appliances(self) -> List[Dict[str, Any]]:
result = [] result = []

View file

@ -6,7 +6,7 @@ import urllib
from contextlib import suppress from contextlib import suppress
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Dict, Optional, Any from typing import Dict, Optional, Any, List
from urllib import parse from urllib import parse
from urllib.parse import quote from urllib.parse import quote
@ -115,7 +115,8 @@ class HonAuth:
async with self._request.get(url) as response: async with self._request.get(url) as response:
text = await response.text() text = await response.text()
self._expires = datetime.utcnow() self._expires = datetime.utcnow()
if not (login_url := re.findall("url = '(.+?)'", text)): login_url: List[str] = re.findall("url = '(.+?)'", text)
if not login_url:
if "oauth/done#access_token=" in text: if "oauth/done#access_token=" in text:
self._parse_token_data(text) self._parse_token_data(text)
raise exceptions.HonNoAuthenticationNeeded() raise exceptions.HonNoAuthenticationNeeded()
@ -184,7 +185,8 @@ class HonAuth:
if response.status == 200: if response.status == 200:
with suppress(json.JSONDecodeError, KeyError): with suppress(json.JSONDecodeError, KeyError):
result = await response.json() result = await response.json()
return result["events"][0]["attributes"]["values"]["url"] url: str = result["events"][0]["attributes"]["values"]["url"]
return url
await self._error_logger(response) await self._error_logger(response)
return "" return ""