Rewrite long strings using \ instead of + (concatenation).

This commit is contained in:
Davide Casale
2023-03-08 16:30:52 +01:00
parent 88e6c79532
commit 894391256d
7 changed files with 44 additions and 41 deletions

View File

@@ -9,12 +9,13 @@ ignore=examples
disable= disable=
multiple-imports, multiple-imports,
missing-docstring, missing-docstring,
logging-not-lazy,
logging-fstring-interpolation,
too-few-public-methods, too-few-public-methods,
too-many-public-methods, too-many-public-methods,
too-many-instance-attributes, too-many-instance-attributes,
dangerous-default-value, dangerous-default-value,
inconsistent-return-statements, inconsistent-return-statements,
logging-not-lazy
[FORMAT] [FORMAT]
@@ -24,4 +25,4 @@ good-names=id,on,pl,t,ip,tf,A,B,C,D,E,F
[TYPECHECK] [TYPECHECK]
generated-members=websockets generated-members=websockets

View File

@@ -42,7 +42,7 @@ class _Serializer(Generic[T]):
labels = list(filter(lambda label: label not in (skip or []), self.__labels)) labels = list(filter(lambda label: label not in (skip or []), self.__labels))
if len(labels) > len(args): if len(labels) > len(args):
raise LabelerSerializerException(f"{self.name} -> <labels> and <*args> " + raise LabelerSerializerException(f"{self.name} -> <labels> and <*args> " \
"arguments should contain the same amount of elements.") "arguments should contain the same amount of elements.")
for index, label in enumerate(labels): for index, label in enumerate(labels):

View File

@@ -53,12 +53,12 @@ class Middleware:
if len(data) and data[0] == "error": if len(data) and data[0] == "error":
if data[1] == Error.ERR_PARAMS: if data[1] == Error.ERR_PARAMS:
raise RequestParametersError("The request was rejected with the " raise RequestParametersError("The request was rejected with the " \
+ f"following parameter error: <{data[2]}>") f"following parameter error: <{data[2]}>")
if data[1] is None or data[1] == Error.ERR_UNK or data[1] == Error.ERR_GENERIC: if data[1] is None or data[1] == Error.ERR_UNK or data[1] == Error.ERR_GENERIC:
raise UnknownGenericError("The server replied to the request with " raise UnknownGenericError("The server replied to the request with " \
+ f"a generic error with message: <{data[2]}>.") f"a generic error with message: <{data[2]}>.")
return data return data
@@ -86,14 +86,14 @@ class Middleware:
if isinstance(data, list) and len(data) and data[0] == "error": if isinstance(data, list) and len(data) and data[0] == "error":
if data[1] == Error.ERR_PARAMS: if data[1] == Error.ERR_PARAMS:
raise RequestParametersError("The request was rejected with the " raise RequestParametersError("The request was rejected with the " \
+ f"following parameter error: <{data[2]}>") f"following parameter error: <{data[2]}>")
if data[1] == Error.ERR_AUTH_FAIL: if data[1] == Error.ERR_AUTH_FAIL:
raise InvalidAuthenticationCredentials("Cannot authenticate with given API-KEY and API-SECRET.") raise InvalidAuthenticationCredentials("Cannot authenticate with given API-KEY and API-SECRET.")
if data[1] is None or data[1] == Error.ERR_UNK or data[1] == Error.ERR_GENERIC: if data[1] is None or data[1] == Error.ERR_UNK or data[1] == Error.ERR_GENERIC:
raise UnknownGenericError("The server replied to the request with " raise UnknownGenericError("The server replied to the request with " \
+ f"a generic error with message: <{data[2]}>.") f"a generic error with message: <{data[2]}>.")
return data return data

View File

@@ -26,8 +26,8 @@ class TestLabeler(unittest.TestCase):
msg="_Serializer::get_labels() should return the right list of labels.") msg="_Serializer::get_labels() should return the right list of labels.")
with self.assertRaises(LabelerSerializerException, with self.assertRaises(LabelerSerializerException,
msg="_Serializer should raise LabelerSerializerException if given " msg="_Serializer should raise LabelerSerializerException if given " \
+ "fewer arguments than the serializer labels."): "fewer arguments than the serializer labels."):
serializer.parse(5, 65.0, "X") serializer.parse(5, 65.0, "X")
def test_generate_recursive_serializer(self): def test_generate_recursive_serializer(self):

View File

