hermes-agent/tests/tools/test_llm_content_none_guard.py
Teknium 39975613b1
test: prune wave 2 + speed fixes — 28,106 → 19,757 test functions, suite wall 315s → 294s
Second, deeper pass over tools/gateway/hermes_cli plus first pass over
the trees wave 1 missed (acp, acp_adapter, skills, computer_use, docker,
dashboard, conformance, monitoring, secret_sources, hermes_state,
providers). Same rubric as wave 1 (AGENTS.md test policy); security,
alternation/caching invariants, issue-number regressions, and E2E kept.

Real test-quality fixes found and rooted out along the way:
- tests/tools/test_command_guards.py made real auxiliary-LLM HTTPS calls
  (DEFAULT_CONFIG smart-approval leaked in) — pinned approval
  mode=manual via autouse fixture: 17.4s → 0.4s.
- test_model_switch_custom_providers.py / test_user_providers_model_switch.py
  silently probed live provider catalogs (~2s/test) — stubbed
  cached_provider_model_ids/provider_model_ids/fetch_api_models.
- test_telegram_noise_filter.py: 15-platform copy-paste matrix over
  shared gateway.run logic → 3 representative platforms (55s → 3.9s).
- test_gateway_shutdown.py: stop()'s 5s interrupt-deadline loop spun on
  MagicMock agents — interrupt.side_effect now clears _running_agents
  (22s → 1.0s).
- test_gateway_inactivity_timeout.py poll-harness timings shrunk 3-5x
  (24s → 1.1s); test_mcp_stability.py backoff/SIGTERM-grace sleeps
  patched (15.4s → 2.5s); test_async_delegation.py negative-drain wait
  5s → 0.5s.
- test_telegram_init_deadline.py: loop-block margin restored to 1.0s
  with rationale comment — the watchdog-dump assertion needs the loop
  blocked well past deadline+grace under parallel load (flaked once in
  the 40-worker verification run at a 0.2s margin).

Verification: full hermetic suite via scripts/run_tests.sh —
2,438 files, 21,718 tests passed, 0 failed, 293.9s wall.
Suite totals vs original baseline: 46,820 → 19,757 test functions
(−57.8%), wall 583.5s → 293.9s (−50%), subprocess CPU 13,564s → 11,623s.
2026-07-29 13:39:40 -07:00

179 lines
6.8 KiB
Python

