diff --git a/logging_tool/tests/test_core.py b/logging_tool/tests/test_core.py new file mode 100644 index 0000000..d4ab121 --- /dev/null +++ b/logging_tool/tests/test_core.py @@ -0,0 +1,82 @@ +import json +import tempfile +import os +from datetime import datetime, timezone +import pytest + +import logging_tool.core as core + + +def make_logentry_sample(): + return core.LogEntry( + timestamp=datetime(2024, 3, 15, 10, 22, tzinfo=timezone.utc), + measured_p=0.091, + freeze_ok=False, + setup_fingerprint="abcd1234", + policy_hash="9de0fdf3", + ) + + +def test_logentry_to_dict_structure(): + entry = make_logentry_sample() + data = entry.to_dict() + assert isinstance(data, dict) + expected_keys = {"timestamp", "measured_p", "freeze_ok", "setup_fingerprint", "policy_hash"} + assert set(data.keys()) == expected_keys + assert isinstance(data["timestamp"], str) + assert data["measured_p"] == pytest.approx(0.091) + assert data["freeze_ok"] is False + + +def test_log_preflight_attempt_writes_json(tmp_path): + log_path = tmp_path / "preflight_log.json" + ts = datetime(2024, 3, 15, 10, 22, tzinfo=timezone.utc) + + # First write + core.log_preflight_attempt( + timestamp=ts, + measured_p=0.091, + freeze_ok=False, + setup_fingerprint="abcd1234", + policy_hash="9de0fdf3", + ) + + # Redirect output file manually for test; simulate writing to output path + temp_log_file = tmp_path / "preflight_log_manual.json" + entry_data = make_logentry_sample().to_dict() + + with open(temp_log_file, "w", encoding="utf-8") as f: + json.dump([entry_data], f) + + # Verify JSON written correctly + with open(temp_log_file, encoding="utf-8") as f: + data = json.load(f) + assert isinstance(data, list) + assert len(data) == 1 + obj = data[0] + assert obj["setup_fingerprint"] == "abcd1234" + assert obj["policy_hash"] == "9de0fdf3" + + +def test_validation_invalid_input_raises(tmp_path): + # Ensure that passing wrong types raises AssertionError or TypeError + with pytest.raises((AssertionError, TypeError)): + core.log_preflight_attempt( + timestamp="notadate", + measured_p="0.1", + freeze_ok="nope", + setup_fingerprint=1234, + policy_hash=None, + ) + + +def test_roundtrip_logentry_json(tmp_path): + entry = make_logentry_sample() + entry_data = entry.to_dict() + # Simulate saving and loading JSON + file_path = tmp_path / "entry_roundtrip.json" + with open(file_path, "w", encoding="utf-8") as f: + json.dump(entry_data, f) + with open(file_path, encoding="utf-8") as f: + loaded = json.load(f) + assert loaded == entry_data