-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_server.py
More file actions
343 lines (260 loc) · 10.6 KB
/
test_server.py
File metadata and controls
343 lines (260 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
"""Unit tests for the WebSocket server module."""
import asyncio
import json
import pathlib
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from websockets import datastructures
from MoBI_View.presenters import main_app_presenter
from MoBI_View.web import broadcaster, server
@pytest.fixture
def mock_presenter() -> MagicMock:
"""Creates a mock MainAppPresenter."""
mock = MagicMock(spec=main_app_presenter.MainAppPresenter)
mock.poll_data.return_value = []
mock.data_inlets = []
return mock
@pytest.fixture
def mock_broadcaster(mock_presenter: MagicMock) -> MagicMock:
"""Creates a mock Broadcaster."""
mock = MagicMock(spec=broadcaster.Broadcaster)
mock.presenter = mock_presenter
return mock
@pytest.fixture
def mock_websocket() -> AsyncMock:
"""Creates a mock ServerConnection."""
return AsyncMock()
def test_ws_handler_registers_and_unregisters_client(
mock_websocket: AsyncMock,
mock_broadcaster: MagicMock,
mock_presenter: MagicMock,
) -> None:
"""Tests ws_handler adds client on connect and removes on disconnect."""
mock_websocket.__aiter__.return_value = iter([])
asyncio.run(server.ws_handler(mock_websocket, mock_broadcaster, mock_presenter))
mock_broadcaster.add_client.assert_called_once_with(mock_websocket)
mock_broadcaster.remove_client.assert_called_once_with(mock_websocket)
def test_ws_handler_removes_client_on_exception(
mock_websocket: AsyncMock,
mock_broadcaster: MagicMock,
mock_presenter: MagicMock,
) -> None:
"""Tests ws_handler removes client even when iteration raises."""
mock_websocket.__aiter__.side_effect = RuntimeError("connection lost")
with pytest.raises(RuntimeError, match="connection lost"):
asyncio.run(server.ws_handler(mock_websocket, mock_broadcaster, mock_presenter))
mock_broadcaster.remove_client.assert_called_once_with(mock_websocket)
def test_ws_handler_dispatches_discover_command(
mock_websocket: AsyncMock,
mock_broadcaster: MagicMock,
mock_presenter: MagicMock,
) -> None:
"""Tests ws_handler forwards a discover command to _handle_discover."""
message = json.dumps({"command": "discover"})
mock_websocket.__aiter__.return_value = iter([message])
with patch.object(server, "_handle_discover", new_callable=AsyncMock) as mock_hd:
asyncio.run(server.ws_handler(mock_websocket, mock_broadcaster, mock_presenter))
mock_hd.assert_awaited_once_with(mock_websocket, mock_presenter)
def test_handle_message_ignores_invalid_json(
mock_websocket: AsyncMock,
mock_presenter: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Tests _handle_message logs warning for non-JSON payload."""
asyncio.run(server._handle_message("not json", mock_websocket, mock_presenter))
assert "invalid JSON" in caplog.text
def test_handle_message_rejects_non_string_input(
mock_websocket: AsyncMock,
mock_presenter: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Tests _handle_message logs warning when input is not str or bytes."""
asyncio.run(
server._handle_message(None, mock_websocket, mock_presenter) # type: ignore[arg-type]
)
assert "invalid JSON" in caplog.text
def test_handle_message_rejects_invalid_bytes(
mock_websocket: AsyncMock,
mock_presenter: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Tests _handle_message logs warning for bytes with invalid encoding."""
asyncio.run(server._handle_message(b"\xff\xfe", mock_websocket, mock_presenter))
assert "invalid JSON" in caplog.text
def test_handle_message_rejects_deeply_nested_json(
mock_websocket: AsyncMock,
mock_presenter: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Tests _handle_message logs warning for deeply nested JSON."""
deeply_nested = "[" * 10000 + "]" * 10000
asyncio.run(server._handle_message(deeply_nested, mock_websocket, mock_presenter))
assert "invalid JSON" in caplog.text
def test_handle_message_rejects_non_dict_json(
mock_websocket: AsyncMock,
mock_presenter: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Tests _handle_message logs warning when JSON is not an object."""
asyncio.run(
server._handle_message('"just a string"', mock_websocket, mock_presenter)
)
assert "Expected JSON object" in caplog.text
def test_handle_message_logs_unknown_command(
mock_websocket: AsyncMock,
mock_presenter: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Tests _handle_message logs warning for unrecognised command."""
msg = json.dumps({"command": "foobar"})
asyncio.run(server._handle_message(msg, mock_websocket, mock_presenter))
assert "Unknown command: foobar" in caplog.text
def test_handle_message_routes_discover_command(
mock_websocket: AsyncMock,
mock_presenter: MagicMock,
) -> None:
"""Tests _handle_message calls _handle_discover for discover command."""
msg = json.dumps({"command": "discover"})
with patch.object(server, "_handle_discover", new_callable=AsyncMock) as mock_hd:
asyncio.run(server._handle_message(msg, mock_websocket, mock_presenter))
mock_hd.assert_awaited_once_with(mock_websocket, mock_presenter)
def test_handle_discover_calls_discovery_and_sends_result(
mock_websocket: AsyncMock,
mock_presenter: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Tests _handle_discover discovers new streams and sends them to client."""
fake_inlet = MagicMock()
fake_inlet.stream_name = "EEG"
with (
patch.object(
server.discovery,
"discover_and_create_inlets",
return_value=[fake_inlet],
),
caplog.at_level("INFO"),
):
asyncio.run(server._handle_discover(mock_websocket, mock_presenter))
mock_websocket.send.assert_awaited_once()
sent = json.loads(mock_websocket.send.call_args[0][0])
assert sent["type"] == "discover_result"
assert sent["streams"] == ["EEG"]
assert fake_inlet in mock_presenter.data_inlets
assert "found 1 new stream(s)" in caplog.text
def test_handle_discover_with_no_new_streams(
mock_websocket: AsyncMock,
mock_presenter: MagicMock,
) -> None:
"""Tests _handle_discover sends empty list when no new streams found."""
with patch.object(
server.discovery,
"discover_and_create_inlets",
return_value=[],
):
asyncio.run(server._handle_discover(mock_websocket, mock_presenter))
sent = json.loads(mock_websocket.send.call_args[0][0])
assert sent["streams"] == []
@pytest.fixture
def static_dir(tmp_path: pathlib.Path) -> pathlib.Path:
"""Creates a temporary static directory mimicking SvelteKit build output."""
(tmp_path / "index.html").write_text("<html></html>")
(tmp_path / "style.css").write_text("body {}")
app_dir = tmp_path / "_app" / "immutable"
app_dir.mkdir(parents=True)
(app_dir / "entry.js").write_text("console.log('ok')")
return tmp_path
def _make_request(path: str, upgrade: str = "") -> MagicMock:
"""Builds a minimal Request-like object with path and headers."""
header_list = []
if upgrade:
header_list.append(("Upgrade", upgrade))
request = MagicMock()
request.path = path
request.headers = datastructures.Headers(header_list)
return request
def test_process_request_passes_websocket_upgrades() -> None:
"""Tests process_request returns None for WebSocket upgrades."""
request = _make_request("/", upgrade="websocket")
connection = MagicMock()
result = asyncio.run(server.process_request(connection, request))
assert result is None
def test_process_request_serves_static_file() -> None:
"""Tests process_request delegates to _serve_static_file for HTTP requests."""
request = _make_request("/style.css")
connection = MagicMock()
fake_response = MagicMock()
with patch.object(
server, "_serve_static_file", return_value=fake_response
) as mock_serve:
result = asyncio.run(server.process_request(connection, request))
mock_serve.assert_called_once_with("/style.css")
assert result is fake_response
@pytest.mark.parametrize("path", ["/", ""])
def test_serve_static_file_returns_index_for_root_paths(
path: str,
static_dir: pathlib.Path,
) -> None:
"""Tests root and empty paths both resolve to index.html."""
with patch.object(server, "STATIC_DIR", static_dir):
result = server._serve_static_file(path)
assert result.status_code == 200
assert b"<html></html>" in result.body
def test_serve_static_file_returns_nested_file(
static_dir: pathlib.Path,
) -> None:
"""Tests subdirectory files are served correctly."""
with patch.object(server, "STATIC_DIR", static_dir):
result = server._serve_static_file("/_app/immutable/entry.js")
assert result.status_code == 200
assert b"console.log" in result.body
def test_serve_static_file_returns_correct_content_type(
static_dir: pathlib.Path,
) -> None:
"""Tests Content-Type header matches the file extension."""
with patch.object(server, "STATIC_DIR", static_dir):
result = server._serve_static_file("/style.css")
assert result.status_code == 200
assert "css" in result.headers.get("Content-Type", "")
def test_serve_static_file_returns_404_for_missing_file(
static_dir: pathlib.Path,
) -> None:
"""Tests missing files return a 404 response."""
with patch.object(server, "STATIC_DIR", static_dir):
result = server._serve_static_file("/nope.txt")
assert result.status_code == 404
@pytest.mark.parametrize(
"malicious_path",
[
"/../../../etc/passwd",
"/%2e%2e/%2e%2e/etc/passwd",
"/..%2F..%2Fetc/passwd",
],
)
def test_serve_static_file_blocks_path_traversal(
malicious_path: str, static_dir: pathlib.Path
) -> None:
"""Tests path traversal attempts return a 403 response."""
with patch.object(server, "STATIC_DIR", static_dir):
result = server._serve_static_file(malicious_path)
assert result.status_code == 403
@pytest.mark.parametrize(
"resolved,expected",
[
("inside", True),
("outside", False),
],
)
def test_is_within_static_dir(
resolved: str,
expected: bool,
tmp_path: pathlib.Path,
) -> None:
"""Tests path containment check against the static directory."""
static = tmp_path / "static"
static.mkdir()
if resolved == "inside":
target = static / "file.html"
else:
target = tmp_path / "file.html"
with patch.object(server, "STATIC_DIR", static):
assert server._is_within_static_dir(target) is expected