1+ import asyncio
2+ from unittest .mock import AsyncMock , MagicMock
3+
4+ import pytest
5+
6+ from mcphawk .web .broadcaster import active_clients , broadcast_new_log
7+
8+
9+ @pytest .mark .asyncio
10+ async def test_broadcast_new_log_with_clients ():
11+ # Create mock websocket clients
12+ mock_client1 = AsyncMock ()
13+ mock_client2 = AsyncMock ()
14+
15+ # Add to active clients
16+ active_clients .append (mock_client1 )
17+ active_clients .append (mock_client2 )
18+
19+ try :
20+ # Broadcast a message
21+ test_log = {
22+ "timestamp" : "2024-01-01T12:00:00Z" ,
23+ "src_ip" : "127.0.0.1" ,
24+ "message" : "test"
25+ }
26+
27+ await broadcast_new_log (test_log )
28+
29+ # Verify both clients received the message
30+ mock_client1 .send_json .assert_called_once_with (test_log )
31+ mock_client2 .send_json .assert_called_once_with (test_log )
32+
33+ finally :
34+ # Clean up
35+ active_clients .clear ()
36+
37+
38+ @pytest .mark .asyncio
39+ async def test_broadcast_new_log_with_disconnected_client ():
40+ # Create mock websocket clients
41+ mock_client1 = AsyncMock ()
42+ mock_client2 = AsyncMock ()
43+
44+ # Make client1 throw an exception (disconnected)
45+ mock_client1 .send_json .side_effect = Exception ("Disconnected" )
46+
47+ # Add to active clients
48+ active_clients .append (mock_client1 )
49+ active_clients .append (mock_client2 )
50+
51+ try :
52+ # Broadcast a message
53+ test_log = {"test" : "data" }
54+
55+ await broadcast_new_log (test_log )
56+
57+ # Client1 should be removed from active_clients
58+ assert mock_client1 not in active_clients
59+ assert mock_client2 in active_clients
60+
61+ # Client2 should still receive the message
62+ mock_client2 .send_json .assert_called_once_with (test_log )
63+
64+ finally :
65+ # Clean up
66+ active_clients .clear ()
67+
68+
69+ @pytest .mark .asyncio
70+ async def test_broadcast_new_log_no_clients ():
71+ # Ensure list is empty
72+ active_clients .clear ()
73+
74+ # Should not raise any errors
75+ await broadcast_new_log ({"test" : "data" })
0 commit comments