Skip to content

Commit f32cc8a

Browse files
committed
Fix code style
1 parent 22919ea commit f32cc8a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+2284
-2118
lines changed

.pre-commit-config.yaml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,15 @@ repos:
1616
(?x)^(
1717
tests/.*
1818
)
19-
- repo: https://github.com/pycqa/isort
20-
rev: 5.13.2
21-
hooks:
22-
- id: isort
2319
- repo: https://github.com/psf/black
2420
rev: 24.10.0
2521
hooks:
2622
- id: black
2723
args: ['reportportal_client', 'tests']
24+
- repo: https://github.com/pycqa/isort
25+
rev: 5.13.2
26+
hooks:
27+
- id: isort
2828
- repo: https://github.com/pycqa/flake8
2929
rev: 7.1.1
3030
hooks:

reportportal_client/__init__.py

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,7 @@ class ClientType(aenum.Enum):
3636

3737
# noinspection PyIncorrectDocstring
3838
def create_client(
39-
client_type: ClientType,
40-
endpoint: str,
41-
project: str,
42-
*,
43-
api_key: str = None,
44-
**kwargs: typing.Any
39+
client_type: ClientType, endpoint: str, project: str, *, api_key: str = None, **kwargs: typing.Any
4540
) -> typing.Optional[RP]:
4641
"""Create and ReportPortal Client based on the type and arguments provided.
4742
@@ -106,21 +101,21 @@ def create_client(
106101
return ThreadedRPClient(endpoint, project, api_key=api_key, **kwargs)
107102
if client_type is ClientType.ASYNC_BATCHED:
108103
return BatchedRPClient(endpoint, project, api_key=api_key, **kwargs)
109-
warnings.warn(f'Unknown ReportPortal Client type requested: {client_type}', RuntimeWarning, stacklevel=2)
104+
warnings.warn(f"Unknown ReportPortal Client type requested: {client_type}", RuntimeWarning, stacklevel=2)
110105

111106

112107
__all__ = [
113-
'ClientType',
114-
'create_client',
115-
'current',
116-
'set_current',
117-
'RP',
118-
'RPClient',
119-
'AsyncRPClient',
120-
'BatchedRPClient',
121-
'ThreadedRPClient',
122-
'OutputType',
123-
'RPLogger',
124-
'RPLogHandler',
125-
'step',
108+
"ClientType",
109+
"create_client",
110+
"current",
111+
"set_current",
112+
"RP",
113+
"RPClient",
114+
"AsyncRPClient",
115+
"BatchedRPClient",
116+
"ThreadedRPClient",
117+
"OutputType",
118+
"RPLogger",
119+
"RPLogHandler",
120+
"step",
126121
]

reportportal_client/_internal/aio/http.py

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,11 @@ class RetryingClientSession:
5151
__retry_delay: float
5252

5353
def __init__(
54-
self,
55-
*args,
56-
max_retry_number: int = DEFAULT_RETRY_NUMBER,
57-
base_retry_delay: float = DEFAULT_RETRY_DELAY,
58-
**kwargs
54+
self,
55+
*args,
56+
max_retry_number: int = DEFAULT_RETRY_NUMBER,
57+
base_retry_delay: float = DEFAULT_RETRY_DELAY,
58+
**kwargs,
5959
):
6060
"""Initialize an instance of the session with arguments.
6161
@@ -82,9 +82,7 @@ def __sleep(self, retry_num: int, retry_factor: int) -> Coroutine:
8282
else:
8383
return self.__nothing()
8484

