Skip to content

Commit

Permalink
Fix code style
Browse files Browse the repository at this point in the history
  • Loading branch information
HardNorth committed Dec 19, 2024
1 parent 22919ea commit f32cc8a
Show file tree
Hide file tree
Showing 52 changed files with 2,284 additions and 2,118 deletions.
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ repos:
(?x)^(
tests/.*
)
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 24.10.0
hooks:
- id: black
args: ['reportportal_client', 'tests']
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/pycqa/flake8
rev: 7.1.1
hooks:
Expand Down
35 changes: 15 additions & 20 deletions reportportal_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,7 @@ class ClientType(aenum.Enum):

# noinspection PyIncorrectDocstring
def create_client(
client_type: ClientType,
endpoint: str,
project: str,
*,
api_key: str = None,
**kwargs: typing.Any
client_type: ClientType, endpoint: str, project: str, *, api_key: str = None, **kwargs: typing.Any
) -> typing.Optional[RP]:
"""Create and ReportPortal Client based on the type and arguments provided.
Expand Down Expand Up @@ -106,21 +101,21 @@ def create_client(
return ThreadedRPClient(endpoint, project, api_key=api_key, **kwargs)
if client_type is ClientType.ASYNC_BATCHED:
return BatchedRPClient(endpoint, project, api_key=api_key, **kwargs)
warnings.warn(f'Unknown ReportPortal Client type requested: {client_type}', RuntimeWarning, stacklevel=2)
warnings.warn(f"Unknown ReportPortal Client type requested: {client_type}", RuntimeWarning, stacklevel=2)


__all__ = [
'ClientType',
'create_client',
'current',
'set_current',
'RP',
'RPClient',
'AsyncRPClient',
'BatchedRPClient',
'ThreadedRPClient',
'OutputType',
'RPLogger',
'RPLogHandler',
'step',
"ClientType",
"create_client",
"current",
"set_current",
"RP",
"RPClient",
"AsyncRPClient",
"BatchedRPClient",
"ThreadedRPClient",
"OutputType",
"RPLogger",
"RPLogHandler",
"step",
]
28 changes: 12 additions & 16 deletions reportportal_client/_internal/aio/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ class RetryingClientSession:
__retry_delay: float

def __init__(
self,
*args,
max_retry_number: int = DEFAULT_RETRY_NUMBER,
base_retry_delay: float = DEFAULT_RETRY_DELAY,
**kwargs
self,
*args,
max_retry_number: int = DEFAULT_RETRY_NUMBER,
base_retry_delay: float = DEFAULT_RETRY_DELAY,
**kwargs,
):
"""Initialize an instance of the session with arguments.
Expand All @@ -82,9 +82,7 @@ def __sleep(self, retry_num: int, retry_factor: int) -> Coroutine:
else:
return self.__nothing()

async def __request(
self, method: Callable, url, **kwargs: Any
) -> ClientResponse:
async def __request(self, method: Callable, url, **kwargs: Any) -> ClientResponse:
"""Make a request and retry if necessary.
The method retries requests depending on error class and retry number. For no-retry errors, such as
Expand Down Expand Up @@ -123,17 +121,15 @@ async def __request(
if sys.version_info > (3, 10):
# noinspection PyCompatibility
raise ExceptionGroup( # noqa: F821
'During retry attempts the following exceptions happened',
exceptions
"During retry attempts the following exceptions happened", exceptions
)
else:
raise exceptions[-1]
else:
raise exceptions[0]
return result

def get(self, url: str, *, allow_redirects: bool = True,
**kwargs: Any) -> Coroutine[Any, Any, ClientResponse]:
def get(self, url: str, *, allow_redirects: bool = True, **kwargs: Any) -> Coroutine[Any, Any, ClientResponse]:
"""Perform HTTP GET request."""
return self.__request(self._client.get, url, allow_redirects=allow_redirects, **kwargs)

Expand All @@ -154,10 +150,10 @@ async def __aenter__(self) -> "RetryingClientSession":
return self

async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
"""Auxiliary method which controls what `async with` construction does on block exit."""
await self.close()
49 changes: 21 additions & 28 deletions reportportal_client/_internal/aio/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

from reportportal_client.aio.tasks import BlockingOperationError, Task

_T = TypeVar('_T')
_T = TypeVar("_T")

DEFAULT_TASK_TRIGGER_NUM: int = 10
DEFAULT_TASK_TRIGGER_INTERVAL: float = 1.0
Expand All @@ -33,11 +33,11 @@ class BatchedTask(Generic[_T], Task[_T]):
__loop: asyncio.AbstractEventLoop

def __init__(
self,
coro: Union[Generator[Future, None, _T], Awaitable[_T]],
*,
loop: asyncio.AbstractEventLoop,
name: Optional[str] = None
self,
coro: Union[Generator[Future, None, _T], Awaitable[_T]],
*,
loop: asyncio.AbstractEventLoop,
name: Optional[str] = None,
) -> None:
"""Initialize an instance of the Task.
Expand Down Expand Up @@ -65,12 +65,12 @@ class ThreadedTask(Generic[_T], Task[_T]):
__wait_timeout: float

