File size: 16,654 Bytes
6b86af2 | 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 | # -*- coding: utf-8 -*-
"""
Unit tests for DebugLoggerMiddleware.
Tests debug logging initialization at the middleware level.
"""
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from starlette.requests import Request
from starlette.responses import Response
class TestDebugLoggerMiddlewareEndpointFiltering:
"""Tests for endpoint filtering in middleware."""
@pytest.mark.asyncio
async def test_skips_health_endpoint(self):
"""
What it does: Verifies that middleware skips /health endpoint.
Purpose: Ensure health checks are not logged.
"""
print("Setup: Creating mock request for /health...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'all'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
# Mock request
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/health"
# Mock call_next
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
# Mock debug_logger at the source module
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch for /health...")
response = await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was NOT called...")
mock_logger.prepare_new_request.assert_not_called()
print("Verifying call_next was called...")
mock_call_next.assert_called_once_with(mock_request)
print(f"Comparing response: Expected {mock_response}, Got {response}")
assert response == mock_response
@pytest.mark.asyncio
async def test_skips_docs_endpoint(self):
"""
What it does: Verifies that middleware skips /docs endpoint.
Purpose: Ensure documentation is not logged.
"""
print("Setup: Creating mock request for /docs...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'all'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/docs"
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch for /docs...")
response = await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was NOT called...")
mock_logger.prepare_new_request.assert_not_called()
@pytest.mark.asyncio
async def test_skips_root_endpoint(self):
"""
What it does: Verifies that middleware skips / endpoint.
Purpose: Ensure root endpoint is not logged.
"""
print("Setup: Creating mock request for /...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'all'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/"
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch for /...")
await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was NOT called...")
mock_logger.prepare_new_request.assert_not_called()
@pytest.mark.asyncio
async def test_processes_chat_completions_endpoint(self):
"""
What it does: Verifies that middleware processes /v1/chat/completions.
Purpose: Ensure OpenAI endpoint is logged.
"""
print("Setup: Creating mock request for /v1/chat/completions...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'all'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/v1/chat/completions"
mock_request.body = AsyncMock(return_value=b'{"model": "test"}')
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch for /v1/chat/completions...")
await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was called...")
mock_logger.prepare_new_request.assert_called_once()
print("Verifying log_request_body was called...")
mock_logger.log_request_body.assert_called_once_with(b'{"model": "test"}')
@pytest.mark.asyncio
async def test_processes_messages_endpoint(self):
"""
What it does: Verifies that middleware processes /v1/messages.
Purpose: Ensure Anthropic endpoint is logged.
"""
print("Setup: Creating mock request for /v1/messages...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'all'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/v1/messages"
mock_request.body = AsyncMock(return_value=b'{"model": "claude"}')
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch for /v1/messages...")
await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was called...")
mock_logger.prepare_new_request.assert_called_once()
class TestDebugLoggerMiddlewareModeHandling:
"""Tests for DEBUG_MODE handling in middleware."""
@pytest.mark.asyncio
async def test_skips_when_debug_mode_off(self):
"""
What it does: Verifies that middleware skips requests when DEBUG_MODE=off.
Purpose: Ensure logging is disabled in off mode.
"""
print("Setup: DEBUG_MODE=off...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'off'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/v1/chat/completions"
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch with DEBUG_MODE=off...")
response = await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was NOT called...")
mock_logger.prepare_new_request.assert_not_called()
print("Verifying call_next was called...")
mock_call_next.assert_called_once()
@pytest.mark.asyncio
async def test_processes_when_debug_mode_errors(self):
"""
What it does: Verifies that middleware works when DEBUG_MODE=errors.
Purpose: Ensure errors mode activates logging.
"""
print("Setup: DEBUG_MODE=errors...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'errors'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/v1/chat/completions"
mock_request.body = AsyncMock(return_value=b'{"test": "data"}')
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch with DEBUG_MODE=errors...")
await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was called...")
mock_logger.prepare_new_request.assert_called_once()
@pytest.mark.asyncio
async def test_processes_when_debug_mode_all(self):
"""
What it does: Verifies that middleware works when DEBUG_MODE=all.
Purpose: Ensure all mode activates logging.
"""
print("Setup: DEBUG_MODE=all...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'all'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/v1/messages"
mock_request.body = AsyncMock(return_value=b'{"test": "data"}')
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch with DEBUG_MODE=all...")
await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was called...")
mock_logger.prepare_new_request.assert_called_once()
class TestDebugLoggerMiddlewareErrorHandling:
"""Tests for error handling in middleware."""
@pytest.mark.asyncio
async def test_handles_body_read_error_gracefully(self):
"""
What it does: Verifies that middleware handles body read errors gracefully.
Purpose: Ensure body read errors don't break the request.
"""
print("Setup: Simulating body read error...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'all'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/v1/chat/completions"
mock_request.body = AsyncMock(side_effect=Exception("Body read error"))
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch with body read error...")
response = await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was called...")
mock_logger.prepare_new_request.assert_called_once()
print("Verifying log_request_body was NOT called (due to error)...")
mock_logger.log_request_body.assert_not_called()
print("Verifying call_next was called (request continued)...")
mock_call_next.assert_called_once()
@pytest.mark.asyncio
async def test_skips_empty_body(self):
"""
What it does: Verifies that middleware doesn't log empty body.
Purpose: Ensure empty requests don't create unnecessary logs.
"""
print("Setup: Creating request with empty body...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'all'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/v1/chat/completions"
mock_request.body = AsyncMock(return_value=b'') # Empty body
mock_response = MagicMock(spec=Response)
mock_call_next = AsyncMock(return_value=mock_response)
with patch('kiro.debug_logger.debug_logger') as mock_logger:
print("Action: Calling dispatch with empty body...")
await middleware.dispatch(mock_request, mock_call_next)
print("Verifying prepare_new_request was called...")
mock_logger.prepare_new_request.assert_called_once()
print("Verifying log_request_body was NOT called (body is empty)...")
mock_logger.log_request_body.assert_not_called()
class TestDebugLoggerMiddlewareResponsePassthrough:
"""Tests for transparent response passthrough."""
@pytest.mark.asyncio
async def test_returns_response_from_call_next(self):
"""
What it does: Verifies that middleware returns response from call_next.
Purpose: Ensure middleware doesn't modify the response.
"""
print("Setup: Creating mock response...")
with patch('kiro.debug_middleware.DEBUG_MODE', 'all'):
from kiro.debug_middleware import DebugLoggerMiddleware
middleware = DebugLoggerMiddleware(app=MagicMock())
mock_request = MagicMock(spec=Request)
mock_request.url.path = "/v1/chat/completions"
mock_request.body = AsyncMock(return_value=b'{"test": "data"}')
expected_response = MagicMock(spec=Response)
expected_response.status_code = 200
mock_call_next = AsyncMock(return_value=expected_response)
with patch('kiro.debug_logger.debug_logger'):
print("Action: Calling dispatch...")
actual_response = await middleware.dispatch(mock_request, mock_call_next)
print(f"Comparing response: Expected {expected_response}, Got {actual_response}")
assert actual_response == expected_response
assert actual_response.status_code == 200
class TestLoggedEndpointsConstant:
"""Tests for LOGGED_ENDPOINTS constant."""
def test_logged_endpoints_contains_chat_completions(self):
"""
What it does: Verifies that LOGGED_ENDPOINTS contains /v1/chat/completions.
Purpose: Ensure OpenAI endpoint is included in logging.
"""
print("Checking LOGGED_ENDPOINTS...")
from kiro.debug_middleware import LOGGED_ENDPOINTS
print(f"LOGGED_ENDPOINTS contents: {LOGGED_ENDPOINTS}")
assert "/v1/chat/completions" in LOGGED_ENDPOINTS
def test_logged_endpoints_contains_messages(self):
"""
What it does: Verifies that LOGGED_ENDPOINTS contains /v1/messages.
Purpose: Ensure Anthropic endpoint is included in logging.
"""
print("Checking LOGGED_ENDPOINTS...")
from kiro.debug_middleware import LOGGED_ENDPOINTS
print(f"LOGGED_ENDPOINTS contents: {LOGGED_ENDPOINTS}")
assert "/v1/messages" in LOGGED_ENDPOINTS
def test_logged_endpoints_is_frozenset(self):
"""
What it does: Verifies that LOGGED_ENDPOINTS is a frozenset.
Purpose: Ensure the constant is immutable.
"""
print("Checking LOGGED_ENDPOINTS type...")
from kiro.debug_middleware import LOGGED_ENDPOINTS
print(f"LOGGED_ENDPOINTS type: {type(LOGGED_ENDPOINTS)}")
assert isinstance(LOGGED_ENDPOINTS, frozenset)
|