# Conflicts: # apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts # apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts # apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts # apps/desktop/e2e/bot-mode-roster-localized.spec.ts # apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts # apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts # apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts # apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts # apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts # apps/desktop/e2e/bot-roster-user-sections.spec.ts # apps/desktop/e2e/bot-routines-pane-narrow.spec.ts # apps/desktop/e2e/bot-row-open-recent-session.spec.ts # apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts # apps/desktop/e2e/group-composer-auto-grow.spec.ts # apps/desktop/e2e/group-create-gate-remote-roster.spec.ts # apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts # apps/desktop/e2e/hosted-room-backend-continuity.spec.ts # apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts # apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts # apps/desktop/e2e/worktree-branch-status.spec.ts # apps/desktop/electron/backend-probes.test.ts # apps/desktop/electron/connection-apply.test.ts # apps/desktop/electron/desktop-electron-pin.test.ts # apps/desktop/electron/desktop-uninstall.test.ts # apps/desktop/electron/gateway-file-download-transport.test.ts # apps/desktop/electron/gateway-stop-before-update.test.ts # apps/desktop/electron/github-api-auth.test.ts # apps/desktop/electron/registry-primary-profile-scope.test.ts # apps/desktop/electron/update-api-check.test.ts # apps/desktop/electron/update-handoff-marker.test.ts # apps/desktop/electron/venv-blocker-scan.test.ts # apps/desktop/scripts/after-extract.test.mjs # apps/desktop/scripts/local-pack-publish.test.mjs # apps/desktop/scripts/tasks-scroll.test.mjs # apps/desktop/src/app/settings/model-settings.test.tsx # apps/desktop/src/app/updates-overlay.blockers.test.tsx # apps/desktop/src/components/desktop-install-overlay.test.tsx # apps/desktop/src/lib/update-copy.test.ts # scripts/ci/check_os_marker_fakes.py # tests-js/desktop-mac-usage-descriptions.test.ts # tests-js/node-engine-alignment.test.ts # tests/agent/lsp/test_install_and_lint_fixes.py # tests/agent/test_command_token_source.py # tests/agent/test_compression_boundary_hook.py # tests/agent/test_create_openai_client_ssl_verify.py # tests/agent/test_custom_provider_ca_probes.py # tests/agent/test_endpoint_blackhole.py # tests/agent/test_estimator_parity.py # tests/agent/test_in_place_compaction.py # tests/agent/test_moa_loop_mode.py # tests/agent/test_model_metadata.py # tests/agent/test_skill_session_platform_gate.py # tests/agent/test_skill_utils.py # tests/agent/test_ssl_ca_guard.py # tests/computer_use/test_doctor.py # tests/cron/test_codex_execution_paths.py # tests/cron/test_cron_bot_chat_delivery.py # tests/cron/test_cron_script.py # tests/cron/test_media_delivery_parity.py # tests/cron/test_misfire_catchup.py # tests/cron/test_parallel_pool.py # tests/cron/test_recurring_eagain_redispatch.py # tests/gateway/test_choice_picker.py # tests/gateway/test_control_socket_windows_live.py # tests/gateway/test_dingtalk.py # tests/gateway/test_feishu.py # tests/gateway/test_feishu_onboard.py # tests/gateway/test_gateway_shutdown.py # tests/gateway/test_matrix.py # tests/gateway/test_model_command_custom_providers.py # tests/gateway/test_reasoning_command.py # tests/gateway/test_runtime_footer.py # tests/gateway/test_session.py # tests/gateway/test_session_hygiene.py # tests/gateway/test_status.py # tests/gateway/test_teams.py # tests/gateway/test_turn_lease.py # tests/gateway/test_whatsapp_connect.py # tests/hermes_cli/test_approvals_command.py # tests/hermes_cli/test_auth_store_lock_concurrent.py # tests/hermes_cli/test_backup.py # tests/hermes_cli/test_banner_git_state.py # tests/hermes_cli/test_certifi_repair.py # tests/hermes_cli/test_cmd_update.py # tests/hermes_cli/test_compat_manifest_targets.py # tests/hermes_cli/test_computer_use_cli.py # tests/hermes_cli/test_cpr_local_leak.py # tests/hermes_cli/test_dashboard_auth_gate.py # tests/hermes_cli/test_dashboard_procs_kill_grace.py # tests/hermes_cli/test_desktop_lifecycle_windows_live.py # tests/hermes_cli/test_doctor.py # tests/hermes_cli/test_doctor_command_install.py # tests/hermes_cli/test_fleet_config_migration_windows_live.py # tests/hermes_cli/test_gateway.py # tests/hermes_cli/test_gateway_platform_gating.py # tests/hermes_cli/test_gateway_restart_loop.py # tests/hermes_cli/test_gateway_task_probe.py # tests/hermes_cli/test_gateway_wsl.py # tests/hermes_cli/test_gui_command.py # tests/hermes_cli/test_install_cua_driver.py # tests/hermes_cli/test_kanban_db.py # tests/hermes_cli/test_lazy_command_exports.py # tests/hermes_cli/test_lazy_refresh_venv_repair.py # tests/hermes_cli/test_linux_desktop_entry.py # tests/hermes_cli/test_local_runtime.py # tests/hermes_cli/test_local_runtime_updates.py # tests/hermes_cli/test_managed_uv.py # tests/hermes_cli/test_mcp_reload_confirm_gate.py # tests/hermes_cli/test_nous_subscription.py # tests/hermes_cli/test_npm_engine.py # tests/hermes_cli/test_personality_none.py # tests/hermes_cli/test_pet_toggle.py # tests/hermes_cli/test_plan_reconciliation_windows_live.py # tests/hermes_cli/test_plugin_event_bus.py # tests/hermes_cli/test_plugin_manifest_v2.py # tests/hermes_cli/test_plugin_packs.py # tests/hermes_cli/test_plugins_cmd.py # tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py # tests/hermes_cli/test_process_identity.py # tests/hermes_cli/test_profiles.py # tests/hermes_cli/test_profiles_sidebar_cache.py # tests/hermes_cli/test_pty_bridge.py # tests/hermes_cli/test_resolve_turn_limit.py # tests/hermes_cli/test_serve_runtime_inventory.py # tests/hermes_cli/test_session_vacuum_config.py # tests/hermes_cli/test_set_config_value.py # tests/hermes_cli/test_signal_handler_kanban_worker.py # tests/hermes_cli/test_slash_confirm_windows.py # tests/hermes_cli/test_stale_pid_guard.py # tests/hermes_cli/test_startup_fast_guards.py # tests/hermes_cli/test_status.py # tests/hermes_cli/test_telegram_managed_bot.py # tests/hermes_cli/test_tools_config.py # tests/hermes_cli/test_update_apply_shallow_count.py # tests/hermes_cli/test_update_autostash.py # tests/hermes_cli/test_update_concurrent_quarantine.py # tests/hermes_cli/test_update_fetch_failure_classifier.py # tests/hermes_cli/test_update_fleet_probe_resume_token.py # tests/hermes_cli/test_update_handoff_backend_reap.py # tests/hermes_cli/test_update_handoff_desktop_rebuild.py # tests/hermes_cli/test_update_head_moved_gate.py # tests/hermes_cli/test_update_host_obligation.py # tests/hermes_cli/test_update_import_guard.py # tests/hermes_cli/test_update_interrupted_recovery.py # tests/hermes_cli/test_update_inventory.py # tests/hermes_cli/test_update_launchd_unloaded_gateway.py # tests/hermes_cli/test_update_missing_configured_deps.py # tests/hermes_cli/test_update_modified_notice.py # tests/hermes_cli/test_update_multiplex_migration_hook.py # tests/hermes_cli/test_update_no_gateway_restart.py # tests/hermes_cli/test_update_orphan_backend_reap.py # tests/hermes_cli/test_update_parked_branch_guard.py # tests/hermes_cli/test_update_post_pull_syntax_guard.py # tests/hermes_cli/test_update_receipt.py # tests/hermes_cli/test_update_self_lock.py # tests/hermes_cli/test_update_shim_fail_closed.py # tests/hermes_cli/test_update_shim_self_lock.py # tests/hermes_cli/test_update_sqlite_remediation.py # tests/hermes_cli/test_update_stale_dashboard.py # tests/hermes_cli/test_update_stale_virtualenv.py # tests/hermes_cli/test_update_venv_health.py # tests/hermes_cli/test_update_venv_ownership_preflight.py # tests/hermes_cli/test_update_wedged_gateway.py # tests/hermes_cli/test_update_yes_flag.py # tests/hermes_cli/test_update_zip_two_phase.py # tests/hermes_cli/test_urllib_security.py # tests/hermes_cli/test_ux_messages_auth_config.py # tests/hermes_cli/test_ux_messages_startup.py # tests/hermes_cli/test_venv_holder_classifier.py # tests/hermes_cli/test_verify_console_scripts.py # tests/hermes_cli/test_verify_core_dependencies.py # tests/hermes_cli/test_web_server.py # tests/hermes_cli/test_web_server_console_ws.py # tests/hermes_cli/test_web_server_ws_ping.py # tests/hermes_cli/test_web_ui_build.py # tests/hermes_state/test_fts_rebuild_admission.py # tests/hermes_state/test_hermes_state.py # tests/plugins/memory/test_memory_lazy_install.py # tests/plugins/test_google_meet_plugin.py # tests/plugins/test_langfuse_plugin.py # tests/plugins/test_security_guidance_plugin.py # tests/plugins/test_transform_llm_output_hook.py # tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py # tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py # tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py # tests/scripts/install/test_install_clone_throttle_fallback.py # tests/scripts/install/test_install_lockfile_churn.py # tests/scripts/install/test_install_no_initial_commit.py # tests/scripts/install/test_install_sh_browser_install.py # tests/scripts/install/test_install_sh_node_prerelease.py # tests/scripts/install/test_install_sh_symlink_stomp.py # tests/scripts/install/test_install_sh_uv_lock_config.py # tests/scripts/install/test_install_unmerged_index.py # tests/scripts/test_contributor_map.py # tests/scripts/test_run_tests_parallel.py # tests/skills/test_competitor_news_monitor_skill.py # tests/skills/test_document_to_action_items_skill.py # tests/skills/test_google_workspace_setup.py # tests/skills/test_google_workspace_setup_deps.py # tests/skills/test_grounded_citations_skill.py # tests/skills/test_ip_as_logo_skill.py # tests/skills/test_live_dashboard_skill.py # tests/skills/test_mcp_oauth_remote_gateway_skill.py # tests/skills/test_office_document_skills.py # tests/skills/test_openclaw_migration.py # tests/skills/test_product_price_monitor_skill.py # tests/skills/test_scrollcraft_skill.py # tests/skills/test_setup_wizard_generator_skill.py # tests/skills/test_weekly_review_planning_skill.py # tests/test_engines_satisfiable.py # tests/test_fast_safe_load.py # tests/test_hermes_bootstrap.py # tests/test_hermes_constants.py # tests/test_hermes_logging.py # tests/test_managed_runtime_resolution.py # tests/test_model_tools_async_bridge.py # tests/test_packaging_build_guard.py # tests/test_packaging_metadata.py # tests/test_yaml_indent_consistency.py # tests/tools/test_approval_timeout_overflow.py # tests/tools/test_base_environment.py # tests/tools/test_bot_mode_dm.py # tests/tools/test_browser_chromium_check.py # tests/tools/test_browser_hardening.py # tests/tools/test_browser_homebrew_paths.py # tests/tools/test_browser_npx_warmup.py # tests/tools/test_browser_orphan_reaper.py # tests/tools/test_browser_real_profile.py # tests/tools/test_browser_use_cli.py # tests/tools/test_clipboard.py # tests/tools/test_code_execution.py # tests/tools/test_code_execution_modes.py # tests/tools/test_code_execution_windows_env.py # tests/tools/test_computer_use.py # tests/tools/test_delegate_liveness_timeout.py # tests/tools/test_execute_code_approval_cluster.py # tests/tools/test_execution_flag_detection.py # tests/tools/test_fal_common.py # tests/tools/test_file_operations.py # tests/tools/test_file_tools.py # tests/tools/test_file_tools_cwd_resolution.py # tests/tools/test_file_tools_live.py # tests/tools/test_lazy_deps.py # tests/tools/test_lazy_deps_durable_target.py # tests/tools/test_lazy_deps_managed.py # tests/tools/test_local_env_blocklist.py # tests/tools/test_local_tempdir.py # tests/tools/test_macos_protected_search.py # tests/tools/test_mcp_npx_cached_bin.py # tests/tools/test_oneshot_completion_linger.py # tests/tools/test_process_registry.py # tests/tools/test_read_file_schema_gating.py # tests/tools/test_skill_improvements.py # tests/tools/test_skills_sync.py # tests/tools/test_termux_api_detection.py # tests/tools/test_tirith_security.py # tests/tools/test_transcription_tools.py # tests/tools/test_tts_streaming.py # tests/tools/test_wake_word.py # tests/tui_gateway/test_compute_host_borrowed_lease.py # tests/tui_gateway/test_compute_host_turn_protocol.py # tests/tui_gateway/test_isolated_orphan_activity.py # tests/tui_gateway/test_protocol.py # tests/tui_gateway/test_slash_worker_profile_home.py # tests/tui_gateway/test_subprocess_encoding.py # tests/tui_gateway/test_tui_gateway_server.py # ui-tui/src/__tests__/terminalParity.test.ts # ui-tui/src/__tests__/termuxComposerLayout.test.ts # ui-tui/src/__tests__/textInputFastEcho.test.ts
462 lines
17 KiB
Python
462 lines
17 KiB
Python
"""Tests for the ``hermes send`` CLI subcommand.
|
|
|
|
Covers the argument parsing / stdin / file / list behavior of
|
|
``hermes_cli.send_cmd``. The underlying ``send_message_tool`` is stubbed so
|
|
no network I/O or gateway is required.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import pytest
|
|
|
|
from hermes_cli import send_cmd
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _parse(argv):
|
|
"""Build the top-level parser and return the parsed args for ``argv``."""
|
|
import argparse
|
|
|
|
parser = argparse.ArgumentParser(prog="hermes")
|
|
subparsers = parser.add_subparsers(dest="command")
|
|
send_cmd.register_send_subparser(subparsers)
|
|
return parser.parse_args(["send", *argv])
|
|
|
|
class _FakeTool:
|
|
"""Replacement for ``tools.send_message_tool.send_message_tool``."""
|
|
|
|
def __init__(self, payload):
|
|
self.payload = payload
|
|
self.calls = []
|
|
|
|
def __call__(self, args, **_kw):
|
|
self.calls.append(dict(args))
|
|
return json.dumps(self.payload)
|
|
|
|
@pytest.fixture
|
|
def fake_tool(monkeypatch):
|
|
"""Install a fake send_message_tool and return the stub for inspection."""
|
|
import sys
|
|
import types
|
|
|
|
fake = _FakeTool({"success": True, "message_id": "m123"})
|
|
|
|
mod = types.ModuleType("tools.send_message_tool")
|
|
mod.send_message_tool = fake
|
|
# Register the stub so ``from tools.send_message_tool import ...`` inside
|
|
# cmd_send resolves to our fake. Also patch the parent ``tools`` package
|
|
# entry so attribute lookup works.
|
|
monkeypatch.setitem(sys.modules, "tools.send_message_tool", mod)
|
|
return fake
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Happy path
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@pytest.fixture
|
|
def whatsapp_bridge(monkeypatch):
|
|
"""Route ``hermes send --to whatsapp:...`` through the real plugin standalone sender into a fake
|
|
bridge; returns the recorded ``(path, payload)`` posts and a mutable ``supports_mentions`` flag."""
|
|
import asyncio
|
|
from types import SimpleNamespace
|
|
|
|
import aiohttp
|
|
|
|
from gateway.config import Platform
|
|
from hermes_cli.plugins import discover_plugins
|
|
|
|
calls = []
|
|
state = {"supports_mentions": True}
|
|
|
|
class BridgeResponse:
|
|
status = 200
|
|
|
|
def __init__(self, *, health=False):
|
|
self.health = health
|
|
|
|
async def json(self):
|
|
if self.health:
|
|
return {"capabilities": {"outboundMentions": state["supports_mentions"]}}
|
|
return {"messageId": f"m{len(calls)}"}
|
|
|
|
async def text(self):
|
|
return ""
|
|
|
|
async def __aenter__(self):
|
|
return self
|
|
|
|
async def __aexit__(self, *_args):
|
|
return False
|
|
|
|
class BridgeSession:
|
|
async def __aenter__(self):
|
|
return self
|
|
|
|
async def __aexit__(self, *_args):
|
|
return False
|
|
|
|
def get(self, url, *, timeout):
|
|
return BridgeResponse(health=True)
|
|
|
|
def post(self, url, *, json, timeout):
|
|
calls.append((url.rsplit("/", 1)[-1], json))
|
|
return BridgeResponse()
|
|
|
|
discover_plugins()
|
|
config = SimpleNamespace(
|
|
platforms={Platform.WHATSAPP: SimpleNamespace(enabled=True, token=None, extra={"bridge_port": 3000})},
|
|
get_home_channel=lambda _platform: None,
|
|
)
|
|
monkeypatch.setattr(send_cmd, "_load_hermes_env", lambda: None)
|
|
monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)
|
|
monkeypatch.setattr("tools.interrupt.is_interrupted", lambda: False)
|
|
monkeypatch.setattr("model_tools._run_async", lambda coro: asyncio.run(coro))
|
|
monkeypatch.setattr("tools.send_message_tool._mirror_sent_message", lambda *_args: False)
|
|
monkeypatch.setattr(aiohttp, "ClientSession", lambda *_args, **_kwargs: BridgeSession())
|
|
return SimpleNamespace(calls=calls, state=state)
|
|
|
|
_GROUP = "whatsapp:120363000000000000@g.us"
|
|
|
|
@pytest.mark.parametrize("argv", [
|
|
["--to", "telegram", "--mention", "15550000001", "hello"],
|
|
["--to", _GROUP, "--mention", "not-a-phone", "hello"],
|
|
["--to", _GROUP, "--mention", "\u0661\u0665\u0665\u0665\u0660\u0660\u0660\u0660\u0660\u0660\u0661", "hello"],
|
|
["--to", _GROUP, "--mention", "\u0661\u0665\u0665\u0665\u0660\u0660\u0660\u0660\u0660\u0660\u0661@s.whatsapp.net", "hello"],
|
|
])
|
|
def test_whatsapp_mention_rejections_never_reach_the_bridge(whatsapp_bridge, capsys, argv):
|
|
"""Non-WhatsApp targets and non-ASCII / non-numeric mention values are usage errors (exit 2)
|
|
raised before any delivery attempt."""
|
|
with pytest.raises(SystemExit) as exc:
|
|
send_cmd.cmd_send(_parse(argv))
|
|
assert exc.value.code == 2
|
|
assert "mention" in capsys.readouterr().err.lower()
|
|
assert whatsapp_bridge.calls == []
|
|
|
|
def test_whatsapp_mentions_ride_the_first_bridge_payload_only(whatsapp_bridge, tmp_path, capsys):
|
|
"""Across chunked text and text+media, exactly one bridge payload carries the normalized,
|
|
deduplicated JIDs; a captioned single-media send carries them on the media payload; a bridge
|
|
without native-mention support fails closed instead of silently sending an unmentioned message."""
|
|
calls = whatsapp_bridge.calls
|
|
image = tmp_path / "photo.png"
|
|
image.write_bytes(b"\x89PNG\r\n\x1a\n")
|
|
long_message = "@15550000001 " + "word " * 1000
|
|
|
|
with pytest.raises(SystemExit) as exc:
|
|
send_cmd.cmd_send(_parse([
|
|
"--to", _GROUP, "--mention", "+1 (555) 000-0001", "--mention", "15550000001@s.whatsapp.net",
|
|
f"{long_message} MEDIA:{image}",
|
|
]))
|
|
assert exc.value.code == 0
|
|
text_payloads = [payload for path, payload in calls if path == "send"]
|
|
assert len(text_payloads) >= 2 and calls[-1][0] == "send-media"
|
|
assert text_payloads[0]["mentions"] == ["15550000001@s.whatsapp.net"]
|
|
assert all("mentions" not in payload for _, payload in calls[1:])
|
|
|
|
calls.clear()
|
|
with pytest.raises(SystemExit) as exc:
|
|
send_cmd.cmd_send(_parse(["--to", _GROUP, "--mention", "15550000001", f"hello @15550000001 MEDIA:{image}"]))
|
|
assert exc.value.code == 0
|
|
assert [path for path, _ in calls] == ["send-media"]
|
|
assert calls[0][1]["mentions"] == ["15550000001@s.whatsapp.net"]
|
|
|
|
calls.clear()
|
|
whatsapp_bridge.state["supports_mentions"] = False
|
|
with pytest.raises(SystemExit) as exc:
|
|
send_cmd.cmd_send(_parse(["--to", _GROUP, "--mention", "15550000001", "hello @15550000001"]))
|
|
assert exc.value.code == 1
|
|
assert "does not support native mentions" in capsys.readouterr().err
|
|
assert calls == []
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# --list
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def test_list_includes_configured_platform_without_discovered_channels(
|
|
monkeypatch, capsys
|
|
):
|
|
"""A configured platform absent from the channel directory must still be
|
|
listed (with a no-channels hint) instead of silently omitted."""
|
|
import types
|
|
import sys
|
|
|
|
class _FakePlatform:
|
|
def __init__(self, value):
|
|
self.value = value
|
|
|
|
class _FakeGwConfig:
|
|
def get_connected_platforms(self):
|
|
return [_FakePlatform("simplex")]
|
|
|
|
fake_gw_config = types.ModuleType("gateway.config")
|
|
fake_gw_config.load_gateway_config = lambda: _FakeGwConfig()
|
|
monkeypatch.setitem(sys.modules, "gateway.config", fake_gw_config)
|
|
|
|
fake_dir = types.ModuleType("gateway.channel_directory")
|
|
fake_dir.load_directory = lambda: {"updated_at": None, "platforms": {}}
|
|
|
|
def _format(platforms=None):
|
|
lines = []
|
|
for name, channels in sorted((platforms or {}).items()):
|
|
lines.append(f"{name}:")
|
|
if not channels:
|
|
lines.append(" (no channels discovered yet)")
|
|
return "\n".join(lines)
|
|
|
|
fake_dir.format_directory_for_display = _format
|
|
monkeypatch.setitem(sys.modules, "gateway.channel_directory", fake_dir)
|
|
|
|
rc = send_cmd._list_targets(None, json_mode=False)
|
|
out = capsys.readouterr().out
|
|
assert rc == 0
|
|
assert "simplex" in out
|
|
assert "no channels discovered yet" in out
|
|
|
|
def test_list_json_includes_configured_platform(monkeypatch, capsys):
|
|
import types
|
|
import sys
|
|
|
|
class _FakePlatform:
|
|
def __init__(self, value):
|
|
self.value = value
|
|
|
|
class _FakeGwConfig:
|
|
def get_connected_platforms(self):
|
|
return [_FakePlatform("simplex"), _FakePlatform("local")]
|
|
|
|
fake_gw_config = types.ModuleType("gateway.config")
|
|
fake_gw_config.load_gateway_config = lambda: _FakeGwConfig()
|
|
monkeypatch.setitem(sys.modules, "gateway.config", fake_gw_config)
|
|
|
|
fake_dir = types.ModuleType("gateway.channel_directory")
|
|
fake_dir.load_directory = lambda: {
|
|
"updated_at": None,
|
|
"platforms": {"telegram": [{"id": "1", "name": "home"}]},
|
|
}
|
|
fake_dir.format_directory_for_display = lambda platforms=None: ""
|
|
monkeypatch.setitem(sys.modules, "gateway.channel_directory", fake_dir)
|
|
|
|
rc = send_cmd._list_targets(None, json_mode=True)
|
|
payload = json.loads(capsys.readouterr().out)
|
|
assert rc == 0
|
|
assert payload["platforms"]["simplex"] == []
|
|
assert "local" not in payload["platforms"] # infra pseudo-platform skipped
|
|
assert payload["platforms"]["telegram"] # discovered entries preserved
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Parser registration contract
|
|
# ---------------------------------------------------------------------------
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Env loader
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def test_load_hermes_env_bridges_config_yaml_scalars(tmp_path, monkeypatch):
|
|
"""Top-level config.yaml scalars should be bridged into os.environ.
|
|
|
|
This mirrors the gateway/run.py bootstrap behavior: without this, running
|
|
``hermes send`` from a fresh shell cannot resolve the home channel
|
|
because ``TELEGRAM_HOME_CHANNEL`` (saved by ``hermes config set``) lives
|
|
in config.yaml, not in .env — and the gateway's config loader reads via
|
|
``os.getenv(...)``.
|
|
"""
|
|
import os
|
|
|
|
hermes_home = tmp_path / ".hermes"
|
|
hermes_home.mkdir()
|
|
(hermes_home / ".env").write_text("SOME_TOKEN=abc123\n", encoding="utf-8")
|
|
(hermes_home / "config.yaml").write_text(
|
|
"TELEGRAM_HOME_CHANNEL: '5550001111'\nnested:\n ignored: true\n"
|
|
)
|
|
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
monkeypatch.delenv("TELEGRAM_HOME_CHANNEL", raising=False)
|
|
monkeypatch.delenv("SOME_TOKEN", raising=False)
|
|
|
|
# Force get_hermes_home() to re-resolve under the patched env.
|
|
from importlib import reload
|
|
|
|
import hermes_cli.config as _hc_config
|
|
reload(_hc_config)
|
|
|
|
send_cmd._load_hermes_env()
|
|
|
|
assert os.environ.get("SOME_TOKEN") == "abc123"
|
|
assert os.environ.get("TELEGRAM_HOME_CHANNEL") == "5550001111"
|
|
|
|
def test_load_hermes_env_utf8_bom_preserves_first_key(tmp_path, monkeypatch):
|
|
"""A leading UTF-8 BOM must not mangle the first .env key name.
|
|
|
|
PowerShell 5.1 `Set-Content -Encoding UTF8` and Notepad prepend a BOM
|
|
(EF BB BF). With encoding=utf-8, python-dotenv kept U+FEFF on the first
|
|
key, so the credential never appeared under its canonical name and
|
|
`hermes send` failed to authenticate.
|
|
"""
|
|
import os
|
|
|
|
hermes_home = tmp_path / ".hermes"
|
|
hermes_home.mkdir()
|
|
(hermes_home / ".env").write_bytes(
|
|
b"\xef\xbb\xbfSEND_BOM_BOT_TOKEN=tok-first\nSEND_BOM_SECOND=two\n"
|
|
)
|
|
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
monkeypatch.delenv("SEND_BOM_BOT_TOKEN", raising=False)
|
|
monkeypatch.delenv("SEND_BOM_SECOND", raising=False)
|
|
|
|
from importlib import reload
|
|
import hermes_cli.config as _hc_config
|
|
reload(_hc_config)
|
|
|
|
send_cmd._load_hermes_env()
|
|
|
|
assert os.environ.get("SEND_BOM_BOT_TOKEN") == "tok-first"
|
|
assert os.environ.get("SEND_BOM_SECOND") == "two"
|
|
assert "\ufeff" + "SEND_BOM_BOT_TOKEN" not in os.environ
|
|
|
|
def test_load_hermes_env_bomless_utf8_still_loads(tmp_path, monkeypatch):
|
|
"""BOM-less UTF-8 .env files must keep loading after the utf-8-sig switch."""
|
|
import os
|
|
|
|
hermes_home = tmp_path / ".hermes"
|
|
hermes_home.mkdir()
|
|
(hermes_home / ".env").write_bytes(b"SEND_PLAIN_TOKEN=plain-val\n")
|
|
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
monkeypatch.delenv("SEND_PLAIN_TOKEN", raising=False)
|
|
|
|
from importlib import reload
|
|
import hermes_cli.config as _hc_config
|
|
reload(_hc_config)
|
|
|
|
send_cmd._load_hermes_env()
|
|
|
|
assert os.environ.get("SEND_PLAIN_TOKEN") == "plain-val"
|
|
|
|
def test_load_hermes_env_latin1_fallback_still_loads(tmp_path, monkeypatch):
|
|
"""Invalid UTF-8 bytes must still load via the latin-1 fallback path,
|
|
and a leading BOM must be stripped before the latin-1 decode so the
|
|
first key keeps its canonical name."""
|
|
import os
|
|
|
|
hermes_home = tmp_path / ".hermes"
|
|
hermes_home.mkdir()
|
|
# BOM + valid first key + latin-1 é (0xE9, invalid UTF-8 alone) in a
|
|
# later value — forces the UnicodeDecodeError → latin-1 stream path.
|
|
(hermes_home / ".env").write_bytes(
|
|
b"\xef\xbb\xbfSEND_L1_TOKEN=tok-l1\nSEND_L1_NOTE=caf\xe9\n"
|
|
)
|
|
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
monkeypatch.delenv("SEND_L1_TOKEN", raising=False)
|
|
monkeypatch.delenv("SEND_L1_NOTE", raising=False)
|
|
|
|
from importlib import reload
|
|
import hermes_cli.config as _hc_config
|
|
reload(_hc_config)
|
|
|
|
send_cmd._load_hermes_env()
|
|
|
|
assert os.environ.get("SEND_L1_TOKEN") == "tok-l1"
|
|
assert os.environ.get("SEND_L1_NOTE") == "caf\xe9"
|
|
assert "\ufeff" + "SEND_L1_TOKEN" not in os.environ
|
|
|
|
def test_load_hermes_env_latin1_fallback_overrides_shell(tmp_path, monkeypatch):
|
|
"""The stream-based latin-1 fallback must keep override=True semantics:
|
|
the .env value wins over a stale shell export, same as the primary path. (A non-credential
|
|
key name: ``*_TOKEN`` values are ASCII-sanitized by the shared loader, by design.)"""
|
|
import os
|
|
|
|
hermes_home = tmp_path / ".hermes"
|
|
hermes_home.mkdir()
|
|
# 0xE9 forces the UnicodeDecodeError \u2192 latin-1 stream fallback.
|
|
(hermes_home / ".env").write_bytes(b"SEND_OVR_LABEL=caf\xe9-file\n")
|
|
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
monkeypatch.setenv("SEND_OVR_LABEL", "stale-shell-value")
|
|
|
|
from importlib import reload
|
|
import hermes_cli.config as _hc_config
|
|
reload(_hc_config)
|
|
|
|
send_cmd._load_hermes_env()
|
|
|
|
assert os.environ.get("SEND_OVR_LABEL") == "caf\xe9-file"
|
|
|
|
def test_load_hermes_env_fallback_read_error_is_swallowed(tmp_path, monkeypatch):
|
|
"""An I/O error inside the latin-1 fallback must not escape \u2014 the send
|
|
path is best-effort by design and must never crash on a broken .env."""
|
|
from pathlib import Path
|
|
|
|
hermes_home = tmp_path / ".hermes"
|
|
hermes_home.mkdir()
|
|
# Invalid UTF-8 so the fallback (and its read_bytes call) is reached.
|
|
(hermes_home / ".env").write_bytes(b"SEND_ERR_TOKEN=caf\xe9\n")
|
|
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
|
|
def _boom(self):
|
|
raise OSError("disk went away")
|
|
|
|
monkeypatch.setattr(Path, "read_bytes", _boom)
|
|
|
|
from importlib import reload
|
|
import hermes_cli.config as _hc_config
|
|
reload(_hc_config)
|
|
|
|
# Should not raise.
|
|
send_cmd._load_hermes_env()
|
|
|
|
def test_load_hermes_env_bom_only_env_is_noop(tmp_path, monkeypatch):
|
|
"""A .env containing only a BOM must load zero vars without error."""
|
|
import os
|
|
|
|
hermes_home = tmp_path / ".hermes"
|
|
hermes_home.mkdir()
|
|
(hermes_home / ".env").write_bytes(b"\xef\xbb\xbf")
|
|
|
|
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
|
|
|
|
from importlib import reload
|
|
import hermes_cli.config as _hc_config
|
|
reload(_hc_config)
|
|
|
|
before = dict(os.environ)
|
|
send_cmd._load_hermes_env()
|
|
|
|
added = {k: v for k, v in os.environ.items() if k not in before}
|
|
assert "\ufeff" not in "".join(added)
|
|
|
|
def test_help_and_empty_list_hint_name_the_resolved_home(tmp_path, monkeypatch, capsys):
|
|
"""``--help`` and the ``--list`` empty-state hint derive their paths from the resolved home instead of a
|
|
hardcoded ``~/.hermes`` (absent on a Windows install or under a profile home)."""
|
|
import argparse
|
|
import sys
|
|
import types
|
|
|
|
home = tmp_path / "AppData" / "Local" / "hermes"
|
|
home.mkdir(parents=True)
|
|
monkeypatch.setenv("HERMES_HOME", str(home))
|
|
|
|
parser = argparse.ArgumentParser(prog="hermes")
|
|
send_parser = send_cmd.register_send_subparser(parser.add_subparsers(dest="command"))
|
|
help_text = send_parser.format_help()
|
|
assert str(home / ".env") in help_text and str(home / "config.yaml") in help_text
|
|
assert "~/.hermes" not in help_text
|
|
|
|
fake_gw_config = types.ModuleType("gateway.config")
|
|
fake_gw_config.load_gateway_config = lambda: types.SimpleNamespace(get_connected_platforms=lambda: [])
|
|
monkeypatch.setitem(sys.modules, "gateway.config", fake_gw_config)
|
|
fake_dir = types.ModuleType("gateway.channel_directory")
|
|
fake_dir.load_directory = lambda: {"updated_at": None, "platforms": {}}
|
|
fake_dir.format_directory_for_display = lambda platforms=None: ""
|
|
monkeypatch.setitem(sys.modules, "gateway.channel_directory", fake_dir)
|
|
|
|
assert send_cmd._list_targets(None, json_mode=False) == 0
|
|
out = capsys.readouterr().out
|
|
assert str(home / "channel_directory.json") in out
|
|
assert "~/.hermes" not in out
|