Files
ewoooc/tests/test_elephant_alpha_engine.py
OoO 6788379d10
All checks were successful
CD Pipeline / deploy (push) Successful in 1m2s
抑制 EA 無實證空告警
2026-05-19 13:04:01 +08:00

162 lines
5.3 KiB
Python

import asyncio
import logging
def test_run_with_timeout_supports_sync_function():
from services.elephant_alpha_autonomous_engine import ElephantAlphaAutonomousEngine
result = asyncio.run(ElephantAlphaAutonomousEngine._run_with_timeout(lambda value: value + 1, 41))
assert result == 42
def test_execute_step_rejects_unknown_action():
from services.elephant_alpha_autonomous_engine import ElephantAlphaAutonomousEngine
engine = ElephantAlphaAutonomousEngine()
try:
asyncio.run(engine._execute_step({"agent": "mystery", "action": "do_anything"}))
except ValueError as exc:
assert "Unrecognized step" in str(exc)
else:
raise AssertionError("unknown action should fail")
def test_execute_step_routes_code_fix_to_autoheal(monkeypatch):
from services.elephant_alpha_autonomous_engine import ElephantAlphaAutonomousEngine
calls = []
engine = ElephantAlphaAutonomousEngine()
monkeypatch.setattr(
engine,
"_run_auto_heal",
lambda error_type, context: calls.append((error_type, context)) or {"ok": True},
)
asyncio.run(engine._execute_step({
"agent": "elephant_alpha",
"action": "code_fix",
"parameters": {"target_file": "services/example.py", "error_message": "Traceback"},
}))
assert calls == [("python_exception", {"target_file": "services/example.py", "error_message": "Traceback"})]
def test_execute_step_routes_price_adjustment_to_human_review(monkeypatch):
from services.elephant_alpha_autonomous_engine import ElephantAlphaAutonomousEngine
calls = []
engine = ElephantAlphaAutonomousEngine()
monkeypatch.setattr(
engine,
"_record_price_adjustment_review",
lambda step: calls.append(step) or {"status": "pending_review", "sku": "SKU-9"},
)
result = asyncio.run(engine._execute_step({
"agent": "nemotron",
"action": "execute_price_adjustment",
"parameters": {"sku": "SKU-9", "recommended_price": 1280},
}))
assert result == {"status": "pending_review", "sku": "SKU-9"}
assert calls[0]["parameters"]["recommended_price"] == 1280
def test_execute_step_skips_legacy_openclaw_resource_strategy():
from services.elephant_alpha_autonomous_engine import ElephantAlphaAutonomousEngine
engine = ElephantAlphaAutonomousEngine()
result = asyncio.run(engine._execute_step({
"agent": "openclaw",
"action": "generate_resource_optimization_strategy",
}))
assert result is None
def test_autoheal_derives_python_exception_from_traceback():
from services.auto_heal_service import AutoHealService
svc = AutoHealService()
assert svc._derive_error_type({"traceback_str": "Traceback (most recent call last):\nNameError"}) == "python_exception"
def test_execute_autonomous_decision_logs_short_circuit_telemetry_failure(monkeypatch, caplog):
from services.elephant_alpha_autonomous_engine import (
AutonomousTrigger,
ElephantAlphaAutonomousEngine,
)
import services.ai_call_logger as ai_call_logger
engine = ElephantAlphaAutonomousEngine()
async def _no_hermes_threats(top_n=5):
return None
def _broken_log_ai_call(*args, **kwargs):
raise RuntimeError("ai telemetry unavailable")
monkeypatch.setattr(engine, "_fetch_hermes_threats_summary", _no_hermes_threats)
monkeypatch.setattr(ai_call_logger, "log_ai_call", _broken_log_ai_call)
caplog.set_level(logging.WARNING, logger="services.elephant_alpha_autonomous_engine")
trigger = AutonomousTrigger(
trigger_type="price_drop_alert",
conditions={},
threshold=0.8,
enabled=True,
)
asyncio.run(engine._execute_autonomous_decision(trigger))
assert "EA short-circuit telemetry failed" in caplog.text
def test_escalate_resource_optimization_without_evidence_is_suppressed(monkeypatch):
import services.elephant_alpha_autonomous_engine as engine_module
from services.elephant_alpha_autonomous_engine import (
AutonomousTrigger,
ElephantAlphaAutonomousEngine,
)
from services.elephant_alpha_orchestrator import StrategicDecision
engine = ElephantAlphaAutonomousEngine()
suppressed = []
cooldown = []
def _raise_if_db_opened():
raise AssertionError("no-concrete resource escalation should not write human_review")
monkeypatch.setattr(engine_module, "get_session", _raise_if_db_opened)
monkeypatch.setattr(engine, "_store_escalation", lambda trigger_type: cooldown.append(trigger_type))
monkeypatch.setattr(
engine,
"_record_suppressed_escalation",
lambda decision, trigger, reason: suppressed.append((trigger.trigger_type, reason)),
)
decision = StrategicDecision(
priority="medium",
agents_required=["openclaw"],
reasoning="資源調配建議信心不足",
expected_outcome="待人工確認",
confidence=0.60,
execution_plan=[],
resource_requirements={},
)
trigger = AutonomousTrigger(
trigger_type="resource_optimization",
conditions={"_resource_metrics": {"action_queue_size": 14, "system_load_pct": 52.0}},
threshold=0.6,
enabled=True,
)
asyncio.run(engine._escalate_to_human(decision, trigger))
assert cooldown == ["resource_optimization"]
assert suppressed == [("resource_optimization", "no_concrete_evidence")]