Download tests/load_testing.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/tests/load_testing.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/tests/load_testing.py
-
curl -L -o load_testing.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/tests/load_testing.py
17.7 kB
| """ | |
| YAZ Care Platform - Load Testing with Locust | |
| Healthcare workflow simulation for performance testing | |
| """ | |
| import json | |
| import random | |
| import time | |
| from datetime import datetime, timedelta | |
| from typing import Dict, List, Any | |
| from uuid import uuid4 | |
| from locust import HttpUser, task, between, events | |
| from locust.contrib.fasthttp import FastHttpUser | |
| # ============================================ | |
| # TEST DATA GENERATORS | |
| # ============================================ | |
| class TestDataGenerator: | |
| """Generate realistic test data for healthcare workflows""" | |
| FIRST_NAMES = ["John", "Jane", "Michael", "Sarah", "David", "Emily", "Robert", "Lisa"] | |
| LAST_NAMES = ["Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller", "Davis"] | |
| PROCEDURE_TYPES = [ | |
| "appendectomy", "cholecystectomy", "hernia_repair", "knee_arthroscopy", | |
| "hip_replacement", "spinal_fusion", "cardiac_catheterization", "colonoscopy" | |
| ] | |
| PRIORITY_LEVELS = ["routine", "urgent", "emergency"] | |
| USER_ROLES = ["doctor", "nurse", "admin", "specialist"] | |
| def generate_patient() -> Dict[str, Any]: | |
| """Generate realistic patient data""" | |
| return { | |
| "first_name": random.choice(TestDataGenerator.FIRST_NAMES), | |
| "last_name": random.choice(TestDataGenerator.LAST_NAMES), | |
| "date_of_birth": (datetime.now() - timedelta(days=random.randint(7300, 29200))).isoformat(), | |
| "gender": random.choice(["male", "female"]), | |
| "email": f"{random.choice(TestDataGenerator.FIRST_NAMES).lower()}.{random.choice(TestDataGenerator.LAST_NAMES).lower()}@example.com", | |
| "phone": f"+1-555-{random.randint(1000, 9999)}", | |
| "mrn": f"MRN{random.randint(100000, 999999)}", | |
| "insurance": { | |
| "provider": random.choice(["Aetna", "Blue Cross", "Cigna", "UnitedHealth"]), | |
| "policy_number": f"POL{random.randint(100000, 999999)}" | |
| } | |
| } | |
| def generate_surgical_procedure() -> Dict[str, Any]: | |
| """Generate surgical procedure data""" | |
| return { | |
| "procedure_type": random.choice(TestDataGenerator.PROCEDURE_TYPES), | |
| "priority": random.choice(TestDataGenerator.PRIORITY_LEVELS), | |
| "scheduled_date": (datetime.now() + timedelta(days=random.randint(1, 30))).isoformat(), | |
| "estimated_duration_minutes": random.randint(30, 480), | |
| "surgeon_id": f"DOC{random.randint(1000, 9999)}", | |
| "room_id": f"OR{random.randint(1, 20)}", | |
| "notes": "Load testing procedure" | |
| } | |
| def generate_clinical_data() -> Dict[str, Any]: | |
| """Generate clinical observation data""" | |
| return { | |
| "vitals": { | |
| "temperature": round(random.uniform(36.0, 37.5), 1), | |
| "heart_rate": random.randint(60, 100), | |
| "blood_pressure_systolic": random.randint(110, 140), | |
| "blood_pressure_diastolic": random.randint(70, 90), | |
| "respiratory_rate": random.randint(12, 20), | |
| "oxygen_saturation": random.randint(95, 100) | |
| }, | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| def generate_auth_credentials() -> Dict[str, str]: | |
| """Generate authentication credentials""" | |
| return { | |
| "username": f"test_user_{random.randint(1000, 9999)}", | |
| "password": "TestPassword123!", | |
| "role": random.choice(TestDataGenerator.USER_ROLES) | |
| } | |
| # ============================================ | |
| # BASE USER CLASS | |
| # ============================================ | |
| class YAZHealthcareUser(FastHttpUser): | |
| """Base class for YAZ Care Platform load testing""" | |
| # Request timing configuration | |
| wait_time = between(1, 5) # Wait 1-5 seconds between tasks | |
| # Connection settings | |
| connection_timeout = 10.0 | |
| network_timeout = 10.0 | |
| def __init__(self, *args, **kwargs): | |
| super().__init__(*args, **kwargs) | |
| self.auth_token = None | |
| self.patient_id = None | |
| self.procedure_id = None | |
| def on_start(self): | |
| """Called when a simulated user starts""" | |
| # Authenticate | |
| self.login() | |
| # Health check | |
| self.client.get("/health", name="/health") | |
| def login(self): | |
| """Authenticate user""" | |
| credentials = TestDataGenerator.generate_auth_credentials() | |
| with self.client.post( | |
| "/api/auth/login", | |
| json=credentials, | |
| catch_response=True, | |
| name="/api/auth/login" | |
| ) as response: | |
| if response.status_code == 200: | |
| data = response.json() | |
| self.auth_token = data.get("access_token") | |
| response.success() | |
| elif response.status_code == 404: | |
| # Auth endpoint not implemented yet | |
| self.auth_token = "test_token" | |
| response.success() | |
| else: | |
| response.failure(f"Login failed: {response.status_code}") | |
| def headers(self) -> Dict[str, str]: | |
| """Get authorization headers""" | |
| return { | |
| "Authorization": f"Bearer {self.auth_token}", | |
| "Content-Type": "application/json" | |
| } | |
| # ============================================ | |
| # PATIENT MANAGEMENT USER | |
| # ============================================ | |
| class PatientManagementUser(YAZHealthcareUser): | |
| """Simulate patient management workflows""" | |
| def create_patient(self): | |
| """Create a new patient record""" | |
| patient_data = TestDataGenerator.generate_patient() | |
| with self.client.post( | |
| "/api/patients", | |
| json=patient_data, | |
| headers=self.headers, | |
| catch_response=True, | |
| name="/api/patients [POST]" | |
| ) as response: | |
| if response.status_code in [200, 201]: | |
| self.patient_id = response.json().get("id") | |
| response.success() | |
| elif response.status_code == 404: | |
| # Endpoint not implemented, mark as success for testing | |
| self.patient_id = str(uuid4()) | |
| response.success() | |
| else: | |
| response.failure(f"Create patient failed: {response.status_code}") | |
| def get_patient(self): | |
| """Retrieve patient information""" | |
| if not self.patient_id: | |
| self.patient_id = str(uuid4()) | |
| self.client.get( | |
| f"/api/patients/{self.patient_id}", | |
| headers=self.headers, | |
| name="/api/patients/{id} [GET]" | |
| ) | |
| def list_patients(self): | |
| """List patients with pagination""" | |
| params = { | |
| "skip": random.randint(0, 100), | |
| "limit": random.randint(10, 50) | |
| } | |
| self.client.get( | |
| "/api/patients", | |
| params=params, | |
| headers=self.headers, | |
| name="/api/patients [GET]" | |
| ) | |
| def update_patient(self): | |
| """Update patient information""" | |
| if not self.patient_id: | |
| self.patient_id = str(uuid4()) | |
| update_data = { | |
| "phone": f"+1-555-{random.randint(1000, 9999)}", | |
| "email": f"updated_{random.randint(1000, 9999)}@example.com" | |
| } | |
| self.client.put( | |
| f"/api/patients/{self.patient_id}", | |
| json=update_data, | |
| headers=self.headers, | |
| name="/api/patients/{id} [PUT]" | |
| ) | |
| def search_patients(self): | |
| """Search patients by criteria""" | |
| search_params = { | |
| "last_name": random.choice(TestDataGenerator.LAST_NAMES), | |
| "limit": 20 | |
| } | |
| self.client.get( | |
| "/api/patients/search", | |
| params=search_params, | |
| headers=self.headers, | |
| name="/api/patients/search [GET]" | |
| ) | |
| # ============================================ | |
| # SURGICAL WORKFLOW USER | |
| # ============================================ | |
| class SurgicalWorkflowUser(YAZHealthcareUser): | |
| """Simulate surgical management workflows (Surgio)""" | |
| def schedule_procedure(self): | |
| """Schedule a surgical procedure""" | |
| procedure_data = TestDataGenerator.generate_surgical_procedure() | |
| procedure_data["patient_id"] = self.patient_id or str(uuid4()) | |
| with self.client.post( | |
| "/apps/surgio/api/procedures", | |
| json=procedure_data, | |
| headers=self.headers, | |
| catch_response=True, | |
| name="/apps/surgio/api/procedures [POST]" | |
| ) as response: | |
| if response.status_code in [200, 201, 404]: | |
| if response.status_code != 404: | |
| self.procedure_id = response.json().get("id") | |
| else: | |
| self.procedure_id = str(uuid4()) | |
| response.success() | |
| else: | |
| response.failure(f"Schedule procedure failed: {response.status_code}") | |
| def get_or_availability(self): | |
| """Check operating room availability""" | |
| params = { | |
| "date": (datetime.now() + timedelta(days=random.randint(1, 7))).date().isoformat() | |
| } | |
| self.client.get( | |
| "/apps/surgio/api/or-availability", | |
| params=params, | |
| headers=self.headers, | |
| name="/apps/surgio/api/or-availability [GET]" | |
| ) | |
| def get_surgical_dashboard(self): | |
| """Load surgical dashboard""" | |
| self.client.get( | |
| "/apps/surgio/api/dashboard", | |
| headers=self.headers, | |
| name="/apps/surgio/api/dashboard [GET]" | |
| ) | |
| def get_procedure_details(self): | |
| """Get procedure details""" | |
| if not self.procedure_id: | |
| self.procedure_id = str(uuid4()) | |
| self.client.get( | |
| f"/apps/surgio/api/procedures/{self.procedure_id}", | |
| headers=self.headers, | |
| name="/apps/surgio/api/procedures/{id} [GET]" | |
| ) | |
| def decision_support(self): | |
| """Request TOPSIS decision support for procedure selection""" | |
| decision_data = { | |
| "patient_id": self.patient_id or str(uuid4()), | |
| "criteria": ["success_rate", "recovery_time", "cost", "risk"], | |
| "alternatives": ["laparoscopic", "open", "robotic"] | |
| } | |
| self.client.post( | |
| "/apps/surgio/api/decision-support", | |
| json=decision_data, | |
| headers=self.headers, | |
| name="/apps/surgio/api/decision-support [POST]" | |
| ) | |
| # ============================================ | |
| # CLINICAL WORKFLOW USER | |
| # ============================================ | |
| class ClinicalWorkflowUser(YAZHealthcareUser): | |
| """Simulate clinical data management workflows (Clinica)""" | |
| def record_vitals(self): | |
| """Record patient vitals""" | |
| vitals_data = TestDataGenerator.generate_clinical_data() | |
| vitals_data["patient_id"] = self.patient_id or str(uuid4()) | |
| self.client.post( | |
| "/apps/clinica/api/vitals", | |
| json=vitals_data, | |
| headers=self.headers, | |
| name="/apps/clinica/api/vitals [POST]" | |
| ) | |
| def get_patient_history(self): | |
| """Retrieve patient medical history""" | |
| if not self.patient_id: | |
| self.patient_id = str(uuid4()) | |
| self.client.get( | |
| f"/apps/clinica/api/patients/{self.patient_id}/history", | |
| headers=self.headers, | |
| name="/apps/clinica/api/patients/{id}/history [GET]" | |
| ) | |
| def clinical_dashboard(self): | |
| """Load clinical dashboard""" | |
| self.client.get( | |
| "/apps/clinica/api/dashboard", | |
| headers=self.headers, | |
| name="/apps/clinica/api/dashboard [GET]" | |
| ) | |
| def create_encounter(self): | |
| """Create clinical encounter""" | |
| encounter_data = { | |
| "patient_id": self.patient_id or str(uuid4()), | |
| "encounter_type": random.choice(["inpatient", "outpatient", "emergency"]), | |
| "chief_complaint": "Load testing encounter", | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| self.client.post( | |
| "/apps/clinica/api/encounters", | |
| json=encounter_data, | |
| headers=self.headers, | |
| name="/apps/clinica/api/encounters [POST]" | |
| ) | |
| def workflow_optimization(self): | |
| """Request workflow optimization recommendations""" | |
| self.client.get( | |
| "/apps/clinica/api/optimization", | |
| headers=self.headers, | |
| name="/apps/clinica/api/optimization [GET]" | |
| ) | |
| # ============================================ | |
| # MIXED WORKFLOW USER | |
| # ============================================ | |
| class MixedWorkflowUser(YAZHealthcareUser): | |
| """Simulate mixed healthcare workflows across applications""" | |
| def health_check(self): | |
| """Check system health""" | |
| self.client.get("/health", name="/health [GET]") | |
| def get_metrics(self): | |
| """Check Prometheus metrics""" | |
| self.client.get("/metrics", name="/metrics [GET]") | |
| def browse_applications(self): | |
| """Browse available applications""" | |
| apps = ["surgio", "clinica", "educa", "insura", "movio"] | |
| app = random.choice(apps) | |
| self.client.get( | |
| f"/apps/{app}", | |
| headers=self.headers, | |
| name="/apps/{app} [GET]" | |
| ) | |
| def api_info(self): | |
| """Get API information""" | |
| self.client.get( | |
| "/api/v1/info", | |
| headers=self.headers, | |
| name="/api/v1/info [GET]" | |
| ) | |
| def search_global(self): | |
| """Perform global search""" | |
| search_params = { | |
| "q": random.choice(["patient", "procedure", "doctor", "appointment"]), | |
| "limit": 20 | |
| } | |
| self.client.get( | |
| "/api/search", | |
| params=search_params, | |
| headers=self.headers, | |
| name="/api/search [GET]" | |
| ) | |
| # ============================================ | |
| # EVENT HANDLERS FOR METRICS | |
| # ============================================ | |
| def on_test_start(environment, **kwargs): | |
| """Called when load test starts""" | |
| print(f"\n🚀 Starting YAZ Care Platform load test at {datetime.now().isoformat()}") | |
| print(f"Target host: {environment.host}") | |
| print(f"Users: {environment.runner.target_user_count}") | |
| print("=" * 80) | |
| def on_test_stop(environment, **kwargs): | |
| """Called when load test stops""" | |
| print("\n" + "=" * 80) | |
| print(f"✅ Load test completed at {datetime.now().isoformat()}") | |
| stats = environment.stats | |
| print(f"\n📊 Summary Statistics:") | |
| print(f" Total requests: {stats.total.num_requests}") | |
| print(f" Total failures: {stats.total.num_failures}") | |
| print(f" Average response time: {stats.total.avg_response_time:.2f}ms") | |
| print(f" Requests/sec: {stats.total.total_rps:.2f}") | |
| print(f" Failure rate: {stats.total.fail_ratio * 100:.2f}%") | |
| # ============================================ | |
| # LOAD TEST SHAPES | |
| # ============================================ | |
| from locust import LoadTestShape | |
| class StepLoadShape(LoadTestShape): | |
| """Step load pattern for gradual ramp-up""" | |
| step_time = 60 # Duration of each step in seconds | |
| step_load = 50 # Users to add per step | |
| spawn_rate = 10 # Users to spawn per second | |
| time_limit = 600 # Total test duration in seconds | |
| def tick(self): | |
| run_time = self.get_run_time() | |
| if run_time > self.time_limit: | |
| return None | |
| current_step = run_time // self.step_time | |
| return (current_step + 1) * self.step_load, self.spawn_rate | |
| class SpikeLoadShape(LoadTestShape): | |
| """Spike load pattern for stress testing""" | |
| time_limit = 600 | |
| spawn_rate = 50 | |
| def tick(self): | |
| run_time = self.get_run_time() | |
| if run_time > self.time_limit: | |
| return None | |
| # Create spikes every 2 minutes | |
| if (run_time % 120) < 30: | |
| # Spike: 500 users | |
| return 500, self.spawn_rate | |
| else: | |
| # Normal: 100 users | |
| return 100, self.spawn_rate | |
| # ============================================ | |
| # COMMAND LINE EXAMPLES | |
| # ============================================ | |
| """ | |
| Run load tests: | |
| # Basic test with 100 users | |
| locust -f load_testing.py --host=http://localhost:8000 --users=100 --spawn-rate=10 --run-time=10m | |
| # Patient management only | |
| locust -f load_testing.py --host=http://localhost:8000 --users=50 --spawn-rate=5 PatientManagementUser | |
| # Surgical workflows | |
| locust -f load_testing.py --host=http://localhost:8000 --users=30 --spawn-rate=3 SurgicalWorkflowUser | |
| # Step load shape | |
| locust -f load_testing.py --host=http://localhost:8000 StepLoadShape | |
| # Headless mode with results | |
| locust -f load_testing.py --host=http://localhost:8000 --headless --users=200 --spawn-rate=20 --run-time=5m --html=results.html | |
| # Production-like load test | |
| locust -f load_testing.py --host=https://yaz.example.com --users=1000 --spawn-rate=50 --run-time=30m --html=production_test.html | |
| """ | |