Skip to content

Commit 575eee7

Browse files
fixed linting errors (#119)
* fixed linting errors * typing error in backwards compatibility fix * fixed missing requests typing * fixed missing import
1 parent 460ba2d commit 575eee7

File tree

7 files changed

+53
-50
lines changed

7 files changed

+53
-50
lines changed

dev-requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ cryptography==44.0.2
247247
# via jwskate
248248
pycparser==2.22
249249
# via jwskate
250+
types-requests==2.32.0.20250328
250251

251252
# The following packages are considered to be unsafe in a requirements file:
252253
# pip

src/s2python/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from importlib.metadata import PackageNotFoundError, version, sys # pragma: no cover
1+
import sys # pragma: no cover
2+
from importlib.metadata import PackageNotFoundError, version # pragma: no cover
23

34
try:
45
# Change here if project is renamed and does not equal the package name
@@ -9,6 +10,5 @@
910
finally:
1011
del version, PackageNotFoundError
1112

12-
from s2python.communication.s2_connection import S2Connection, AssetDetails
13-
sys.modules['s2python.s2_connection'] = sys.modules.get('s2python.communication.s2_connection', None)
14-
13+
from s2python.communication.s2_connection import S2Connection, AssetDetails # pragma: no cover
14+
sys.modules['s2python.s2_connection'] = sys.modules['s2python.communication.s2_connection'] # pragma: no cover

src/s2python/authorization/client.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import json
77
import uuid
88
import datetime
9+
import logging
910
from typing import Dict, Optional, Tuple, Union, List, Any
1011

1112

@@ -27,6 +28,9 @@
2728
PAIRING_TIMEOUT = datetime.timedelta(minutes=5)
2829
KEY_ALGORITHM = "RSA-OAEP-256"
2930

31+
# Set up logging
32+
logging.basicConfig(level=logging.INFO)
33+
logger = logging.getLogger("S2AbstractClient")
3034

3135
class PairingDetails(BaseModel):
3236
"""Contains all details from the pairing process."""
@@ -188,7 +192,7 @@ def request_pairing(self) -> PairingResponse:
188192
self.store_key_pair(public_key, private_key)
189193

190194
# Create pairing request
191-
print("Creating pairing request")
195+
logger.info("Creating pairing request")
192196
pairing_request = PairingRequest(
193197
token=self.token,
194198
publicKey=self._public_key,
@@ -198,14 +202,14 @@ def request_pairing(self) -> PairingResponse:
198202
)
199203

200204
# Make pairing request
201-
print("Making pairing request")
205+
logger.info("Making pairing request")
202206
status_code, response_text = self._make_https_request(
203207
url=self.pairing_uri,
204208
method="POST",
205209
data=pairing_request.model_dump(exclude_none=True),
206210
headers={"Content-Type": "application/json"},
207211
)
208-
print(f"Pairing request response: {status_code} {response_text}")
212+
logger.info('Pairing request response: %s %s', status_code, response_text)
209213

210214
# Parse response
211215
if status_code != 200:
@@ -290,14 +294,12 @@ def request_connection(self) -> ConnectionDetails:
290294
connection_details = ConnectionDetails.model_validate(
291295
connection_data
292296
)
293-
print(f"Updated relative WebSocket URI to absolute: {full_ws_url}")
297+
logger.info('Updated relative WebSocket URI to absolute: %s', full_ws_url)
294298
except (ValueError, TypeError, KeyError) as e:
295-
print(f"Failed to update WebSocket URI: {e}")
299+
logger.info('Failed to update WebSocket URI: %s', e)
296300
else:
297301
# Log a warning but don't modify the URI if we can't create a proper absolute URI
298-
print(
299-
"Received relative WebSocket URI but pairing_uri is not available to create absolute URL"
300-
)
302+
logger.info('Received relative WebSocket URI but pairing_uri is not available to create absolute URL')
301303

302304
# Store for later use
303305
self._connection_details = connection_details

src/s2python/authorization/default_client.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import base64
99
import json
1010
import uuid
11+
import logging
1112
from typing import Dict, Optional, Tuple, Union, List, Any, Mapping
1213

1314
import requests
@@ -27,6 +28,9 @@
2728
PairingDetails,
2829
)
2930

31+
# Set up logging
32+
logging.basicConfig(level=logging.INFO)
33+
logger = logging.getLogger("S2DefaultClient")
3034

