Skip to content

Apply Sourcery suggested refactoring. #448

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 16 additions & 28 deletions pyoverkiz/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
TooManyConcurrentRequestsException,
TooManyExecutionsException,
TooManyRequestsException,
UnknownException,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Raise specific exception instead of genericException

)
from pyoverkiz.models import (
Command,
Expand Down Expand Up @@ -119,7 +120,7 @@ def __init__(
self.gateways: list[Gateway] = []
self.event_listener_id: str | None = None

self.session = session if session else ClientSession()
self.session = session or ClientSession()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Simplify if expression by using or

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed


async def __aenter__(self) -> OverkizClient:
return self
Expand Down Expand Up @@ -186,7 +187,7 @@ async def somfy_tahoma_get_access_token(self) -> str:
"""
# Request access token
async with self.session.post(
SOMFY_API + "/oauth/oauth/v2/token",
f"{SOMFY_API}/oauth/oauth/v2/token",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Use f-string instead of string concatenation

data=FormData(
{
"grant_type": "password",
Expand Down Expand Up @@ -230,7 +231,7 @@ async def refresh_token(self) -> None:
# &grant_type=refresh_token&refresh_token=REFRESH_TOKEN
# Request access token
async with self.session.post(
SOMFY_API + "/oauth/oauth/v2/token",
f"{SOMFY_API}/oauth/oauth/v2/token",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Use f-string instead of string concatenation

data=FormData(
{
"grant_type": "refresh_token",
Expand Down Expand Up @@ -263,7 +264,7 @@ async def cozytouch_login(self) -> str:
"""
# Request access token
async with self.session.post(
COZYTOUCH_ATLANTIC_API + "/token",
f"{COZYTOUCH_ATLANTIC_API}/token",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Use f-string instead of string concatenation

data=FormData(
{
"grant_type": "password",
Expand All @@ -288,7 +289,7 @@ async def cozytouch_login(self) -> str:

# Request JWT
async with self.session.get(
COZYTOUCH_ATLANTIC_API + "/gacoma/gacomawcfservice/accounts/jwt",
f"{COZYTOUCH_ATLANTIC_API}/gacoma/gacomawcfservice/accounts/jwt",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Use f-string instead of string concatenation

headers={"Authorization": f"Bearer {token['access_token']}"},
) as response:
jwt = await response.text()
Expand All @@ -298,7 +299,7 @@ async def cozytouch_login(self) -> str:

jwt = jwt.strip('"') # Remove surrounding quotes

return jwt
return str(jwt)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mypy: pyoverkiz/client.py:302: error: Returning Any from function declared to return "str" [no-any-return]

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should cast it if we know it is a string for sure.


async def nexity_login(self) -> str:
"""
Expand Down Expand Up @@ -458,9 +459,7 @@ async def get_execution_history(self) -> list[HistoryExecution]:
List execution history
"""
response = await self.__get("history/executions")
execution_history = [HistoryExecution(**h) for h in humps.decamelize(response)]

return execution_history
return [HistoryExecution(**h) for h in humps.decamelize(response)]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Inline variable that is immediately returned


@backoff.on_exception(
backoff.expo, NotAuthenticatedException, max_tries=2, on_backoff=relogin
Expand All @@ -485,9 +484,7 @@ async def get_state(self, deviceurl: str) -> list[State]:
response = await self.__get(
f"setup/devices/{urllib.parse.quote_plus(deviceurl)}/states"
)
state = [State(**s) for s in humps.decamelize(response)]

return state
return [State(**s) for s in humps.decamelize(response)]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Inline variable that is immediately returned


@backoff.on_exception(
backoff.expo, NotAuthenticatedException, max_tries=2, on_backoff=relogin
Expand Down Expand Up @@ -534,9 +531,7 @@ async def fetch_events(self) -> list[Event]:
"""
await self._refresh_token_if_expired()
response = await self.__post(f"events/{self.event_listener_id}/fetch")
events = [Event(**e) for e in humps.decamelize(response)]

return events
return [Event(**e) for e in humps.decamelize(response)]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Inline variable that is immediately returned


async def unregister_event_listener(self) -> None:
"""
Expand All @@ -553,19 +548,15 @@ async def unregister_event_listener(self) -> None:
async def get_current_execution(self, exec_id: str) -> Execution:
"""Get an action group execution currently running"""
response = await self.__get(f"exec/current/{exec_id}")
execution = Execution(**humps.decamelize(response))

return execution
return Execution(**humps.decamelize(response))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Inline variable that is immediately returned


@backoff.on_exception(
backoff.expo, NotAuthenticatedException, max_tries=2, on_backoff=relogin
)
async def get_current_executions(self) -> list[Execution]:
"""Get all action groups executions currently running"""
response = await self.__get("exec/current")
executions = [Execution(**e) for e in humps.decamelize(response)]

return executions
return [Execution(**e) for e in humps.decamelize(response)]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Inline variable that is immediately returned


@backoff.on_exception(backoff.expo, TooManyExecutionsException, max_tries=10)
@backoff.on_exception(
Expand Down Expand Up @@ -629,8 +620,7 @@ async def get_scenarios(self) -> list[Scenario]:
async def get_places(self) -> Place:
"""List the places"""
response = await self.__get("setup/places")
places = Place(**humps.decamelize(response))
return places
return Place(**humps.decamelize(response))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Inline variable that is immediately returned


@backoff.on_exception(
backoff.expo,
Expand Down Expand Up @@ -681,9 +671,7 @@ async def get_local_tokens(
Access scope : Full enduser API access (enduser/*)
"""
response = await self.__get(f"/config/{gateway_id}/local/tokens/{scope}")
local_tokens = [LocalToken(**lt) for lt in humps.decamelize(response)]

return local_tokens
return [LocalToken(**lt) for lt in humps.decamelize(response)]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Inline variable that is immediately returned


@backoff.on_exception(
backoff.expo,
Expand Down Expand Up @@ -764,7 +752,7 @@ async def check_response(response: ClientResponse) -> None:
result = await response.text()
if "Server is down for maintenance" in result:
raise MaintenanceException("Server is down for maintenance") from error
raise Exception(
raise UnknownException(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Raise a specific error instead of the general Exception.

f"Unknown error while requesting {response.url}. {response.status} - {result}"
) from error

Expand Down Expand Up @@ -823,7 +811,7 @@ async def check_response(response: ClientResponse) -> None:
if "Not such token with UUID: " in message:
raise NotSuchTokenException(message)

raise Exception(message if message else result)
raise UnknownException(message or result)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Raise a specific error instead of the general Exception.
Sourcery - Simplify if expression by using or


async def _refresh_token_if_expired(self) -> None:
"""Check if token is expired and request a new one."""
Expand Down
4 changes: 4 additions & 0 deletions pyoverkiz/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,7 @@ class SomfyBadCredentialsException(BadCredentialsException):

class SomfyServiceException(Exception):
pass


class UnknownException(Exception):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Raise a specific error instead of the general Exception.

pass
5 changes: 1 addition & 4 deletions pyoverkiz/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,10 +316,7 @@ class States:
_states: list[State]

def __init__(self, states: list[dict[str, Any]] | None = None) -> None:
if states:
self._states = [State(**state) for state in states]
else:
self._states = []
self._states = [State(**state) for state in states] if states else []
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Replace if statement with if expression


def __iter__(self) -> Iterator[State]:
return self._states.__iter__()
Expand Down
2 changes: 1 addition & 1 deletion pyoverkiz/obfuscate.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def obfuscate_email(email: str | None) -> str:

def obfuscate_string(input: str) -> str:
"""Mask string"""
return re.sub(r"[a-zA-Z0-9_.-]*", "*", str(input))
return re.sub(r"[a-zA-Z0-9_.-]*", "*", input)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery - Remove unnecessary casts to int, str, float or bool



def obfuscate_sensitive_data(data: dict[str, Any]) -> JSON:
Expand Down