| 1 |
"""Tests for plot command.""" |
| 2 |
|
| 3 |
import argparse |
| 4 |
import json |
| 5 |
import os |
| 6 |
from pathlib import Path |
| 7 |
from typing import Any, List, Tuple |
| 8 |
from unittest.mock import MagicMock, Mock, mock_open, patch |
| 9 |
import pytest |
| 10 |
|
| 11 |
pytest.importorskip("matplotlib") |
| 12 |
from con_duct import cli, plot |
| 13 |
from con_duct._formatter import FILESIZE_UNITS |
| 14 |
|
| 15 |
|
| 16 |
@pytest.mark.parametrize( |
| 17 |
"min_ratio,span_seconds,expected_unit", |
| 18 |
[ |
| 19 |
|
| 20 |
(-1, 2, "s"), |
| 21 |
(-1, 3700, "s"), |
| 22 |
(-1, 3 * 60 * 60 * 24, "s"), |
| 23 |
|
| 24 |
(1.5, 90, "min"), |
| 25 |
(1.5, 90 * 60, "h"), |
| 26 |
(1.5, 36 * 60 * 60, "d"), |
| 27 |
|
| 28 |
(3.0, 2, "s"), |
| 29 |
(3.0, 3 * 60, "min"), |
| 30 |
(3.0, 3 * 60 * 60, "h"), |
| 31 |
(3.0, 3 * 60 * 60 * 24, "d"), |
| 32 |
|
| 33 |
(5.0, 4 * 60, "s"), |
| 34 |
(5.0, 5 * 60, "min"), |
| 35 |
(5.0, 4 * 60 * 60, "min"), |
| 36 |
(5.0, 5 * 60 * 60, "h"), |
| 37 |
], |
| 38 |
) |
| 39 |
def test_pick_unit_with_varying_ratios( |
| 40 |
min_ratio: float, span_seconds: float, expected_unit: str |
| 41 |
) -> None: |
| 42 |
"""Test pick_unit selects appropriate unit based on min_ratio.""" |
| 43 |
formatter: Any = plot.HumanizedAxisFormatter( |
| 44 |
min_ratio=min_ratio, units=plot._TIME_UNITS |
| 45 |
) |
| 46 |
unit_name, _ = formatter.pick_unit(span_seconds) |
| 47 |
assert unit_name == expected_unit |
| 48 |
|
| 49 |
|
| 50 |
@pytest.mark.parametrize( |
| 51 |
"units,axis_range,value,expected", |
| 52 |
[ |
| 53 |
|
| 54 |
(plot._TIME_UNITS, (0, 30), 15, "15.0s"), |
| 55 |
(plot._TIME_UNITS, (0, 300), 2.3 * 60, "2.3min"), |
| 56 |
(plot._TIME_UNITS, (0, 11000), 7.8 * 60 * 60, "7.8h"), |
| 57 |
(plot._TIME_UNITS, (0, 260000), 3.2 * 60 * 60 * 24, "3.2d"), |
| 58 |
|
| 59 |
(FILESIZE_UNITS, (0, 5 * 1000), 2.6 * 1000, "2.6kB"), |
| 60 |
(FILESIZE_UNITS, (0, 4 * 1000**2), 1.5 * (1000**2), "1.5MB"), |
| 61 |
(FILESIZE_UNITS, (0, 3 * 1000**3), 8.3 * 1000**3, "8.3GB"), |
| 62 |
(FILESIZE_UNITS, (0, 3 * 1000**4), 1.3 * 1000**4, "1.3TB"), |
| 63 |
(FILESIZE_UNITS, (0, 3.1 * 1000**5), 6.5 * 1000**5, "6.5PB"), |
| 64 |
], |
| 65 |
) |
| 66 |
def test_formatter_output( |
| 67 |
units: List[Tuple[str, float]], |
| 68 |
axis_range: Tuple[float, float], |
| 69 |
value: float, |
| 70 |
expected: str, |
| 71 |
) -> None: |
| 72 |
"""Test HumanizedAxisFormatter formats values correctly for time and memory units.""" |
| 73 |
formatter: Any = plot.HumanizedAxisFormatter(min_ratio=3.0, units=units) |
| 74 |
formatter.axis = Mock() |
| 75 |
formatter.axis.get_view_interval.return_value = axis_range |
| 76 |
result = formatter(value, 0) |
| 77 |
assert result == expected |
| 78 |
|
| 79 |
|
| 80 |
class TestPlotMatplotlib: |
| 81 |
|
| 82 |
@patch("matplotlib.pyplot.savefig") |
| 83 |
def test_matplotlib_plot_sanity(self, mock_plot_save: MagicMock) -> None: |
| 84 |
args = argparse.Namespace( |
| 85 |
command="plot", |
| 86 |
file_path="test/data/mriqc-example/usage.json", |
| 87 |
output="outfile.png", |
| 88 |
func=plot.matplotlib_plot, |
| 89 |
log_level="INFO", |
| 90 |
min_ratio=3.0, |
| 91 |
cpu="ps-pcpu", |
| 92 |
) |
| 93 |
assert cli.execute(args) == 0 |
| 94 |
mock_plot_save.assert_called_once_with("outfile.png") |
| 95 |
|
| 96 |
@patch("matplotlib.pyplot.savefig") |
| 97 |
@patch("matplotlib.use") |
| 98 |
def test_matplotlib_plot_uses_agg_backend_with_output( |
| 99 |
self, mock_use: MagicMock, mock_plot_save: MagicMock |
| 100 |
) -> None: |
| 101 |
"""Test that Agg backend is used when --output is specified.""" |
| 102 |
args = argparse.Namespace( |
| 103 |
command="plot", |
| 104 |
file_path="test/data/mriqc-example/usage.json", |
| 105 |
output="outfile.png", |
| 106 |
func=plot.matplotlib_plot, |
| 107 |
log_level="INFO", |
| 108 |
min_ratio=3.0, |
| 109 |
cpu="ps-pcpu", |
| 110 |
) |
| 111 |
assert cli.execute(args) == 0 |
| 112 |
mock_use.assert_called_once_with("Agg") |
| 113 |
mock_plot_save.assert_called_once_with("outfile.png") |
| 114 |
|
| 115 |
@patch("matplotlib.pyplot.savefig") |
| 116 |
def test_matplotlib_plot_file_not_found(self, mock_plot_save: MagicMock) -> None: |
| 117 |
args = argparse.Namespace( |
| 118 |
command="plot", |
| 119 |
file_path="test/data/mriqc-example/usage_not_to_be_found.json", |
| 120 |
output="outfile.png", |
| 121 |
func=plot.matplotlib_plot, |
| 122 |
log_level="INFO", |
| 123 |
) |
| 124 |
assert cli.execute(args) == 1 |
| 125 |
mock_plot_save.assert_not_called() |
| 126 |
|
| 127 |
@patch("matplotlib.pyplot.savefig") |
| 128 |
@patch("builtins.open", new_callable=mock_open, read_data='{"invalid": "json"') |
| 129 |
def test_matplotlib_plot_invalid_json( |
| 130 |
self, _mock_open: MagicMock, mock_plot_save: MagicMock |
| 131 |
) -> None: |
| 132 |
args = argparse.Namespace( |
| 133 |
command="plot", |
| 134 |
file_path="test/data/mriqc-example/usage.json", |
| 135 |
output="outfile.png", |
| 136 |
func=plot.matplotlib_plot, |
| 137 |
log_level="INFO", |
| 138 |
) |
| 139 |
assert cli.execute(args) == 1 |
| 140 |
mock_plot_save.assert_not_called() |
| 141 |
|
| 142 |
@patch("matplotlib.pyplot.savefig") |
| 143 |
def test_matplotlib_plot_info_json(self, mock_plot_save: MagicMock) -> None: |
| 144 |
"""When user passes info.json, usage.json is retrieved and used""" |
| 145 |
args = argparse.Namespace( |
| 146 |
command="plot", |
| 147 |
file_path="test/data/mriqc-example/info.json", |
| 148 |
output="outfile.png", |
| 149 |
func=plot.matplotlib_plot, |
| 150 |
log_level="INFO", |
| 151 |
min_ratio=3.0, |
| 152 |
cpu="ps-pcpu", |
| 153 |
) |
| 154 |
assert cli.execute(args) == 0 |
| 155 |
mock_plot_save.assert_called_once_with("outfile.png") |
| 156 |
|
| 157 |
@patch("matplotlib.pyplot.savefig") |
| 158 |
def test_matplotlib_plot_info_json_absolute_path( |
| 159 |
self, mock_plot_save: MagicMock, monkeypatch: Any, tmp_path: Any |
| 160 |
) -> None: |
| 161 |
"""Test that absolute path to info.json correctly resolves usage.json path |
| 162 |
when cwd is not the original execution wd. |
| 163 |
""" |
| 164 |
abs_info_path = os.path.abspath("test/data/mriqc-example/info.json") |
| 165 |
|
| 166 |
|
| 167 |
monkeypatch.chdir(tmp_path) |
| 168 |
|
| 169 |
args = argparse.Namespace( |
| 170 |
command="plot", |
| 171 |
file_path=abs_info_path, |
| 172 |
output="outfile.png", |
| 173 |
func=plot.matplotlib_plot, |
| 174 |
log_level="INFO", |
| 175 |
min_ratio=3.0, |
| 176 |
cpu="ps-pcpu", |
| 177 |
) |
| 178 |
assert cli.execute(args) == 0 |
| 179 |
mock_plot_save.assert_called_once_with("outfile.png") |
| 180 |
|
| 181 |
@patch("matplotlib.pyplot.savefig") |
| 182 |
@patch( |
| 183 |
"builtins.open", new_callable=mock_open, read_data='{"missing": "timestamp"}' |
| 184 |
) |
| 185 |
def test_matplotlib_plot_malformed_usage_file( |
| 186 |
self, _mock_open: MagicMock, mock_plot_save: MagicMock |
| 187 |
) -> None: |
| 188 |
"""Test that malformed usage.json files are handled gracefully""" |
| 189 |
args = argparse.Namespace( |
| 190 |
command="plot", |
| 191 |
file_path="test/data/malformed_usage.json", |
| 192 |
output="outfile.png", |
| 193 |
func=plot.matplotlib_plot, |
| 194 |
log_level="INFO", |
| 195 |
) |
| 196 |
assert cli.execute(args) == 1 |
| 197 |
mock_plot_save.assert_not_called() |
| 198 |
|
| 199 |
@patch( |
| 200 |
"matplotlib.get_backend", |
| 201 |
side_effect=AttributeError("get_backend not available"), |
| 202 |
) |
| 203 |
@patch.dict("matplotlib.rcParams", {"backend": "Agg"}) |
| 204 |
def test_matplotlib_plot_non_interactive_backend( |
| 205 |
self, |
| 206 |
_mock_get_backend: MagicMock, |
| 207 |
) -> None: |
| 208 |
"""Test that plotting without output in non-interactive backend returns error.""" |
| 209 |
import matplotlib.backends |
| 210 |
|
| 211 |
if not hasattr(matplotlib.backends, "backend_registry"): |
| 212 |
pytest.skip("requires backend_registry (matplotlib >= 3.9)") |
| 213 |
|
| 214 |
args = argparse.Namespace( |
| 215 |
command="plot", |
| 216 |
file_path="test/data/mriqc-example/usage.json", |
| 217 |
output=None, |
| 218 |
func=plot.matplotlib_plot, |
| 219 |
log_level="INFO", |
| 220 |
min_ratio=3.0, |
| 221 |
cpu="ps-pcpu", |
| 222 |
) |
| 223 |
result = cli.execute(args) |
| 224 |
assert result == 1 |
| 225 |
|
| 226 |
@patch("matplotlib.get_backend", return_value="Agg") |
| 227 |
def test_matplotlib_plot_non_interactive_backend_with_get_backend( |
| 228 |
self, |
| 229 |
_mock_get_backend: MagicMock, |
| 230 |
) -> None: |
| 231 |
"""Test that plotting without output in non-interactive backend returns error using get_backend.""" |
| 232 |
import matplotlib.backends |
| 233 |
|
| 234 |
if not hasattr(matplotlib.backends, "backend_registry"): |
| 235 |
pytest.skip("requires backend_registry (matplotlib >= 3.9)") |
| 236 |
|
| 237 |
args = argparse.Namespace( |
| 238 |
command="plot", |
| 239 |
file_path="test/data/mriqc-example/usage.json", |
| 240 |
output=None, |
| 241 |
func=plot.matplotlib_plot, |
| 242 |
log_level="INFO", |
| 243 |
min_ratio=3.0, |
| 244 |
cpu="ps-pcpu", |
| 245 |
) |
| 246 |
result = cli.execute(args) |
| 247 |
assert result == 1 |
| 248 |
|
| 249 |
@patch("matplotlib.pyplot.show") |
| 250 |
@patch("matplotlib.get_backend", return_value="tkagg") |
| 251 |
def test_matplotlib_plot_interactive_backend_with_get_backend( |
| 252 |
self, |
| 253 |
_mock_get_backend: MagicMock, |
| 254 |
mock_show: MagicMock, |
| 255 |
) -> None: |
| 256 |
"""Test that plotting without output in interactive backend calls plt.show() successfully.""" |
| 257 |
|
| 258 |
args = argparse.Namespace( |
| 259 |
command="plot", |
| 260 |
file_path="test/data/mriqc-example/usage.json", |
| 261 |
output=None, |
| 262 |
func=plot.matplotlib_plot, |
| 263 |
log_level="INFO", |
| 264 |
min_ratio=3.0, |
| 265 |
cpu="ps-pcpu", |
| 266 |
) |
| 267 |
result = cli.execute(args) |
| 268 |
assert result == 0 |
| 269 |
mock_show.assert_called_once() |
| 270 |
|
| 271 |
@patch( |
| 272 |
"builtins.__import__", side_effect=ImportError("No module named 'matplotlib'") |
| 273 |
) |
| 274 |
def test_matplotlib_plot_missing_dependency(self, _mock_import: MagicMock) -> None: |
| 275 |
"""Test that plotting with missing matplotlib shows helpful error.""" |
| 276 |
args = argparse.Namespace( |
| 277 |
command="plot", |
| 278 |
file_path="test/data/mriqc-example/usage.json", |
| 279 |
output=None, |
| 280 |
func=plot.matplotlib_plot, |
| 281 |
log_level="INFO", |
| 282 |
) |
| 283 |
|
| 284 |
result = cli.execute(args) |
| 285 |
assert result == 1 |
| 286 |
|
| 287 |
@patch("matplotlib.pyplot.show") |
| 288 |
def test_matplotlib_plot_no_backend_registry( |
| 289 |
self, |
| 290 |
mock_show: MagicMock, |
| 291 |
monkeypatch: Any, |
| 292 |
caplog: Any, |
| 293 |
) -> None: |
| 294 |
"""Test fallback when backend_registry unavailable (matplotlib < 3.9).""" |
| 295 |
import matplotlib.backends |
| 296 |
|
| 297 |
|
| 298 |
if hasattr(matplotlib.backends, "backend_registry"): |
| 299 |
monkeypatch.delattr(matplotlib.backends, "backend_registry") |
| 300 |
|
| 301 |
args = argparse.Namespace( |
| 302 |
command="plot", |
| 303 |
file_path="test/data/mriqc-example/usage.json", |
| 304 |
output=None, |
| 305 |
func=plot.matplotlib_plot, |
| 306 |
log_level="INFO", |
| 307 |
min_ratio=3.0, |
| 308 |
cpu="ps-pcpu", |
| 309 |
) |
| 310 |
result = cli.execute(args) |
| 311 |
assert result == 0 |
| 312 |
mock_show.assert_called_once() |
| 313 |
assert "matplotlib < 3.9" in caplog.text |
| 314 |
|
| 315 |
|
| 316 |
class TestBuildPidSeriesCpuMode: |
| 317 |
"""``cpu`` series content varies by ``cpu_mode``.""" |
| 318 |
|
| 319 |
@staticmethod |
| 320 |
def _record(ts: str, pid: str, pcpu: float, etime: str) -> dict: |
| 321 |
return { |
| 322 |
"timestamp": ts, |
| 323 |
"processes": { |
| 324 |
pid: { |
| 325 |
"pcpu": pcpu, |
| 326 |
"pmem": 0.0, |
| 327 |
"rss": 0, |
| 328 |
"etime": etime, |
| 329 |
"timestamp": ts, |
| 330 |
"cmd": "x", |
| 331 |
} |
| 332 |
}, |
| 333 |
} |
| 334 |
|
| 335 |
def test_ps_pcpu_takes_raw_values(self) -> None: |
| 336 |
data = [ |
| 337 |
self._record("2026-05-06T00:00:00", "1", 1.5, "00:01"), |
| 338 |
self._record("2026-05-06T00:01:00", "1", 2.5, "01:01"), |
| 339 |
self._record("2026-05-06T00:02:00", "1", 3.5, "02:01"), |
| 340 |
] |
| 341 |
series = plot._build_pid_series(data, cpu_mode=plot.CPU_MODE_PS_PCPU) |
| 342 |
assert series["1"]["cpu"] == [1.5, 2.5, 3.5] |
| 343 |
|
| 344 |
def test_ps_pcpu_includes_etime_zero_record(self) -> None: |
| 345 |
|
| 346 |
|
| 347 |
data = [ |
| 348 |
self._record("2026-05-06T00:00:00", "1", 0.0, "00:00"), |
| 349 |
self._record("2026-05-06T00:01:00", "1", 5.0, "01:00"), |
| 350 |
] |
| 351 |
series = plot._build_pid_series(data, cpu_mode=plot.CPU_MODE_PS_PCPU) |
| 352 |
assert series["1"]["cpu"] == [0.0, 5.0] |
| 353 |
|
| 354 |
def test_ps_cpu_timepoint_drops_first_and_etime_zero(self) -> None: |
| 355 |
|
| 356 |
|
| 357 |
data = [ |
| 358 |
self._record("2026-05-06T00:00:00", "1", 10.0, "01:00"), |
| 359 |
self._record("2026-05-06T00:01:00", "1", 0.0, "00:00"), |
| 360 |
self._record("2026-05-06T00:02:00", "1", 50.0, "03:00"), |
| 361 |
] |
| 362 |
series = plot._build_pid_series(data, cpu_mode=plot.CPU_MODE_PS_CPU_TIMEPOINT) |
| 363 |
cpu = series["1"]["cpu"] |
| 364 |
assert cpu[0] is None |
| 365 |
assert cpu[1] is None |
| 366 |
|
| 367 |
def test_default_is_ps_pcpu(self) -> None: |
| 368 |
data = [self._record("2026-05-06T00:00:00", "1", 7.0, "00:30")] |
| 369 |
series = plot._build_pid_series(data) |
| 370 |
assert series["1"]["cpu"] == [7.0] |
| 371 |
|
| 372 |
|
| 373 |
class TestLoadHostMemoryTotal: |
| 374 |
"""Best-effort host memory_total lookup for the rss legend label.""" |
| 375 |
|
| 376 |
def _write_info(self, path: Path, data: dict) -> None: |
| 377 |
path.write_text(json.dumps(data)) |
| 378 |
|
| 379 |
def test_info_json_input(self, tmp_path: Path) -> None: |
| 380 |
info = tmp_path / "run_info.json" |
| 381 |
self._write_info(info, {"system": {"memory_total": 12345}}) |
| 382 |
assert plot._load_host_memory_total(info) == 12345 |
| 383 |
|
| 384 |
def test_usage_jsonl_with_sibling(self, tmp_path: Path) -> None: |
| 385 |
info = tmp_path / "run_info.json" |
| 386 |
usage = tmp_path / "run_usage.jsonl" |
| 387 |
self._write_info(info, {"system": {"memory_total": 67890}}) |
| 388 |
usage.write_text("") |
| 389 |
assert plot._load_host_memory_total(usage) == 67890 |
| 390 |
|
| 391 |
def test_usage_legacy_with_sibling(self, tmp_path: Path) -> None: |
| 392 |
info = tmp_path / "run_info.json" |
| 393 |
usage = tmp_path / "run_usage.json" |
| 394 |
self._write_info(info, {"system": {"memory_total": 42}}) |
| 395 |
usage.write_text("") |
| 396 |
assert plot._load_host_memory_total(usage) == 42 |
| 397 |
|
| 398 |
def test_no_sibling_returns_none(self, tmp_path: Path) -> None: |
| 399 |
usage = tmp_path / "run_usage.jsonl" |
| 400 |
usage.write_text("") |
| 401 |
assert plot._load_host_memory_total(usage) is None |
| 402 |
|
| 403 |
def test_missing_key_returns_none(self, tmp_path: Path) -> None: |
| 404 |
info = tmp_path / "run_info.json" |
| 405 |
self._write_info(info, {"system": {}}) |
| 406 |
assert plot._load_host_memory_total(info) is None |
| 407 |
|
| 408 |
def test_invalid_json_returns_none(self, tmp_path: Path) -> None: |
| 409 |
info = tmp_path / "run_info.json" |
| 410 |
info.write_text("{not json") |
| 411 |
assert plot._load_host_memory_total(info) is None |
| 412 |
|
| 413 |
def test_unparseable_filename_returns_none(self, tmp_path: Path) -> None: |
| 414 |
weird = tmp_path / "weird.txt" |
| 415 |
weird.write_text("") |
| 416 |
assert plot._load_host_memory_total(weird) is None |