3135
class S2DefaultClient(S2AbstractClient):
3236
"""Default implementation of the S2AbstractClient using the requests library for HTTP
@@ -63,7 +67,7 @@ def generate_key_pair(self) -> Tuple[str, str]:
6367
Returns:
6468
Tuple[str, str]: (public_key, private_key) pair as PEM encoded strings
6569
"""
66-
print("Generating key pair")
70+
logger.info("Generating key pair")
6771
self._key_pair = Jwk.generate_for_alg(KEY_ALGORITHM).with_kid_thumbprint()
6872
self._public_jwk = self._key_pair
6973
self._private_jwk = self._key_pair
@@ -82,7 +86,7 @@ def store_key_pair(self, public_key: str, private_key: str) -> None:
8286
public_key: PEM encoded public key
8387
private_key: PEM encoded private key
8488
"""
85-
print("Storing key pair")
89+
logger.info("Storing key pair")
8690
self._public_key = public_key
8791
self._private_key = private_key
8892

@@ -182,12 +186,12 @@ def solve_challenge(self, challenge: Optional[str] = None) -> str:
182186
decrypted_challenge_str=decrypted_challenge_str,
183187
)
184188

185-
print(f"Decrypted challenge: {decrypted_challenge_str}")
189+
logger.info('Decrypted challenge: %s', decrypted_challenge_str)
186190
return decrypted_challenge_str
187191

188192
except (ValueError, TypeError, KeyError, json.JSONDecodeError) as e:
189193
error_msg = f"Failed to solve challenge: {e}"
190-
print(error_msg)
194+
logger.info(error_msg)
191195
raise RuntimeError(error_msg) from e
192196

193197
def establish_secure_connection(self) -> Dict[str, Any]:
@@ -219,12 +223,8 @@ def establish_secure_connection(self) -> Dict[str, Any]:
219223
"Challenge solution not available. Call solve_challenge first."
220224
)
221225

222-
print(
223-
f"Would establish WebSocket connection to {self._connection_details.connectionUri}"
224-
)
225-
print(
226-
f"Using solved challenge: {self._pairing_details.decrypted_challenge_str}"
227-
)
226+
logger.info('Establishing WebSocket connection to %s,', self._connection_details.connectionUri)
227+
logger.info('Using solved challenge: %s', self._pairing_details.decrypted_challenge_str)
228228

229229
# Placeholder for the connection object
230230
self._ws_connection = {
@@ -240,6 +240,5 @@ def close_connection(self) -> None:
240240
"""
241241
if self._ws_connection:
242242

243-
print("Would close WebSocket connection")
244-
self._ws_connection.close()
243+
logger.info("Would close WebSocket connection")
245244
self._ws_connection = None

src/s2python/communication/examples/example_pairing_frbc_rm.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,3 +87,4 @@
8787

8888
except Exception as e:
8989
logger.error("Error during pairing process: %s", e)
90+
raise e

src/s2python/communication/examples/mock_s2_server.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@
33
import json
44
from typing import Any
55
import uuid
6-
from urllib.parse import urlparse, parse_qs
7-
import ssl
8-
import threading
96
import logging
107
import random
118
import string
@@ -39,14 +36,14 @@ def generate_token() -> str:
3936

4037

4138
class MockS2Handler(http.server.BaseHTTPRequestHandler):
42-
def do_POST(self) -> None:
39+
def do_POST(self) -> None: # pylint: disable=C0103
4340
content_length = int(self.headers.get("Content-Length", 0))
4441
post_data = self.rfile.read(content_length).decode("utf-8")
4542

4643
try:
4744
request_json = json.loads(post_data)
48-
logger.info(f"Received request at {self.path} ")
49-
# logger.info(f"Request body: {request_json}")
45+
logger.info('Received request at %s', self.path)
46+
logger.debug('Request body: %s', request_json)
5047

5148
if self.path == "/requestPairing":
5249
# Handle pairing request
@@ -59,8 +56,8 @@ def do_POST(self) -> None:
5956
else:
6057
request_token_string = token_obj
6158

62-
logger.info(f"Extracted token: {request_token_string}")
63-
logger.info(f"Expected token: {PAIRING_TOKEN}")
59+
logger.info('Extracted token: %s', request_token_string)
60+
logger.info('Expected token: %s', PAIRING_TOKEN)
6461

6562
if request_token_string == PAIRING_TOKEN:
6663
self.send_response(200)
@@ -115,24 +112,25 @@ def do_POST(self) -> None:
115112
self.send_header("Content-Type", "application/json")
116113
self.end_headers()
117114
self.wfile.write(json.dumps({"error": "Endpoint not found"}).encode())
118-
logger.error(f"Unknown endpoint: {self.path}")
115+
logger.error('Unknown endpoint: %s', self.path)
119116