def __init__(
self,
coro: Union[Generator[Future, None, _T], Awaitable[_T]],
wait_timeout: float,
*,
loop: asyncio.AbstractEventLoop,
name: Optional[str] = None
self,
coro: Union[Generator[Future, None, _T], Awaitable[_T]],
wait_timeout: float,
*,
loop: asyncio.AbstractEventLoop,
name: Optional[str] = None,
) -> None:
"""Initialize an instance of the Task.
Expand All @@ -90,24 +90,21 @@ def blocking_result(self) -> _T:
if self.done():
return self.result()
if not self.__loop.is_running() or self.__loop.is_closed():
raise BlockingOperationError('Running loop is not alive')
raise BlockingOperationError("Running loop is not alive")
start_time = time.time()
sleep_time = sys.getswitchinterval()
while not self.done() and time.time() - start_time < self.__wait_timeout:
time.sleep(sleep_time)
if not self.done():
raise BlockingOperationError('Timed out waiting for the task execution')
raise BlockingOperationError("Timed out waiting for the task execution")
return self.result()


class BatchedTaskFactory:
"""Factory protocol which creates Batched Tasks."""

def __call__(
self,
loop: asyncio.AbstractEventLoop,
factory: Union[Coroutine[Any, Any, _T], Generator[Any, None, _T]],
**_
self, loop: asyncio.AbstractEventLoop, factory: Union[Coroutine[Any, Any, _T], Generator[Any, None, _T]], **_
) -> Task[_T]:
"""Create Batched Task in appropriate Event Loop.
Expand All @@ -130,10 +127,7 @@ def __init__(self, wait_timeout: float):
self.__wait_timeout = wait_timeout

def __call__(
self,
loop: asyncio.AbstractEventLoop,
factory: Union[Coroutine[Any, Any, _T], Generator[Any, None, _T]],
**_
self, loop: asyncio.AbstractEventLoop, factory: Union[Coroutine[Any, Any, _T], Generator[Any, None, _T]], **_
) -> Task[_T]:
"""Create Threaded Task in appropriate Event Loop.
Expand All @@ -151,9 +145,9 @@ class TriggerTaskBatcher(Generic[_T]):
__trigger_num: int
__trigger_interval: float

def __init__(self,
trigger_num: int = DEFAULT_TASK_TRIGGER_NUM,
trigger_interval: float = DEFAULT_TASK_TRIGGER_INTERVAL) -> None:
def __init__(
self, trigger_num: int = DEFAULT_TASK_TRIGGER_NUM, trigger_interval: float = DEFAULT_TASK_TRIGGER_INTERVAL
) -> None:
"""Initialize an instance of the Batcher.
:param trigger_num: object number threshold which triggers batch return and reset
Expand All @@ -169,8 +163,7 @@ def __ready_to_run(self) -> bool:
last_time = self.__last_run_time
if len(self.__task_list) <= 0:
return False
if (len(self.__task_list) >= self.__trigger_num
or current_time - last_time >= self.__trigger_interval):
if len(self.__task_list) >= self.__trigger_num or current_time - last_time >= self.__trigger_interval:
self.__last_run_time = current_time
return True
return False
Expand Down Expand Up @@ -213,7 +206,7 @@ def __remove_finished(self):
if not task.done():
break
i += 1
self.__task_list = self.__task_list[i + 1:]
self.__task_list = self.__task_list[i + 1 :]

def append(self, value: _T) -> None:
"""Add an object to internal batch.
Expand Down
2 changes: 1 addition & 1 deletion reportportal_client/_internal/local/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

def current():
"""Return current ReportPortal client."""
if hasattr(__INSTANCES, 'current'):
if hasattr(__INSTANCES, "current"):
return __INSTANCES.current


Expand Down
2 changes: 0 additions & 2 deletions reportportal_client/_internal/local/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,4 @@ from typing import Optional
from reportportal_client import RP

def current() -> Optional[RP]: ...


def set_current(client: Optional[RP]) -> None: ...
4 changes: 2 additions & 2 deletions reportportal_client/_internal/logs/batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

logger = logging.getLogger(__name__)

T_co = TypeVar('T_co', bound='RPRequestLog', covariant=True)
T_co = TypeVar("T_co", bound="RPRequestLog", covariant=True)


class LogBatcher(Generic[T_co]):
Expand Down Expand Up @@ -102,7 +102,7 @@ def __getstate__(self) -> Dict[str, Any]:
"""
state = self.__dict__.copy()
# Don't pickle 'session' field, since it contains unpickling 'socket'
del state['_lock']
del state["_lock"]
return state

def __setstate__(self, state: Dict[str, Any]) -> None:
Expand Down
31 changes: 12 additions & 19 deletions reportportal_client/_internal/services/client_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,24 @@


