mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-07-31 19:16:29 +00:00
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.
223 lines
7.9 KiB
Python
223 lines
7.9 KiB
Python
"""Tests for the provider-agnostic streaming TTS backend (tools.tts_streaming)
|
|
and its dispatch through tools.tts_tool.stream_tts_to_speaker.
|
|
|
|
No live audio or network: the ElevenLabs/OpenAI SDKs, sounddevice, and the sync
|
|
synth path are all mocked. Covers the registry/resolver, provider availability,
|
|
the chunked-streamer playback path, and the universal per-sentence sync fallback.
|
|
"""
|
|
|
|
import queue
|
|
import threading
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
import tools.tts_streaming as ts
|
|
|
|
pytest.importorskip("numpy")
|
|
|
|
|
|
# ── SentenceChunker ──────────────────────────────────────────────────────
|
|
|
|
|
|
class TestSentenceChunker:
|
|
def test_cuts_sentence_the_moment_its_boundary_arrives(self):
|
|
c = ts.SentenceChunker()
|
|
assert c.feed("This is the first full") == []
|
|
assert c.feed(" sentence of it all. And") == ["This is the first full sentence of it all. "]
|
|
assert c.flush() == ["And"]
|
|
|
|
|
|
def test_think_blocks_are_stripped_even_across_deltas(self):
|
|
c = ts.SentenceChunker()
|
|
assert c.feed("<think>secret reason") == []
|
|
assert c.feed("ing</think>The actual spoken answer. ") == ["The actual spoken answer. "]
|
|
|
|
|
|
def test_paragraph_break_is_a_boundary(self):
|
|
c = ts.SentenceChunker()
|
|
assert c.feed("A paragraph without punctuation\n\nnext one") == [
|
|
"A paragraph without punctuation\n\n"
|
|
]
|
|
|
|
|
|
# ── Interruption latch ───────────────────────────────────────────────────
|
|
|
|
|
|
class TestSpeechInterruptedLatch:
|
|
def test_take_pops_and_reports_recent_barge(self):
|
|
ts.mark_speech_interrupted()
|
|
assert ts.take_speech_interrupted() is True
|
|
assert ts.take_speech_interrupted() is False # one-shot
|
|
|
|
|
|
def test_stale_barge_expires(self, monkeypatch):
|
|
ts.mark_speech_interrupted()
|
|
at = ts._interrupted_at
|
|
monkeypatch.setattr(ts.time, "monotonic", lambda: at + ts._INTERRUPT_TTL_S + 1)
|
|
assert ts.take_speech_interrupted() is False
|
|
|
|
|
|
# ── Registry + resolver ──────────────────────────────────────────────────
|
|
|
|
|
|
def _register_fake(monkeypatch, name, available=True, chunks=(b"\x00\x00",)):
|
|
class _Fake(ts.StreamingTTSProvider):
|
|
sample_rate = 24000
|
|
|
|
@staticmethod
|
|
def available():
|
|
return available
|
|
|
|
def stream(self, text):
|
|
yield from chunks
|
|
|
|
monkeypatch.setitem(ts._REGISTRY, name, _Fake)
|
|
return _Fake
|
|
|
|
|
|
def test_resolve_returns_configured_streamer(monkeypatch):
|
|
_register_fake(monkeypatch, "faketts")
|
|
prov = ts.resolve_streaming_provider({"provider": "faketts"})
|
|
assert isinstance(prov, ts.StreamingTTSProvider)
|
|
|
|
|
|
def test_never_swaps_provider_for_streaming(monkeypatch):
|
|
# A registered streamer must NOT be substituted when the user picked another
|
|
# (non-streaming) provider — that would silently change their voice.
|
|
_register_fake(monkeypatch, "elevenlabs")
|
|
assert ts.resolve_streaming_provider({"provider": "edge"}) is None
|
|
|
|
|
|
# ── Built-in provider availability ───────────────────────────────────────
|
|
|
|
|
|
def test_elevenlabs_available_reflects_key(monkeypatch):
|
|
# Key lookups now route through the provider-secret resolver
|
|
# (config > env/.env > credential pool), not bare get_env_value.
|
|
monkeypatch.setattr(ts, "_resolve_key", lambda env, pid: "key" if env == "ELEVENLABS_API_KEY" else "")
|
|
assert ts.ElevenLabsStreamer.available() is True
|
|
monkeypatch.setattr(ts, "_resolve_key", lambda env, pid: "")
|
|
assert ts.ElevenLabsStreamer.available() is False
|
|
|
|
|
|
def test_openai_available_reflects_audio_key_resolution(monkeypatch):
|
|
monkeypatch.setattr(ts, "_openai_config_api_key", lambda: "")
|
|
monkeypatch.setattr(ts, "resolve_openai_audio_api_key", lambda: "voice-key")
|
|
assert ts.OpenAIStreamer.available() is True
|
|
monkeypatch.setattr(ts, "resolve_openai_audio_api_key", lambda: "")
|
|
assert ts.OpenAIStreamer.available() is False
|
|
# tts.openai.api_key from config.yaml counts too
|
|
monkeypatch.setattr(ts, "_openai_config_api_key", lambda: "cfg-key")
|
|
assert ts.OpenAIStreamer.available() is True
|
|
|
|
|
|
def test_openai_streamer_prefers_configured_api_key(monkeypatch):
|
|
captured = {}
|
|
|
|
class _Response:
|
|
def __enter__(self):
|
|
return self
|
|
|
|
def __exit__(self, *_args):
|
|
return False
|
|
|
|
def iter_bytes(self):
|
|
yield b"\x01\x00"
|
|
|
|
class _StreamingCreate:
|
|
@staticmethod
|
|
def create(**kwargs):
|
|
return _Response()
|
|
|
|
class _OpenAI:
|
|
def __init__(self, **kwargs):
|
|
captured["client"] = kwargs
|
|
self.audio = MagicMock()
|
|
self.audio.speech.with_streaming_response = _StreamingCreate()
|
|
|
|
monkeypatch.setattr(ts, "resolve_openai_audio_api_key", lambda: "env-key")
|
|
monkeypatch.setattr(ts, "get_env_value", lambda key, *args: None)
|
|
monkeypatch.setattr("openai.OpenAI", _OpenAI)
|
|
|
|
config = {
|
|
"provider": "openai",
|
|
"openai": {"api_key": "cfg-key", "base_url": "http://local-tts.example/v1"},
|
|
}
|
|
streamer = ts.resolve_streaming_provider(config)
|
|
|
|
assert streamer is not None
|
|
assert list(streamer.stream("Streaming test.")) == [b"\x01\x00"]
|
|
assert captured["client"]["api_key"] == "cfg-key"
|
|
|
|
|
|
# ── Dispatch: chunked streamer path ──────────────────────────────────────
|
|
|
|
|
|
def _drain_queue(sentences):
|
|
q = queue.Queue()
|
|
for s in sentences:
|
|
q.put(s)
|
|
q.put(None)
|
|
return q
|
|
|
|
|
|
def _sd_mock():
|
|
sd = MagicMock()
|
|
out = MagicMock()
|
|
sd.OutputStream.return_value = out
|
|
return sd, out
|
|
|
|
|
|
# ── Dispatch: universal per-sentence sync fallback ───────────────────────
|
|
|
|
|
|
# ── tts.streaming.provider config knob (salvaged from PR #47588) ─────────
|
|
|
|
|
|
# ── Credential routing: resolve_provider_secret, never bare env ──────────
|
|
|
|
|
|
def test_elevenlabs_available_routes_through_secret_resolver(monkeypatch):
|
|
calls = []
|
|
|
|
def _fake_resolve(env_var, provider_id):
|
|
calls.append((env_var, provider_id))
|
|
return "pool-key"
|
|
|
|
monkeypatch.setattr(ts, "_resolve_key", _fake_resolve)
|
|
assert ts.ElevenLabsStreamer.available() is True
|
|
assert ("ELEVENLABS_API_KEY", "elevenlabs") in calls
|
|
|
|
|
|
def test_xai_available_uses_oauth_credential_resolver(monkeypatch):
|
|
import sys
|
|
import types
|
|
|
|
fake = types.ModuleType("tools.xai_http")
|
|
fake.resolve_xai_http_credentials = lambda: {"api_key": "xai-key"}
|
|
monkeypatch.setitem(sys.modules, "tools.xai_http", fake)
|
|
assert ts.XAIStreamer.available() is True
|
|
fake.resolve_xai_http_credentials = lambda: {"api_key": ""}
|
|
assert ts.XAIStreamer.available() is False
|
|
|
|
|
|
# ── Gemini SSE parsing ────────────────────────────────────────────────────
|
|
|
|
|
|
# ── xAI WebSocket bridge ─────────────────────────────────────────────────
|
|
|
|
|
|
# ── 16 MiB per-sentence stream cap ───────────────────────────────────────
|
|
|
|
|
|
def test_stream_cap_truncates_runaway_upstream(monkeypatch):
|
|
monkeypatch.setattr(ts, "_STREAM_SENTENCE_BYTE_CAP", 100)
|
|
|
|
def _endless():
|
|
while True:
|
|
yield b"\x00" * 64
|
|
|
|
out = list(ts._capped(_endless(), "test"))
|
|
assert len(out) == 1 # 64 ok, 128 > cap → stop
|
|
assert sum(len(c) for c in out) <= 100
|