Buckets:

download
raw
42.7 kB
""" Chaos Engineering Tests - Comprehensive Failure Injection Resilience testing through controlled failure injection: - Network failures (timeout, connection reset, DNS, latency) - Database failures (connection lost, lock timeout, disk full, query timeout) - External service failures (tool not found, crash, invalid output, permission) - Resource exhaustion (memory limit, CPU throttling, file descriptor limit) - Agent failures (crash recovery, message loss, state corruption) - Orchestrator failures (backend unavailable, circuit breaker, fallback) ZIEL: System Resilience unter Fehlerbedingungen! """ import asyncio import errno import os import random import resource import shutil import socket import sqlite3 import subprocess import sys import tempfile import time from concurrent.futures import ThreadPoolExecutor from io import StringIO from typing import Any, Dict, List, Optional from unittest.mock import AsyncMock, MagicMock, Mock, patch import pytest pytestmark = [ pytest.mark.chaos, pytest.mark.resilience, pytest.mark.asyncio, ] # ============================================================================= # 1. NETWORK FAILURES # ============================================================================= @pytest.mark.chaos class TestNetworkFailures: """Test system resilience to network failures""" @pytest.mark.asyncio async def test_api_timeout_handling(self): """Test API behavior under timeout conditions""" from core.cache import MemoryCache cache = MemoryCache() async def slow_operation(): await asyncio.sleep(5) # Would timeout return "result" # Test timeout handling start = time.time() try: result = await asyncio.wait_for(slow_operation(), timeout=0.1) except asyncio.TimeoutError: result = None elapsed = time.time() - start assert result is None assert elapsed < 0.5 # Should fail fast @pytest.mark.asyncio async def test_connection_reset_handling(self): """Test handling of connection reset errors""" connection_errors = [] async def simulate_connection(): try: # Simulate connection reset raise ConnectionResetError("Connection reset by peer") except ConnectionResetError as e: connection_errors.append(str(e)) return {"status": "error", "fallback": True} result = await simulate_connection() assert len(connection_errors) == 1 assert result["fallback"] is True @pytest.mark.asyncio async def test_dns_resolution_failure(self): """Test handling of DNS resolution failures""" # Simulate DNS failure original_getaddrinfo = socket.getaddrinfo def failing_getaddrinfo(*args, **kwargs): raise socket.gaierror("Name or service not known") socket.getaddrinfo = failing_getaddrinfo try: socket.getaddrinfo("invalid.domain.example", None) except socket.gaierror as e: error_handled = True error_message = str(e) finally: socket.getaddrinfo = original_getaddrinfo assert error_handled assert "not known" in error_message or "Name" in error_message @pytest.mark.asyncio async def test_slow_network_latency(self): """Test system behavior under high network latency""" latencies = [] async def request_with_latency(latency_ms: int): await asyncio.sleep(latency_ms / 1000) latencies.append(latency_ms) return {"status": "success", "latency_ms": latency_ms} # Simulate varying latencies tasks = [request_with_latency(entry) for entry in [50, 100, 200, 500, 1000]] results = await asyncio.gather(*tasks) assert len(results) == 5 assert max(latencies) == 1000 assert min(latencies) == 50 @pytest.mark.asyncio async def test_intermittent_network_failure(self): """Test handling of intermittent network failures with retry""" failure_count = 0 max_failures = 3 async def flaky_request(): nonlocal failure_count failure_count += 1 if failure_count < max_failures: raise ConnectionError("Network unreachable") return {"status": "success", "attempt": failure_count} # Retry logic result = None for attempt in range(5): try: result = await flaky_request() break except ConnectionError: await asyncio.sleep(0.01) assert result is not None assert result["attempt"] == 3 assert failure_count == 3 @pytest.mark.asyncio async def test_network_partition_simulation(self): """Test behavior during network partition""" nodes = ["node1", "node2", "node3"] partitioned_nodes = {"node2"} # Simulated partition results = {} for node in nodes: if node in partitioned_nodes: results[node] = {"status": "unreachable"} else: results[node] = {"status": "healthy"} assert results["node1"]["status"] == "healthy" assert results["node2"]["status"] == "unreachable" assert results["node3"]["status"] == "healthy" # ============================================================================= # 2. DATABASE FAILURES # ============================================================================= @pytest.mark.chaos class TestDatabaseFailures: """Test database failure handling""" @pytest.mark.asyncio async def test_database_connection_lost(self): """Test handling of lost database connections""" connection_lost = False async def db_operation(): nonlocal connection_lost try: raise sqlite3.OperationalError("database is locked") except sqlite3.OperationalError: connection_lost = True return {"status": "error", "fallback": "cache"} result = await db_operation() assert connection_lost is True assert result["fallback"] == "cache" @pytest.mark.asyncio async def test_database_lock_timeout(self): """Test handling of database lock timeouts""" lock_timeouts = 0 async def concurrent_access(): nonlocal lock_timeouts try: # Simulate lock contention raise sqlite3.OperationalError("database is locked") except sqlite3.OperationalError as e: if "locked" in str(e): lock_timeouts += 1 return {"status": "retry_needed"} # Simulate concurrent access tasks = [concurrent_access() for _ in range(5)] results = await asyncio.gather(*tasks) assert lock_timeouts == 5 assert all(r["status"] == "retry_needed" for r in results) @pytest.mark.asyncio async def test_disk_full_simulation(self): """Test handling of disk full conditions""" disk_error_handled = False async def write_operation(): nonlocal disk_error_handled try: raise OSError(errno.ENOSPC, "No space left on device") except OSError as e: if e.errno == errno.ENOSPC: disk_error_handled = True return {"status": "disk_full", "action": "cleanup"} result = await write_operation() assert disk_error_handled is True assert result["action"] == "cleanup" @pytest.mark.asyncio async def test_query_timeout_handling(self): """Test handling of slow query timeouts""" from core.cache import MemoryCache cache = MemoryCache() async def slow_query(): await asyncio.sleep(3) # Slow query return ["result1", "result2"] start = time.time() try: result = await asyncio.wait_for(slow_query(), timeout=0.2) except asyncio.TimeoutError: result = [] elapsed = time.time() - start assert result == [] assert elapsed < 1.0 # Should timeout quickly @pytest.mark.asyncio async def test_database_connection_pool_exhaustion(self): """Test behavior when DB connection pool is exhausted""" max_connections = 5 active_connections = 0 exhausted_errors = 0 async def get_connection(): nonlocal active_connections, exhausted_errors if active_connections >= max_connections: exhausted_errors += 1 raise Exception("Connection pool exhausted") active_connections += 1 await asyncio.sleep(0.01) active_connections -= 1 return {"connection_id": active_connections} # Try to get more connections than available tasks = [get_connection() for _ in range(10)] results = await asyncio.gather(*tasks, return_exceptions=True) assert exhausted_errors > 0 @pytest.mark.asyncio async def test_graceful_degradation_on_db_failure(self): """Test graceful degradation when DB fails""" from api.models.scan import Scan # Mock complete DB failure with patch.object(Scan, "find_many", return_value=MagicMock()): mock_query = MagicMock() mock_query.limit.return_value.skip.return_value.to_list = AsyncMock( side_effect=Exception("Database connection lost") ) with patch.object(Scan, "find_many", return_value=mock_query): try: query = Scan.find_many() results = await query.limit(10).to_list() except Exception: results = [] # Fallback to empty results assert results == [] # ============================================================================= # 3. EXTERNAL SERVICE FAILURES # ============================================================================= @pytest.mark.chaos class TestExternalServiceFailures: """Test external service failure handling""" @pytest.mark.asyncio async def test_tool_not_found_handling(self): """Test handling when external tool is not found""" tool_errors = [] async def execute_tool(tool_name: str): try: raise FileNotFoundError(f"Tool '{tool_name}' not found in PATH") except FileNotFoundError as e: tool_errors.append(str(e)) return {"status": "error", "tool": tool_name, "fallback": "mock_scan"} result = await execute_tool("nmap") assert len(tool_errors) == 1 assert result["fallback"] == "mock_scan" @pytest.mark.asyncio async def test_tool_crash_non_zero_exit(self): """Test handling of tool crashes (non-zero exit codes)""" exit_codes = [1, 2, 127, 255] results = [] async def execute_tool_with_exit_code(exit_code: int): try: raise subprocess.CalledProcessError(exit_code, "nmap", output=b"", stderr=b"Error occurred") except subprocess.CalledProcessError as e: return {"status": "crashed", "exit_code": e.returncode, "stderr": e.stderr.decode() if e.stderr else ""} for code in exit_codes: result = await execute_tool_with_exit_code(code) results.append(result) assert len(results) == 4 assert all(r["status"] == "crashed" for r in results) @pytest.mark.asyncio async def test_invalid_output_format_handling(self): """Test handling of invalid/malformed tool output""" from xml.etree.ElementTree import ParseError invalid_outputs = [ "not valid xml", "{invalid json", "", None, ] async def parse_nmap_output(output): try: if not output: raise ValueError("Empty output") # Simulate XML parsing if "<" not in output: raise ParseError("not well-formed") return {"parsed": True} except (ParseError, ValueError) as e: return {"parsed": False, "error": str(e), "raw": output} results = [] for output in invalid_outputs: result = await parse_nmap_output(output) results.append(result) assert all(not r["parsed"] for r in results) assert len(results) == 4 @pytest.mark.asyncio async def test_permission_denied_handling(self): """Test handling of permission denied errors""" permission_errors = [] async def execute_restricted_operation(): try: raise PermissionError(13, "Permission denied") except PermissionError as e: permission_errors.append(str(e)) return {"status": "permission_denied", "action": "escalate_or_skip"} result = await execute_restricted_operation() assert len(permission_errors) == 1 assert result["status"] == "permission_denied" @pytest.mark.asyncio async def test_tool_execution_timeout(self): """Test handling of tool execution timeouts""" timeout_occurred = False async def long_running_tool(): nonlocal timeout_occurred try: await asyncio.sleep(10) return {"status": "completed"} except asyncio.TimeoutError: timeout_occurred = True return {"status": "timeout", "killed": True} try: result = await asyncio.wait_for(long_running_tool(), timeout=0.1) except asyncio.TimeoutError: timeout_occurred = True result = {"status": "timeout", "killed": True} assert timeout_occurred is True assert result["killed"] is True @pytest.mark.asyncio async def test_api_rate_limit_handling(self): """Test handling of API rate limiting""" rate_limited_count = 0 async def make_api_request(request_num: int): nonlocal rate_limited_count if request_num > 50: # Rate limit kicks in rate_limited_count += 1 return {"status": 429, "error": "Rate limit exceeded"} return {"status": 200, "data": f"response_{request_num}"} # Simulate burst requests tasks = [make_api_request(i) for i in range(60)] results = await asyncio.gather(*tasks) assert rate_limited_count == 9 # 51-59 assert sum(1 for r in results if r["status"] == 429) == 9 # ============================================================================= # 4. RESOURCE EXHAUSTION # ============================================================================= @pytest.mark.chaos class TestResourceExhaustion: """Test behavior under resource exhaustion""" @pytest.mark.asyncio async def test_memory_limit_handling(self): """Test system behavior under memory pressure""" from core.cache import MemoryCache cache = MemoryCache() memory_warnings = [] # Fill cache with data large_data = "x" * 10000 # 10KB per entry for i in range(100): # ~1MB total await cache.set(f"large_key_{i}", large_data) # Simulate memory monitoring if i > 80: memory_warnings.append(f"High memory usage at entry {i}") # Verify cache still works result = await cache.get("large_key_0") assert result == large_data assert len(memory_warnings) == 19 # 81-99 @pytest.mark.asyncio async def test_cpu_throttling_simulation(self): """Test behavior under CPU throttling""" cpu_throttled = False async def cpu_intensive_with_throttle_detection(): nonlocal cpu_throttled start = time.perf_counter() # Simulate work that would be throttled iterations = 0 while time.perf_counter() - start < 0.1: _ = [i**2 for i in range(100)] iterations += 1 # If iterations are low, CPU was throttled if iterations < 100: # Arbitrary threshold cpu_throttled = True return {"iterations": iterations, "throttled": cpu_throttled} result = await cpu_intensive_with_throttle_detection() # Just verify the detection mechanism works assert "iterations" in result @pytest.mark.asyncio async def test_file_descriptor_limit_handling(self): """Test handling of file descriptor exhaustion""" fd_errors = 0 max_simulated_fds = 10 open_fds = 0 async def open_file(): nonlocal fd_errors, open_fds if open_fds >= max_simulated_fds: fd_errors += 1 raise OSError(errno.EMFILE, "Too many open files") open_fds += 1 return {"fd_id": open_fds} # Try to open more files than allowed results = [] for _ in range(15): try: result = await open_file() results.append(result) except OSError: pass assert fd_errors == 5 # 10-14 @pytest.mark.asyncio async def test_disk_space_monitoring(self): """Test disk space monitoring and alerts""" # Get disk usage disk = shutil.disk_usage("/") free_percent = (disk.free / disk.total) * 100 # Simulate alert if disk space is low alert_triggered = free_percent < 10 # Test passes if we can check disk space assert isinstance(free_percent, float) assert 0 <= free_percent <= 100 @pytest.mark.asyncio async def test_temporary_file_cleanup_on_exhaustion(self): """Test cleanup of temporary files on resource exhaustion""" temp_files = [] cleanup_triggered = False async def create_temp_file(): nonlocal cleanup_triggered try: # Simulate temp file creation fd, path = tempfile.mkstemp() temp_files.append(path) os.close(fd) if len(temp_files) > 50: cleanup_triggered = True # Simulate cleanup for f in temp_files[:25]: if os.path.exists(f): os.remove(f) temp_files[:] = temp_files[25:] return {"path": path} except Exception as e: return {"error": str(e)} # Create many temp files for _ in range(60): await create_temp_file() # Cleanup remaining files for f in temp_files: if os.path.exists(f): os.remove(f) assert cleanup_triggered is True # ============================================================================= # 5. AGENT FAILURES # ============================================================================= @pytest.mark.chaos class TestAgentFailures: """Test agent failure handling""" @pytest.mark.asyncio async def test_agent_crash_recovery(self): """Test automatic agent recovery after crash""" crash_count = 0 retry_attempts = 0 recovered = False async def agent_with_recovery(): nonlocal crash_count, recovered if crash_count < 2: crash_count += 1 raise RuntimeError(f"Agent crashed: attempt {crash_count}") recovered = True return {"status": "recovered", "attempt": crash_count} # Attempt recovery with retry for _ in range(5): try: result = await agent_with_recovery() break except RuntimeError: retry_attempts += 1 await asyncio.sleep(0.01) assert recovered is True assert crash_count == 2 assert retry_attempts == 2 @pytest.mark.asyncio async def test_message_loss_handling(self): """Test handling of lost messages between agents""" messages_sent = [] messages_lost = [] messages_received = [] async def send_message(msg_id: str, loss_probability: float = 0.3): messages_sent.append(msg_id) # Simulate message loss if random.random() < loss_probability: messages_lost.append(msg_id) return {"status": "lost", "msg_id": msg_id} messages_received.append(msg_id) return {"status": "delivered", "msg_id": msg_id} random.seed(42) # Reproducible tasks = [send_message(f"msg_{i}") for i in range(20)] results = await asyncio.gather(*tasks) delivered = sum(1 for r in results if r["status"] == "delivered") lost = sum(1 for r in results if r["status"] == "lost") assert delivered + lost == 20 assert len(messages_received) == delivered assert len(messages_lost) == lost @pytest.mark.asyncio async def test_state_corruption_recovery(self): """Test recovery from corrupted agent state""" corrupted_states = [] async def agent_with_state_check(): # Simulate corrupted state state = {"status": "running", "data": None} if state["data"] is None: corrupted_states.append("null_data") # Reset to safe defaults state["data"] = {} state["status"] = "reset" return state result = await agent_with_state_check() assert len(corrupted_states) == 1 assert result["status"] == "reset" assert result["data"] == {} @pytest.mark.asyncio async def test_agent_restart_capability(self): """Test agent can restart and resume work""" restart_count = 0 tasks_completed = 0 async def resilient_agent(): nonlocal restart_count, tasks_completed try: if restart_count == 0: restart_count += 1 raise Exception("First start failure") # Resume work after restart tasks_completed = 5 return {"status": "running", "restarts": restart_count, "tasks_completed": tasks_completed} except Exception: restart_count += 1 # Simulate restart and retry return await resilient_agent() result = await resilient_agent() assert result["status"] == "running" assert result["restarts"] >= 1 assert result["tasks_completed"] == 5 @pytest.mark.asyncio async def test_agent_pool_failure_isolation(self): """Test that one agent failure doesn't affect others""" agents = [{"id": f"agent_{i}", "healthy": True, "task_count": 0} for i in range(5)] # Simulate one agent failure agents[2]["healthy"] = False async def process_tasks(agent): if not agent["healthy"]: return {"agent_id": agent["id"], "status": "failed"} agent["task_count"] += 1 return {"agent_id": agent["id"], "status": "success"} results = await asyncio.gather(*[process_tasks(a) for a in agents]) successful = [r for r in results if r["status"] == "success"] failed = [r for r in results if r["status"] == "failed"] assert len(successful) == 4 assert len(failed) == 1 assert failed[0]["agent_id"] == "agent_2" # ============================================================================= # 6. ORCHESTRATOR FAILURES # ============================================================================= @pytest.mark.chaos class TestOrchestratorFailures: """Test orchestrator failure handling""" @pytest.mark.asyncio async def test_backend_unavailability_handling(self): """Test handling when LLM backend is unavailable""" backend_failures = 0 fallback_used = False async def call_backend(): nonlocal backend_failures, fallback_used backends = ["kimi", "openai", "anthropic"] for backend in backends: try: if backend == "kimi": backend_failures += 1 raise ConnectionError("Kimi backend unreachable") if backend == "openai": backend_failures += 1 raise ConnectionError("OpenAI backend unreachable") # Fallback to anthropic succeeds fallback_used = True return {"backend": backend, "response": "success"} except ConnectionError: continue return {"error": "All backends failed"} result = await call_backend() assert fallback_used is True assert result["backend"] == "anthropic" assert backend_failures == 2 @pytest.mark.asyncio async def test_circuit_breaker_trigger(self): """Test circuit breaker triggers after repeated failures""" failure_count = 0 circuit_state = "closed" fallback_invocations = 0 async def operation_with_circuit_breaker(): nonlocal failure_count, circuit_state, fallback_invocations if circuit_state == "open": fallback_invocations += 1 return {"status": "fallback", "circuit": "open"} try: failure_count += 1 if failure_count <= 3: raise Exception("Service unavailable") failure_count = 0 circuit_state = "closed" return {"status": "success"} except Exception: if failure_count >= 3: circuit_state = "open" raise # Trigger circuit breaker results = [] for _ in range(10): try: result = await operation_with_circuit_breaker() results.append(result) except Exception: pass # Circuit should open assert circuit_state == "open" assert fallback_invocations > 0 @pytest.mark.asyncio async def test_fallback_mechanism_activation(self): """Test fallback mechanism activates on primary failure""" primary_failed = False fallback_result = None async def primary_service(): nonlocal primary_failed primary_failed = True raise Exception("Primary service failed") async def fallback_service(): nonlocal fallback_result fallback_result = {"status": "success", "source": "fallback"} return fallback_result async def resilient_operation(): try: return await primary_service() except Exception: return await fallback_service() result = await resilient_operation() assert primary_failed is True assert fallback_result is not None assert result["source"] == "fallback" @pytest.mark.asyncio async def test_circuit_breaker_half_open_state(self): """Test circuit breaker half-open state during recovery""" from zen_shield.circuit_breaker import CircuitBreaker, CircuitState cb = CircuitBreaker(failure_threshold=2, recovery_timeout=0.1, half_open_max_calls=1) # Fast for testing # Force circuit to open cb.state = CircuitState.OPEN cb.metrics.failures = 2 cb.metrics.last_failure_time = time.time() - 0.2 # Past recovery timeout # Next call should transition to half-open async def test_operation(): return {"status": "success"} # Wait for recovery timeout await asyncio.sleep(0.15) # Circuit should attempt recovery result = await cb.execute(test_operation) assert result is not None @pytest.mark.asyncio async def test_orchestrator_graceful_shutdown(self): """Test graceful shutdown during active operations""" active_tasks = 5 completed_tasks = 0 shutdown_initiated = False async def long_running_task(task_id: int): nonlocal completed_tasks try: await asyncio.sleep(0.1) if shutdown_initiated: return {"task_id": task_id, "status": "cancelled"} completed_tasks += 1 return {"task_id": task_id, "status": "completed"} except asyncio.CancelledError: return {"task_id": task_id, "status": "cancelled"} # Start tasks tasks = [long_running_task(i) for i in range(active_tasks)] # Initiate shutdown after brief delay await asyncio.sleep(0.05) shutdown_initiated = True results = await asyncio.gather(*tasks, return_exceptions=True) # All tasks should have a result assert len(results) == active_tasks # ============================================================================= # 7. RETRY LOGIC TESTS # ============================================================================= @pytest.mark.chaos class TestRetryLogic: """Test retry logic under various failure conditions""" @pytest.mark.asyncio async def test_exponential_backoff_retry(self): """Test exponential backoff in retry logic""" delays = [] attempt_count = 0 async def operation_with_backoff(): nonlocal attempt_count attempt_count += 1 if attempt_count < 4: delay = 0.01 * (2 ** (attempt_count - 1)) # Exponential delays.append(delay) await asyncio.sleep(delay) raise ConnectionError(f"Attempt {attempt_count} failed") return {"status": "success", "attempts": attempt_count} # Retry with exponential backoff result = None for attempt in range(5): try: result = await operation_with_backoff() break except ConnectionError: pass assert result is not None assert result["attempts"] == 4 assert len(delays) == 3 @pytest.mark.asyncio async def test_retry_with_jitter(self): """Test retry with random jitter to prevent thundering herd""" random.seed(42) retry_delays = [] for i in range(5): base_delay = 0.01 * (2**i) jitter = random.uniform(0, base_delay * 0.1) retry_delays.append(base_delay + jitter) # Verify jitter adds variation assert len(set(retry_delays)) == 5 # All different due to jitter @pytest.mark.asyncio async def test_retry_limit_enforcement(self): """Test that retry limits are properly enforced""" max_retries = 3 attempt_count = 0 async def always_failing_operation(): nonlocal attempt_count attempt_count += 1 raise Exception("Always fails") # Attempt with retry limit result = None final_error = None for attempt in range(max_retries + 1): try: result = await always_failing_operation() except Exception as e: final_error = e if attempt >= max_retries: break assert result is None assert attempt_count == max_retries + 1 # Initial + retries assert final_error is not None @pytest.mark.asyncio async def test_retry_only_transient_errors(self): """Test that only transient errors trigger retry""" retryable_errors = [ConnectionError, TimeoutError, OSError] non_retryable_errors = [ValueError, TypeError, KeyError] retry_count = 0 async def operation_with_error_type(error_type): nonlocal retry_count retry_count += 1 raise error_type("Test error") # Test retryable errors for error_type in retryable_errors: retry_count = 0 for _ in range(3): try: await operation_with_error_type(error_type) except Exception as e: if type(e) in retryable_errors and retry_count < 3: continue # Should have retried # Test non-retryable errors retry_count = 0 try: await operation_with_error_type(ValueError) except ValueError: pass assert retry_count == 1 # No retry # ============================================================================= # 8. RECOVERY BEHAVIOR VALIDATION # ============================================================================= @pytest.mark.chaos class TestRecoveryBehavior: """Validate recovery behavior after failures""" @pytest.mark.asyncio async def test_automatic_recovery_sequence(self): """Test full automatic recovery sequence""" attempts = 0 max_attempts = 3 recovered = False async def flaky_service(): nonlocal attempts, recovered attempts += 1 if attempts < 3: raise ConnectionError(f"Service failure #{attempts}") recovered = True return {"status": "success", "attempt": attempts} result = None for _ in range(max_attempts): try: result = await flaky_service() break except ConnectionError: await asyncio.sleep(0.01) assert result is not None assert result["status"] == "success" assert recovered is True assert attempts == 3 @pytest.mark.asyncio async def test_state_consistency_after_recovery(self): """Test data consistency after failure recovery""" from core.cache import MemoryCache cache = MemoryCache() # Set initial state await cache.set("transaction_1", "pending") await cache.set("transaction_2", "pending") # Simulate failure during transaction_1 await cache.set("transaction_1", "failed") # Recovery: retry transaction_1 await cache.set("transaction_1", "completed") await cache.set("transaction_2", "completed") # Verify consistency t1 = await cache.get("transaction_1") t2 = await cache.get("transaction_2") assert t1 == "completed" assert t2 == "completed" @pytest.mark.asyncio async def test_recovery_metrics_tracking(self): """Test that recovery metrics are properly tracked""" recovery_metrics = { "failures": 0, "recoveries": 0, "recovery_time_ms": [], } async def monitored_operation(): nonlocal recovery_metrics recovery_metrics["failures"] += 1 start = time.time() # Simulate recovery work await asyncio.sleep(0.01) recovery_metrics["recoveries"] += 1 recovery_metrics["recovery_time_ms"].append((time.time() - start) * 1000) return {"status": "recovered"} # Simulate multiple failures and recoveries for _ in range(3): await monitored_operation() assert recovery_metrics["failures"] == 3 assert recovery_metrics["recoveries"] == 3 assert len(recovery_metrics["recovery_time_ms"]) == 3 @pytest.mark.asyncio async def test_rolling_recovery_capability(self): """Test rolling recovery without full system restart""" services = { "api": {"healthy": False, "restarting": False}, "worker": {"healthy": True, "restarting": False}, "scheduler": {"healthy": True, "restarting": False}, } async def rolling_recovery(): for service_name, state in services.items(): if not state["healthy"]: state["restarting"] = True await asyncio.sleep(0.01) # Restart time state["healthy"] = True state["restarting"] = False await rolling_recovery() # All services should be healthy assert all(s["healthy"] for s in services.values()) assert all(not s["restarting"] for s in services.values()) # ============================================================================= # 9. CHAOS SCENARIOS # ============================================================================= @pytest.mark.chaos class TestChaosScenarios: """Complex chaos scenarios combining multiple failures""" @pytest.mark.asyncio async def test_cascade_failure_prevention(self): """Test prevention of cascade failures""" services = { "auth": {"healthy": True, "dependencies": []}, "api": {"healthy": True, "dependencies": ["auth", "db"]}, "db": {"healthy": True, "dependencies": []}, } # Simulate DB failure services["db"]["healthy"] = False # Check if cascade is prevented # API should degrade gracefully, not fail completely api_can_degrade = True # API should use cached data or fallback assert api_can_degrade @pytest.mark.asyncio async def test_chaos_monkey_simulation(self): """Simulate random failures (Chaos Monkey style)""" random.seed(42) # Reproducible components = ["db", "cache", "external_api", "queue"] # Randomly fail components failed = random.sample(components, k=random.randint(0, 2)) # System should continue operating with remaining components operational = [c for c in components if c not in failed] assert len(operational) >= len(components) - 2 @pytest.mark.asyncio async def test_burst_failure_handling(self): """Test handling of burst failures""" concurrent_failures = 10 handled = 0 async def handle_failure(failure_id: int): nonlocal handled await asyncio.sleep(0.001) # Processing time handled += 1 return {"failure_id": failure_id, "handled": True} # Simulate burst tasks = [handle_failure(i) for i in range(concurrent_failures)] results = await asyncio.gather(*tasks) assert handled == concurrent_failures assert all(r["handled"] for r in results) @pytest.mark.asyncio async def test_partial_system_degradation(self): """Test system continues with partial functionality""" features = { "scanning": {"available": True, "degraded": False}, "reporting": {"available": True, "degraded": False}, "notifications": {"available": False, "degraded": True}, } available_features = [name for name, state in features.items() if state["available"]] # Core features should still work assert "scanning" in available_features assert "reporting" in available_features # ============================================================================= # 10. STRESS-INDUCED FAILURE TESTS # ============================================================================= @pytest.mark.chaos class TestStressInducedFailures: """Test failures induced by high stress/load""" @pytest.mark.asyncio async def test_stress_induced_timeout(self): """Test timeouts under stress conditions""" timeout_count = 0 async def stressed_operation(): nonlocal timeout_count try: # Simulate slow operation under stress await asyncio.sleep(0.05) return {"status": "completed"} except asyncio.TimeoutError: timeout_count += 1 return {"status": "timeout"} # Run many concurrent operations tasks = [stressed_operation() for _ in range(50)] results = await asyncio.gather(*tasks) completed = sum(1 for r in results if r["status"] == "completed") assert completed == 50 # All completed with short delay @pytest.mark.asyncio async def test_memory_leak_detection(self): """Test detection of memory leaks under stress""" from core.cache import MemoryCache cache = MemoryCache() memory_readings = [] # Simulate operations that might leak for i in range(100): await cache.set(f"key_{i}", {"data": "x" * 1000}) if i % 20 == 0: memory_readings.append(i) # Cleanup for i in range(100): await cache.delete(f"key_{i}") # Verify cleanup worked result = await cache.get("key_0") assert result is None @pytest.mark.asyncio async def test_resource_cleanup_on_failure(self): """Test resources are cleaned up on failure""" resources_allocated = [] resources_freed = [] async def operation_with_cleanup(): resource_id = f"res_{len(resources_allocated)}" resources_allocated.append(resource_id) try: if len(resources_allocated) == 3: raise Exception("Simulated failure") return {"status": "success"} except Exception: resources_freed.append(resource_id) raise finally: if resource_id not in resources_freed: resources_freed.append(resource_id) # Run operations for i in range(5): try: await operation_with_cleanup() except Exception: pass # All resources should be freed assert len(resources_freed) == len(resources_allocated) if __name__ == "__main__": pytest.main([__file__, "-v", "--tb=short"])
"""
Chaos Engineering Tests - Comprehensive Failure Injection
Resilience testing through controlled failure injection:
- Network failures (timeout, connection reset, DNS, latency)
- Database failures (connection lost, lock timeout, disk full, query timeout)
- External service failures (tool not found, crash, invalid output, permission)
- Resource exhaustion (memory limit, CPU throttling, file descriptor limit)
- Agent failures (crash recovery, message loss, state corruption)
- Orchestrator failures (backend unavailable, circuit breaker, fallback)
ZIEL: System Resilience unter Fehlerbedingungen!
"""
import asyncio
import errno
import os
import random
import resource
import shutil
import socket
import sqlite3
import subprocess
import sys
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor
from io import StringIO
from typing import Any, Dict, List, Optional
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
pytestmark = [
pytest.mark.chaos,
pytest.mark.resilience,
pytest.mark.asyncio,
]
# =============================================================================
# 1. NETWORK FAILURES
# =============================================================================
@pytest.mark.chaos
class TestNetworkFailures:
"""Test system resilience to network failures"""
@pytest.mark.asyncio
async def test_api_timeout_handling(self):
"""Test API behavior under timeout conditions"""
from core.cache import MemoryCache
cache = MemoryCache()
async def slow_operation():
await asyncio.sleep(5) # Would timeout
return "result"
# Test timeout handling
start = time.time()
try:
result = await asyncio.wait_for(slow_operation(), timeout=0.1)
except asyncio.TimeoutError:
result = None
elapsed = time.time() - start
assert result is None
assert elapsed < 0.5 # Should fail fast
@pytest.mark.asyncio
async def test_connection_reset_handling(self):
"""Test handling of connection reset errors"""
connection_errors = []
async def simulate_connection():
try:
# Simulate connection reset
raise ConnectionResetError("Connection reset by peer")
except ConnectionResetError as e:
connection_errors.append(str(e))
return {"status": "error", "fallback": True}
result = await simulate_connection()
assert len(connection_errors) == 1
assert result["fallback"] is True
@pytest.mark.asyncio
async def test_dns_resolution_failure(self):
"""Test handling of DNS resolution failures"""
# Simulate DNS failure
original_getaddrinfo = socket.getaddrinfo
def failing_getaddrinfo(*args, **kwargs):
raise socket.gaierror("Name or service not known")
socket.getaddrinfo = failing_getaddrinfo

Xet Storage Details

Size:
42.7 kB
·
Xet hash:
4820b9a55f01c5109e1ca697e46247ffb536c1bb7d1416936882d0c79ad07f1f

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.