Skip to content

Commit 7efffb0

Browse files
committed
Claude...
1 parent cefe59a commit 7efffb0

3 files changed

Lines changed: 67 additions & 67 deletions

File tree

src/pubsub_ws.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,15 @@
1616
logger = logging.getLogger(__name__)
1717

1818

19-
# --- DÉBUT MODIFICATION POUR LA GESTION DE LA DB ET LES TESTS ---
19+
# --- START MODIFICATION FOR DB MANAGEMENT AND TESTS ---
2020
def init_db(db_name: str, connection: Optional[sqlite3.Connection] = None) -> None:
2121
"""Initialize the SQLite database and run migrations if necessary."""
2222
if connection:
2323
conn = connection
24-
close_conn = False # Ne pas fermer la connection si elle est fournie
24+
close_conn = False # Don't close connection if provided
2525
else:
2626
conn = sqlite3.connect(db_name)
27-
close_conn = True # Fermer la connection si elle est créée ici
27+
close_conn = True # Close connection if created here
2828

2929
try:
3030
c = conn.cursor()
@@ -39,11 +39,11 @@ def init_db(db_name: str, connection: Optional[sqlite3.Connection] = None) -> No
3939
else:
4040
logger.error(f"[INIT DB] Migration script not found: {migration_script}")
4141
finally:
42-
if close_conn and conn: # Fermez la connection seulement si elle a été ouverte ici
42+
if close_conn and conn: # Close connection only if it was opened here
4343
conn.close()
4444

4545

46-
# Nom du fichier de la DB par défaut
46+
# Default DB file name
4747
DB_FILE_NAME = "pubsub.db"
4848
# --- FIN MODIFICATION POUR LA GESTION DE LA DB ET LES TESTS ---
4949

@@ -52,13 +52,13 @@ def init_db(db_name: str, connection: Optional[sqlite3.Connection] = None) -> No
5252
app.config["SECRET_KEY"] = "secret!"
5353
socketio = SocketIO(app, cors_allowed_origins="*", async_mode="eventlet")
5454

55-
# Initialisez la base de données réelle lors du démarrage de l'application
55+
# Initialize the real database when starting the application
5656
if __name__ == "__main__":
5757
init_db(DB_FILE_NAME)
5858

5959

6060
class Broker:
61-
# Le broker peut recevoir une connection existante pour les tests
61+
# The broker can receive an existing connection for tests
6262
def __init__(self, db_name: str, test_conn: Optional[sqlite3.Connection] = None):
6363
"""
6464
Initialize the Broker with a database name.
@@ -67,17 +67,17 @@ def __init__(self, db_name: str, test_conn: Optional[sqlite3.Connection] = None)
6767
:param test_conn: An optional existing SQLite connection for testing purposes.
6868
"""
6969
self.db_name = db_name
70-
self._test_conn = test_conn # Stocke la connection de test
70+
self._test_conn = test_conn # Store test connection
7171

7272
def _get_db_connection(self) -> sqlite3.Connection:
7373
"""Helper to get a database connection. Uses test_conn if available."""
7474
if self._test_conn:
75-
return self._test_conn # Retourne la connection de test
75+
return self._test_conn # Return test connection
7676
return sqlite3.connect(self.db_name)
7777

7878
def _close_db_connection(self, conn: sqlite3.Connection) -> None:
7979
"""Helper to close a database connection, if it's not a test connection."""
80-
if conn != self._test_conn: # Ne ferme pas la connection de test
80+
if conn != self._test_conn: # Don't close test connection
8181
conn.close()
8282

8383
def register_subscription(self, sid: str, consumer: str, topic: str) -> None:
@@ -105,7 +105,7 @@ def register_subscription(self, sid: str, consumer: str, topic: str) -> None:
105105
conn.rollback() # Rollback on error
106106
finally:
107107
if conn:
108-
self._close_db_connection(conn) # Utilisez la nouvelle méthode de fermeture
108+
self._close_db_connection(conn) # Use the new close method
109109

110110
def unregister_client(self, sid: str) -> None:
111111
conn = None
@@ -272,9 +272,9 @@ def get_consumptions(self) -> List[Dict[str, Any]]:
272272
self._close_db_connection(conn)
273273

274274

275-
# Créez l'instance du Broker avec le nom du fichier de base de données réel
276-
# Cette ligne est exécutée uniquement si __name__ == "__main__"
277-
# Pour les tests, le Broker est instancié via la fixture
275+
# Create the Broker instance with the real database filename
276+
# This line is executed only if __name__ == "__main__"
277+
# For tests, the Broker is instantiated via the fixture
278278
broker = Broker(DB_FILE_NAME)
279279

280280

@@ -291,7 +291,7 @@ def publish() -> Tuple[Dict[str, str], int]:
291291
return jsonify({"status": "error", "message": "Missing topic, message_id, message, or producer"}), 400
292292

