test_ssh.py 7.83 KB
Newer Older
one's avatar
one committed
1
2
3
4
5
6
7
"""Tests for hytop.core.ssh.collect_from_host (subprocess mocked)."""

from __future__ import annotations

import subprocess
from unittest.mock import MagicMock, patch

one's avatar
one committed
8
from hytop.core.ssh import SSHOptions, collect_from_host, collect_python_from_host
one's avatar
one committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93


def _make_proc(returncode=0, stdout="", stderr=""):
    m = MagicMock()
    m.returncode = returncode
    m.stdout = stdout
    m.stderr = stderr
    return m


class TestCollectFromHostLocal:
    @patch("hytop.core.ssh.subprocess.run")
    def test_success_returns_no_error(self, mock_run):
        mock_run.return_value = _make_proc(stdout='{"card0":{}}')
        result = collect_from_host(
            "localhost", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"]
        )
        assert result.error is None
        assert result.host == "localhost"

    @patch("hytop.core.ssh.subprocess.run")
    def test_local_invokes_hy_smi_directly(self, mock_run):
        mock_run.return_value = _make_proc()
        collect_from_host("localhost", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"])
        cmd = mock_run.call_args[0][0]
        assert cmd[0] == "hy-smi"
        assert "ssh" not in cmd

    @patch("hytop.core.ssh.subprocess.run")
    def test_127_0_0_1_treated_as_local(self, mock_run):
        mock_run.return_value = _make_proc()
        collect_from_host("127.0.0.1", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"])
        cmd = mock_run.call_args[0][0]
        assert cmd[0] == "hy-smi"

    @patch("hytop.core.ssh.subprocess.run")
    def test_nonzero_exit_returns_error(self, mock_run):
        mock_run.return_value = _make_proc(returncode=1, stderr="permission denied")
        result = collect_from_host(
            "localhost", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"]
        )
        assert result.error is not None
        assert "exit 1" in result.error

    @patch(
        "hytop.core.ssh.subprocess.run",
        side_effect=subprocess.TimeoutExpired("cmd", 10),
    )
    def test_timeout_returns_error(self, mock_run):
        result = collect_from_host(
            "localhost", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"]
        )
        assert result.error is not None
        assert "timeout" in result.error

    @patch("hytop.core.ssh.subprocess.run", side_effect=OSError("no such file"))
    def test_oserror_returns_error(self, mock_run):
        result = collect_from_host(
            "localhost", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"]
        )
        assert result.error is not None
        assert "no such file" in result.error


class TestCollectFromHostRemote:
    @patch("hytop.core.ssh.subprocess.run")
    def test_remote_uses_ssh(self, mock_run):
        mock_run.return_value = _make_proc(stdout="{}")
        collect_from_host("node01", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"])
        cmd = mock_run.call_args[0][0]
        assert cmd[0] == "ssh"

    @patch("hytop.core.ssh.subprocess.run")
    def test_remote_hostname_in_cmd(self, mock_run):
        mock_run.return_value = _make_proc(stdout="{}")
        collect_from_host("node01", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"])
        cmd = mock_run.call_args[0][0]
        assert "node01" in cmd

    @patch("hytop.core.ssh.subprocess.run")
    def test_remote_batch_mode_set(self, mock_run):
        mock_run.return_value = _make_proc(stdout="{}")
        collect_from_host("node01", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"])
        cmd = mock_run.call_args[0][0]
        assert "BatchMode=yes" in cmd
one's avatar
one committed
94
95
        assert "-n" in cmd
        assert "-T" in cmd
one's avatar
one committed
96
97
98
99
100
101
102
103
104
105
106
107
108

    @patch("hytop.core.ssh.subprocess.run")
    def test_hy_smi_args_forwarded(self, mock_run):
        mock_run.return_value = _make_proc(stdout="{}")
        collect_from_host(
            "node01",
            ssh_timeout=5,
            cmd_timeout=10,
            hy_smi_args=["--json", "--showtemp"],
        )
        cmd = mock_run.call_args[0][0]
        assert "--json" in cmd
        assert "--showtemp" in cmd
one's avatar
one committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147


class TestCollectPythonFromHost:
    @patch("hytop.core.ssh.subprocess.run")
    def test_remote_uses_ssh(self, mock_run):
        mock_run.return_value = _make_proc(stdout='{"ok":1}')
        collect_python_from_host("node01", ssh_timeout=5, cmd_timeout=10, python_code="print('ok')")
        cmd = mock_run.call_args[0][0]
        assert cmd[0] == "ssh"
        assert any(str(part).startswith("python3 -c ") for part in cmd)

    @patch("hytop.core.ssh.subprocess.run")
    def test_mux_options_applied(self, mock_run):
        mock_run.return_value = _make_proc(stdout='{"ok":1}')
        collect_python_from_host(
            "node01",
            ssh_timeout=5,
            cmd_timeout=10,
            python_code="print('ok')",
            ssh_options=SSHOptions(use_mux=True),
        )
        cmd = mock_run.call_args[0][0]
        assert "ControlMaster=auto" in cmd
        assert any(str(item).startswith("ControlPersist=") for item in cmd)

    @patch("hytop.core.ssh.subprocess.run")
    def test_multiline_script_is_single_remote_arg(self, mock_run):
        mock_run.return_value = _make_proc(stdout='{"ok":1}')
        collect_python_from_host(
            "node01",
            ssh_timeout=5,
            cmd_timeout=10,
            python_code="import json\nprint(json.dumps({'ok': True}))",
        )
        cmd = mock_run.call_args[0][0]
        remote_parts = [
            part for part in cmd if isinstance(part, str) and part.startswith("python3 -c ")
        ]
        assert len(remote_parts) == 1
one's avatar
one committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166


class TestSubprocessStdinIsolation:
    @patch("hytop.core.ssh.subprocess.run")
    def test_collect_from_host_uses_devnull_stdin(self, mock_run):
        mock_run.return_value = _make_proc(stdout='{"card0":{}}')
        collect_from_host("localhost", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"])
        assert mock_run.call_args.kwargs["stdin"] == subprocess.DEVNULL

    @patch("hytop.core.ssh.subprocess.run")
    def test_collect_python_from_host_uses_devnull_stdin(self, mock_run):
        mock_run.return_value = _make_proc(stdout='{"ok":1}')
        collect_python_from_host(
            "node01",
            ssh_timeout=5,
            cmd_timeout=10,
            python_code="print('ok')",
        )
        assert mock_run.call_args.kwargs["stdin"] == subprocess.DEVNULL
one's avatar
one committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212


class TestHostTargetParsing:
    def test_parse_host_target_simple(self):
        from hytop.core.ssh import parse_host_target

        target = parse_host_target("node01")
        assert target.name == "node01"
        assert target.hostname == "node01"
        assert target.port is None

    def test_parse_host_target_with_port(self):
        from hytop.core.ssh import parse_host_target

        target = parse_host_target("node01:3333")
        assert target.name == "node01:3333"
        assert target.hostname == "node01"
        assert target.port == 3333

    def test_parse_host_target_invalid_port(self):
        from hytop.core.ssh import parse_host_target

        target = parse_host_target("node01:abc")
        assert target.name == "node01:abc"
        assert target.hostname == "node01:abc"
        assert target.port is None

    @patch("hytop.core.ssh.subprocess.run")
    def test_collect_from_host_custom_port(self, mock_run):
        mock_run.return_value = _make_proc(stdout="{}")
        collect_from_host("node01:3333", ssh_timeout=5, cmd_timeout=10, hy_smi_args=["--json"])
        cmd = mock_run.call_args[0][0]
        assert cmd[0] == "ssh"
        assert "-p" in cmd
        assert "3333" in cmd

    @patch("hytop.core.ssh.subprocess.run")
    def test_collect_python_from_host_custom_port(self, mock_run):
        mock_run.return_value = _make_proc(stdout='{"ok":1}')
        collect_python_from_host(
            "node01:3333", ssh_timeout=5, cmd_timeout=10, python_code="print()"
        )
        cmd = mock_run.call_args[0][0]
        assert cmd[0] == "ssh"
        assert "-p" in cmd
        assert "3333" in cmd