class __NoSectionConfigParser(configparser.ConfigParser):
DEFAULT_SECTION = 'DEFAULT'
DEFAULT_SECTION = "DEFAULT"

def __preprocess_file(self, fp):
content = u'[' + self.DEFAULT_SECTION + ']\n' + fp.read()
content = "[" + self.DEFAULT_SECTION + "]\n" + fp.read()
return io.StringIO(content)

def read(self, filenames, encoding=None):
if isinstance(filenames, str):
filenames = [filenames]
for filename in filenames:
with open(filename, 'r') as fp:
with open(filename, "r") as fp:
preprocessed_fp = self.__preprocess_file(fp)
self.read_file(
preprocessed_fp,
filename)
self.read_file(preprocessed_fp, filename)

def write(self, fp, space_around_delimiters=True):
for key, value in self.items(self.DEFAULT_SECTION):
delimiter = ' = ' if space_around_delimiters else '='
fp.write(u'{}{}{}\n'.format(key, delimiter, value))
delimiter = " = " if space_around_delimiters else "="
fp.write("{}{}{}\n".format(key, delimiter, value))


def __read_config():
Expand All @@ -57,19 +55,16 @@ def __read_config():

def _read_client_id():
config = __read_config()
if config.has_option(__NoSectionConfigParser.DEFAULT_SECTION,
CLIENT_ID_PROPERTY):
return config.get(__NoSectionConfigParser.DEFAULT_SECTION,
CLIENT_ID_PROPERTY)
if config.has_option(__NoSectionConfigParser.DEFAULT_SECTION, CLIENT_ID_PROPERTY):
return config.get(__NoSectionConfigParser.DEFAULT_SECTION, CLIENT_ID_PROPERTY)


def _store_client_id(client_id):
config = __read_config()
if not os.path.exists(RP_FOLDER_PATH):
os.makedirs(RP_FOLDER_PATH)
config.set(__NoSectionConfigParser.DEFAULT_SECTION, CLIENT_ID_PROPERTY,
client_id)
with open(RP_PROPERTIES_FILE_PATH, 'w') as fp:
config.set(__NoSectionConfigParser.DEFAULT_SECTION, CLIENT_ID_PROPERTY, client_id)
with open(RP_PROPERTIES_FILE_PATH, "w") as fp:
config.write(fp)


Expand All @@ -79,13 +74,11 @@ def get_client_id():
try:
client_id = _read_client_id()
except (PermissionError, IOError) as error:
logger.exception('[%s] Unknown exception has occurred. '
'Skipping client ID reading.', error)
logger.exception("[%s] Unknown exception has occurred. " "Skipping client ID reading.", error)
if not client_id:
client_id = str(uuid4())
try:
_store_client_id(client_id)
except (PermissionError, IOError) as error:
logger.exception('[%s] Unknown exception has occurred. '
'Skipping client ID saving.', error)
logger.exception("[%s] Unknown exception has occurred. " "Skipping client ID saving.", error)
return client_id
4 changes: 0 additions & 4 deletions reportportal_client/_internal/services/client_id.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,5 @@
from typing import Optional, Text

def _read_client_id() -> Optional[Text]: ...


def _store_client_id(client_id: Text) -> None: ...


def get_client_id() -> Text: ...
15 changes: 7 additions & 8 deletions reportportal_client/_internal/services/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,13 @@ def _decode_string(text):
:param text: Encoded string
:return: Decoded value
"""
base64_bytes = text.encode('ascii')
base64_bytes = text.encode("ascii")
message_bytes = base64.b64decode(base64_bytes)
return message_bytes.decode('ascii')
return message_bytes.decode("ascii")


CLIENT_INFO = \
_decode_string('Ry1XUDU3UlNHOFhMOm5Ib3dqRjJQUVotNDFJbzBPcDRoZlE=')
ENDPOINT = 'https://www.google-analytics.com/mp/collect'
CLIENT_ID_PROPERTY = 'client.id'
RP_FOLDER_PATH = os.path.join(os.path.expanduser('~'), '.rp')
RP_PROPERTIES_FILE_PATH = os.path.join(RP_FOLDER_PATH, 'rp.properties')
CLIENT_INFO = _decode_string("Ry1XUDU3UlNHOFhMOm5Ib3dqRjJQUVotNDFJbzBPcDRoZlE=")
ENDPOINT = "https://www.google-analytics.com/mp/collect"
CLIENT_ID_PROPERTY = "client.id"
RP_FOLDER_PATH = os.path.join(os.path.expanduser("~"), ".rp")
RP_PROPERTIES_FILE_PATH = os.path.join(RP_FOLDER_PATH, "rp.properties")
1 change: 0 additions & 1 deletion reportportal_client/_internal/services/constants.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ from typing import Text

def _decode_string(text: Text) -> Text: ...


CLIENT_INFO: Text
ENDPOINT: Text
CLIENT_ID_PROPERTY: Text
Expand Down
Loading

0 comments on commit f32cc8a

Please sign in to comment.