""" Test suite for YAZ Care Platform Core functionality and API endpoint tests """ import pytest from fastapi.testclient import TestClient from datetime import datetime import sys import os # Add src directory to path sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src')) from factory import create_app from apps.shared.engines import impact_toolkit, study_protocol_engine, data_processor from studies.oujda_2025_gastric_adk_ci import Oujda2025Protocol # Fixtures @pytest.fixture def client(): """Create test client.""" app = create_app() return TestClient(app) @pytest.fixture def sample_patient_data(): """Sample patient data for testing.""" return { "age": 62, "gender": "M", "ecog_ps": 1, "clinical_stage": "T3N1M0", "histology": "adenocarcinoma", "bmi": 24.5 } @pytest.fixture def sample_surgical_procedure(): """Sample surgical procedure data.""" return { "patient_id": 1, "procedure_name": "Laparoscopic Gastrectomy", "procedure_code": "43644", "planned_date": datetime.now().isoformat(), "surgeon_id": 1, "procedure_type": "gastric", "estimated_duration": 180 } # API Tests class TestCoreAPI: """Test core API endpoints.""" def test_health_check(self, client): """Test health check endpoint.""" response = client.get("/health") print(f"Response status: {response.status_code}") print(f"Response content: {response.text}") assert response.status_code == 200 data = response.json() assert data["status"] == "healthy" assert data["service"] == "YAZ Care Platform" def test_validation_run(self, client): """Test validation engine endpoint.""" request_data = { "cohort": "test_cohort", "protocols": ["oujda-2025"], "optimization_level": 80, "background_processing": False } response = client.post("/core/api/validation/run", json=request_data) assert response.status_code == 200 result = response.json() assert "snapshot_id" in result assert result["cohort"] == "test_cohort" assert "baseline" in result assert "optimized" in result def test_oujda_2025_protocol(self, client): """Test Oujda-2025 protocol endpoint.""" response = client.get("/core/api/studies/oujda-2025/protocol") assert response.status_code == 200 protocol = response.json() assert protocol["protocol_id"] == "OUJDA-2025-GAC-CI" assert protocol["version"] == "2.1" assert "treatment_arms" in protocol assert "inclusion_criteria" in protocol def test_oujda_2025_patient_validation(self, client, sample_patient_data): """Test Oujda-2025 patient validation.""" response = client.post("/core/api/studies/oujda-2025/validate-patient", json=sample_patient_data) assert response.status_code == 200 result = response.json() assert "eligible" in result assert "violations" in result assert result["protocol_id"] == "OUJDA-2025-GAC-CI" class TestSurgioAPI: """Test Surgio API endpoints.""" def test_surgio_info(self, client): """Test Surgio application info.""" response = client.get("/api/v1/surgio/") assert response.status_code == 200 info = response.json() assert info["application"] == "Surgio" assert "features" in info def test_get_procedures(self, client): """Test get procedures endpoint.""" response = client.get("/api/v1/surgio/procedures/") assert response.status_code == 200 procedures = response.json() assert isinstance(procedures, list) def test_create_procedure(self, client, sample_surgical_procedure): """Test create procedure endpoint.""" response = client.post("/api/v1/surgio/procedures/", json=sample_surgical_procedure) assert response.status_code == 200 procedure = response.json() assert procedure["procedure_name"] == sample_surgical_procedure["procedure_name"] assert "id" in procedure def test_study_protocols(self, client): """Test study protocols endpoint.""" response = client.get("/api/v1/surgio/studies/protocols/") assert response.status_code == 200 protocols = response.json() assert isinstance(protocols, list) assert len(protocols) > 0 assert protocols[0]["protocol_name"] == "Oujda-2025 Gastric Adenocarcinoma Study" def test_oujda_2025_dashboard(self, client): """Test Oujda-2025 dashboard endpoint.""" response = client.get("/api/v1/surgio/studies/oujda-2025/dashboard/") assert response.status_code == 200 dashboard = response.json() assert "study_info" in dashboard assert "enrollment" in dashboard assert "outcomes" in dashboard assert dashboard["study_info"]["name"] == "Oujda-2025 Gastric Adenocarcinoma Comparative Study" # Engine Tests class TestEngines: """Test shared engines functionality.""" def test_impact_toolkit_validation(self, sample_surgical_procedure): """Test Impact Toolkit validation engine.""" result = impact_toolkit.validate_data(sample_surgical_procedure, "surgical_procedure") assert hasattr(result, 'is_valid') assert hasattr(result, 'errors') assert hasattr(result, 'warnings') assert hasattr(result, 'validated_at') def test_impact_toolkit_export(self): """Test Impact Toolkit export functionality.""" test_data = [{"id": 1, "name": "test"}, {"id": 2, "name": "test2"}] result = impact_toolkit.export_data(test_data, "json") assert "export_id" in result assert result["records_count"] == 2 assert "exported_at" in result def test_study_protocol_registration(self): """Test study protocol engine registration.""" protocol_config = { "name": "Test Protocol", "version": "1.0", "inclusion_criteria": ["Age >= 18"], "exclusion_criteria": ["Pregnancy"] } success = study_protocol_engine.register_protocol("TEST-001", protocol_config) assert success == True assert "TEST-001" in study_protocol_engine.active_protocols def test_data_processor_anonymization(self): """Test data processing engine anonymization.""" test_data = [ {"name": "John Doe", "email": "john@example.com", "age": 30}, {"name": "Jane Smith", "email": "jane@example.com", "age": 25} ] config = {"fields": ["name", "email"]} result = data_processor.process(test_data, "anonymize", config) assert result["operation"] == "anonymize" assert result["input_records"] == 2 assert len(result["result"]) == 2 # Check that sensitive fields are hashed for record in result["result"]: assert len(record["name"]) == 8 # Hash length assert len(record["email"]) == 8 assert record["age"] in [30, 25] # Age should not be anonymized class TestOujda2025Protocol: """Test Oujda-2025 study protocol.""" def test_protocol_constants(self): """Test protocol constants.""" assert Oujda2025Protocol.PROTOCOL_ID == "OUJDA-2025-GAC-CI" assert Oujda2025Protocol.PROTOCOL_VERSION == "2.1" assert Oujda2025Protocol.STUDY_PHASE == "Phase III" def test_eligibility_validation_eligible_patient(self, sample_patient_data): """Test eligibility validation for eligible patient.""" result = Oujda2025Protocol.validate_eligibility(sample_patient_data) assert "eligible" in result assert "violations" in result assert result["protocol_id"] == "OUJDA-2025-GAC-CI" # Patient should be eligible (age 62, ECOG 1, T3N1M0) assert result["eligible"] == True def test_eligibility_validation_ineligible_age(self): """Test eligibility validation for patient with ineligible age.""" patient_data = { "age": 80, # Too old "ecog_ps": 1, "clinical_stage": "T3N1M0" } result = Oujda2025Protocol.validate_eligibility(patient_data) assert result["eligible"] == False assert any("Age" in violation for violation in result["violations"]) def test_eligibility_validation_metastatic_disease(self): """Test eligibility validation for metastatic disease.""" patient_data = { "age": 62, "ecog_ps": 1, "clinical_stage": "T3N1M1" # Metastatic } result = Oujda2025Protocol.validate_eligibility(patient_data) assert result["eligible"] == False assert any("M1" in violation for violation in result["violations"]) def test_data_mapping(self): """Test data mapping configuration.""" mapping = Oujda2025Protocol.get_data_mapping() assert "patient_demographics" in mapping assert "tumor_characteristics" in mapping assert "surgical_details" in mapping assert "pathologic_results" in mapping # Check specific field mappings assert mapping["patient_demographics"]["age"]["type"] == "integer" assert mapping["tumor_characteristics"]["primary_location"]["type"] == "categorical" # Integration Tests class TestPortalAPI: """Test portal API endpoints.""" def test_portal_status(self, client): """Test portal status endpoint.""" response = client.get("/api/v1/portal/") assert response.status_code == 200 status = response.json() assert status["platform"] == "YAZ Care Platform" assert "services" in status class TestClinicaAPI: """Test Clinica API endpoints.""" def test_clinica_info(self, client): """Test Clinica application info.""" response = client.get("/api/v1/clinica/") assert response.status_code == 200 info = response.json() assert info["application"] == "Clinica" assert "features" in info def test_get_patients(self, client): """Test get patients endpoint.""" response = client.get("/api/v1/clinica/patients/") assert response.status_code == 200 patients = response.json() assert isinstance(patients, list) def test_create_patient(self, client): """Test create patient endpoint.""" patient_data = { "mrn": "MRN123456", "first_name": "John", "last_name": "Doe", "date_of_birth": "1980-01-01", "gender": "Male", "phone": "555-123-4567", "address": {"street": "123 Test St", "city": "Test City", "state": "TS", "zip": "12345"}, "insurance": {"primary": {"plan": "Test Insurance", "id": "TEST123"}}, "emergency_contact": {"name": "Jane Doe", "phone": "555-987-6543", "relationship": "Spouse"} } response = client.post("/api/v1/clinica/patients/", json=patient_data) assert response.status_code == 200 patient = response.json() assert patient["mrn"] == "MRN123456" assert "id" in patient def test_get_appointments(self, client): """Test get appointments endpoint.""" response = client.get("/api/v1/clinica/appointments/") assert response.status_code == 200 appointments = response.json() assert isinstance(appointments, list) if __name__ == "__main__": pytest.main([__file__, "-v"])