Files
hermes-agent/tests/agent/test_strict_api_validation.py
teknium1 d10bb2ab6f test: make tests/ mirror the source tree; drop issue numbers from filenames
`scripts/run_tests.sh tests/<dir>/` is how a change gets its regression
coverage run, so a test filed under the wrong directory is a test nobody
runs when that code changes. Two kinds of drift had accumulated.

Parallel directories for one source package, folded into the mirror:
  tests/acp        -> tests/acp_adapter   (its __init__/conftest move with it)
  tests/cli        -> tests/hermes_cli    (prompt_toolkit fixture merged into
                                           hermes_cli/conftest.py)
  tests/run_agent  -> tests/agent         (backoff fixture becomes
                                           agent/conftest.py)
  tests/relay      -> tests/gateway/relay
  tests/state      -> tests/hermes_state

246 loose files at tests/ root, routed by the package they import/patch:
hermes_cli, hermes_state, agent, gateway, tools, plugins, tui_gateway, cron.
Installer and desktop-update script tests go to tests/scripts/{install,
desktop_update}/. 43 tests of root-level modules (batch_runner, utils,
hermes_constants, packaging) stay at the root.

Filenames drop their issue numbers (95 files: test_89315_x.py -> test_x.py);
the number stays in the module docstring where it has context.

Collisions: test_cli_skin_integration.py existed in both tests/ and tests/cli
with different subsets — merged into one (10 tests, all kept);
run_agent/test_pre_compress_memory_context.py -> agent/..._handoff.py;
tests/test_account_usage.py -> agent/test_account_usage_fetch.py;
tests/test_web_server.py -> hermes_cli/test_web_server_ws_ping.py.
Deleted: test_minisweagent_path.py (empty since PR #2804),
test_model_picker_scroll.py (tested a private copy of the logic, imported
nothing), test_process_loop_event_loop_warning.py (asserted asyncio behaviour,
imported nothing from Hermes).

Repo-root path arithmetic (Path(__file__).parents[N], dirname chains) is
bumped for the 202 files that changed depth and verified by evaluating every
such expression against the new location. classify_changes' desktop-updater
lane prefix, tests-os.yml's ignore glob and every in-tree path comment follow
the moves. tests/test_tests_tree_layout.py keeps the tree from drifting back.
2026-09-13 09:18:02 -07:00

132 lines
4.6 KiB
Python

"""Test validation error prevention for strict APIs (Fireworks, etc.)"""
import sys
import types
sys.modules.setdefault("fire", types.SimpleNamespace(Fire=lambda *a, **k: None))
sys.modules.setdefault("firecrawl", types.SimpleNamespace(Firecrawl=object))
sys.modules.setdefault("fal_client", types.SimpleNamespace())
from run_agent import AIAgent
# ── Helpers ──────────────────────────────────────────────────────────────────
def _tool_defs(*names):
return [
{
"type": "function",
"function": {
"name": n,
"description": f"{n} tool",
"parameters": {"type": "object", "properties": {}},
},
}
for n in names
]
class _FakeOpenAI:
def __init__(self, **kw):
self.api_key = kw.get("api_key", "test")
self.base_url = kw.get("base_url", "http://test")
def close(self):
pass
def _make_agent(monkeypatch, provider, api_mode="chat_completions", base_url="https://openrouter.ai/api/v1"):
monkeypatch.setattr("model_tools.get_tool_definitions", lambda **kw: _tool_defs("web_search", "terminal"))
monkeypatch.setattr("model_tools.check_toolset_requirements", lambda: {})
monkeypatch.setattr("agent.process_bootstrap.OpenAI", _FakeOpenAI)
return AIAgent(
api_key="test",
base_url=base_url,
provider=provider,
api_mode=api_mode,
max_iterations=4,
quiet_mode=True,
skip_context_files=True,
skip_memory=True,
)
class TestStrictApiValidation:
"""Verify tool_call field sanitization prevents 400 errors on strict APIs."""
def test_fireworks_compatible_messages_after_sanitization(self, monkeypatch):
"""Messages should be Fireworks-compatible after sanitization."""
agent = _make_agent(monkeypatch, "openrouter")
agent.api_mode = "chat_completions" # Fireworks uses chat completions
messages = [
{"role": "user", "content": "hi"},
{
"role": "assistant",
"content": "Checking now.",
"tool_calls": [
{
"id": "call_123",
"call_id": "call_123", # Codex-only field
"response_item_id": "fc_123", # Codex-only field
"type": "function",
"function": {"name": "terminal", "arguments": '{"command":"pwd"}'},
}
],
},
{"role": "tool", "tool_call_id": "call_123", "content": "/tmp"},
]
# After _build_api_kwargs, Codex fields should be stripped
kwargs = agent._build_api_kwargs(messages)
assistant_msg = kwargs["messages"][1]
tool_call = assistant_msg["tool_calls"][0]
# Fireworks rejects these fields
assert "call_id" not in tool_call
assert "response_item_id" not in tool_call
# Standard fields should remain
assert tool_call["id"] == "call_123"
assert tool_call["function"]["name"] == "terminal"
def test_codex_preserves_fields_for_replay(self, monkeypatch):
"""Codex mode should preserve fields for Responses API replay."""
agent = _make_agent(monkeypatch, "openrouter")
agent.api_mode = "codex_responses"
messages = [
{"role": "user", "content": "hi"},
{
"role": "assistant",
"content": "Checking now.",
"tool_calls": [
{
"id": "call_123",
"call_id": "call_123",
"response_item_id": "fc_123",
"type": "function",
"function": {"name": "terminal", "arguments": '{"command":"pwd"}'},
}
],
},
]
# In Codex mode, original messages should NOT be mutated
assert messages[1]["tool_calls"][0]["call_id"] == "call_123"
assert messages[1]["tool_calls"][0]["response_item_id"] == "fc_123"
def test_sanitize_method_with_fireworks_provider(self, monkeypatch):
"""Simulating Fireworks provider should trigger sanitization."""
agent = _make_agent(
monkeypatch,
"fireworks",
api_mode="chat_completions",
base_url="https://api.fireworks.ai/inference/v1"
)
# Should sanitize for Fireworks (chat_completions mode)
assert agent._should_sanitize_tool_calls() is True