The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(gateway): keep one invariant test per bare-name owner
kshitijk4poorb18c5752e373
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.pyindex 94afbbad3ef..8345b5e4dfa 100644--- a/tests/hermes_cli/test_gateway_service.py+++ b/tests/hermes_cli/test_gateway_service.py@@ -45,9 +45,6 @@ class TestUserSystemdPrivateSocketPreflight:class TestSystemdServiceRefresh:---def test_systemd_restart_timeout_prints_status_guidance(self, monkeypatch, capsys):"""`hermes gateway restart` must not surface a raw TimeoutExpired traceback.@@ -87,7 +84,6 @@ class TestSystemdServiceRefresh:assert "still restarting after 90s" in outputassert "hermes gateway status" in output-def test_refresh_refuses_to_bake_pytest_tmpdir_into_real_user_unit(self, tmp_path, monkeypatch):@@ -143,7 +139,6 @@ class TestSystemdServiceRefresh:), "daemon-reload must not run when write was refused"-class TestTempHomeServiceDefinitionGuard:"""_temp_home_in_service_definition() — structural temp-dir detection."""@@ -154,7 +149,6 @@ class TestTempHomeServiceDefinitionGuard:== "/tmp/hermes-e2e-41264")-def test_detects_tempdir_env_home(self, monkeypatch, tmp_path):import tempfile as _tempfile@@ -163,9 +157,6 @@ class TestTempHomeServiceDefinitionGuard:assert gateway_cli._temp_home_in_service_definition(unit) is not None---class TestRequireServiceInstalled:def test_exits_with_install_hint_when_unit_missing(self, tmp_path, monkeypatch, capsys):unit_path = tmp_path / "hermes-gateway.service"@@ -234,24 +225,6 @@ class TestServiceIdentityForForeignHome:monkeypatch.setenv("HERMES_HOME", str(sudo_default))assert gateway_cli.get_service_name() == "hermes-gateway"- def test_sudo_user_named_and_custom_homes_remain_distinct(- self, machine_home, tmp_path, monkeypatch- ):- sudo_home = tmp_path / "alice"- named_home = sudo_home / ".hermes" / "profiles" / "alpha"- custom_home = tmp_path / "custom-hermes"- named_home.mkdir(parents=True)- custom_home.mkdir()- monkeypatch.setattr(os, "geteuid", lambda: 0)- monkeypatch.setenv("SUDO_USER", "alice")- monkeypatch.setattr(pwd, "getpwnam", lambda user: SimpleNamespace(pw_dir=str(sudo_home)))-- monkeypatch.setenv("HERMES_HOME", str(named_home))- assert gateway_cli.get_service_name() == "hermes-gateway-alpha"-- monkeypatch.setenv("HERMES_HOME", str(custom_home))- assert gateway_cli.get_service_name() not in {"hermes-gateway", "hermes-gateway-alpha"}-class TestUninstallRefusesForeignUnit:"""systemd_uninstall must not stop/disable/unlink a unit pinned to another HERMES_HOME."""@@ -445,7 +418,6 @@ class TestGeneratedSystemdUnits:assert "SoftResourceLimits" not in plist-class TestGatewayStopCleanup:@pytest.mark.linux_onlydef test_stop_only_kills_current_profile_by_default(self, tmp_path, monkeypatch):@@ -500,8 +472,6 @@ class TestLaunchdServiceRecovery:def test_wait_for_pid_exit_ignores_nonpositive_pid(self):assert gateway_cli._wait_for_pid_exit(0, timeout=30) is True--def test_refresh_defers_reload_when_running_inside_gateway_tree(self, tmp_path, monkeypatch):"""#43842: when the refresh runs inside the gateway's own process tree,a direct bootout would kill this CLI before bootstrap. The reload must@@ -622,7 +592,6 @@ class TestLaunchdServiceRecovery:assert popen_calls[0][:2] == ["launchctl", "submit"]assert not [c for c in run_calls if "bootout" in c or "bootstrap" in c]-def test_deferred_reload_waits_for_old_gateway_pid_before_bootstrap(self, tmp_path, monkeypatch):@@ -676,7 +645,6 @@ class TestLaunchdServiceRecovery:# The wait must be bounded, so a wedged gateway can't block the reload.assert "_wait_deadline" in script-def test_refresh_falls_back_to_direct_reload_when_helper_cannot_spawn(self, tmp_path, monkeypatch):@@ -741,7 +709,6 @@ class TestLaunchdServiceRecovery:# Drained the old pid between bootout and bootstrap.assert waited and waited[0][0] == 4242-def test_launchd_domain_uses_user_domain(self, monkeypatch):# The user/<uid> domain (not gui/<uid>) is the one reachable from# non-Aqua/background sessions on macOS 26+ (issue #23387).@@ -760,22 +727,17 @@ class TestLaunchdServiceRecovery:assert gateway_cli._launchd_domain() == "user/501"-# ── PID parsing ──────────────────────────────────────────────────────--# ── Probe requires PID ───────────────────────────────────────────────# ── Unsupport marker lifecycle ───────────────────────────────────────-# ── launchd_status with active supervision ───────────────────────────-def test_launchd_status_reports_fallback_when_unsupported_and_pid_running(self, tmp_path, monkeypatch, capsys):"""When the unsupported marker exists and a fallback PID is running."""plist_path = tmp_path / "ai.hermes.gateway.plist"@@ -836,7 +798,6 @@ class TestLaunchdDomainDetection:# Should have probed gui firstassert run_calls[0] == ["launchctl", "print", f"gui/501/{label}"]-def test_managername_background_selects_user_domain(self, monkeypatch):"""When managername is Background (non-Aqua), use user/<uid>."""self._reset_domain_cache()@@ -1216,11 +1177,6 @@ class TestGatewaySystemServiceRouting:assert "did not revive" in outassert "✓ Service restarted" in out-----@pytest.mark.macos_onlydef test_gateway_restart_does_not_fallback_to_foreground_when_launchd_restart_fails(self, tmp_path, monkeypatch):"""macOS-gated: the branch under test is ``elif is_macos() and@@ -1280,7 +1236,6 @@ class TestDetectVenvDir:result = gateway_cli._detect_venv_dir()assert result == dot_venv-def test_returns_none_when_no_virtualenv(self, tmp_path, monkeypatch):monkeypatch.setattr("sys.prefix", "/usr")monkeypatch.setattr("sys.base_prefix", "/usr")@@ -1416,7 +1371,6 @@ class TestSystemUnitHermesHome:assert 'HERMES_HOME=/home/alice/.hermes' in unitassert '/root/.hermes' not in unit-def test_user_unit_unaffected_by_change(self):# User-scope units should still use the calling user's HERMES_HOMEunit = gateway_cli.generate_systemd_unit(system=False)@@ -1567,8 +1521,6 @@ class TestHermesHomeForTargetUser:assert result == "/home/alice/.hermes"--class TestGeneratedUnitUsesDetectedVenv:def test_systemd_unit_uses_dot_venv_when_detected(self, tmp_path, monkeypatch):dot_venv = tmp_path / ".venv"@@ -1589,7 +1541,6 @@ class TestGeneratedUnitUsesDetectedVenv:class TestGeneratedUnitIncludesLocalBin:"""~/.local/bin must be in PATH so uvx/pipx tools are discoverable."""-def test_system_unit_includes_local_bin_in_path(self, monkeypatch):monkeypatch.setattr(gateway_cli,@@ -1642,7 +1593,6 @@ class TestSystemServiceIdentityRootHandling:class TestEnsureUserSystemdEnv:"""Tests for _ensure_user_systemd_env() D-Bus session bus auto-detection."""-def test_sets_dbus_address_when_bus_socket_exists(self, tmp_path, monkeypatch):runtime = tmp_path / "runtime"runtime.mkdir()@@ -1657,8 +1607,6 @@ class TestEnsureUserSystemdEnv:assert os.environ["DBUS_SESSION_BUS_ADDRESS"] == f"unix:path={bus_socket}"--def test_systemctl_cmd_calls_ensure_for_user_mode(self, monkeypatch):calls = []monkeypatch.setattr(gateway_cli, "_ensure_user_systemd_env", lambda: calls.append("called"))@@ -1676,7 +1624,6 @@ class TestPreflightUserSystemd:which previously failed with a raw ``CalledProcessError`` and no remediation."""-def test_raises_when_linger_disabled_and_loginctl_denied(self, monkeypatch):"""Rick's scenario: no D-Bus, no linger, non-root SSH → clear error."""monkeypatch.setattr(@@ -1709,8 +1656,6 @@ class TestPreflightUserSystemd:assert "hermes gateway run" in msg # foreground fallback mentionedassert "Interactive authentication required" in msg--def test_enable_linger_succeeds_and_socket_appears(self, monkeypatch, capsys):"""Happy remediation path: polkit allows enable-linger, socket spawns."""monkeypatch.setattr(@@ -1748,12 +1693,6 @@ class TestPreflightUserSystemd:class TestProfileArg:"""Tests for _profile_arg — returns '--profile <name>' for named profiles."""------def test_systemd_unit_for_target_user_includes_named_profile(self, tmp_path, monkeypatch):"""sudo system install must keep the target user's named profile in ExecStart."""root_home = tmp_path / "root"@@ -1959,11 +1898,6 @@ class TestLegacyHermesUnitDetection:)return user_dir, system_dir-----def test_detects_both_scopes_simultaneously(self, tmp_path, monkeypatch):"""When a user has BOTH user-scope and system-scope legacy units,both are reported so the migration step can remove them together."""@@ -2002,7 +1936,6 @@ class TestLegacyHermesUnitDetection:results = gateway_cli._find_legacy_hermes_units()assert len(results) == 1, f"Variant {i} not detected: {execstart!r}"-def test_print_legacy_unit_warning_shows_migration_hint(self, tmp_path, monkeypatch, capsys):user_dir, _ = self._setup_search_paths(tmp_path, monkeypatch)(user_dir / "hermes.service").write_text(self._OUR_UNIT_TEXT, encoding="utf-8")@@ -2015,7 +1948,6 @@ class TestLegacyHermesUnitDetection:assert "hermes gateway migrate-legacy" in out-class TestRemoveLegacyHermesUnits:"""Tests for remove_legacy_hermes_units (the migration action)."""@@ -2046,8 +1978,6 @@ class TestRemoveLegacyHermesUnits:monkeypatch.setattr(gateway_cli.os, "geteuid", lambda: 0 if as_root else 1000)return user_dir, system_dir, systemctl_calls--def test_removes_user_scope_legacy_unit(self, tmp_path, monkeypatch, capsys):user_dir, _, calls = self._setup(tmp_path, monkeypatch)legacy = user_dir / "hermes.service"@@ -2064,8 +1994,6 @@ class TestRemoveLegacyHermesUnits:assert any("--user disable hermes.service" in c for c in cmds_joined)assert any("--user daemon-reload" in c for c in cmds_joined)--def test_does_not_touch_profile_units_during_migration(self, tmp_path, monkeypatch, capsys):@@ -2087,7 +2015,6 @@ class TestRemoveLegacyHermesUnits:assert default_unit.exists()-class TestMigrateLegacyCommand:"""Tests for the `hermes gateway migrate-legacy` subcommand dispatch."""@@ -2157,7 +2084,6 @@ class TestGatewayStatusParser:assert result.returncode == 0assert "unrecognized arguments" not in result.stderr-def test_migrate_legacy_on_unsupported_platform_prints_message(self, monkeypatch, capsys):@@ -2324,7 +2250,6 @@ class TestSystemScopeRequiresRootError:assert str(excinfo.value) == "System gateway start requires root. Re-run with sudo."assert f"Failed: {excinfo.value}" == "Failed: System gateway start requires root. Re-run with sudo."-def test_error_is_runtime_error_subclass(self):"""Wizards use ``except Exception`` guards — the error must be a``RuntimeError`` (catchable by ``Exception``), NOT a ``SystemExit``@@ -2364,7 +2289,6 @@ class TestSystemScopeWizardPreCheck:assert gateway_cli._system_scope_wizard_would_need_root() is True-def test_non_root_with_explicit_system_arg_returns_true(self, tmp_path, monkeypatch):# Caller passed system=True explicitly (e.g. ``hermes gateway start --system``).self._setup_units(tmp_path, monkeypatch, system_present=False, user_present=False)@@ -2432,8 +2356,6 @@ class TestServiceWorkingDirIsStable:deleted checkout can't crash-loop the unit on CHDIR (status=200)."""--def test_user_unit_workingdirectory_is_hermes_home_not_checkout(self, tmp_path, monkeypatch):home = tmp_path / ".hermes"home.mkdir()@@ -2512,7 +2434,6 @@ class TestLaunchctlBootstrapEioRetry:DOMAIN = "gui/501"LABEL = "ai.hermes.gateway"-def test_eio_triggers_bootout_then_retry(self, monkeypatch):calls = []@@ -2781,54 +2702,6 @@ class TestUnitAnchoredServiceIdentity:an identity authority for launchd labels, Windows tasks, or s6 slots, which share the same resolver."""- @pytest.mark.linux_only- def test_service_name_survives_hermes_home_adoption_from_unit(self, tmp_path, monkeypatch):- alice_home = tmp_path / "alice" / ".hermes"- alice_home.mkdir(parents=True)- root_home = tmp_path / "root" / ".hermes"- root_home.mkdir(parents=True)- unit_dir = tmp_path / "systemd"- unit_dir.mkdir()- unit_path = unit_dir / f"{gateway_cli._SERVICE_BASE}.service"- unit_path.write_text(f'[Service]\nEnvironment="HERMES_HOME={alice_home}"\n', encoding="utf-8")- monkeypatch.setattr(gateway_cli, "_SYSTEM_UNIT_DIR", unit_dir, raising=False)- monkeypatch.setattr(hermes_constants, "_get_platform_default_hermes_home", lambda: root_home)- monkeypatch.delenv("HERMES_HOME", raising=False)- pre_name = gateway_cli.get_service_name()- monkeypatch.setenv("HERMES_HOME", str(alice_home))- assert gateway_cli.get_service_name() == pre_name-- @pytest.mark.linux_only- def test_unit_pinned_home_owns_the_bare_name(self, tmp_path, monkeypatch):- alice_home = tmp_path / "alice" / ".hermes"- alice_home.mkdir(parents=True)- root_home = tmp_path / "root" / ".hermes"- root_home.mkdir(parents=True)- unit_dir = tmp_path / "systemd"- unit_dir.mkdir()- unit_path = unit_dir / f"{gateway_cli._SERVICE_BASE}.service"- unit_path.write_text(f'[Service]\nEnvironment="HERMES_HOME={alice_home}"\n', encoding="utf-8")- monkeypatch.setattr(gateway_cli, "_SYSTEM_UNIT_DIR", unit_dir, raising=False)- monkeypatch.setattr(hermes_constants, "_get_platform_default_hermes_home", lambda: root_home)- monkeypatch.setenv("HERMES_HOME", str(alice_home))- assert gateway_cli.get_service_name() == gateway_cli._SERVICE_BASE- assert gateway_cli.get_systemd_unit_path(system=True) == unit_path-- @pytest.mark.linux_only- def test_foreign_home_without_installed_unit_keeps_its_suffix(self, tmp_path, monkeypatch):- unit_dir = tmp_path / "empty"- unit_dir.mkdir()- foreign = tmp_path / "elsewhere"- foreign.mkdir()- root_home = tmp_path / "root" / ".hermes"- root_home.mkdir(parents=True)- monkeypatch.setattr(gateway_cli, "_SYSTEM_UNIT_DIR", unit_dir, raising=False)- monkeypatch.setattr(hermes_constants, "_get_platform_default_hermes_home", lambda: root_home)- monkeypatch.setenv("HERMES_HOME", str(foreign))- name = gateway_cli.get_service_name()- assert name != gateway_cli._SERVICE_BASE- assert name.startswith(gateway_cli._SERVICE_BASE + "-")-@pytest.mark.linux_onlydef test_home_not_pinned_by_unit_keeps_its_suffix(self, tmp_path, monkeypatch):alice_home = tmp_path / "alice" / ".hermes"@@ -2893,28 +2766,3 @@ class TestUnitAnchoredServiceIdentity:assert os.environ["HERMES_HOME"] == str(alice_home) # the sync really ranassert gateway_cli.get_service_name() == pre_sync_name-- @pytest.mark.linux_only- def test_unreadable_unit_does_not_grant_the_bare_name(self, tmp_path, monkeypatch):- """A unit we cannot read must not hand its bare name to an unrelated home: the parser returns- None on OSError, so resolution falls through to the suffix branches."""- foreign_home = tmp_path / "elsewhere"- foreign_home.mkdir()- root_home = tmp_path / "root" / ".hermes"- root_home.mkdir(parents=True)- unit_dir = tmp_path / "systemd"- unit_dir.mkdir()- unit_path = unit_dir / f"{gateway_cli._SERVICE_BASE}.service"- unit_path.write_text(f'[Service]\nEnvironment="HERMES_HOME={foreign_home}"\n', encoding="utf-8")- real_read_text = Path.read_text-- def deny_unit(self, *args, **kwargs):- if self == unit_path:- raise PermissionError(13, "Permission denied")- return real_read_text(self, *args, **kwargs)-- monkeypatch.setattr(gateway_cli, "_SYSTEM_UNIT_DIR", unit_dir, raising=False)- monkeypatch.setattr(hermes_constants, "_get_platform_default_hermes_home", lambda: root_home)- monkeypatch.setattr(Path, "read_text", deny_unit)- monkeypatch.setenv("HERMES_HOME", str(foreign_home))- assert gateway_cli.get_service_name().startswith(gateway_cli._SERVICE_BASE + "-")