Skip to content
This repository was archived by the owner on Feb 14, 2023. It is now read-only.

Commit

Permalink
Code style now is Black ✨. Fix test data for steam.Client.
Browse files Browse the repository at this point in the history
  • Loading branch information
somespecialone committed Jan 25, 2022
1 parent 4f3ecb3 commit 4de4b2c
Show file tree
Hide file tree
Showing 21 changed files with 314 additions and 245 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
[![codecov](https://codecov.io/gh/somespecialone/python-steam-tradeoffer-manager/branch/master/graph/badge.svg?token=H3JL81SL7P)](https://codecov.io/gh/somespecialone/python-steam-tradeoffer-manager)
[![CodeFactor](https://www.codefactor.io/repository/github/somespecialone/python-steam-tradeoffer-manager/badge)](https://www.codefactor.io/repository/github/somespecialone/python-steam-tradeoffer-manager)
[![versions](https://img.shields.io/pypi/pyversions/steam-tradeoffer-manager)](https://pypi.org/project/steam-tradeoffer-manager)
[![black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![steam](https://shields.io/badge/steam-1b2838?logo=steam)](https://store.steampowered.com/)

## Installation
Expand Down
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ pytest-cov = "^3.0.0"
mkdocs = "^1.2.3"
mkdocs-material = "^8.1.6"
mkdocs-git-revision-date-localized-plugin = "^0.11.1"
black = "^21.12b0"

[tool.black]
line-length = 120
target-version = ['py310']

[tool.pytest.ini_options]
testpaths = ["tests"]
Expand Down
4 changes: 2 additions & 2 deletions steam_tradeoffer_manager/_monkey_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ async def poll_trades_patched(self: state.ConnectionState) -> None:
async def get_api_key_patched(self: http.HTTPClient) -> str | None:
resp = await self.get(models.URL.COMMUNITY / "dev/apikey")
if (
"<h2>Access Denied</h2>" in resp
or "You must have a validated email address to create a Steam Web API key" in resp
"<h2>Access Denied</h2>" in resp
or "You must have a validated email address to create a Steam Web API key" in resp
):
return

Expand Down
42 changes: 28 additions & 14 deletions steam_tradeoffer_manager/base/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,46 +7,60 @@ class AbstractBasePool(metaclass=ABCMeta):
"""Abstract base class for pool"""

@abstractmethod
def add(self, *args, **kwargs): ...
def add(self, *args, **kwargs):
...

@abstractmethod
def remove(self, *args, **kwargs): ...
def remove(self, *args, **kwargs):
...

@abstractmethod
def startup(self): ...
def startup(self):
...

@abstractmethod
def shutdown(self): ...
def shutdown(self):
...

@abstractmethod
def get(self, k): ...
def get(self, k):
...

@abstractmethod
def pop(self, k): ...
def pop(self, k):
...

@abstractmethod
def _bind(self, *args): ...
def _bind(self, *args):
...

@abstractmethod
def _unbind(self, *args): ...
def _unbind(self, *args):
...

@abstractmethod
def __contains__(self, item): ...
def __contains__(self, item):
...

@abstractmethod
def __len__(self): ...
def __len__(self):
...

@abstractmethod
def __iter__(self): ...
def __iter__(self):
...

@abstractmethod
def __getitem__(self, item): ...
def __getitem__(self, item):
...

# @abstractmethod
# def __setitem__(self, key, value): ...

@abstractmethod
def __delitem__(self, key): ...
def __delitem__(self, key):
...

@abstractmethod
def __bool__(self): ...
def __bool__(self):
...
49 changes: 26 additions & 23 deletions steam_tradeoffer_manager/base/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
from .enums import BotState
from .mixins import PoolBotMixin

__all__ = ('SteamBot',)
__all__ = ("SteamBot",)

_log = logging.getLogger(__name__)
_P = TypeVar("_P", bound='pool.SteamBotPool')
_P = TypeVar("_P", bound="pool.SteamBotPool")
_I = TypeVar("_I", bound=int)


Expand All @@ -21,25 +21,25 @@ class SteamBot(steam.Client, PoolBotMixin[_I, _P]):
`id` attr must be steam id64
"""

constraints = ('username',)
dimension = 'steam'
constraints = ("username",)
dimension = "steam"

def __init__(
self,
username: str,
password: str,
shared_secret: str,
identity_secret: str,
*,
id: _I = None,
whitelist: set[int] | None = None,
user_agent: str | None = None,
proxy: str | None = None,
proxy_auth: BasicAuth | None = None,
connector: BaseConnector | None = None,
randomizer: Callable[[], int] | None = None,
domain: str | None = None,
**options: Any,
self,
username: str,
password: str,
shared_secret: str,
identity_secret: str,
*,
id: _I = None,
whitelist: set[int] | None = None,
user_agent: str | None = None,
proxy: str | None = None,
proxy_auth: BasicAuth | None = None,
connector: BaseConnector | None = None,
randomizer: Callable[[], int] | None = None,
domain: str | None = None,
**options: Any,
) -> None:
self._id = id

Expand Down Expand Up @@ -167,7 +167,8 @@ def randomizer(self, value: Callable[[], int]):

async def on_ready(self) -> None:
self._state = BotState.Active
if not self.id: setattr(self, "_id", self.user.id64) # id will be automatically set when client is ready
if not self.id:
setattr(self, "_id", self.user.id64) # id will be automatically set when client is ready

_log.info(f"Bot {self.user} is ready")

Expand Down Expand Up @@ -198,10 +199,12 @@ def __del__(self):
if not self.is_closed():
import warnings

warnings.warn(f'Unstopped bot {self}!', ResourceWarning, source=self)
if self._refresh_task: self._refresh_task.cancel()
warnings.warn(f"Unstopped bot {self}!", ResourceWarning, source=self)
if self._refresh_task:
self._refresh_task.cancel()
# maybe asyncio.call_exception_handler needed
if self.pool: del self.pool[self.id]
if self.pool:
del self.pool[self.id]
super().__del__()

def __str__(self) -> str:
Expand Down
12 changes: 6 additions & 6 deletions steam_tradeoffer_manager/base/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
from random import randint, random
from typing import Callable

__all__ = ('BotState', 'ONCE_EVERY')
__all__ = ("BotState", "ONCE_EVERY")


class BotState(enum.Enum):
Active = 'active' # working fine
Waiting = 'waiting' # waiting until ready
InvalidCredentials = 'invalid credentials'
UnknownError = 'unknown exception' # stopped by error
Stopped = 'stopped' # just stopped
Active = "active" # working fine
Waiting = "waiting" # waiting until ready
InvalidCredentials = "invalid credentials"
UnknownError = "unknown exception" # stopped by error
Stopped = "stopped" # just stopped


class Timings:
Expand Down
21 changes: 13 additions & 8 deletions steam_tradeoffer_manager/base/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
from .exceptions import ConstraintException
from ..utils import join_multiple_in_string

__all__ = ('PoolBotMixin', 'ConstraintsMixin')
__all__ = ("PoolBotMixin", "ConstraintsMixin")

_log = logging.getLogger(__name__)
_P = TypeVar("_P", bound=AbstractBasePool)
_I = TypeVar('_I')
_I = TypeVar("_I")


class ConstraintsMixin:
Expand All @@ -20,20 +20,24 @@ class ConstraintsMixin:
but always must be passed like arguments to `__init__` and be `hashable`.
Implement `__del__` method to clean up hashes in storage while garbage collecting,
"""

__storage__: Final[dict[str, set[int]]] = {}

constraints: Sequence[str | Sequence[str]] = ()
dimension: str

def __init_subclass__(cls, dimension: str = None, **kwargs):
super().__init_subclass__(**kwargs)
subclass_dimension = getattr(cls, 'dimension', None)
subclass_dimension = getattr(cls, "dimension", None)
arg_dimension = dimension
if subclass_dimension and arg_dimension:
import warnings

warnings.warn('Subclass overrides `dimension` and `dimension` arg has been passed to subclass init. '
f'Used [{subclass_dimension}] by default.', stacklevel=len(inspect.stack()) + 1)
warnings.warn(
"Subclass overrides `dimension` and `dimension` arg has been passed to subclass init. "
f"Used [{subclass_dimension}] by default.",
stacklevel=len(inspect.stack()) + 1,
)

if subclass_dimension:
cls.dimension = subclass_dimension
Expand Down Expand Up @@ -78,7 +82,7 @@ def _check_constraints(self):
if h in self.__storage__[self.dimension]:
f = join_multiple_in_string(self.constraints)
# would be great if I write violated constraints here
raise ConstraintException(f'Instance with unique values({f}) already created.')
raise ConstraintException(f"Instance with unique values({f}) already created.")

self.__storage__[self.dimension].update(self._hashes)

Expand All @@ -88,6 +92,7 @@ def __del__(self) -> None:

class _MappingPoolBotMixin(ConstraintsMixin, Generic[_I, _P]): # pragma: no cover
"""Mixin for bot. Contains required methods to interact with pool"""

# maps to ids and pool
__ids__: Final[dict[str, _I]] = {}
__pools__: Final[dict[str, _P]] = {}
Expand Down Expand Up @@ -118,11 +123,11 @@ class _PropertyPoolBotMixin(ConstraintsMixin, Generic[_I, _P]):
# pure properties
@property
def id(self) -> _I | None:
return getattr(self, '_id', None)
return getattr(self, "_id", None)

@property
def pool(self) -> _P | None:
return getattr(self, '_pool', None)
return getattr(self, "_pool", None)

def __repr__(self) -> str:
return f"<{self.__class__.__name__} id={self.id}>"
Expand Down
3 changes: 2 additions & 1 deletion steam_tradeoffer_manager/base/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ def add(self, bot: _B, raise_=True) -> None:
if bot.pool:
import warnings
import inspect

msg = f"Bot with id {bot.id} already in pool"

if raise_:
Expand Down Expand Up @@ -76,7 +77,7 @@ def _unbind(self, bot: _B) -> None:
def _bind(self, bot: _B) -> None:
if not bot.id:
raise ValueError(f"Bot id is {bot.id}")
setattr(bot, '_pool', self)
setattr(bot, "_pool", self)
self._store[bot.id] = bot

# container methods https://docs.python.org/3/reference/datamodel.html#emulating-container-types
Expand Down
Loading

0 comments on commit 4de4b2c

Please sign in to comment.