Buckets:

download
raw
18.3 kB
"""
ACGS-2 Enhanced Agent Bus - Shared Test Fixtures
Constitutional Hash: cdd01ef066bc6cf2
Provides common fixtures for all test modules.
"""
import os
import sys
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock
from enhanced_agent_bus.observability.structured_logging import get_logger
# Only mock torch if it's not installed - torch is now a real dependency
try:
import torch
except ImportError:
sys.modules["torch"] = MagicMock()
logger = get_logger(__name__)
# Ensure the sandbox environment guard is satisfied for the entire worker process.
# ``require_sandbox_endpoint`` raises HTTP 503 when ENVIRONMENT is not in the
# sandbox set. Set it once at conftest load time (before any module is imported)
# so every EAB test sees a consistent sandbox environment. Individual tests that
# need a different value (e.g. to assert 503 for production) can still override
# via ``patch.dict(os.environ, {"ENVIRONMENT": "production"})``.
# Constitutional Hash: cdd01ef066bc6cf2
os.environ.setdefault("ENVIRONMENT", "test")
# CRITICAL: Block Rust imports BEFORE any module imports
_test_with_rust = os.environ.get("TEST_WITH_RUST", "0") == "1"
if not _test_with_rust:
sys.modules["enhanced_agent_bus_rust"] = None
import pytest # noqa: E402
# Add enhanced_agent_bus directory to path if not already there
enhanced_agent_bus_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if enhanced_agent_bus_dir not in sys.path:
sys.path.insert(0, enhanced_agent_bus_dir)
def _patch_optional(pkg_name: str, flat_name: str | None = None) -> Any | None:
"""Import a module and register both flat and qualified names in sys.modules.
Args:
pkg_name: Fully-qualified module name (e.g. "enhanced_agent_bus.api").
flat_name: Short alias for sys.modules (e.g. "api"). If None, derived from pkg_name.
Returns:
The imported module, or None if ImportError.
"""
if flat_name is None:
flat_name = pkg_name.rsplit(".", 1)[-1]
try:
mod = __import__(pkg_name, fromlist=[flat_name])
sys.modules[flat_name] = mod
# Also register as enhanced_agent_bus.X for tests that use that path
eab_name = f"enhanced_agent_bus.{flat_name}"
sys.modules[eab_name] = mod
# pytest importlib mode creates 'core.enhanced_agent_bus' prefix; register there too
core_eab_name = f"core.enhanced_agent_bus.{flat_name}"
sys.modules[core_eab_name] = mod
return mod
except ImportError:
return None
# ── Core module imports (required) ──────────────────────────────────────────
_THIS_PACKAGE_ROOT = Path(__file__).resolve().parents[1]
def _qualified_test_package() -> str:
"""Use parent-repo import path only when it resolves to this checkout."""
imported_package = sys.modules.get("enhanced_agent_bus")
imported_path = Path(getattr(imported_package, "__file__", "")).resolve()
if imported_path.parent == _THIS_PACKAGE_ROOT:
return "enhanced_agent_bus"
package_alias = sys.modules.get("packages.enhanced_agent_bus")
alias_path = Path(getattr(package_alias, "__file__", "")).resolve()
if alias_path.parent == _THIS_PACKAGE_ROOT:
return "packages.enhanced_agent_bus"
return "enhanced_agent_bus"
_PKG = _qualified_test_package()
import enhanced_agent_bus.audit_client as _audit_client # noqa: E402
import enhanced_agent_bus.dependency_bridge as _dependency_bridge # noqa: E402
# imports.py deleted (v3.1 cleanup) — dependency_bridge.py is the canonical source
import enhanced_agent_bus.exceptions as _exceptions # noqa: E402
import enhanced_agent_bus.interfaces as _interfaces # noqa: E402
import enhanced_agent_bus.maci_enforcement as _maci_enforcement # noqa: E402
import enhanced_agent_bus.models as _models # noqa: E402
import enhanced_agent_bus.registry as _registry # noqa: E402
import enhanced_agent_bus.utils as _utils # noqa: E402
import enhanced_agent_bus.validators as _validators # noqa: E402
# PM-015 core-module fix: `import packages.enhanced_agent_bus.X as _X` uses the
# IMPORT_FROM opcode which follows the attribute chain on M_PEAB. Because
# M_PEAB.__init__ re-registers itself as sys.modules["enhanced_agent_bus"] and
# subsequent flat imports (from enhanced_agent_bus.X) overwrite M_PEAB.X with
# M_X_EA, the attribute chain returns M_X_EA — not M_X_PEAB from sys.modules.
# Resolve canonical M_X_PEAB directly from sys.modules after the import has
# triggered loading.
def _canonical(submod: str) -> object:
"""Return sys.modules["enhanced_agent_bus.<submod>"] (M_X_PEAB)."""
return sys.modules.get(f"enhanced_agent_bus.{submod}") or sys.modules.get(
f"enhanced_agent_bus.{submod}"
)
_audit_client = _canonical("audit_client") or _audit_client
_dependency_bridge = _canonical("dependency_bridge") or _dependency_bridge
_exceptions = _canonical("exceptions") or _exceptions
_interfaces = _canonical("interfaces") or _interfaces
_maci_enforcement = _canonical("maci_enforcement") or _maci_enforcement
_models = _canonical("models") or _models
_registry = _canonical("registry") or _registry
_utils = _canonical("utils") or _utils
_validators = _canonical("validators") or _validators
# Patch flat names for tests that import without package prefix
# CRITICAL: DO NOT hijack sys.modules["core"]
sys.modules["audit_client"] = _audit_client
sys.modules["models"] = _models
sys.modules["validators"] = _validators
sys.modules["exceptions"] = _exceptions
sys.modules["interfaces"] = _interfaces
sys.modules["registry"] = _registry
sys.modules["maci_enforcement"] = _maci_enforcement
sys.modules["utils"] = _utils
sys.modules["imports"] = _dependency_bridge # backward compat alias
# ── Optional module imports (may not have all deps installed) ───────────────
_agent_bus = _patch_optional(f"{_PKG}.agent_bus")
_message_processor = _patch_optional(f"{_PKG}.message_processor")
_processing_strategies = _patch_optional(f"{_PKG}.processing_strategies")
_online_learning = _patch_optional(f"{_PKG}.online_learning")
_ab_testing = _patch_optional(f"{_PKG}.ab_testing")
_ml_versioning = _patch_optional(f"{_PKG}.ml_versioning")
_feedback_handler = _patch_optional(f"{_PKG}.feedback_handler")
_drift_monitoring = _patch_optional(f"{_PKG}.drift_monitoring")
_api = _patch_optional(f"{_PKG}.api")
_batch_processor = _patch_optional(f"{_PKG}.batch_processor")
_context_memory = _patch_optional(f"{_PKG}.context_memory")
_runtime_security = _patch_optional(f"{_PKG}.runtime_security")
_enums = _patch_optional(f"{_PKG}.enums")
_config = _patch_optional(f"{_PKG}.config")
sys.modules["config"] = _config # flat import alias for test_config.py and importlib mode
_cb_factory = _patch_optional(f"{_PKG}.cb_factory")
# PM-015 cb_factory: Python's import machinery sets
# sys.modules["enhanced_agent_bus"].cb_factory = M_CBF_EA when enhanced_agent_bus.cb_factory
# is loaded, overwriting the attribute that was M_CBF_PEAB. This causes
# 'import packages.enhanced_agent_bus.cb_factory as cbf' to return M_CBF_EA (via the
# IMPORT_FROM attribute chain) while 'from packages.enhanced_agent_bus.cb_factory import fn'
# returns fn from M_CBF_PEAB — two different module dicts, breaking singleton patching.
# Fix: restore the canonical M_CBF_PEAB as the attribute on the package object.
if _cb_factory is not None:
_eab_pkg = sys.modules.get("packages.enhanced_agent_bus") or sys.modules.get(
"enhanced_agent_bus"
)
if _eab_pkg is not None:
_eab_pkg.cb_factory = _cb_factory
_deliberation_layer = _patch_optional(f"{_PKG}.deliberation_layer")
_constitutional = _patch_optional(f"{_PKG}.constitutional")
_middlewares = _patch_optional(f"{_PKG}.middlewares", flat_name="middleware")
# Deliberation layer sub-modules need patching for flat-name imports.
# Under pytest --import-mode=importlib the deliberation_layer package is already
# loaded via the 'core.enhanced_agent_bus' prefix which prevents normal
# sub-module imports. Use importlib.import_module to force the correct path.
if _deliberation_layer is not None:
import importlib as _il
try:
_impact_scorer = _il.import_module("enhanced_agent_bus.deliberation_layer.impact_scorer")
sys.modules["enhanced_agent_bus.deliberation_layer.impact_scorer"] = _impact_scorer
sys.modules["core.enhanced_agent_bus.deliberation_layer.impact_scorer"] = _impact_scorer
except ImportError:
pass
# Observability has sub-modules that also need patching
try:
import enhanced_agent_bus.observability as _observability
sys.modules["observability"] = _observability
sys.modules["enhanced_agent_bus.observability"] = _observability
import enhanced_agent_bus.observability.telemetry as _telemetry
sys.modules["observability.telemetry"] = _telemetry
sys.modules["enhanced_agent_bus.observability.telemetry"] = _telemetry
except ImportError:
_observability = None
# Canonicalize multi_tenancy ORM imports to avoid duplicate mappers in parallel runs
try:
import enhanced_agent_bus.multi_tenancy as _multi_tenancy
import enhanced_agent_bus.multi_tenancy.orm_models as _orm_models
sys.modules["enhanced_agent_bus.multi_tenancy"] = _multi_tenancy
sys.modules["core.enhanced_agent_bus.multi_tenancy"] = _multi_tenancy
sys.modules["enhanced_agent_bus.multi_tenancy.orm_models"] = _orm_models
sys.modules["core.enhanced_agent_bus.multi_tenancy.orm_models"] = _orm_models
if hasattr(_orm_models, "_dedupe_class_registry"):
_orm_models._dedupe_class_registry()
except ImportError:
pass
# Set the agent_bus alias (prefer agent_bus module)
if sys.modules.get("enhanced_agent_bus.agent_bus"):
sys.modules["agent_bus"] = sys.modules["enhanced_agent_bus.agent_bus"]
# Canonicalize all core module sys.modules aliases (PM-015 extended).
# Optional module imports above may trigger re-loading of EAB's __init__ which
# sets sys.modules["enhanced_agent_bus"] = M_PEAB and may overwrite
# sys.modules["enhanced_agent_bus.X"] or flat aliases back to M_X_EA.
# Re-assert M_X_PEAB as canonical for all three alias forms.
# PM-015: Canonicalize session_context, multi_tenancy.context, sdpc.pacar_manager,
# deliberation_layer.llm_assistant, and pipeline.legacy_wrapper to fix xdist flakes
# caused by dual module identity (packages.enhanced_agent_bus.X vs enhanced_agent_bus.X).
for _submod in [
"session_context",
"multi_tenancy.context",
"sdpc.pacar_manager",
"deliberation_layer.llm_assistant",
"pipeline.legacy_wrapper",
]:
_canon = sys.modules.get(f"enhanced_agent_bus.{_submod}")
if _canon is not None:
sys.modules[f"enhanced_agent_bus.{_submod}"] = _canon
sys.modules[f"core.enhanced_agent_bus.{_submod}"] = _canon
for _cmod_name, _cmod in [
("audit_client", _audit_client),
("dependency_bridge", _dependency_bridge),
("exceptions", _exceptions),
("interfaces", _interfaces),
("maci_enforcement", _maci_enforcement),
("models", _models),
("registry", _registry),
("utils", _utils),
("validators", _validators),
]:
if _cmod is not None:
sys.modules[f"enhanced_agent_bus.{_cmod_name}"] = _cmod
sys.modules[f"core.enhanced_agent_bus.{_cmod_name}"] = _cmod
sys.modules[_cmod_name] = _cmod # re-assert flat alias
# ── Rust availability ───────────────────────────────────────────────────────
if not _test_with_rust:
# Disable Rust for tests by default; dependency_bridge doesn't expose a
# mutable USE_RUST attribute, so we set it on the aliased module directly
# and mark the feature flag unavailable in DependencyRegistry.
_dependency_bridge.USE_RUST = False
RUST_AVAILABLE = False
else:
try:
RUST_AVAILABLE = True
_dependency_bridge.USE_RUST = True
except ImportError:
RUST_AVAILABLE = False
_dependency_bridge.USE_RUST = False
# ── Re-export commonly used items (public API for test files) ───────────────
AgentMessage = _models.AgentMessage
MessageType = _models.MessageType
Priority = _models.Priority
MessageStatus = _models.MessageStatus
CONSTITUTIONAL_HASH = _models.CONSTITUTIONAL_HASH
ValidationResult = _validators.ValidationResult
try:
from enhanced_agent_bus.message_processor import MessageProcessor
except ImportError:
try:
import message_processor
MessageProcessor = message_processor.MessageProcessor
except (ImportError, AttributeError):
MessageProcessor = None
try:
from enhanced_agent_bus.agent_bus import EnhancedAgentBus
except ImportError:
EnhancedAgentBus = None
# ── Fixtures ────────────────────────────────────────────────────────────────
def _reset_singletons() -> None:
"""Reset all known singletons to prevent state pollution between tests."""
for import_path, func_name in [
("enhanced_agent_bus.deliberation_layer.integration", "reset_deliberation_layer"),
("enhanced_agent_bus.batch_processor", "reset_batch_processor"),
("enhanced_agent_bus.impact_scorer_infra.service", "reset_impact_scorer"),
("enhanced_agent_bus.deliberation_layer.adaptive_router", "reset_adaptive_router"),
("enhanced_agent_bus.deliberation_layer.deliberation_queue", "reset_deliberation_queue"),
]:
try:
mod = __import__(import_path, fromlist=[func_name])
getattr(mod, func_name)()
except (ImportError, AttributeError):
pass
# Reset bundle_registry global distribution service to prevent xdist state leak
try:
import enhanced_agent_bus.bundle_registry as _br
_br._distribution_service = None
except (ImportError, AttributeError):
pass
@pytest.fixture(autouse=True)
def _disable_redis_rate_limiting(monkeypatch):
"""Disable Redis-backed rate limiting in all EnhancedAgentBus tests.
Redis requires authentication in this environment; tests that specifically
need rate limiting should override this fixture.
Constitutional Hash: cdd01ef066bc6cf2
"""
try:
from enhanced_agent_bus.bus.core import EnhancedAgentBus
_original_init = EnhancedAgentBus.__init__
def _patched_init(self, *args, **kwargs):
kwargs.setdefault("enable_rate_limiting", False)
kwargs.setdefault("allow_unstarted", True)
_original_init(self, *args, **kwargs)
monkeypatch.setattr(EnhancedAgentBus, "__init__", _patched_init)
# Also patch the re-exported reference in agent_bus module
try:
import enhanced_agent_bus.agent_bus as _ab_mod
monkeypatch.setattr(_ab_mod, "EnhancedAgentBus", EnhancedAgentBus)
except (ImportError, AttributeError):
pass
except (ImportError, AttributeError) as exc:
import warnings
warnings.warn(f"Failed to patch EnhancedAgentBus: {exc}", stacklevel=2)
@pytest.fixture(autouse=True)
def reset_global_state():
"""Reset global singletons before each test to prevent state pollution.
Constitutional Hash: cdd01ef066bc6cf2
"""
_reset_singletons()
# Reset runtime security scanner with Docker sandbox disabled
try:
import enhanced_agent_bus.runtime_security as _rt_sec
config = _rt_sec.RuntimeSecurityConfig(enable_runtime_guardrails=False)
_rt_sec._scanner = _rt_sec.RuntimeSecurityScanner(config)
except (ImportError, AttributeError):
pass
yield # Run the test
# Restore cached _ENVIRONMENT to the real OS value to prevent test pollution
try:
import enhanced_agent_bus.api.routes.messages as _msg_mod
_msg_mod._ENVIRONMENT = os.environ.get("ENVIRONMENT", "").lower()
except (ImportError, AttributeError):
pass
_reset_singletons()
# Pytest hook to reorder tests - run test_integration_coverage_expansion.py LAST
# to prevent its sys.modules pollution from affecting other tests
def pytest_collection_modifyitems(config, items):
"""Reorder test items to run polluting tests last.
The test_integration_coverage_expansion.py file uses _load_module to create
fresh module instances which pollutes sys.modules. Running it last prevents
it from affecting other test files.
Constitutional Hash: cdd01ef066bc6cf2
"""
regular_tests = []
polluting_tests = []
for item in items:
if "test_integration_coverage_expansion" in str(item.fspath):
polluting_tests.append(item)
else:
regular_tests.append(item)
items[:] = regular_tests + polluting_tests
# ─────────────────────────────────────────────────────────────────────────────
# Test API Key Fixture
# ─────────────────────────────────────────────────────────────────────────────
# Moved from api_key_auth.py to prevent hardcoded test key in production module
TEST_API_KEY = "test-api-key-for-unit-tests"
@pytest.fixture
def test_api_key():
"""Provide test API key for authentication tests."""
return TEST_API_KEY
@pytest.fixture(autouse=True)
def _disable_slowapi_limiter(monkeypatch: pytest.MonkeyPatch) -> None:
"""Disable slowapi's in-memory rate-limit storage between tests.
Tests using TestClient hit real endpoints with real rate limiting.
Running multiple tests against the same endpoint in sequence can exhaust
per-minute limits. Disabling the limiter avoids spurious 429 errors.
"""
try:
from enhanced_agent_bus.api.rate_limiting import limiter
monkeypatch.setattr(limiter, "enabled", False)
except ImportError:
pass

Xet Storage Details

Size:
18.3 kB
·
Xet hash:
945ad449a2c2b70ca416b2d84aab1705c7c7c6311dffaed6b22940f914f64808

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