Skip to content
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

fix: lints / code cleanup #116

Merged
merged 2 commits into from
Feb 7, 2025
Merged
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
4 changes: 2 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


@pytest_asyncio.fixture(scope="function")
async def auth_mgr(event_loop):
async def auth_mgr():
session = SignedSession()
mgr = AuthenticationManager(session, "abc", "123", "http://localhost")
mgr.oauth = OAuth2TokenResponse.model_validate_json(
Expand All @@ -37,7 +37,7 @@ async def auth_mgr(event_loop):


@pytest_asyncio.fixture(scope="function")
async def xal_mgr(event_loop):
async def xal_mgr():
session = SignedSession()
mgr = XALManager(
session,
Expand Down
6 changes: 3 additions & 3 deletions tests/data/test_signing_key.pem
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIObr5IVtB+DQcn25+R9n4K/EyUUSbVvxIJY7WhVeELUuoAoGCCqGSM49
AwEHoUQDQgAEOKyCQ9qH5U4lZcS0c5/LxIyKvOpKe0l3x4Eg5OgDbzezKNLRgT28
fd4Fq3rU/1OQKmx6jSq0vTB5Ao/48m0iGg==
MHcCAQEEIObr5IVtB+DQcn25+R9n4K/EyUUSbVvxIJY7WhVeELUuoAoGCCqGSM49AwEHoUQDQgAE
OKyCQ9qH5U4lZcS0c5/LxIyKvOpKe0l3x4Eg5OgDbzezKNLRgT28fd4Fq3rU/1OQKmx6jSq0vTB5
Ao/48m0iGg==
-----END EC PRIVATE KEY-----
19 changes: 10 additions & 9 deletions tests/test_ratelimits.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import asyncio
from datetime import datetime, timedelta

from httpx import Response
import pytest
import asyncio

from tests.common import get_response_json
from xbox.webapi.api.provider.ratelimitedprovider import RateLimitedProvider

from xbox.webapi.common.exceptions import RateLimitExceededException, XboxException
from xbox.webapi.common.ratelimits import CombinedRateLimit
from xbox.webapi.common.ratelimits.models import TimePeriod

from tests.common import get_response_json


def helper_test_combinedratelimit(
crl: CombinedRateLimit, burstLimit: int, sustainLimit: int
Expand All @@ -18,8 +19,8 @@ def helper_test_combinedratelimit(
sustain = crl.get_limits_by_period(TimePeriod.SUSTAIN)

# These functions should return a list with one element
assert type(burst) == list
assert type(sustain) == list
assert isinstance(burst, list)
assert isinstance(sustain, list)

assert len(burst) == 1
assert len(sustain) == 1
Expand Down Expand Up @@ -111,7 +112,7 @@ async def make_request():
route = respx_mock.get("https://social.xboxlive.com").mock(
return_value=Response(200, json=get_response_json("people_summary_own"))
)
ret = await xbl_client.people.get_friends_summary_own()
await xbl_client.people.get_friends_summary_own()

assert route.called

Expand Down Expand Up @@ -145,7 +146,7 @@ async def helper_reach_and_wait_for_burst(
make_request, start_time, burst_limit: int, expected_counter: int
):
# Make as many requests as possible without exceeding the BURST limit.
for i in range(burst_limit):
for _ in range(burst_limit):
await make_request()

# Make another request, ensure that it raises the exception.
Expand Down Expand Up @@ -175,7 +176,7 @@ async def make_request():
route = respx_mock.get("https://social.xboxlive.com").mock(
return_value=Response(200, json=get_response_json("people_summary_own"))
)
ret = await xbl_client.people.get_friends_summary_own()
await xbl_client.people.get_friends_summary_own()

assert route.called

Expand All @@ -201,7 +202,7 @@ async def make_request():
)

# Now, make the rest of the requests (10 left, 20/30 done!)
for i in range(10):
for _ in range(10):
await make_request()

# Wait for the burst limit to 'reset'.
Expand Down
11 changes: 6 additions & 5 deletions xbox/webapi/api/provider/ratelimitedprovider.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
Subclassed by providers with rate limit support
"""

from typing import Union, Dict
from typing import Dict, Union

from xbox.webapi.api.provider.baseprovider import BaseProvider
from xbox.webapi.common.exceptions import XboxException
from xbox.webapi.common.ratelimits.models import LimitType, ParsedRateLimit, TimePeriod
from xbox.webapi.common.ratelimits import CombinedRateLimit
from xbox.webapi.common.ratelimits.models import LimitType, ParsedRateLimit, TimePeriod


class RateLimitedProvider(BaseProvider):
Expand Down Expand Up @@ -62,10 +63,10 @@ def __handle_rate_limit_setup(self):
def __parse_rate_limit_key(
self, key: Union[int, Dict[str, int]], period: TimePeriod
) -> ParsedRateLimit:
key_type = type(key)
if key_type == int:
if isinstance(key, int) and not isinstance(key, bool):
# bool is a subclass of int, hence the explicit check
return ParsedRateLimit(read=key, write=key, period=period)
elif key_type == dict:
elif isinstance(key, dict):
# TODO: schema here?
# Since the key-value pairs match we can just pass the dict to the model
return ParsedRateLimit(**key, period=period)
Expand Down
13 changes: 6 additions & 7 deletions xbox/webapi/common/ratelimits/__init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
from abc import ABCMeta, abstractmethod
from datetime import datetime, timedelta
from typing import Union, List
from typing import List, Union

from xbox.webapi.common.ratelimits.models import (
IncrementResult,
LimitType,
ParsedRateLimit,
TimePeriod,
LimitType,
IncrementResult,
)

from abc import ABCMeta, abstractmethod


class RateLimit(metaclass=ABCMeta):
"""
Expand Down Expand Up @@ -209,7 +208,7 @@ def get_reset_after(self) -> Union[datetime, None]:

# Construct a new list with only elements of instance datetime
# (Effectively filtering out any None elements)
dates_valid = [elem for elem in dates if type(elem) == datetime]
dates_valid = [elem for elem in dates if isinstance(elem, datetime)]

# If dates_valid has any elements, return the one with the *later* timestamp.
# This means that if two or more limits have been exceeded, we wait for both to have reset (by returning the later timestamp)
Expand Down Expand Up @@ -238,7 +237,7 @@ def get_limits_by_period(self, period: TimePeriod) -> List[SingleRateLimit]:
def is_exceeded(self) -> bool:
"""
This function returns `True` if **any** rate limit has been exceeded.

It behaves like an OR logic gate.
"""

Expand Down
Loading