293293
logger.info(f"Publishing message {message_id} to topic {topic} by {producer}")
294-
# Le broker réel sera utilisé ici, pas le mock
294+
# The real broker will be used here, not the mock
295295
broker.save_message(topic=topic, message_id=message_id, message=message, producer=producer)
296296

297297
payload = {"topic": topic, "message_id": message_id, "message": message, "producer": producer}
@@ -375,10 +375,10 @@ def handle_consumed(data: Dict[str, Any]) -> None:
375375

376376

377377
@socketio.on("disconnect")
378-
def handle_disconnect() -> None: # <-- Signature sans argument explicit pour le SID
378+
def handle_disconnect() -> None: # <-- Signature without explicit argument for the SID
379379
"""Handle client disconnection."""
380380
# noinspection PyUnresolvedReferences
381-
sid = request.sid # Toujours récupérer le SID via request.sid
381+
sid = request.sid # Always get SID via request.sid
382382
logger.info(f"Client disconnected (SID: {sid})")
383383
broker.unregister_client(sid)
384384

tests/test_pubsub_client.py

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -13,27 +13,27 @@
1313
from client import BASE_URL, PubSubClient # noqa: E402
1414

1515

16-
# Mock du socketio.Client
17-
# On va mocker la class socketio.Client elle-même, pas son instance directement
18-
# Ensuite, on accède à mock_sio_client.return_value pour mocker les méthodes de l'instance
16+
# Mock of socketio.Client
17+
# We will mock the socketio.Client class itself, not its instance directly
18+
# Then, we access mock_sio_client.return_value to mock the instance methods
1919
@pytest.fixture
2020
def mock_sio_client():
21-
"""Mocke l'instance de socketio.Client utilisée par PubSubClient."""
21+
"""Mocks the socketio.Client instance used by PubSubClient."""
2222
with patch("client.socketio.Client") as MockClient: # <-- Patch la class directement dans le module client
23-
instance = MockClient.return_value # Ceci est le mock de l'instance qui sera créée
24-
instance.connected = False # Simule l'état initial déconnecté
25-
yield MockClient # On yield le Mock de la CLASS Client elle-même, pas son instance
23+
instance = MockClient.return_value # This is the mock of the instance that will be created
24+
instance.connected = False # Simulate initial disconnected state
25+
yield MockClient # We yield the Mock of the Client CLASS itself, not its instance
2626

2727

2828
# Mock de requests.post
2929
@pytest.fixture
3030
def mock_requests_post():
3131
"""Mocke requests.post pour les appels de publication HTTP."""
32-
# Patch requests.post dans le module client où il est utilisé
32+
# Patch requests.post in the client module where it is used
3333
with patch("client.requests.post") as mock_post: # <-- Patch requests.post dans le module client
3434
mock_response = MagicMock()
3535
mock_response.json.return_value = {"status": "ok", "message_id": "test_id_returned"}
36-
mock_response.raise_for_status.return_value = None # Pas d'erreurs HTTP par défaut
36+
mock_response.raise_for_status.return_value = None # No HTTP errors by default
3737
mock_post.return_value = mock_response
3838
yield mock_post
3939

@@ -42,18 +42,18 @@ def mock_requests_post():
4242

4343

4444
def test_pubsub_client_init(mock_sio_client):
45-
"""Vérifie l'initialisation du client et l'enregistrement des gestionnaires."""
45+
"""Verifies client initialization and handler registration."""
4646
consumer = "test_alice"
4747
topics = ["sport", "finance"]
4848
client = PubSubClient(consumer, topics)
4949

5050
assert client.consumer_name == consumer
5151
assert client.topics == topics
5252

53-
# Vérifiez que socketio.Client a été appelé une fois avec le bon argument
53+
# Verify that socketio.Client was called once with the correct argument
5454
mock_sio_client.assert_called_once_with(reconnection=True)
5555

56-
# Vérifiez que les gestionnaires d'événements sont enregistrés sur l'instance mockée
56+
# Verify that event handlers are registered on the mocked instance
5757
mock_sio_client.return_value.on.assert_any_call("message", client.on_message)
5858
mock_sio_client.return_value.on.assert_any_call("new_client", client.on_new_client)
5959
mock_sio_client.return_value.on.assert_any_call("client_disconnected", client.on_client_disconnected)
@@ -62,26 +62,26 @@ def test_pubsub_client_init(mock_sio_client):
6262

6363

6464
def test_pubsub_client_connect_success(mock_sio_client):
65-
"""Teste la méthode connect en cas de succès."""
65+
"""Tests the connect method in case of success."""
6666
consumer = "test_bob"
6767
topics = ["tech"]
6868
client = PubSubClient(consumer, topics)
6969

