Add hotspot_logging/tests/test_core.py

This commit is contained in:
Mika 2026-03-25 11:11:48 +00:00
parent e68e24731e
commit 0eaf2bcba4

View file

@ -0,0 +1,66 @@
import json
import io
import os
from datetime import datetime
import pytest
import hotspot_logging.core as core
@pytest.fixture
def mock_output_file(tmp_path):
path = tmp_path / "hotspot_log.json"
yield path
if path.exists():
path.unlink()
@pytest.mark.parametrize(
"near_expiry, total, expected",
[
(0, 10, 0.0),
(5, 10, 0.5),
(10, 10, 1.0),
],
)
def test_log_hotspot_ratio_valid(monkeypatch, tmp_path, near_expiry, total, expected):
output_file = tmp_path / "hotspot_log.json"
records = []
def fake_print(entry):
records.append(entry)
monkeypatch.setattr(core, "_write_log_entry", lambda entry, _: records.append(entry))
core.log_hotspot_ratio(1.0, near_expiry, total, output_path=output_file)
assert len(records) == 1
entry = records[0]
# Validate log entry schema
assert isinstance(entry, dict)
assert set(entry.keys()) == {"timestamp", "hotspot_ratio"}
assert isinstance(entry["timestamp"], str)
assert isinstance(entry["hotspot_ratio"], float)
# Ratio tolerance
assert abs(entry["hotspot_ratio"] - expected) < 1e-9
# Valid ISO-8601 timestamp
datetime.fromisoformat(entry["timestamp"])
def test_log_hotspot_ratio_zero_jobs(monkeypatch, tmp_path):
output_file = tmp_path / "hotspot_log.json"
records = []
monkeypatch.setattr(core, "_write_log_entry", lambda entry, _: records.append(entry))
with pytest.raises(ValueError):
core.log_hotspot_ratio(1.0, 5, 0, output_path=output_file)
def test_json_written_to_file(tmp_path):
output_file = tmp_path / "hotspot_log.json"
core.log_hotspot_ratio(2.0, 1, 4, output_path=output_file)
assert output_file.exists()
content = json.loads(output_file.read_text())
assert isinstance(content, list)
assert len(content) == 1
entry = content[0]
assert set(entry.keys()) == {"timestamp", "hotspot_ratio"}
assert isinstance(entry["hotspot_ratio"], float)