"""Tests for None guard on response.choices[0].message.content.strip().
OpenAI-compatible APIs return ``message.content = None`` when the model
responds with tool calls only or reasoning-only output (e.g. DeepSeek-R1,
Qwen-QwQ via OpenRouter with ``reasoning.enabled = True``). Calling
``.strip()`` on ``None`` raises ``AttributeError``.
These tests verify that every call site handles ``content is None`` safely,
and that ``extract_content_or_reasoning()`` falls back to structured
reasoning fields when content is empty.
"""
import asyncio
import types
import pytest
from agent.auxiliary_client import extract_content_or_reasoning
# ── helpers ────────────────────────────────────────────────────────────────
def _make_response(content, **msg_attrs):
"""Build a minimal OpenAI-compatible ChatCompletion response stub.
Extra keyword args are set as attributes on the message object
(e.g. reasoning="...", reasoning_content="...", reasoning_details=[...]).
"""
message = types.SimpleNamespace(content=content, tool_calls=None, **msg_attrs)
choice = types.SimpleNamespace(message=message)
return types.SimpleNamespace(choices=[choice])
def _run(coro):
"""Run an async coroutine synchronously."""
return asyncio.get_event_loop().run_until_complete(coro)
# ── web_tools — LLM content processor (line 419) ─────────────────────────
class TestWebToolsProcessorContentNone:
"""tools/web_tools.py — _process_with_llm() return line"""
def test_none_content_raises_before_fix(self):
response = _make_response(None)
with pytest.raises(AttributeError):
response.choices[0].message.content.strip()
def test_none_content_safe_with_or_guard(self):
response = _make_response(None)
content = (response.choices[0].message.content or "").strip()
assert content == ""
# ── web_tools — synthesis/summarization (line 538) ────────────────────────
class TestWebToolsSynthesisContentNone:
"""tools/web_tools.py — synthesize_content() final_summary line"""
def test_none_content_raises_before_fix(self):
response = _make_response(None)
with pytest.raises(AttributeError):
response.choices[0].message.content.strip()
def test_none_content_safe_with_or_guard(self):
response = _make_response(None)
content = (response.choices[0].message.content or "").strip()
assert content == ""
# ── vision_tools (line 350) ───────────────────────────────────────────────
class TestVisionToolsContentNone:
"""tools/vision_tools.py — analyze_image() analysis extraction"""
def test_none_content_raises_before_fix(self):
response = _make_response(None)
with pytest.raises(AttributeError):
response.choices[0].message.content.strip()
def test_none_content_safe_with_or_guard(self):
response = _make_response(None)
content = (response.choices[0].message.content or "").strip()
assert content == ""
# ── skills_guard (line 963) ───────────────────────────────────────────────
class TestSkillsGuardContentNone:
"""tools/skills_guard.py — _llm_audit_skill() llm_text extraction"""
def test_none_content_raises_before_fix(self):
response = _make_response(None)
with pytest.raises(AttributeError):
response.choices[0].message.content.strip()
def test_none_content_safe_with_or_guard(self):
response = _make_response(None)
content = (response.choices[0].message.content or "").strip()
assert content == ""
# ── integration: verify the actual source lines are guarded ───────────────
class TestSourceLinesAreGuarded:
"""Read the actual source files and verify the fix is applied.
These tests will FAIL before the fix (bare .content.strip()) and
PASS after ((.content or "").strip()).
"""
@staticmethod
def _read_file(rel_path: str) -> str:
import os
base = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
with open(os.path.join(base, rel_path)) as f:
return f.read()
def test_web_tools_guarded(self):
src = self._read_file("tools/web_tools.py")
assert ".message.content.strip()" not in src, (
"tools/web_tools.py still has unguarded "
".content.strip() — apply `(... or \"\").strip()` guard"
)
def test_vision_tools_guarded(self):
src = self._read_file("tools/vision_tools.py")
assert ".message.content.strip()" not in src, (
"tools/vision_tools.py still has unguarded "
".content.strip() — apply `(... or \"\").strip()` guard"
)
def test_skills_guard_guarded(self):
src = self._read_file("tools/skills_guard.py")
assert ".message.content.strip()" not in src, (
"tools/skills_guard.py still has unguarded "
".content.strip() — apply `(... or \"\").strip()` guard"
)
# ── extract_content_or_reasoning() ────────────────────────────────────────
class TestExtractContentOrReasoning:
"""agent/auxiliary_client.py — extract_content_or_reasoning()"""
def test_normal_content_returned(self):
response = _make_response(" Hello world ")
assert extract_content_or_reasoning(response) == "Hello world"
def test_none_content_returns_empty(self):
response = _make_response(None)
assert extract_content_or_reasoning(response) == ""
def test_think_blocks_stripped_with_remaining_content(self):
response = _make_response("<think>internal reasoning</think>The answer is 42.")
assert extract_content_or_reasoning(response) == "The answer is 42."
def test_think_only_content_falls_back_to_reasoning_field(self):
"""When content is only think blocks, fall back to structured reasoning."""
response = _make_response(
"<think>some reasoning</think>",
reasoning="The actual reasoning output",
)
assert extract_content_or_reasoning(response) == "The actual reasoning output"
def test_content_preferred_over_reasoning(self):
"""When both content and reasoning exist, content wins."""
response = _make_response("Actual answer", reasoning="Internal reasoning")
assert extract_content_or_reasoning(response) == "Actual answer"