| 1 |
"""Tests for s_tui.helper_functions module.""" |
| 2 |
|
| 3 |
import csv |
| 4 |
import json |
| 5 |
import os |
| 6 |
import signal |
| 7 |
from unittest.mock import MagicMock, patch |
| 8 |
|
| 9 |
import psutil |
| 10 |
import pytest |
| 11 |
|
| 12 |
from s_tui.helper_functions import ( |
| 13 |
__version__, |
| 14 |
cat, |
| 15 |
config_dir_exists, |
| 16 |
get_config_dir, |
| 17 |
get_processor_name, |
| 18 |
get_user_config_dir, |
| 19 |
get_user_config_file, |
| 20 |
kill_child_processes, |
| 21 |
make_user_config_dir, |
| 22 |
output_to_csv, |
| 23 |
output_to_json, |
| 24 |
output_to_terminal, |
| 25 |
seconds_to_text, |
| 26 |
str_to_bool, |
| 27 |
user_config_dir_exists, |
| 28 |
user_config_file_exists, |
| 29 |
which, |
| 30 |
) |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
class TestSecondsToText: |
| 38 |
def test_zero(self): |
| 39 |
assert seconds_to_text(0) == "00:00:00" |
| 40 |
|
| 41 |
def test_seconds_only(self): |
| 42 |
assert seconds_to_text(45) == "00:00:45" |
| 43 |
|
| 44 |
def test_minutes_and_seconds(self): |
| 45 |
assert seconds_to_text(125) == "00:02:05" |
| 46 |
|
| 47 |
def test_hours_minutes_seconds(self): |
| 48 |
assert seconds_to_text(3661) == "01:01:01" |
| 49 |
|
| 50 |
def test_large_value(self): |
| 51 |
assert seconds_to_text(86400) == "24:00:00" |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
class TestStrToBool: |
| 60 |
def test_true(self): |
| 61 |
assert str_to_bool("True") is True |
| 62 |
|
| 63 |
def test_false(self): |
| 64 |
assert str_to_bool("False") is False |
| 65 |
|
| 66 |
def test_invalid_raises(self): |
| 67 |
with pytest.raises(ValueError): |
| 68 |
str_to_bool("true") |
| 69 |
|
| 70 |
def test_empty_raises(self): |
| 71 |
with pytest.raises(ValueError): |
| 72 |
str_to_bool("") |
| 73 |
|
| 74 |
def test_random_string_raises(self): |
| 75 |
with pytest.raises(ValueError): |
| 76 |
str_to_bool("yes") |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
class TestCat: |
| 85 |
def test_read_binary(self, tmp_path): |
| 86 |
f = tmp_path / "test.txt" |
| 87 |
f.write_bytes(b"hello world\n") |
| 88 |
result = cat(str(f), binary=True) |
| 89 |
assert result == b"hello world" |
| 90 |
|
| 91 |
def test_read_text(self, tmp_path): |
| 92 |
f = tmp_path / "test.txt" |
| 93 |
f.write_text("hello world\n") |
| 94 |
result = cat(str(f), binary=False) |
| 95 |
assert result == "hello world" |
| 96 |
|
| 97 |
def test_strips_whitespace(self, tmp_path): |
| 98 |
f = tmp_path / "test.txt" |
| 99 |
f.write_text(" content \n") |
| 100 |
result = cat(str(f), binary=False) |
| 101 |
assert result == "content" |
| 102 |
|
| 103 |
def test_missing_file_raises(self): |
| 104 |
with pytest.raises((IOError, OSError)): |
| 105 |
cat("/nonexistent/file/path") |
| 106 |
|
| 107 |
def test_missing_file_with_fallback(self): |
| 108 |
result = cat("/nonexistent/file/path", fallback="default") |
| 109 |
assert result == "default" |
| 110 |
|
| 111 |
def test_missing_file_fallback_none(self): |
| 112 |
result = cat("/nonexistent/file/path", fallback=None) |
| 113 |
assert result is None |
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
class TestWhich: |
| 122 |
def test_finds_existing_program(self): |
| 123 |
|
| 124 |
result = which("python3") |
| 125 |
assert result is not None |
| 126 |
assert os.path.isfile(result) |
| 127 |
|
| 128 |
def test_returns_none_for_nonexistent(self): |
| 129 |
assert which("nonexistent_program_xyz_12345") is None |
| 130 |
|
| 131 |
def test_absolute_path_executable(self, tmp_path): |
| 132 |
exe = tmp_path / "myexe" |
| 133 |
exe.write_text("#!/bin/sh\n") |
| 134 |
exe.chmod(0o755) |
| 135 |
assert which(str(exe)) == str(exe) |
| 136 |
|
| 137 |
def test_absolute_path_not_executable(self, tmp_path): |
| 138 |
f = tmp_path / "notexe" |
| 139 |
f.write_text("not executable") |
| 140 |
f.chmod(0o644) |
| 141 |
assert which(str(f)) is None |
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
class TestGetProcessorName: |
| 150 |
def test_returns_something(self): |
| 151 |
"""get_processor_name should return a non-empty value on any platform.""" |
| 152 |
result = get_processor_name() |
| 153 |
assert result is not None |
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
class TestConfigDirHelpers: |
| 162 |
def test_get_config_dir_with_xdg(self, monkeypatch): |
| 163 |
monkeypatch.setenv("XDG_CONFIG_HOME", "/tmp/test_xdg") |
| 164 |
assert get_config_dir() == "/tmp/test_xdg" |
| 165 |
|
| 166 |
def test_get_config_dir_fallback(self, monkeypatch): |
| 167 |
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False) |
| 168 |
result = get_config_dir() |
| 169 |
assert result.endswith(".config") |
| 170 |
|
| 171 |
def test_get_user_config_dir(self, monkeypatch): |
| 172 |
monkeypatch.setenv("XDG_CONFIG_HOME", "/tmp/test_xdg") |
| 173 |
assert get_user_config_dir() == "/tmp/test_xdg/s-tui" |
| 174 |
|
| 175 |
def test_get_user_config_file(self, monkeypatch): |
| 176 |
monkeypatch.setenv("XDG_CONFIG_HOME", "/tmp/test_xdg") |
| 177 |
assert get_user_config_file() == "/tmp/test_xdg/s-tui/s-tui.conf" |
| 178 |
|
| 179 |
def test_user_config_dir_exists_false(self, monkeypatch): |
| 180 |
monkeypatch.setenv("XDG_CONFIG_HOME", "/tmp/nonexistent_xdg_test") |
| 181 |
assert user_config_dir_exists() is False |
| 182 |
|
| 183 |
def test_config_dir_exists_false(self, monkeypatch): |
| 184 |
monkeypatch.setenv("XDG_CONFIG_HOME", "/tmp/nonexistent_xdg_test") |
| 185 |
assert config_dir_exists() is False |
| 186 |
|
| 187 |
def test_user_config_file_exists_false(self, monkeypatch): |
| 188 |
monkeypatch.setenv("XDG_CONFIG_HOME", "/tmp/nonexistent_xdg_test") |
| 189 |
assert user_config_file_exists() is False |
| 190 |
|
| 191 |
def test_make_user_config_dir(self, tmp_path, monkeypatch): |
| 192 |
xdg = tmp_path / "xdg_config" |
| 193 |
monkeypatch.setenv("XDG_CONFIG_HOME", str(xdg)) |
| 194 |
result = make_user_config_dir() |
| 195 |
assert result is not None |
| 196 |
assert os.path.isdir(result) |
| 197 |
assert os.path.isdir(os.path.join(result, "hooks.d")) |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
class TestKillChildProcesses: |
| 206 |
def test_none_parent(self): |
| 207 |
"""Should handle None gracefully.""" |
| 208 |
kill_child_processes(None) |
| 209 |
|
| 210 |
def test_sigterm_via_process_group(self): |
| 211 |
"""Should send SIGTERM to the process group first.""" |
| 212 |
parent = MagicMock() |
| 213 |
parent.pid = 12345 |
| 214 |
parent.children.return_value = [] |
| 215 |
|
| 216 |
with ( |
| 217 |
patch("os.getpgid", return_value=12345) as mock_getpgid, |
| 218 |
patch("os.killpg") as mock_killpg, |
| 219 |
patch("psutil.wait_procs", return_value=([], [])), |
| 220 |
): |
| 221 |
kill_child_processes(parent, timeout=1) |
| 222 |
mock_getpgid.assert_called_once_with(12345) |
| 223 |
mock_killpg.assert_called_once_with(12345, signal.SIGTERM) |
| 224 |
|
| 225 |
def test_fallback_to_per_process_terminate(self): |
| 226 |
"""When process group kill fails, falls back to per-process terminate.""" |
| 227 |
child = MagicMock() |
| 228 |
parent = MagicMock() |
| 229 |
parent.pid = 100 |
| 230 |
parent.children.return_value = [child] |
| 231 |
|
| 232 |
with ( |
| 233 |
patch("os.getpgid", side_effect=OSError("no pgid")), |
| 234 |
patch("psutil.wait_procs", return_value=([], [])), |
| 235 |
): |
| 236 |
kill_child_processes(parent, timeout=1) |
| 237 |
child.terminate.assert_called_once() |
| 238 |
parent.terminate.assert_called_once() |
| 239 |
|
| 240 |
def test_sigkill_stragglers_after_timeout(self): |
| 241 |
"""Processes still alive after timeout get SIGKILL.""" |
| 242 |
straggler = MagicMock() |
| 243 |
parent = MagicMock() |
| 244 |
parent.pid = 200 |
| 245 |
parent.children.return_value = [] |
| 246 |
|
| 247 |
with ( |
| 248 |
patch("os.getpgid", return_value=200), |
| 249 |
patch("os.killpg"), |
| 250 |
patch("psutil.wait_procs", return_value=([], [straggler])), |
| 251 |
): |
| 252 |
kill_child_processes(parent, timeout=1) |
| 253 |
straggler.kill.assert_called_once() |
| 254 |
|
| 255 |
def test_already_dead_process(self): |
| 256 |
"""Should not raise when process is already dead.""" |
| 257 |
parent = MagicMock() |
| 258 |
parent.pid = 300 |
| 259 |
|
| 260 |
with ( |
| 261 |
patch("os.getpgid", side_effect=ProcessLookupError()), |
| 262 |
patch.object(parent, "children", side_effect=psutil.NoSuchProcess(300)), |
| 263 |
): |
| 264 |
kill_child_processes(parent, timeout=1) |
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
class _Summary: |
| 273 |
"""Minimal wrapper matching the dict-of-summary objects used by output_to_csv.""" |
| 274 |
|
| 275 |
def __init__(self, source): |
| 276 |
self.source = source |
| 277 |
|
| 278 |
|
| 279 |
class TestOutputFunctions: |
| 280 |
def _make_mock_source(self, name, sensors_summary, suffixes=None): |
| 281 |
"""Create a minimal mock source object.""" |
| 282 |
sensor_names = list(sensors_summary.keys()) |
| 283 |
_suffixes = suffixes or [""] * len(sensor_names) |
| 284 |
|
| 285 |
class _MockSrc: |
| 286 |
def get_is_available(self): |
| 287 |
return True |
| 288 |
|
| 289 |
def update(self): |
| 290 |
pass |
| 291 |
|
| 292 |
def get_source_name(self): |
| 293 |
return name |
| 294 |
|
| 295 |
def get_sensors_summary(self): |
| 296 |
return sensors_summary |
| 297 |
|
| 298 |
def get_sensor_list(self): |
| 299 |
return sensor_names |
| 300 |
|
| 301 |
def get_sensor_suffixes(self): |
| 302 |
return _suffixes |
| 303 |
|
| 304 |
return _MockSrc() |
| 305 |
|
| 306 |
def test_output_to_terminal(self, capsys): |
| 307 |
src = self._make_mock_source("Util", {"Avg": "25.0", "Core 0": "30.0"}) |
| 308 |
with pytest.raises(SystemExit): |
| 309 |
output_to_terminal([src]) |
| 310 |
captured = capsys.readouterr() |
| 311 |
assert "Util" in captured.out |
| 312 |
assert "25.0" in captured.out |
| 313 |
|
| 314 |
def test_output_to_json(self, capsys): |
| 315 |
src = self._make_mock_source("Util", {"Avg": "25.0"}) |
| 316 |
with pytest.raises(SystemExit): |
| 317 |
output_to_json([src]) |
| 318 |
captured = capsys.readouterr() |
| 319 |
data = json.loads(captured.out) |
| 320 |
assert "Util" in data |
| 321 |
assert data["Util"]["Avg"] == "25.0" |
| 322 |
|
| 323 |
def test_output_to_terminal_skips_unavailable(self, capsys): |
| 324 |
class _Unavailable: |
| 325 |
def get_is_available(self): |
| 326 |
return False |
| 327 |
|
| 328 |
with pytest.raises(SystemExit): |
| 329 |
output_to_terminal([_Unavailable()]) |
| 330 |
captured = capsys.readouterr() |
| 331 |
|
| 332 |
assert captured.out.strip() == "" |
| 333 |
|
| 334 |
def test_json_includes_throttle(self, capsys): |
| 335 |
src = self._make_mock_source( |
| 336 |
"Frequency", |
| 337 |
{"Avg": "2400", "Core 0": "2400"}, |
| 338 |
suffixes=["T/W", "T/W"], |
| 339 |
) |
| 340 |
with pytest.raises(SystemExit): |
| 341 |
output_to_json([src]) |
| 342 |
data = json.loads(capsys.readouterr().out) |
| 343 |
assert data["Frequency"]["Avg"] == "2400" |
| 344 |
assert data["Throttle"] == "T/W" |
| 345 |
|
| 346 |
def test_json_throttle_empty_when_no_throttling(self, capsys): |
| 347 |
src = self._make_mock_source("Frequency", {"Avg": "2400"}) |
| 348 |
with pytest.raises(SystemExit): |
| 349 |
output_to_json([src]) |
| 350 |
data = json.loads(capsys.readouterr().out) |
| 351 |
assert data["Throttle"] == "" |
| 352 |
|
| 353 |
def test_terminal_includes_throttle(self, capsys): |
| 354 |
src = self._make_mock_source( |
| 355 |
"Frequency", |
| 356 |
{"Avg": "2400"}, |
| 357 |
suffixes=["W"], |
| 358 |
) |
| 359 |
with pytest.raises(SystemExit): |
| 360 |
output_to_terminal([src]) |
| 361 |
out = capsys.readouterr().out |
| 362 |
assert "Throttle" in out |
| 363 |
assert "W" in out |
| 364 |
|
| 365 |
def test_csv_throttle_is_last_column(self, tmp_path): |
| 366 |
csv_file = str(tmp_path / "test.csv") |
| 367 |
|
| 368 |
src = self._make_mock_source( |
| 369 |
"Frequency", |
| 370 |
{"Avg": "2400", "Core 0": "2400"}, |
| 371 |
suffixes=["T/W", ""], |
| 372 |
) |
| 373 |
sources = {"Frequency": _Summary(src)} |
| 374 |
output_to_csv(sources, csv_file) |
| 375 |
|
| 376 |
with open(csv_file) as f: |
| 377 |
reader = csv.DictReader(f) |
| 378 |
fieldnames = reader.fieldnames |
| 379 |
row = next(reader) |
| 380 |
assert fieldnames[-1] == "Throttle" |
| 381 |
assert row["Throttle"] == "T/W" |
| 382 |
assert row["Frequency:Avg"] == "2400" |
| 383 |
|
| 384 |
def test_csv_throttle_empty_when_no_throttling(self, tmp_path): |
| 385 |
csv_file = str(tmp_path / "test.csv") |
| 386 |
|
| 387 |
src = self._make_mock_source("Frequency", {"Avg": "2400"}) |
| 388 |
sources = {"Frequency": _Summary(src)} |
| 389 |
output_to_csv(sources, csv_file) |
| 390 |
|
| 391 |
with open(csv_file) as f: |
| 392 |
reader = csv.DictReader(f) |
| 393 |
row = next(reader) |
| 394 |
assert row["Throttle"] == "" |
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
class TestVersion: |
| 403 |
def test_version_is_string(self): |
| 404 |
assert isinstance(__version__, str) |
| 405 |
|
| 406 |
def test_version_format(self): |
| 407 |
parts = __version__.split(".") |
| 408 |
assert len(parts) == 3 |
| 409 |
for p in parts: |
| 410 |
assert p.isdigit() |