""" Tests for API endpoint validation and error handling. Tests the comprehensive validation and error handling in FastAPI endpoints. """ import pytest import json import tempfile import os from unittest.mock import Mock, AsyncMock, patch from fastapi.testclient import TestClient from fastapi import HTTPException from uuid import uuid4 # Import the FastAPI app and dependencies from orchestrator.main import app, get_current_user from shared.models import UserContext, AnalysisSession, AnalysisStatus from shared.error_handling import ValidationError, ApplicationError, ErrorCategory, ErrorSeverity class TestAPIValidation: """Test API endpoint validation.""" @pytest.fixture def client(self): """Create test client.""" return TestClient(app) @pytest.fixture def mock_user_context(self): """Mock user context.""" return UserContext( user_id="test_user_123", email="test@example.com", roles=["user"] ) @pytest.fixture def valid_auth_header(self): """Valid authorization header.""" return {"Authorization": "Bearer valid_jwt_token_here"} def test_health_endpoint(self, client): """Test health check endpoint.""" response = client.get("/health") assert response.status_code == 200 data = response.json() assert data["status"] == "healthy" assert "timestamp" in data assert "version" in data @patch('orchestrator.main.get_current_user') def test_detailed_health_with_auth(self, mock_get_user, client, mock_user_context): """Test detailed health check with authentication.""" mock_get_user.return_value = mock_user_context response = client.get( "/health/detailed", headers={"Authorization": "Bearer valid_token"} ) assert response.status_code == 200 def test_detailed_health_without_auth(self, client): """Test detailed health check without authentication.""" response = client.get("/health/detailed") assert response.status_code == 401 def test_invalid_auth_header_format(self, client): """Test invalid authorization header format.""" # Missing Bearer prefix response = client.get( "/health/detailed", headers={"Authorization": "invalid_token"} ) assert response.status_code == 401 error_data = response.json() assert "error" in error_data assert "message" in error_data assert "suggestions" in error_data def test_empty_auth_token(self, client): """Test empty authorization token.""" response = client.get( "/health/detailed", headers={"Authorization": "Bearer "} ) assert response.status_code == 401 def test_malformed_auth_header(self, client): """Test malformed authorization header.""" response = client.get( "/health/detailed", headers={"Authorization": "Bearer token with spaces"} ) assert response.status_code == 401 def test_suspicious_auth_token(self, client): """Test authorization token with suspicious characters.""" response = client.get( "/health/detailed", headers={"Authorization": "Bearer "} ) assert response.status_code == 401 class TestAnalysisStartEndpoint: """Test analysis start endpoint validation.""" @pytest.fixture def client(self): return TestClient(app) @pytest.fixture def mock_user_context(self): return UserContext( user_id="test_user_123", email="test@example.com", roles=["user"] ) @pytest.fixture def valid_csv_content(self): """Valid CSV file content.""" return b"name,age,salary\nJohn,25,50000\nJane,30,60000\nBob,35,70000" @pytest.fixture def valid_business_context(self): """Valid business context.""" return "Analyze employee salary data to identify compensation trends and potential pay equity issues across different age groups and departments." @patch('orchestrator.main.get_current_user') @patch('orchestrator.main.analysis_orchestrator.start_analysis') @patch('orchestrator.main.session_manager.get_user_active_sessions_count') def test_start_analysis_valid_input( self, mock_session_count, mock_start_analysis, mock_get_user, client, mock_user_context, valid_csv_content, valid_business_context ): """Test analysis start with valid input.""" mock_get_user.return_value = mock_user_context mock_session_count.return_value = 0 mock_start_analysis.return_value = AnalysisSession( id=uuid4(), user_id=mock_user_context.user_id, name="Test Analysis", business_context=valid_business_context, status=AnalysisStatus.PENDING ) # Create temporary file with tempfile.NamedTemporaryFile(suffix='.csv', delete=False) as temp_file: temp_file.write(valid_csv_content) temp_file.flush() try: with open(temp_file.name, 'rb') as f: response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={ "business_context": valid_business_context, "analysis_name": "Test Analysis" }, files={"file": ("test_data.csv", f, "text/csv")} ) assert response.status_code == 200 data = response.json() assert "id" in data assert data["name"] == "Test Analysis" finally: os.unlink(temp_file.name) @patch('orchestrator.main.get_current_user') def test_start_analysis_no_file(self, mock_get_user, client, mock_user_context, valid_business_context): """Test analysis start without file.""" mock_get_user.return_value = mock_user_context response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={"business_context": valid_business_context} ) assert response.status_code == 422 # FastAPI validation error @patch('orchestrator.main.get_current_user') def test_start_analysis_empty_file(self, mock_get_user, client, mock_user_context, valid_business_context): """Test analysis start with empty file.""" mock_get_user.return_value = mock_user_context # Create empty temporary file with tempfile.NamedTemporaryFile(suffix='.csv', delete=False) as temp_file: temp_file.flush() try: with open(temp_file.name, 'rb') as f: response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={"business_context": valid_business_context}, files={"file": ("empty.csv", f, "text/csv")} ) assert response.status_code == 400 error_data = response.json() assert "error" in error_data assert "empty" in error_data["message"].lower() finally: os.unlink(temp_file.name) @patch('orchestrator.main.get_current_user') def test_start_analysis_invalid_file_type(self, mock_get_user, client, mock_user_context, valid_business_context): """Test analysis start with invalid file type.""" mock_get_user.return_value = mock_user_context # Create temporary text file with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as temp_file: temp_file.write(b"This is not a valid data file") temp_file.flush() try: with open(temp_file.name, 'rb') as f: response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={"business_context": valid_business_context}, files={"file": ("invalid.txt", f, "text/plain")} ) assert response.status_code == 400 error_data = response.json() assert "error" in error_data assert "file type" in error_data["message"].lower() or "format" in error_data["message"].lower() finally: os.unlink(temp_file.name) @patch('orchestrator.main.get_current_user') def test_start_analysis_large_file(self, mock_get_user, client, mock_user_context, valid_business_context): """Test analysis start with file too large.""" mock_get_user.return_value = mock_user_context # Create large temporary file (simulate > 100MB) large_content = b"x" * (101 * 1024 * 1024) # 101MB with tempfile.NamedTemporaryFile(suffix='.csv', delete=False) as temp_file: # Don't actually write the large content to avoid disk space issues # Just test the validation logic temp_file.write(b"name,age\nJohn,25") temp_file.flush() try: # Mock the file size check with patch('orchestrator.main.file.read', return_value=large_content): with open(temp_file.name, 'rb') as f: response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={"business_context": valid_business_context}, files={"file": ("large.csv", f, "text/csv")} ) assert response.status_code == 400 error_data = response.json() assert "error" in error_data finally: os.unlink(temp_file.name) @patch('orchestrator.main.get_current_user') def test_start_analysis_invalid_business_context(self, mock_get_user, client, mock_user_context, valid_csv_content): """Test analysis start with invalid business context.""" mock_get_user.return_value = mock_user_context # Test with XSS attempt in business context malicious_context = "" with tempfile.NamedTemporaryFile(suffix='.csv', delete=False) as temp_file: temp_file.write(valid_csv_content) temp_file.flush() try: with open(temp_file.name, 'rb') as f: response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={"business_context": malicious_context}, files={"file": ("test.csv", f, "text/csv")} ) assert response.status_code == 400 error_data = response.json() assert "error" in error_data finally: os.unlink(temp_file.name) @patch('orchestrator.main.get_current_user') def test_start_analysis_short_business_context(self, mock_get_user, client, mock_user_context, valid_csv_content): """Test analysis start with too short business context.""" mock_get_user.return_value = mock_user_context short_context = "Short" # Too short with tempfile.NamedTemporaryFile(suffix='.csv', delete=False) as temp_file: temp_file.write(valid_csv_content) temp_file.flush() try: with open(temp_file.name, 'rb') as f: response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={"business_context": short_context}, files={"file": ("test.csv", f, "text/csv")} ) assert response.status_code == 400 error_data = response.json() assert "error" in error_data finally: os.unlink(temp_file.name) @patch('orchestrator.main.get_current_user') def test_start_analysis_invalid_parameters_json(self, mock_get_user, client, mock_user_context, valid_csv_content, valid_business_context): """Test analysis start with invalid parameters JSON.""" mock_get_user.return_value = mock_user_context invalid_json = '{"invalid": json,}' # Invalid JSON syntax with tempfile.NamedTemporaryFile(suffix='.csv', delete=False) as temp_file: temp_file.write(valid_csv_content) temp_file.flush() try: with open(temp_file.name, 'rb') as f: response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={ "business_context": valid_business_context, "parameters": invalid_json }, files={"file": ("test.csv", f, "text/csv")} ) assert response.status_code == 400 error_data = response.json() assert "error" in error_data assert "json" in error_data["message"].lower() assert "suggestions" in error_data finally: os.unlink(temp_file.name) @patch('orchestrator.main.get_current_user') def test_start_analysis_path_traversal_filename(self, mock_get_user, client, mock_user_context, valid_csv_content, valid_business_context): """Test analysis start with path traversal in filename.""" mock_get_user.return_value = mock_user_context with tempfile.NamedTemporaryFile(suffix='.csv', delete=False) as temp_file: temp_file.write(valid_csv_content) temp_file.flush() try: with open(temp_file.name, 'rb') as f: response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={"business_context": valid_business_context}, files={"file": ("../../../etc/passwd.csv", f, "text/csv")} ) # Should succeed but filename should be sanitized # The actual validation happens in the endpoint logic assert response.status_code in [200, 400] # Depends on implementation finally: os.unlink(temp_file.name) @patch('orchestrator.main.get_current_user') @patch('orchestrator.main.session_manager.get_user_active_sessions_count') def test_start_analysis_rate_limiting(self, mock_session_count, mock_get_user, client, mock_user_context, valid_csv_content, valid_business_context): """Test analysis start with rate limiting.""" mock_get_user.return_value = mock_user_context mock_session_count.return_value = 10 # Exceed limit with tempfile.NamedTemporaryFile(suffix='.csv', delete=False) as temp_file: temp_file.write(valid_csv_content) temp_file.flush() try: with open(temp_file.name, 'rb') as f: response = client.post( "/analysis/start", headers={"Authorization": "Bearer valid_token"}, data={"business_context": valid_business_context}, files={"file": ("test.csv", f, "text/csv")} ) assert response.status_code == 400 error_data = response.json() assert "concurrent" in error_data["message"].lower() or "limit" in error_data["message"].lower() finally: os.unlink(temp_file.name) class TestAnalysisStatusEndpoint: """Test analysis status endpoint validation.""" @pytest.fixture def client(self): return TestClient(app) @pytest.fixture def mock_user_context(self): return UserContext( user_id="test_user_123", email="test@example.com", roles=["user"] ) @patch('orchestrator.main.get_current_user') @patch('orchestrator.main.session_manager.get_session') def test_get_analysis_status_valid_uuid(self, mock_get_session, mock_get_user, client, mock_user_context): """Test get analysis status with valid UUID.""" mock_get_user.return_value = mock_user_context session_id = str(uuid4()) mock_session = AnalysisSession( id=session_id, user_id=mock_user_context.user_id, name="Test Analysis", business_context="Test context", status=AnalysisStatus.RUNNING ) mock_get_session.return_value = mock_session response = client.get( f"/analysis/{session_id}/status", headers={"Authorization": "Bearer valid_token"} ) assert response.status_code == 200 data = response.json() assert data["id"] == session_id assert data["status"] == "running" @patch('orchestrator.main.get_current_user') def test_get_analysis_status_invalid_uuid(self, mock_get_user, client, mock_user_context): """Test get analysis status with invalid UUID.""" mock_get_user.return_value = mock_user_context response = client.get( "/analysis/invalid-uuid/status", headers={"Authorization": "Bearer valid_token"} ) assert response.status_code == 400 error_data = response.json() assert "error" in error_data assert "uuid" in error_data["message"].lower() or "invalid" in error_data["message"].lower() @patch('orchestrator.main.get_current_user') @patch('orchestrator.main.session_manager.get_session') def test_get_analysis_status_not_found(self, mock_get_session, mock_get_user, client, mock_user_context): """Test get analysis status for non-existent session.""" mock_get_user.return_value = mock_user_context mock_get_session.return_value = None session_id = str(uuid4()) response = client.get( f"/analysis/{session_id}/status", headers={"Authorization": "Bearer valid_token"} ) assert response.status_code == 404 error_data = response.json() assert "error" in error_data assert "not found" in error_data["message"].lower() class TestErrorResponseFormat: """Test error response format consistency.""" @pytest.fixture def client(self): return TestClient(app) def test_validation_error_format(self, client): """Test validation error response format.""" response = client.get("/health/detailed") # No auth assert response.status_code == 401 error_data = response.json() # Check required fields assert "error" in error_data assert "message" in error_data # Check optional fields if "suggestions" in error_data: assert isinstance(error_data["suggestions"], list) if "error_id" in error_data: assert isinstance(error_data["error_id"], str) def test_application_error_format(self, client): """Test application error response format.""" # This would test internal server errors # Implementation depends on how errors are structured pass def test_error_message_user_friendly(self, client): """Test that error messages are user-friendly.""" response = client.get( "/health/detailed", headers={"Authorization": "invalid"} ) assert response.status_code == 401 error_data = response.json() # Error message should be user-friendly, not technical message = error_data.get("message", "") assert len(message) > 0 assert not any(tech_term in message.lower() for tech_term in [ "traceback", "exception", "stack", "null pointer" ]) if __name__ == "__main__": pytest.main([__file__, "-v"])