-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtest_logging.py
More file actions
508 lines (430 loc) · 18 KB
/
test_logging.py
File metadata and controls
508 lines (430 loc) · 18 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
"""Test logging infrastructure."""
from __future__ import annotations
import sys
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, Mock
import pytest
from starlette.requests import Request
from starlette.responses import Response
from app.config.log_config import LogCategory, LogConfig, setup_logging
from app.logs import CategoryLogger
from app.middleware.logging_middleware import LoggingMiddleware
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.mark.unit
class TestLogCategory:
"""Test LogCategory Flag enum."""
def test_log_category_none(self) -> None:
"""Test NONE category has value 0."""
assert LogCategory.NONE.value == 0
def test_log_category_all_combines_all_flags(self) -> None:
"""Test ALL combines all individual categories."""
expected = (
LogCategory.REQUESTS
| LogCategory.AUTH
| LogCategory.DATABASE
| LogCategory.EMAIL
| LogCategory.ERRORS
| LogCategory.ADMIN
| LogCategory.API_KEYS
)
assert expected == LogCategory.ALL
def test_log_category_bitwise_operations(self) -> None:
"""Test combining categories with | operator."""
combined = LogCategory.AUTH | LogCategory.DATABASE
assert bool(combined & LogCategory.AUTH)
assert bool(combined & LogCategory.DATABASE)
assert not bool(combined & LogCategory.EMAIL)
@pytest.mark.unit
class TestLogConfig:
"""Test LogConfig class."""
def test_parse_categories_none(self, mocker: MockerFixture) -> None:
"""Test parsing 'NONE' returns LogCategory.NONE."""
# COVERS: log_config.py lines 54-55
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="NONE",
log_filename="api.log",
log_console_enabled=False,
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
config = LogConfig()
assert config.enabled_categories == LogCategory.NONE
def test_parse_categories_comma_separated(
self, mocker: MockerFixture
) -> None:
"""Test parsing comma-separated categories."""
# COVERS: log_config.py lines 57-62
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="AUTH,DATABASE,EMAIL",
log_filename="api.log",
log_console_enabled=False,
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
config = LogConfig()
expected = LogCategory.AUTH | LogCategory.DATABASE | LogCategory.EMAIL
assert config.enabled_categories == expected
def test_parse_categories_with_invalid_category(
self, mocker: MockerFixture
) -> None:
"""Test invalid category names are ignored."""
# COVERS: log_config.py lines 57-62
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="AUTH,INVALID,DATABASE",
log_filename="api.log",
log_console_enabled=False,
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
config = LogConfig()
# INVALID should be ignored, only AUTH and DATABASE should be set
assert bool(config.enabled_categories & LogCategory.AUTH)
assert bool(config.enabled_categories & LogCategory.DATABASE)
assert not bool(config.enabled_categories & LogCategory.EMAIL)
def test_parse_categories_mixed_case(self, mocker: MockerFixture) -> None:
"""Test case-insensitive parsing."""
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="auth,Database,EMAIL",
log_filename="api.log",
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
config = LogConfig()
expected = LogCategory.AUTH | LogCategory.DATABASE | LogCategory.EMAIL
assert config.enabled_categories == expected
def test_is_enabled_with_combined_categories(
self, mocker: MockerFixture
) -> None:
"""Test is_enabled works with combined categories."""
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="AUTH,DATABASE",
log_filename="api.log",
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
config = LogConfig()
assert config.is_enabled(LogCategory.AUTH)
assert config.is_enabled(LogCategory.DATABASE)
assert not config.is_enabled(LogCategory.EMAIL)
def test_log_filename_with_forward_slash_raises_error(
self, mocker: MockerFixture
) -> None:
"""Test log_filename with forward slash raises ValueError."""
# COVERS: log_config.py lines 49-53
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="ALL",
log_filename="../malicious.log",
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
with pytest.raises(
ValueError,
match="log_filename cannot contain path separators",
):
LogConfig()
def test_log_filename_with_backslash_raises_error(
self, mocker: MockerFixture
) -> None:
"""Test log_filename with backslash raises ValueError."""
# COVERS: log_config.py lines 49-53
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="ALL",
log_filename="subfolder\\malicious.log",
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
with pytest.raises(
ValueError,
match="log_filename cannot contain path separators",
):
LogConfig()
def test_console_logging_disabled_by_default(
self, mocker: MockerFixture
) -> None:
"""Test console logging is disabled by default."""
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="ALL",
log_filename="api.log",
log_console_enabled=False,
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
config = LogConfig()
assert config.console_enabled is False
def test_console_logging_can_be_enabled(
self, mocker: MockerFixture
) -> None:
"""Test console logging can be enabled via setting."""
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="ALL",
log_filename="api.log",
log_console_enabled=True,
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
config = LogConfig()
assert config.console_enabled is True
def test_setup_logging_skips_console_when_disabled(
self, mocker: MockerFixture
) -> None:
"""Test setup_logging() doesn't add console handler when disabled."""
# COVERS: log_config.py line 87-93 (the if block)
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="ALL",
log_filename="api.log",
log_console_enabled=False,
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
# Mock logger methods
mock_logger_add = mocker.patch("app.config.log_config.logger.add")
mocker.patch("app.config.log_config.logger.remove")
setup_logging()
# Verify logger.add was called only once (for file handler, not console)
assert mock_logger_add.call_count == 1
# Verify it was called with a file path (str), not sys.stderr
call_args = mock_logger_add.call_args[0][0]
assert isinstance(call_args, str)
def test_setup_logging_adds_console_when_enabled(
self, mocker: MockerFixture
) -> None:
"""Test setup_logging() adds console handler when enabled."""
# COVERS: log_config.py line 88-93 (inside the if block)
mock_settings = Mock(
log_path="./logs",
log_level="INFO",
log_rotation="1 day",
log_retention="30 days",
log_compression="zip",
log_categories="ALL",
log_filename="api.log",
log_console_enabled=True,
)
mocker.patch(
"app.config.settings.get_settings", return_value=mock_settings
)
# Mock logger methods
mock_logger_add = mocker.patch("app.config.log_config.logger.add")
mocker.patch("app.config.log_config.logger.remove")
setup_logging()
# Verify logger.add was called twice (console + file)
expected_handler_count = 2 # console + file
assert mock_logger_add.call_count == expected_handler_count
# First call should be for console (sys.stderr)
first_call_args = mock_logger_add.call_args_list[0][0][0]
# Second call should be for file (str path)
second_call_args = mock_logger_add.call_args_list[1][0][0]
# Verify first is sys.stderr and second is string path
assert first_call_args == sys.stderr
assert isinstance(second_call_args, str)
@pytest.mark.unit
class TestCategoryLogger:
"""Test CategoryLogger wrapper class."""
def test_debug_when_category_enabled(self, mocker: MockerFixture) -> None:
"""Test debug logs when category is enabled."""
# COVERS: logs.py lines 43-44
mock_logger = Mock()
mock_log_config = mocker.patch("app.logs.log_config")
mock_log_config.is_enabled.return_value = True
category_logger = CategoryLogger(mock_logger)
category_logger.debug("Debug message", LogCategory.AUTH)
mock_log_config.is_enabled.assert_called_once_with(LogCategory.AUTH)
mock_logger.debug.assert_called_once_with("Debug message")
def test_debug_when_category_disabled(self, mocker: MockerFixture) -> None:
"""Test debug doesn't log when category is disabled."""
# COVERS: logs.py lines 43-44
mock_logger = Mock()
mock_log_config = mocker.patch("app.logs.log_config")
mock_log_config.is_enabled.return_value = False
category_logger = CategoryLogger(mock_logger)
category_logger.debug("Debug message", LogCategory.AUTH)
mock_log_config.is_enabled.assert_called_once_with(LogCategory.AUTH)
mock_logger.debug.assert_not_called()
def test_info_when_category_enabled(self, mocker: MockerFixture) -> None:
"""Test info method works correctly."""
mock_logger = Mock()
mock_log_config = mocker.patch("app.logs.log_config")
mock_log_config.is_enabled.return_value = True
category_logger = CategoryLogger(mock_logger)
category_logger.info("Info message", LogCategory.DATABASE)
mock_log_config.is_enabled.assert_called_once_with(LogCategory.DATABASE)
mock_logger.info.assert_called_once_with("Info message")
def test_error_when_category_disabled(self, mocker: MockerFixture) -> None:
"""Test error doesn't log when disabled."""
mock_logger = Mock()
mock_log_config = mocker.patch("app.logs.log_config")
mock_log_config.is_enabled.return_value = False
category_logger = CategoryLogger(mock_logger)
category_logger.error("Error message", LogCategory.ERRORS)
mock_log_config.is_enabled.assert_called_once_with(LogCategory.ERRORS)
mock_logger.error.assert_not_called()
@pytest.mark.unit
@pytest.mark.asyncio
class TestLoggingMiddleware:
"""Test LoggingMiddleware class."""
async def test_middleware_skips_logging_when_requests_disabled(
self, mocker: MockerFixture
) -> None:
"""Test middleware bypasses logging when REQUESTS disabled."""
# COVERS: logging_middleware.py line 30
mock_log_config = mocker.patch(
"app.middleware.logging_middleware.log_config"
)
mock_log_config.is_enabled.return_value = False
mock_logger = mocker.patch("app.middleware.logging_middleware.logger")
middleware = LoggingMiddleware(app=Mock())
# Create mock request and response
mock_request = Mock(spec=Request)
mock_response = Mock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
result = await middleware.dispatch(mock_request, mock_call_next)
# Verify early return path
mock_log_config.is_enabled.assert_called_once_with(LogCategory.REQUESTS)
mock_call_next.assert_called_once_with(mock_request)
mock_logger.info.assert_not_called()
assert result == mock_response
async def test_middleware_logs_when_requests_enabled(
self, mocker: MockerFixture
) -> None:
"""Test middleware logs requests when enabled."""
mock_log_config = mocker.patch(
"app.middleware.logging_middleware.log_config"
)
mock_log_config.is_enabled.return_value = True
mock_logger = mocker.patch("app.middleware.logging_middleware.logger")
middleware = LoggingMiddleware(app=Mock())
# Create mock request with necessary attributes
mock_request = Mock(spec=Request)
mock_request.client = Mock(host="127.0.0.1")
mock_request.method = "GET"
mock_request.url.path = "/api/users"
mock_response = Mock(spec=Response)
mock_response.status_code = 200
mock_call_next = AsyncMock(return_value=mock_response)
result = await middleware.dispatch(mock_request, mock_call_next)
# Verify logging occurred
mock_log_config.is_enabled.assert_called_once_with(LogCategory.REQUESTS)
mock_call_next.assert_called_once_with(mock_request)
mock_logger.info.assert_called_once()
# Verify log message format
log_message = mock_logger.info.call_args[0][0]
assert "127.0.0.1" in log_message
assert "GET /api/users" in log_message
assert "200" in log_message
assert result == mock_response
async def test_middleware_logs_query_parameters(
self, mocker: MockerFixture
) -> None:
"""Test middleware includes query parameters in logs."""
mock_log_config = mocker.patch(
"app.middleware.logging_middleware.log_config"
)
mock_log_config.is_enabled.return_value = True
mock_logger = mocker.patch("app.middleware.logging_middleware.logger")
middleware = LoggingMiddleware(app=Mock())
# Create mock request with query parameters
mock_request = Mock(spec=Request)
mock_request.client = Mock(host="127.0.0.1")
mock_request.method = "GET"
mock_request.url.path = "/api/users"
mock_request.url.query = "page=2&limit=10"
mock_response = Mock(spec=Response)
mock_response.status_code = 200
mock_call_next = AsyncMock(return_value=mock_response)
result = await middleware.dispatch(mock_request, mock_call_next)
# Verify logging occurred with query parameters
mock_logger.info.assert_called_once()
log_message = mock_logger.info.call_args[0][0]
assert "127.0.0.1" in log_message
assert "GET /api/users?page=2&limit=10" in log_message
assert "200" in log_message
assert result == mock_response
async def test_middleware_logs_without_query_parameters(
self, mocker: MockerFixture
) -> None:
"""Test middleware logs cleanly when no query parameters present."""
mock_log_config = mocker.patch(
"app.middleware.logging_middleware.log_config"
)
mock_log_config.is_enabled.return_value = True
mock_logger = mocker.patch("app.middleware.logging_middleware.logger")
middleware = LoggingMiddleware(app=Mock())
# Create mock request without query parameters
mock_request = Mock(spec=Request)
mock_request.client = Mock(host="127.0.0.1")
mock_request.method = "POST"
mock_request.url.path = "/api/users"
mock_request.url.query = "" # Empty query string
mock_response = Mock(spec=Response)
mock_response.status_code = 201
mock_call_next = AsyncMock(return_value=mock_response)
result = await middleware.dispatch(mock_request, mock_call_next)
# Verify logging occurred without trailing ?
mock_logger.info.assert_called_once()
log_message = mock_logger.info.call_args[0][0]
assert "127.0.0.1" in log_message
assert "POST /api/users" in log_message
assert "POST /api/users?" not in log_message # No trailing ?
assert "201" in log_message
assert result == mock_response