Files
cleverclaude-core/features/environment.py
T
2025-08-10 12:00:13 -04:00

181 lines
4.8 KiB
Python

"""
Behave test environment setup for CleverClaude.
This module configures the testing environment for BDD scenarios,
providing fixtures, test data, and integration with the CleverClaude system.
"""
from __future__ import annotations
import asyncio
import os
import shutil
import sys
import tempfile
from pathlib import Path
from typing import Any
from behave import fixture, use_fixture
from behave.runner import Context
def before_all(context):
"""Set up test environment."""
project_root = Path(__file__).parent.parent
src_path = project_root / "src"
if str(src_path) not in sys.path:
sys.path.insert(0, str(src_path))
context.project_root = project_root
# Initialize test context for CleverClaude testing
context.test_context = TestContext()
# Set testing environment
os.environ["CLEVERCLAUDE_ENVIRONMENT"] = "testing"
os.environ["CLEVERCLAUDE_DEBUG"] = "true"
os.environ["CLEVERCLAUDE_MONITORING_LOG_LEVEL"] = "DEBUG"
print("Starting CleverClaude BDD test suite")
def before_scenario(context, scenario):
"""Reset context before each scenario."""
context.runner = None
context.result = None
# Setup for CleverClaude testing
print(f"Starting scenario: {scenario.name}")
# Setup fixtures for each scenario
use_fixture(temp_directory, context)
use_fixture(event_loop, context)
# Clear test results
context.test_context.test_results.clear()
context.test_context.created_agents.clear()
context.test_context.created_swarms.clear()
def after_scenario(context, scenario):
"""Cleanup after each scenario."""
print(f"Completed scenario: {scenario.name} - {scenario.status.name}")
# Additional cleanup if needed
if hasattr(context.test_context, "temp_dir") and context.test_context.temp_dir:
try:
if context.test_context.temp_dir.exists():
shutil.rmtree(context.test_context.temp_dir, ignore_errors=True)
except Exception as e:
print(f"Error cleaning up temp directory: {e}")
def after_all(_context):
"""Global cleanup after all tests."""
print("CleverClaude BDD test suite completed")
# Clean up environment variables
for var in ["CLEVERCLAUDE_ENVIRONMENT", "CLEVERCLAUDE_DEBUG", "CLEVERCLAUDE_CONFIG_DIR"]:
if var in os.environ:
del os.environ[var]
class TestContext:
"""Test context for CleverClaude BDD scenarios."""
def __init__(self):
self.app: Any | None = None
self.agent_manager: Any | None = None
self.swarm_coordinator: Any | None = None
self.mcp_client: Any | None = None
self.temp_dir: Path | None = None
self.config_dir: Path | None = None
self.created_agents: list[str] = []
self.created_swarms: list[str] = []
self.test_results: dict[str, Any] = {}
self.event_loop: asyncio.AbstractEventLoop | None = None
@fixture
def temp_directory(context: Context):
"""Create a temporary directory for test files."""
temp_dir = Path(tempfile.mkdtemp(prefix="cleverclaude_test_"))
context.test_context.temp_dir = temp_dir
# Create config directory structure
config_dir = temp_dir / ".cleverclaude"
config_dir.mkdir(exist_ok=True)
(config_dir / "data").mkdir(exist_ok=True)
(config_dir / "logs").mkdir(exist_ok=True)
(config_dir / "cache").mkdir(exist_ok=True)
context.test_context.config_dir = config_dir
# Create basic test config
test_config = f"""
# Test CleverClaude Configuration
app:
name: "CleverClaude Test"
version: "2.0.0"
environment: "testing"
debug: true
database:
url: "sqlite+aiosqlite:///{config_dir}/test.db"
echo: false
redis:
url: "redis://localhost:6379/15" # Test database
agents:
max_agents: 10
default_timeout: 30
health_check_interval: 5
swarm:
default_topology: "mesh"
max_swarm_size: 5
coordination_timeout: 30
api:
host: "127.0.0.1"
port: 8080 # Different port for testing
docs_enabled: false
monitoring:
metrics_enabled: false
log_level: "DEBUG"
log_format: "json"
"""
(config_dir / "config.yaml").write_text(test_config)
yield temp_dir
# Cleanup
if temp_dir.exists():
shutil.rmtree(temp_dir, ignore_errors=True)
@fixture
def event_loop(context: Context):
"""Create an event loop for async tests."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
context.test_context.event_loop = loop
yield loop
# Cleanup pending tasks
try:
pending = asyncio.all_tasks(loop)
if pending:
for task in pending:
task.cancel()
loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
except Exception as e:
print(f"Error cleaning up tasks: {e}")
finally:
loop.close()