85-
async def __request(
86-
self, method: Callable, url, **kwargs: Any
87-
) -> ClientResponse:
85+
async def __request(self, method: Callable, url, **kwargs: Any) -> ClientResponse:
8886
"""Make a request and retry if necessary.
8987
9088
The method retries requests depending on error class and retry number. For no-retry errors, such as
@@ -123,17 +121,15 @@ async def __request(
123121
if sys.version_info > (3, 10):
124122
# noinspection PyCompatibility
125123
raise ExceptionGroup( # noqa: F821
126-
'During retry attempts the following exceptions happened',
127-
exceptions
124+
"During retry attempts the following exceptions happened", exceptions
128125
)
129126
else:
130127
raise exceptions[-1]
131128
else:
132129
raise exceptions[0]
133130
return result
134131

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

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

156152
async def __aexit__(
157-
self,
158-
exc_type: Optional[Type[BaseException]],
159-
exc_val: Optional[BaseException],
160-
exc_tb: Optional[TracebackType],
153+
self,
154+
exc_type: Optional[Type[BaseException]],
155+
exc_val: Optional[BaseException],
156+
exc_tb: Optional[TracebackType],
161157
) -> None:
162158
"""Auxiliary method which controls what `async with` construction does on block exit."""
163159
await self.close()

reportportal_client/_internal/aio/tasks.py

Lines changed: 21 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
from reportportal_client.aio.tasks import BlockingOperationError, Task
2323

24-
_T = TypeVar('_T')
24+
_T = TypeVar("_T")
2525

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

3535
def __init__(
36-
self,
37-
coro: Union[Generator[Future, None, _T], Awaitable[_T]],
38-
*,
39-
loop: asyncio.AbstractEventLoop,
40-
name: Optional[str] = None
36+
self,
37+
coro: Union[Generator[Future, None, _T], Awaitable[_T]],
38+
*,
39+
loop: asyncio.AbstractEventLoop,
40+
name: Optional[str] = None,
4141
) -> None:
4242
"""Initialize an instance of the Task.
4343
@@ -65,12 +65,12 @@ class ThreadedTask(Generic[_T], Task[_T]):
6565
__wait_timeout: float
6666

6767
def __init__(
68-
self,
69-
coro: Union[Generator[Future, None, _T], Awaitable[_T]],
70-
wait_timeout: float,
71-
*,
72-
loop: asyncio.AbstractEventLoop,
73-
name: Optional[str] = None
68+
self,
69+
coro: Union[Generator[Future, None, _T], Awaitable[_T]],
70+
wait_timeout: float,
71+
*,
72+
loop: asyncio.AbstractEventLoop,
73+
name: Optional[str] = None,
7474
) -> None:
7575
"""Initialize an instance of the Task.
7676
@@ -90,24 +90,21 @@ def blocking_result(self) -> _T:
9090
if self.done():
9191
return self.result()
9292
if not self.__loop.is_running() or self.__loop.is_closed():
93-
raise BlockingOperationError('Running loop is not alive')
93+
raise BlockingOperationError("Running loop is not alive")
9494
start_time = time.time()
9595
sleep_time = sys.getswitchinterval()
9696
while not self.done() and time.time() - start_time < self.__wait_timeout:
9797
time.sleep(sleep_time)
9898
if not self.done():
99-
raise BlockingOperationError('Timed out waiting for the task execution')
99+
raise BlockingOperationError("Timed out waiting for the task execution")
100100
return self.result()
101101

102102

103103
class BatchedTaskFactory:
104104
"""Factory protocol which creates Batched Tasks."""
105105

106106
def __call__(
107-
self,
108-
loop: asyncio.AbstractEventLoop,
109-
factory: Union[Coroutine[Any, Any, _T], Generator[Any, None, _T]],
110-
**_
107+
self, loop: asyncio.AbstractEventLoop, factory: Union[Coroutine[Any, Any, _T], Generator[Any, None, _T]], **_
111108
) -> Task[_T]:
112109
"""Create Batched Task in appropriate Event Loop.
113110
@@ -130,10 +127,7 @@ def __init__(self, wait_timeout: float):
130127
self.__wait_timeout = wait_timeout
131128

132129
def __call__(
133-
self,
134-
loop: asyncio.AbstractEventLoop,
135-
factory: Union[Coroutine[Any, Any, _T], Generator[Any, None, _T]],
136-
**_
130+
self, loop: asyncio.AbstractEventLoop, factory: Union[Coroutine[Any, Any, _T], Generator[Any, None, _T]], **_
137131
) -> Task[_T]:
138132
"""Create Threaded Task in appropriate Event Loop.
139133
@@ -151,9 +145,9 @@ class TriggerTaskBatcher(Generic[_T]):
151145
__trigger_num: int
152146
__trigger_interval: float
153147

154-
def __init__(self,
155-
trigger_num: int = DEFAULT_TASK_TRIGGER_NUM,
156-
trigger_interval: float = DEFAULT_TASK_TRIGGER_INTERVAL) -> None:
148+
def __init__(
149+
self, trigger_num: int = DEFAULT_TASK_TRIGGER_NUM, trigger_interval: float = DEFAULT_TASK_TRIGGER_INTERVAL
150+
) -> None:
157151
"""Initialize an instance of the Batcher.
158152
159153
:param trigger_num: object number threshold which triggers batch return and reset
@@ -169,8 +163,7 @@ def __ready_to_run(self) -> bool:
169163
last_time = self.__last_run_time
170164
if len(self.__task_list) <= 0:
171165
return False
172-
if (len(self.__task_list) >= self.__trigger_num
173-
or current_time - last_time >= self.__trigger_interval):
166+
if len(self.__task_list) >= self.__trigger_num or current_time - last_time >= self.__trigger_interval:
174167
self.__last_run_time = current_time
175168
return True
176169
return False
@@ -213,7 +206,7 @@ def __remove_finished(self):
213206
if not task.done():
214207
break
215208
i += 1
216-
self.__task_list = self.__task_list[i + 1:]
209+
self.__task_list = self.__task_list[i + 1 :]
217210