70-
# Obtenez le mock de l'instance client qui a été créée
70+
# Get the mock of the client instance that was created
7171
mock_instance = mock_sio_client.return_value
72-
mock_instance.connected = True # Simule une connection réussie
72+
mock_instance.connected = True # Simulate successful connection
7373

7474
client.connect()
7575

76-
# Vérifiez que connect a été appelé sur l'instance mockée avec la bonne URL
76+
# Verify that connect was called on the mocked instance with the correct URL
7777
mock_instance.connect.assert_called_once_with(BASE_URL)
7878

79-
# Vérifiez que l'événement "subscribe" a été émis sur l'instance mockée
79+
# Verify that the "subscribe" event was emitted on the mocked instance
8080
mock_instance.emit.assert_called_once_with("subscribe", {"consumer": consumer, "topics": topics})
8181

8282

8383
def test_pubsub_client_connect_failure(mock_sio_client, caplog):
84-
"""Teste la méthode connect en cas d'échec de connection."""
84+
"""Tests the connect method in case of connection failure."""
8585
consumer = "test_charlie"
8686
topics = ["music"]
8787
client = PubSubClient(consumer, topics)
@@ -94,9 +94,9 @@ def test_pubsub_client_connect_failure(mock_sio_client, caplog):
9494
with caplog.at_level(logging.ERROR): # Capture les logs d'erreur
9595
client.connect()
9696

97-
# Le message d'erreur doit être dans les logs
97+
# The error message should be in the logs
9898
assert "Failed to connect to server: Connection refused" in caplog.text
99-
# Vérifiez que connect a été appelé même s'il a levé une exception
99+
# Verify that connect was called even if it raised an exception
100100
mock_instance.connect.assert_called_once()
101101

102102

@@ -113,7 +113,7 @@ def test_pubsub_client_on_message(caplog):
113113

114114

115115
def test_pubsub_client_publish(mock_requests_post):
116-
"""Teste la méthode publish."""
116+
"""Tests the publish method."""
117117
consumer = "test_eve"
118118
topics = ["travel"]
119119
client = PubSubClient(consumer, topics)
@@ -124,7 +124,7 @@ def test_pubsub_client_publish(mock_requests_post):
124124

125125
response = client.publish(topic_to_publish, message_content, message_id)
126126

127-
# Vérifiez que requests.post a été appelé avec les bonnes données
127+
# Verify that requests.post was called with the correct data
128128
expected_url = f"{BASE_URL}/publish"
129129
expected_json = {
130130
"topic": topic_to_publish,
@@ -134,41 +134,41 @@ def test_pubsub_client_publish(mock_requests_post):
134134
}
135135
mock_requests_post.assert_called_once_with(expected_url, json=expected_json)
136136

137-
# Vérifiez la réponse renvoyée par la méthode publish
137+
# Verify the response returned by the publish method
138138
assert response == {"status": "ok", "message_id": "test_id_returned"}
139139

140140

141141
def test_pubsub_client_disconnect_connected(mock_sio_client, caplog):
142-
"""Teste la déconnection quand le client est connecté."""
142+
"""Tests disconnection when the client is connected."""
143143
consumer = "test_frank"
144144
topics = ["sports"]
145145
client = PubSubClient(consumer, topics)
146146

147147
# Obtenez le mock de l'instance client
148148
mock_instance = mock_sio_client.return_value
149-
mock_instance.connected = True # Simule un état connecté
149+
mock_instance.connected = True # Simulate connected state
150150

151151
with caplog.at_level(logging.INFO):
152152
client.disconnect()
153153

154-
# Vérifiez que disconnect a été appelé sur l'instance mockée
154+
# Verify that disconnect was called on the mocked instance
155155
mock_instance.disconnect.assert_called_once()
156156
assert f"Disconnected {consumer} from server." in caplog.text
157157

158158

159159
def test_pubsub_client_disconnect_not_connected(mock_sio_client, caplog):
160-
"""Teste la déconnection quand le client n'est pas connecté."""
160+
"""Tests disconnection when the client is not connected."""
161161
consumer = "test_grace"
162162
topics = ["art"]
163163
client = PubSubClient(consumer, topics)
164164

165165
# Obtenez le mock de l'instance client
166166
mock_instance = mock_sio_client.return_value
167-
mock_instance.connected = False # Simule un état non connecté
167+
mock_instance.connected = False # Simulate disconnected state
168168

169169
with caplog.at_level(logging.INFO):
170170
client.disconnect()
171171

172-
# Vérifiez que disconnect n'a PAS été appelé sur l'instance mockée
172+
# Verify that disconnect was NOT called on the mocked instance
173173
mock_instance.disconnect.assert_not_called()
174174
assert f"Disconnected {consumer} from server." not in caplog.text

0 commit comments

Comments
 (0)