-
Notifications
You must be signed in to change notification settings - Fork 382
Expand file tree
/
Copy pathapp_test.py
More file actions
85 lines (65 loc) · 3.16 KB
/
app_test.py
File metadata and controls
85 lines (65 loc) · 3.16 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
# pylint: disable=redefined-outer-name
"""Tests for the FastAPI application."""
import logging
import os
from backend.app import create_app
from fastapi import FastAPI
from httpx import ASGITransport
from httpx import AsyncClient
from opentelemetry.sdk._logs import LoggingHandler
import pytest
@pytest.fixture
def app() -> FastAPI:
"""Fixture to create a test app instance."""
return create_app()
@pytest.mark.asyncio
async def test_health_check(app: FastAPI):
"""Test the /health endpoint returns a healthy status."""
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
response = await ac.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "healthy"}
@pytest.mark.asyncio
async def test_backend_routes_exist(app: FastAPI):
"""Ensure /api routes are available (smoke test)."""
# Check available routes include /api prefix from backend_router
routes = [route.path for route in app.router.routes]
backend_routes = [r for r in routes if r.startswith("/api")]
assert backend_routes, "No backend routes found under /api prefix"
def test_logging_handler_deduplication():
"""Test that creating multiple apps doesn't accumulate LoggingHandler instances."""
# Set up Application Insights connection string to trigger telemetry setup
# Use a valid UUID format for the instrumentation key
connection_string = "InstrumentationKey=12345678-1234-5678-1234-567812345678;IngestionEndpoint=https://test.com"
original_env = os.environ.get("APPLICATIONINSIGHTS_CONNECTION_STRING")
try:
os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = connection_string
# Get root logger and count existing LoggingHandlers
root_logger = logging.getLogger()
initial_handler_count = sum(1 for h in root_logger.handlers if isinstance(h, LoggingHandler))
# Create first app
app1 = create_app()
handler_count_after_first = sum(1 for h in root_logger.handlers if isinstance(h, LoggingHandler))
# Create second app
app2 = create_app()
handler_count_after_second = sum(1 for h in root_logger.handlers if isinstance(h, LoggingHandler))
# Assert only one LoggingHandler exists after multiple create_app() calls
assert handler_count_after_first == initial_handler_count + 1, \
"First create_app() should add one LoggingHandler"
assert handler_count_after_second == handler_count_after_first, \
"Second create_app() should not add another LoggingHandler (de-duplication should work)"
# Clean up - remove the handler we added
for handler in list(root_logger.handlers):
if isinstance(handler, LoggingHandler):
root_logger.removeHandler(handler)
try:
handler.close()
except Exception:
pass
finally:
# Restore original environment
if original_env is not None:
os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] = original_env
else:
os.environ.pop("APPLICATIONINSIGHTS_CONNECTION_STRING", None)