120117
except Exception as e:
121118
self.send_response(500)
122119
self.send_header("Content-Type", "application/json")
123120
self.end_headers()
124121
self.wfile.write(json.dumps({"error": str(e)}).encode())
125-
logger.error(f"Error handling request: {e}")
122+
logger.error('Error handling request: %s', e)
123+
raise e
126124

127-
def log_message(self, format: str, *args: Any) -> None:
128-
logger.info(format % args)
125+
def log_message(self, format: str, *args: Any) -> None: # pylint: disable=W0622
126+
logger.info(format % args) # pylint: disable=W1201
129127

130128

131129
def run_server() -> None:
132130
with socketserver.TCPServer(("localhost", HTTP_PORT), MockS2Handler) as httpd:
133-
logger.info(f"Mock S2 Server running at http://localhost:{HTTP_PORT}")
134-
logger.info(f"Use pairing token: {PAIRING_TOKEN}")
135-
logger.info(f"Pairing endpoint: http://localhost:{HTTP_PORT}/requestPairing")
131+
logger.info('Mock S2 Server running at: http://localhost:%s', HTTP_PORT)
132+
logger.info('Use pairing token: %s', PAIRING_TOKEN)
133+
logger.info('Pairing endpoint: http://localhost:%s/requestPairing', HTTP_PORT)
136134
httpd.serve_forever()
137135

138136

src/s2python/communication/examples/mock_s2_websocket.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import asyncio
2-
import websockets
32
import logging
43
import json
54
import uuid
65
from datetime import datetime, timezone
6+
import websockets
77

88
# Set up logging
99
logging.basicConfig(level=logging.INFO)
@@ -18,7 +18,7 @@ async def handle_connection(
1818
websocket: websockets.WebSocketServerProtocol, path: str
1919
) -> None:
2020
client_id = str(uuid.uuid4())
21-
logger.info(f"Client {client_id} connected on path: {path}")
21+
logger.info('Client %s connected on path: %s', client_id, path)
2222

2323
try:
2424
# Send handshake message to client
@@ -29,13 +29,13 @@ async def handle_connection(
2929
"timestamp": datetime.now(timezone.utc).isoformat(),
3030
}
3131
await websocket.send(json.dumps(handshake))
32-
logger.info(f"Sent handshake to client {client_id}")
32+
logger.info('Sent handshake to client %s', client_id)
3333

3434
# Listen for messages
3535
async for message in websocket:
3636
try:
3737
data = json.loads(message)
38-
logger.info(f"Received message from client {client_id}: {data}")
38+
logger.info('Received message from client %s: %s', client_id, data)
3939

4040
# Extract message type
4141
message_type = data.get("type", "")
@@ -50,7 +50,7 @@ async def handle_connection(
5050
"status": "OK",
5151
}
5252
await websocket.send(json.dumps(reception_status))
53-
logger.info(f"Sent reception status for message {message_id}")
53+
logger.info('Sent reception status for message %s', message_id)
5454

5555
# Handle specific message types
5656
if message_type == "HandshakeResponse":
@@ -59,21 +59,23 @@ async def handle_connection(
5959
# For FRBC messages, you could add specific handling here
6060

6161
except json.JSONDecodeError:
62-
logger.error(f"Invalid JSON received from client {client_id}")
62+
logger.error('Invalid JSON received from client %s', client_id)
6363
except Exception as e:
64-
logger.error(f"Error processing message from client {client_id}: {e}")
64+
logger.error('Error processing message from client %s: %s', client_id, e)
65+
raise e
6566

6667
except websockets.exceptions.ConnectionClosed:
67-
logger.info(f"Connection with client {client_id} closed")
68+
logger.info('Connection with client %s closed', client_id)
6869
except Exception as e:
69-
logger.error(f"Error with client {client_id}: {e}")
70+
logger.error('Error with client %s: %s', client_id, e)
71+
raise e
7072
finally:
71-
logger.info(f"Client {client_id} disconnected")
73+
logger.info('Client %s disconnected', client_id)
7274

7375

7476
async def start_server() -> None:
7577
server = await websockets.serve(handle_connection, "localhost", WS_PORT)
76-
logger.info(f"WebSocket server started on ws://localhost:{WS_PORT}")
78+
logger.info('WebSocket server started on ws://localhost:%s', WS_PORT)
7779

7880
# Keep the server running
7981
await server.wait_closed()

0 commit comments

Comments
 (0)