218211
def append(self, value: _T) -> None:
219212
"""Add an object to internal batch.

reportportal_client/_internal/local/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
def current():
2222
"""Return current ReportPortal client."""
23-
if hasattr(__INSTANCES, 'current'):
23+
if hasattr(__INSTANCES, "current"):
2424
return __INSTANCES.current
2525

2626

reportportal_client/_internal/local/__init__.pyi

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,4 @@ from typing import Optional
1616
from reportportal_client import RP
1717

1818
def current() -> Optional[RP]: ...
19-
20-
2119
def set_current(client: Optional[RP]) -> None: ...

reportportal_client/_internal/logs/batcher.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
logger = logging.getLogger(__name__)
2424

25-
T_co = TypeVar('T_co', bound='RPRequestLog', covariant=True)
25+
T_co = TypeVar("T_co", bound="RPRequestLog", covariant=True)
2626

2727

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

108108
def __setstate__(self, state: Dict[str, Any]) -> None:

reportportal_client/_internal/services/client_id.py

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -26,26 +26,24 @@
2626

2727

2828
class __NoSectionConfigParser(configparser.ConfigParser):
29-
DEFAULT_SECTION = 'DEFAULT'
29+
DEFAULT_SECTION = "DEFAULT"
3030

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

3535
def read(self, filenames, encoding=None):
3636
if isinstance(filenames, str):
3737
filenames = [filenames]
3838
for filename in filenames:
39-
with open(filename, 'r') as fp:
39+
with open(filename, "r") as fp:
4040
preprocessed_fp = self.__preprocess_file(fp)
41-
self.read_file(
42-
preprocessed_fp,
43-
filename)
41+
self.read_file(preprocessed_fp, filename)
4442

4543
def write(self, fp, space_around_delimiters=True):
4644
for key, value in self.items(self.DEFAULT_SECTION):
47-
delimiter = ' = ' if space_around_delimiters else '='
48-
fp.write(u'{}{}{}\n'.format(key, delimiter, value))
45+
delimiter = " = " if space_around_delimiters else "="
46+
fp.write("{}{}{}\n".format(key, delimiter, value))
4947

5048

5149
def __read_config():
@@ -57,19 +55,16 @@ def __read_config():
5755

5856
def _read_client_id():
5957
config = __read_config()
60-
if config.has_option(__NoSectionConfigParser.DEFAULT_SECTION,
61-
CLIENT_ID_PROPERTY):
62-
return config.get(__NoSectionConfigParser.DEFAULT_SECTION,
63-
CLIENT_ID_PROPERTY)
58+
if config.has_option(__NoSectionConfigParser.DEFAULT_SECTION, CLIENT_ID_PROPERTY):
59+
return config.get(__NoSectionConfigParser.DEFAULT_SECTION, CLIENT_ID_PROPERTY)
6460

6561

6662
def _store_client_id(client_id):
6763
config = __read_config()
6864
if not os.path.exists(RP_FOLDER_PATH):
6965
os.makedirs(RP_FOLDER_PATH)
70-
config.set(__NoSectionConfigParser.DEFAULT_SECTION, CLIENT_ID_PROPERTY,
71-
client_id)
72-
with open(RP_PROPERTIES_FILE_PATH, 'w') as fp:
66+
config.set(__NoSectionConfigParser.DEFAULT_SECTION, CLIENT_ID_PROPERTY, client_id)
67+
with open(RP_PROPERTIES_FILE_PATH, "w") as fp:
7368
config.write(fp)
7469

7570

@@ -79,13 +74,11 @@ def get_client_id():
7974
try:
8075
client_id = _read_client_id()
8176
except (PermissionError, IOError) as error:
82-
logger.exception('[%s] Unknown exception has occurred. '
83-
'Skipping client ID reading.', error)
77+
logger.exception("[%s] Unknown exception has occurred. " "Skipping client ID reading.", error)
8478
if not client_id:
8579
client_id = str(uuid4())
8680
try:
8781
_store_client_id(client_id)
8882
except (PermissionError, IOError) as error:
89-
logger.exception('[%s] Unknown exception has occurred. '
90-
'Skipping client ID saving.', error)
83+
logger.exception("[%s] Unknown exception has occurred. " "Skipping client ID saving.", error)
9184
return client_id

reportportal_client/_internal/services/client_id.pyi

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,5 @@
1414
from typing import Optional, Text
1515

1616
def _read_client_id() -> Optional[Text]: ...
17-
18-
1917
def _store_client_id(client_id: Text) -> None: ...
20-
21-
2218
def get_client_id() -> Text: ...

reportportal_client/_internal/services/constants.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,13 @@ def _decode_string(text):
2323
:param text: Encoded string
2424
:return: Decoded value
2525
"""
26-
base64_bytes = text.encode('ascii')
26+
base64_bytes = text.encode("ascii")
2727
message_bytes = base64.b64decode(base64_bytes)
28-
return message_bytes.decode('ascii')
28+
return message_bytes.decode("ascii")
2929

3030

31-
CLIENT_INFO = \
32-
_decode_string('Ry1XUDU3UlNHOFhMOm5Ib3dqRjJQUVotNDFJbzBPcDRoZlE=')
33-
ENDPOINT = 'https://www.google-analytics.com/mp/collect'
34-
CLIENT_ID_PROPERTY = 'client.id'
35-
RP_FOLDER_PATH = os.path.join(os.path.expanduser('~'), '.rp')
36-
RP_PROPERTIES_FILE_PATH = os.path.join(RP_FOLDER_PATH, 'rp.properties')
31+
CLIENT_INFO = _decode_string("Ry1XUDU3UlNHOFhMOm5Ib3dqRjJQUVotNDFJbzBPcDRoZlE=")
32+
ENDPOINT = "https://www.google-analytics.com/mp/collect"
33+
CLIENT_ID_PROPERTY = "client.id"
34+
RP_FOLDER_PATH = os.path.join(os.path.expanduser("~"), ".rp")
35+
RP_PROPERTIES_FILE_PATH = os.path.join(RP_FOLDER_PATH, "rp.properties")

0 commit comments

Comments
 (0)