"""
Integration tests for error handling across the entire system.
Tests error handling in real scenarios with MCP servers, database, and API endpoints.
"""
import pytest
import asyncio
import tempfile
import os
import json
from unittest.mock import Mock, AsyncMock, patch
from uuid import uuid4
from shared.error_handling import (
error_handler, ErrorContext, ApplicationError, ValidationError,
ErrorCategory, ErrorSeverity, retry_with_backoff, RetryConfig,
degradation_handler, DataCorruptionDetector
)
from shared.validation import ValidationSchemas, validate_file_content
from shared.models import UserContext
from mcp_servers.data_cleaning.server import DataCleaningMCPServer
class TestEndToEndErrorHandling:
"""Test error handling across the entire system."""
@pytest.fixture
def user_context(self):
return UserContext(
user_id="test_user_123",
email="test@example.com",
roles=["user"]
)
@pytest.fixture
def error_context(self):
return ErrorContext(
user_id="test_user_123",
component="integration_test",
operation="test_operation"
)
@pytest.mark.asyncio
async def test_file_upload_error_cascade(self, user_context, error_context):
"""Test error handling cascade from file upload through processing."""
# Test 1: Invalid file format
with pytest.raises(ValidationError) as exc_info:
validator = ValidationSchemas.get_comprehensive_file_validator()
validation_data = {
"filename": "malicious_file.exe",
"file_size": 1024,
"mime_type": "application/octet-stream",
"business_context": "Test context for analysis"
}
validator.validate_and_raise(validation_data, error_context)
error = exc_info.value
assert error.category == ErrorCategory.VALIDATION
assert "suggestions" in error.recovery_suggestions[0].lower() or len(error.recovery_suggestions) > 0
@pytest.mark.asyncio
async def test_data_corruption_detection_integration(self):
"""Test data corruption detection in realistic scenarios."""
# Test with corrupted CSV file
corrupted_csv = b"name,age,salary\nJohn,25,\nJane,,60000\n,30,70000"
issues = validate_file_content(corrupted_csv, "corrupted.csv")
# Should detect issues but not fail completely
assert isinstance(issues, list)
# Test with completely invalid file
invalid_content = b"This is not a valid data file at all"
issues = validate_file_content(invalid_content, "invalid.csv")
assert len(issues) > 0
assert any("failed" in issue.lower() or "invalid" in issue.lower() for issue in issues)
@pytest.mark.asyncio
async def test_mcp_server_error_handling(self, user_context):
"""Test error handling in MCP server operations."""
# Create a mock MCP server
server = DataCleaningMCPServer()
# Test with invalid arguments
with pytest.raises((ValidationError, ApplicationError, ValueError)):
await server._upload_dataset(user_context, {}) # Missing required params
# Test with malicious filename
with pytest.raises((ValidationError, ApplicationError, ValueError)):
await server._upload_dataset(user_context, {
"file_content": "dGVzdA==", # base64 "test"
"filename": "../../../etc/passwd",
"file_size": 4
})
@pytest.mark.asyncio
async def test_retry_mechanism_integration(self):
"""Test retry mechanism with realistic failure scenarios."""
call_count = 0
async def flaky_database_operation():
nonlocal call_count
call_count += 1
if call_count == 1:
raise ConnectionError("Database connection lost")
elif call_count == 2:
raise TimeoutError("Database timeout")
else:
return {"success": True, "data": "retrieved"}
# Should succeed after retries
retry_config = RetryConfig(
max_attempts=5,
base_delay=0.01,
retryable_exceptions=[ConnectionError, TimeoutError]
)
result = await retry_with_backoff(
flaky_database_operation,
retry_config=retry_config
)
assert result["success"] == True
assert call_count == 3
@pytest.mark.asyncio
async def test_graceful_degradation_integration(self):
"""Test graceful degradation with component failures."""
# Register a fallback for a critical component
async def primary_analysis_function():
raise ConnectionError("Analysis service unavailable")
async def fallback_analysis_function():
return {
"status": "degraded",
"message": "Using simplified analysis due to service unavailability",
"results": {"basic_stats": {"mean": 50, "count": 100}}
}
degradation_handler.register_fallback("analysis_service", fallback_analysis_function)
# Execute with fallback
result = await degradation_handler.execute_with_fallback(
"analysis_service",
primary_analysis_function
)
assert result["status"] == "degraded"
assert "analysis_service" in degradation_handler.degraded_components
@pytest.mark.asyncio
async def test_security_validation_integration(self):
"""Test security validation across different input types."""
# Test SQL injection prevention
validator = ValidationSchemas.get_secure_input_validator()
malicious_inputs = [
"'; DROP TABLE users; --",
"",
"../../../etc/passwd",
"javascript:alert('xss')",
"UNION SELECT password FROM users"
]
for malicious_input in malicious_inputs:
errors = validator.validate({"user_input": malicious_input})
assert "user_input" in errors, f"Failed to detect malicious input: {malicious_input}"
@pytest.mark.asyncio
async def test_error_context_propagation(self, user_context):
"""Test that error context is properly propagated through the system."""
error_context = ErrorContext(
user_id=user_context.user_id,
session_id=str(uuid4()),
component="test_component",
operation="test_operation",
request_id=str(uuid4())
)
# Create an error with context
app_error = ApplicationError(
"Test error with context",
category=ErrorCategory.DATA_PROCESSING,
severity=ErrorSeverity.MEDIUM,
context=error_context,
recovery_suggestions=["Try again", "Check input data"]
)
# Handle the error
error_info = await error_handler.handle_error(app_error, error_context)
# Verify context propagation
assert error_info.context.user_id == user_context.user_id
assert error_info.context.session_id == error_context.session_id
assert error_info.context.component == "test_component"
assert error_info.context.operation == "test_operation"
assert error_info.context.request_id == error_context.request_id
assert len(error_info.recovery_suggestions) > 0
@pytest.mark.asyncio
async def test_concurrent_error_handling(self):
"""Test error handling under concurrent load."""
async def concurrent_operation(operation_id: int):
"""Simulate concurrent operations with some failures."""
if operation_id % 3 == 0: # Every 3rd operation fails
raise ValueError(f"Operation {operation_id} failed")
# Simulate some processing time
await asyncio.sleep(0.01)
return f"Operation {operation_id} succeeded"
# Run multiple concurrent operations
tasks = []
for i in range(20):
error_context = ErrorContext(
user_id=f"user_{i % 5}", # 5 different users
component="concurrent_test",
operation=f"operation_{i}"
)
async def wrapped_operation(op_id=i, ctx=error_context):
try:
return await concurrent_operation(op_id)
except Exception as e:
await error_handler.handle_error(e, ctx)
return f"Operation {op_id} handled error"
tasks.append(wrapped_operation())
# Wait for all operations to complete
results = await asyncio.gather(*tasks, return_exceptions=True)
# Verify all operations completed (either succeeded or handled errors)
assert len(results) == 20
assert all(isinstance(result, str) for result in results)
# Check error statistics
stats = error_handler.get_error_statistics()
assert stats["total_errors"] > 0 # Some operations should have failed
@pytest.mark.asyncio
async def test_file_processing_error_recovery(self):
"""Test error recovery in file processing scenarios."""
# Test with various problematic files
test_cases = [
{
"name": "empty_file.csv",
"content": b"",
"expected_issues": ["empty"]
},
{
"name": "malformed.csv",
"content": b"name,age\nJohn,25,extra_column\nJane",
"expected_issues": ["parsing", "format"]
},
{
"name": "encoding_issue.csv",
"content": "name,age\nJöhn,25\nJané,30".encode('latin1'),
"expected_issues": [] # Should handle encoding gracefully
}
]
for test_case in test_cases:
issues = validate_file_content(test_case["content"], test_case["name"])
# Should detect issues but provide recovery suggestions
if test_case["expected_issues"]:
assert len(issues) > 0
# Check if any expected issue keywords are found
issues_text = " ".join(issues).lower()
assert any(keyword in issues_text for keyword in test_case["expected_issues"])
@pytest.mark.asyncio
async def test_database_error_simulation(self):
"""Test database error handling and recovery."""
# Simulate database connection issues
async def simulate_db_operation():
# Simulate different types of database errors
import random
error_type = random.choice([
ConnectionError("Database connection lost"),
TimeoutError("Database query timeout"),
ValueError("Invalid query parameters"),
Exception("Unknown database error")
])
raise error_type
# Test with different retry configurations
retry_configs = [
RetryConfig(max_attempts=3, base_delay=0.01, retryable_exceptions=[ConnectionError]),
RetryConfig(max_attempts=2, base_delay=0.01, retryable_exceptions=[TimeoutError]),
RetryConfig(max_attempts=1, base_delay=0.01, retryable_exceptions=[]) # No retries
]
for config in retry_configs:
try:
await retry_with_backoff(
simulate_db_operation,
retry_config=config
)
assert False, "Should have raised an exception"
except Exception as e:
# Should either be the original exception or ApplicationError from retry failure
assert isinstance(e, (ConnectionError, TimeoutError, ValueError, Exception, ApplicationError))
@pytest.mark.asyncio
async def test_system_health_monitoring(self):
"""Test system health monitoring and degradation detection."""
# Simulate component failures
components = ["mcp_server_1", "mcp_server_2", "database", "external_api"]
for component in components:
# Register components as healthy initially
degradation_handler.component_health[component] = True
# Simulate some failures
degradation_handler.mark_component_degraded("mcp_server_1", "Connection timeout")
degradation_handler.mark_component_degraded("external_api", "Service unavailable")
# Check system health
health_status = degradation_handler.get_system_health_status()
assert health_status["overall_health"] == "degraded"
assert health_status["healthy_components"] == 2
assert health_status["total_components"] == 4
assert health_status["health_percentage"] == 50.0
assert "mcp_server_1" in health_status["degraded_components"]
assert "external_api" in health_status["degraded_components"]
@pytest.mark.asyncio
async def test_error_logging_and_metrics(self):
"""Test error logging and metrics collection."""
# Create various types of errors
errors = [
ValidationError("Invalid input", category=ErrorCategory.VALIDATION),
ApplicationError("Service unavailable", category=ErrorCategory.MCP_SERVER, severity=ErrorSeverity.HIGH),
ApplicationError("Database error", category=ErrorCategory.DATABASE, severity=ErrorSeverity.CRITICAL)
]
# Handle each error
for error in errors:
error_context = ErrorContext(
user_id="test_user",
component="test_component",
operation="test_operation"
)
await error_handler.handle_error(error, error_context)
# Check error statistics
stats = error_handler.get_error_statistics()
assert stats["total_errors"] >= len(errors)
assert "category_breakdown" in stats
assert "severity_breakdown" in stats
# Verify different categories are tracked
category_breakdown = stats["category_breakdown"]
assert category_breakdown.get("validation", 0) >= 1
assert category_breakdown.get("mcp_server", 0) >= 1
assert category_breakdown.get("database", 0) >= 1
class TestRealWorldScenarios:
"""Test error handling in real-world scenarios."""
@pytest.mark.asyncio
async def test_large_file_processing_errors(self):
"""Test error handling with large file processing."""
# Simulate large file content validation
large_csv_header = "name,age,salary,department,location,start_date,performance_score"
large_csv_rows = []
# Generate a moderately large dataset
for i in range(1000):
row = f"User{i},25,50000,Engineering,New York,2023-01-01,85.5"
large_csv_rows.append(row)
large_csv_content = (large_csv_header + "\n" + "\n".join(large_csv_rows)).encode('utf-8')
# Test file content validation
issues = validate_file_content(large_csv_content, "large_dataset.csv")
# Should handle large files gracefully
assert isinstance(issues, list)
# May have warnings about size but shouldn't fail completely
@pytest.mark.asyncio
async def test_malformed_data_recovery(self):
"""Test recovery from malformed data scenarios."""
malformed_scenarios = [
{
"name": "mixed_delimiters.csv",
"content": b"name,age;salary\nJohn,25;50000\nJane;30,60000",
"description": "Mixed delimiters"
},
{
"name": "inconsistent_columns.csv",
"content": b"name,age,salary\nJohn,25\nJane,30,60000,extra",
"description": "Inconsistent column count"
},
{
"name": "special_characters.csv",
"content": "name,age,salary\nJöhn Döe,25,50000\nJané Smith,30,60000".encode('utf-8'),
"description": "Special characters"
}
]
for scenario in malformed_scenarios:
issues = validate_file_content(scenario["content"], scenario["name"])
# Should detect issues but provide actionable feedback
if issues:
# Verify issues are descriptive
issues_text = " ".join(issues)
assert len(issues_text) > 0
# Should not contain technical jargon
assert not any(tech_term in issues_text.lower() for tech_term in [
"traceback", "exception", "null pointer", "segfault"
])
@pytest.mark.asyncio
async def test_network_failure_simulation(self):
"""Test handling of network failures in external service calls."""
async def simulate_external_api_call():
"""Simulate external API call that may fail."""
import random
failure_types = [
ConnectionError("Network unreachable"),
TimeoutError("Request timeout"),
Exception("Service temporarily unavailable"),
ValueError("Invalid API response")
]
if random.random() < 0.7: # 70% failure rate
raise random.choice(failure_types)
return {"status": "success", "data": "api_response"}
# Test with network retry configuration
retry_config = RetryConfig(
max_attempts=5,
base_delay=0.01,
max_delay=0.1,
exponential_base=2.0,
jitter=True,
retryable_exceptions=[ConnectionError, TimeoutError]
)
success_count = 0
total_attempts = 10
for _ in range(total_attempts):
try:
result = await retry_with_backoff(
simulate_external_api_call,
retry_config=retry_config
)
if result["status"] == "success":
success_count += 1
except Exception:
# Some calls may still fail after all retries
pass
# Should have some successes due to retry mechanism
# (exact number depends on randomness, but should be > 0)
assert success_count >= 0 # At least some attempts should work with retries
@pytest.mark.asyncio
async def test_user_input_sanitization_comprehensive(self):
"""Test comprehensive user input sanitization."""
dangerous_inputs = [
# SQL Injection attempts
"'; DROP TABLE users; --",
"1' OR '1'='1",
"UNION SELECT * FROM passwords",
# XSS attempts
"",
"javascript:alert('xss')",
"
",
# Path traversal attempts
"../../../etc/passwd",
"..\\..\\windows\\system32\\config\\sam",
"%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd",
# Command injection attempts
"; rm -rf /",
"| cat /etc/passwd",
"&& format c:",
# LDAP injection
"admin)(&(password=*))",
"*)(uid=*",
# XML/XXE attempts
"]>&test;",
]
validator = ValidationSchemas.get_secure_input_validator()
for dangerous_input in dangerous_inputs:
errors = validator.validate({"user_input": dangerous_input})
# Should detect and reject dangerous input
assert "user_input" in errors, f"Failed to detect dangerous input: {dangerous_input[:50]}..."
# Error messages should be user-friendly
error_messages = " ".join(errors["user_input"])
assert len(error_messages) > 0
assert not any(tech_term in error_messages.lower() for tech_term in [
"regex", "pattern", "injection", "xss" # Don't expose technical details
])
if __name__ == "__main__":
pytest.main([__file__, "-v"])