@@ -10,11 +10,12 @@ class TestRestSerializers(unittest.TestCase):
def test_rest_serializers(self): def test_rest_serializers(self):
for serializer in map(serializers.__dict__.get, serializers.__serializers__): for serializer in map(serializers.__dict__.get, serializers.__serializers__):
self.assertTrue(issubclass(serializer.klass, _Type), self.assertTrue(issubclass(serializer.klass, _Type),
f"_Serializer <{serializer.name}>: .klass field must be a subclass of _Type (got {serializer.klass}).") f"_Serializer <{serializer.name}>: .klass field must be a subclass " \
f"of _Type (got {serializer.klass}).")
self.assertListEqual(serializer.get_labels(), list(serializer.klass.__annotations__), self.assertListEqual(serializer.get_labels(), list(serializer.klass.__annotations__),
f"_Serializer <{serializer.name}> and _Type <{serializer.klass.__name__}> " f"_Serializer <{serializer.name}> and _Type <{serializer.klass.__name__}> " \
+ "must have matching labels and fields.") "must have matching labels and fields.")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@@ -10,11 +10,12 @@ class TestWebsocketSerializers(unittest.TestCase):
def test_websocket_serializers(self): def test_websocket_serializers(self):
for serializer in map(serializers.__dict__.get, serializers.__serializers__): for serializer in map(serializers.__dict__.get, serializers.__serializers__):
self.assertTrue(issubclass(serializer.klass, _Type), self.assertTrue(issubclass(serializer.klass, _Type),
f"_Serializer <{serializer.name}>: .klass field must be a subclass of _Type (got {serializer.klass}).") f"_Serializer <{serializer.name}>: .klass field must be a subclass " \
f"of _Type (got {serializer.klass}).")
self.assertListEqual(serializer.get_labels(), list(serializer.klass.__annotations__), self.assertListEqual(serializer.get_labels(), list(serializer.klass.__annotations__),
f"_Serializer <{serializer.name}> and _Type <{serializer.klass.__name__}> " f"_Serializer <{serializer.name}> and _Type <{serializer.klass.__name__}> " \
+ "must have matching labels and fields.") "must have matching labels and fields.")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@@ -22,8 +22,8 @@ from ...utils.logger import ColorLogger, FileLogger
def _require_websocket_authentication(function: F) -> F: def _require_websocket_authentication(function: F) -> F:
async def wrapper(self, *args, **kwargs): async def wrapper(self, *args, **kwargs):
if hasattr(self, "authentication") and not self.authentication: if hasattr(self, "authentication") and not self.authentication:
raise WebsocketAuthenticationRequired("To perform this action you need to authenticate " + raise WebsocketAuthenticationRequired("To perform this action you need to " \
"using your API_KEY and API_SECRET.") "authenticate using your API_KEY and API_SECRET.")
await _require_websocket_connection(function)(self, *args, **kwargs) await _require_websocket_connection(function)(self, *args, **kwargs)
@@ -86,9 +86,9 @@ class BfxWebsocketClient:
async def start(self, connections = 5): async def start(self, connections = 5):
if connections > BfxWebsocketClient.MAXIMUM_CONNECTIONS_AMOUNT: if connections > BfxWebsocketClient.MAXIMUM_CONNECTIONS_AMOUNT:
self.logger.warning(f"It is not safe to use more than {BfxWebsocketClient.MAXIMUM_CONNECTIONS_AMOUNT} " self.logger.warning(f"It is not safe to use more than {BfxWebsocketClient.MAXIMUM_CONNECTIONS_AMOUNT} " \
+ f"buckets from the same connection ({connections} in use), the server could momentarily " f"buckets from the same connection ({connections} in use), the server could momentarily " \
+ "block the client with <429 Too Many Requests>.") "block the client with <429 Too Many Requests>.")
for _ in range(connections): for _ in range(connections):
self.on_open_events.append(asyncio.Event()) self.on_open_events.append(asyncio.Event())
@@ -113,9 +113,9 @@ class BfxWebsocketClient:
async with websockets.connect(self.host) as websocket: async with websockets.connect(self.host) as websocket:
if reconnection.status: if reconnection.status:
self.logger.info(f"Reconnect attempt successful (attempt no.{reconnection.attempts}): The " self.logger.info(f"Reconnect attempt successful (attempt no.{reconnection.attempts}): The " \
+ f"client has been offline for a total of {datetime.now() - reconnection.timestamp} " f"client has been offline for a total of {datetime.now() - reconnection.timestamp} " \
+ f"(connection lost at: {reconnection.timestamp:%d-%m-%Y at %H:%M:%S}).") f"(connection lost at: {reconnection.timestamp:%d-%m-%Y at %H:%M:%S}).")
reconnection = Reconnection(status=False, attempts=0, timestamp=None) reconnection = Reconnection(status=False, attempts=0, timestamp=None)
@@ -133,9 +133,9 @@ class BfxWebsocketClient:
if isinstance(message, dict): if isinstance(message, dict):
if message["event"] == "info" and "version" in message: if message["event"] == "info" and "version" in message:
if BfxWebsocketClient.VERSION != message["version"]: if BfxWebsocketClient.VERSION != message["version"]:
raise OutdatedClientVersion("Mismatch between the client version and the server " raise OutdatedClientVersion("Mismatch between the client version and the server " \
+ "version. Update the library to the latest version to continue (client version: " "version. Update the library to the latest version to continue (client version: " \
+ f"{BfxWebsocketClient.VERSION}, server version: {message['version']}).") f"{BfxWebsocketClient.VERSION}, server version: {message['version']}).")
elif message["event"] == "info" and message["code"] == 20051: elif message["event"] == "info" and message["code"] == 20051:
rcvd = websockets.frames.Close(code=1012, rcvd = websockets.frames.Close(code=1012,
reason="Stop/Restart Websocket Server (please reconnect).") reason="Stop/Restart Websocket Server (please reconnect).")
@@ -165,20 +165,20 @@ class BfxWebsocketClient:
except (websockets.ConnectionClosedError, socket.gaierror) as error: except (websockets.ConnectionClosedError, socket.gaierror) as error:
if isinstance(error, websockets.ConnectionClosedError) and error.code in (1006, 1012): if isinstance(error, websockets.ConnectionClosedError) and error.code in (1006, 1012):
if error.code == 1006: if error.code == 1006:
self.logger.error("Connection lost: no close frame received " self.logger.error("Connection lost: no close frame received " \
+ "or sent (1006). Attempting to reconnect...") "or sent (1006). Attempting to reconnect...")
if error.code == 1012: if error.code == 1012:
self.logger.info("WSS server is about to restart, reconnection " self.logger.info("WSS server is about to restart, reconnection " \
+ "required (client received 20051). Attempt in progress...") "required (client received 20051). Attempt in progress...")
reconnection = Reconnection(status=True, attempts=1, timestamp=datetime.now()) reconnection = Reconnection(status=True, attempts=1, timestamp=datetime.now())
delay = _Delay(backoff_factor=1.618) delay = _Delay(backoff_factor=1.618)
elif isinstance(error, socket.gaierror) and reconnection.status: elif isinstance(error, socket.gaierror) and reconnection.status:
self.logger.warning(f"Reconnection attempt no.{reconnection.attempts} has failed. " self.logger.warning(f"Reconnection attempt no.{reconnection.attempts} has failed. " \
+ f"Next reconnection attempt in ~{round(delay.peek()):.1f} seconds. (at the moment " f"Next reconnection attempt in ~{round(delay.peek()):.1f} seconds. (at the moment " \
+ f"the client has been offline for {datetime.now() - reconnection.timestamp})") f"the client has been offline for {datetime.now() - reconnection.timestamp})")
reconnection = reconnection._replace(attempts=reconnection.attempts + 1) reconnection = reconnection._replace(attempts=reconnection.attempts + 1)
else: raise error else: raise error
@@ -231,8 +231,8 @@ class BfxWebsocketClient:
def on(self, *events, callback = None): def on(self, *events, callback = None):
for event in events: for event in events:
if event not in BfxWebsocketClient.EVENTS: if event not in BfxWebsocketClient.EVENTS:
raise EventNotSupported(f"Event <{event}> is not supported. To get a list " raise EventNotSupported(f"Event <{event}> is not supported. To get a list " \
+ "of available events print BfxWebsocketClient.EVENTS") "of available events print BfxWebsocketClient.EVENTS")
if callback is not None: if callback is not None:
for event in events: for event in events:
@@ -248,8 +248,8 @@ class BfxWebsocketClient:
def once(self, *events, callback = None): def once(self, *events, callback = None):
for event in events: for event in events:
if event not in BfxWebsocketClient.EVENTS: if event not in BfxWebsocketClient.EVENTS:
raise EventNotSupported(f"Event <{event}> is not supported. To get a list " raise EventNotSupported(f"Event <{event}> is not supported. To get a list " \
+ "of available events print BfxWebsocketClient.EVENTS") "of available events print BfxWebsocketClient.EVENTS")
if callback is not None: if callback is not None:
for event in events: for event in events: