Download tests/performance/test_api_performance.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/tests/performance/test_api_performance.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/tests/performance/test_api_performance.py
-
curl -L -o test_api_performance.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/tests/performance/test_api_performance.py
11.4 kB
| """ | |
| Performance Testing Suite for YAZ Care Platform | |
| This module provides comprehensive performance testing utilities | |
| to validate SLA compliance (<200ms p95 latency, <1% error rate). | |
| Usage: | |
| pytest tests/performance/ -v | |
| pytest tests/performance/test_api_performance.py::TestAPILatency -v | |
| """ | |
| import pytest | |
| import time | |
| import asyncio | |
| from typing import List, Dict, Any | |
| from statistics import mean, median | |
| from httpx import AsyncClient | |
| from main import app | |
| class PerformanceMetrics: | |
| """Calculate and store performance metrics""" | |
| def __init__(self, latencies: List[float]): | |
| self.latencies = sorted(latencies) | |
| self.n = len(latencies) | |
| def p50(self) -> float: | |
| """50th percentile (median)""" | |
| return self.latencies[int(self.n * 0.50)] | |
| def p95(self) -> float: | |
| """95th percentile (SLA target)""" | |
| return self.latencies[int(self.n * 0.95)] | |
| def p99(self) -> float: | |
| """99th percentile""" | |
| return self.latencies[int(self.n * 0.99)] | |
| def mean_latency(self) -> float: | |
| """Average latency""" | |
| return mean(self.latencies) | |
| def median_latency(self) -> float: | |
| """Median latency""" | |
| return median(self.latencies) | |
| def min_latency(self) -> float: | |
| """Minimum latency""" | |
| return min(self.latencies) | |
| def max_latency(self) -> float: | |
| """Maximum latency""" | |
| return max(self.latencies) | |
| def summary(self) -> Dict[str, float]: | |
| """Get summary of all metrics""" | |
| return { | |
| "p50": self.p50, | |
| "p95": self.p95, | |
| "p99": self.p99, | |
| "mean": self.mean_latency, | |
| "median": self.median_latency, | |
| "min": self.min_latency, | |
| "max": self.max_latency | |
| } | |
| def print_report(self, test_name: str): | |
| """Print formatted performance report""" | |
| print(f"\n{'='*60}") | |
| print(f"Performance Report: {test_name}") | |
| print(f"{'='*60}") | |
| print(f"Requests: {self.n}") | |
| print(f"P50 (Median): {self.p50:.2f}ms") | |
| print(f"P95 (Target): {self.p95:.2f}ms {'✅' if self.p95 < 200 else '❌'}") | |
| print(f"P99: {self.p99:.2f}ms") | |
| print(f"Mean: {self.mean_latency:.2f}ms") | |
| print(f"Min: {self.min_latency:.2f}ms") | |
| print(f"Max: {self.max_latency:.2f}ms") | |
| print(f"{'='*60}\n") | |
| if self.p95 >= 200: | |
| print(f"⚠️ WARNING: P95 latency {self.p95:.2f}ms exceeds SLA target of 200ms") | |
| class TestAPILatency: | |
| """Test API endpoint latency against SLA targets""" | |
| async def async_client(self): | |
| """Create async HTTP client""" | |
| async with AsyncClient(app=app, base_url="http://test") as client: | |
| yield client | |
| async def auth_headers(self, async_client): | |
| """Get authentication headers""" | |
| # For testing, use mock authentication or test credentials | |
| return { | |
| "Authorization": "Bearer test_token", | |
| "X-Tenant-ID": "test-tenant-001" | |
| } | |
| async def measure_endpoint( | |
| self, | |
| client: AsyncClient, | |
| method: str, | |
| url: str, | |
| headers: Dict[str, str], | |
| json_data: Dict[str, Any] = None, | |
| iterations: int = 100 | |
| ) -> PerformanceMetrics: | |
| """Measure endpoint latency over multiple iterations""" | |
| latencies = [] | |
| for _ in range(iterations): | |
| start = time.time() | |
| try: | |
| if method == "GET": | |
| response = await client.get(url, headers=headers) | |
| elif method == "POST": | |
| response = await client.post(url, json=json_data or {}, headers=headers) | |
| elif method == "PUT": | |
| response = await client.put(url, json=json_data or {}, headers=headers) | |
| elif method == "DELETE": | |
| response = await client.delete(url, headers=headers) | |
| latency_ms = (time.time() - start) * 1000 | |
| latencies.append(latency_ms) | |
| # Verify response is valid | |
| assert response.status_code in [200, 201, 400, 401, 403, 404] | |
| except Exception as e: | |
| print(f"Request failed: {e}") | |
| continue | |
| return PerformanceMetrics(latencies) | |
| async def test_health_endpoint_latency(self, async_client): | |
| """ | |
| Test health check endpoint latency | |
| Target: <50ms p95 (should be extremely fast) | |
| """ | |
| metrics = await self.measure_endpoint( | |
| async_client, | |
| "GET", | |
| "/health", | |
| {}, | |
| iterations=100 | |
| ) | |
| metrics.print_report("Health Endpoint") | |
| # Health check should be very fast | |
| assert metrics.p95 < 50, f"Health check P95 {metrics.p95:.2f}ms exceeds 50ms" | |
| async def test_api_root_latency(self, async_client): | |
| """Test API root endpoint latency""" | |
| metrics = await self.measure_endpoint( | |
| async_client, | |
| "GET", | |
| "/api/v1/", | |
| {}, | |
| iterations=100 | |
| ) | |
| metrics.print_report("API Root") | |
| assert metrics.p95 < 100 | |
| async def test_patient_list_latency(self, async_client, auth_headers): | |
| """ | |
| Test patient list endpoint latency | |
| Target: <200ms p95 (SLA requirement) | |
| """ | |
| metrics = await self.measure_endpoint( | |
| async_client, | |
| "GET", | |
| "/api/v1/clinica/patients?page=1&per_page=20", | |
| auth_headers, | |
| iterations=50 | |
| ) | |
| metrics.print_report("Patient List") | |
| assert metrics.p95 < 200, f"Patient list P95 {metrics.p95:.2f}ms exceeds SLA" | |
| async def test_concurrent_requests(self, async_client, auth_headers): | |
| """ | |
| Test API performance under concurrent load | |
| Simulates multiple users accessing the API simultaneously | |
| """ | |
| async def make_request(): | |
| start = time.time() | |
| try: | |
| response = await async_client.get( | |
| "/api/v1/clinica/patients", | |
| headers=auth_headers | |
| ) | |
| return (time.time() - start) * 1000 | |
| except Exception: | |
| return None | |
| # Simulate 50 concurrent users | |
| tasks = [make_request() for _ in range(50)] | |
| latencies = await asyncio.gather(*tasks) | |
| # Filter out failed requests | |
| valid_latencies = [lat for lat in latencies if lat is not None] | |
| if valid_latencies: | |
| metrics = PerformanceMetrics(valid_latencies) | |
| metrics.print_report("Concurrent Requests (50 users)") | |
| # Under load, p95 should still meet SLA | |
| assert metrics.p95 < 500, f"Concurrent P95 {metrics.p95:.2f}ms exceeds 500ms" | |
| class TestDatabasePerformance: | |
| """Test database query performance""" | |
| async def test_simple_query_performance(self, db_session): | |
| """Test simple SELECT query performance""" | |
| latencies = [] | |
| for _ in range(50): | |
| start = time.time() | |
| try: | |
| # Simple query test | |
| result = await db_session.execute("SELECT 1") | |
| latency_ms = (time.time() - start) * 1000 | |
| latencies.append(latency_ms) | |
| except Exception as e: | |
| print(f"Query failed: {e}") | |
| continue | |
| if latencies: | |
| metrics = PerformanceMetrics(latencies) | |
| metrics.print_report("Simple Database Query") | |
| # Database queries should be fast | |
| assert metrics.p95 < 50, f"DB query P95 {metrics.p95:.2f}ms exceeds 50ms" | |
| class TestCachePerformance: | |
| """Test Redis cache performance""" | |
| def test_cache_hit_rate(self, redis_client): | |
| """ | |
| Test cache hit rate meets target (>80%) | |
| Target: 80%+ cache hit rate for optimal performance | |
| """ | |
| # TODO: Implement cache hit rate measurement | |
| # This requires access to Redis INFO stats | |
| pass | |
| def test_cache_latency(self, redis_client): | |
| """Test Redis cache operation latency""" | |
| latencies = [] | |
| for i in range(100): | |
| start = time.time() | |
| try: | |
| # Test cache set operation | |
| redis_client.set(f"test_key_{i}", f"test_value_{i}") | |
| # Test cache get operation | |
| redis_client.get(f"test_key_{i}") | |
| latency_ms = (time.time() - start) * 1000 | |
| latencies.append(latency_ms) | |
| except Exception as e: | |
| print(f"Cache operation failed: {e}") | |
| continue | |
| if latencies: | |
| metrics = PerformanceMetrics(latencies) | |
| metrics.print_report("Redis Cache Operations") | |
| # Cache operations should be very fast | |
| assert metrics.p95 < 10, f"Cache P95 {metrics.p95:.2f}ms exceeds 10ms" | |
| class TestLoadScenarios: | |
| """Test realistic load scenarios""" | |
| async def test_patient_creation_workflow(self, async_client, auth_headers): | |
| """ | |
| Test complete patient creation workflow | |
| Workflow: Create patient → Add vitals → Add diagnosis | |
| Target: <500ms end-to-end | |
| """ | |
| latencies = [] | |
| for i in range(20): | |
| start = time.time() | |
| try: | |
| # Step 1: Create patient | |
| patient_response = await async_client.post( | |
| "/api/v1/clinica/patients", | |
| json={ | |
| "first_name": f"Patient{i}", | |
| "last_name": "Test", | |
| "mrn": f"MRN-{i}" | |
| }, | |
| headers=auth_headers | |
| ) | |
| if patient_response.status_code == 201: | |
| patient_id = patient_response.json()["data"]["id"] | |
| # Step 2: Add vitals (if endpoint exists) | |
| # Step 3: Add diagnosis (if endpoint exists) | |
| latency_ms = (time.time() - start) * 1000 | |
| latencies.append(latency_ms) | |
| except Exception as e: | |
| print(f"Workflow failed: {e}") | |
| continue | |
| if latencies: | |
| metrics = PerformanceMetrics(latencies) | |
| metrics.print_report("Patient Creation Workflow") | |
| # End-to-end workflow target | |
| assert metrics.p95 < 500, \ | |
| f"Workflow P95 {metrics.p95:.2f}ms exceeds 500ms target" | |
| if __name__ == "__main__": | |
| pytest.main([__file__, "-v", "--tb=short"]) | |