Add timestamp_logger/tests/test_core.py

This commit is contained in:
Mika 2026-02-14 15:31:58 +00:00
parent dad2ecb563
commit 7ad2827c3c

View file

@ -0,0 +1,56 @@
import io
import json
import tempfile
import os
from datetime import datetime
import pytest
from pathlib import Path
import src.timestamp_logger.core as core
def test_log_timestamps_success(monkeypatch):
# create temp file path
with tempfile.TemporaryDirectory() as tmpdir:
log_path = Path(tmpdir) / "mess_log.jsonl"
# monkeypatch the output file path if defined inside the module
monkeypatch.setattr(core, "LOG_FILE_PATH", log_path, raising=False)
t_publish = datetime(2024, 4, 12, 14, 32, 45)
t_gate_read = datetime(2024, 4, 12, 14, 34, 1)
t_index_visible = datetime(2024, 4, 12, 14, 36, 33)
result = core.log_timestamps(t_publish, t_gate_read, t_index_visible)
assert result is True
assert log_path.exists()
content = log_path.read_text(encoding="utf-8").strip().splitlines()
assert len(content) == 1
entry = json.loads(content[0])
assert entry["t_publish"] == t_publish.isoformat()
assert entry["t_gate_read"] == t_gate_read.isoformat()
assert entry["t_index_visible"] == t_index_visible.isoformat()
def test_log_timestamps_invalid_input_type():
invalid_time = "2024-04-12T14:32:45"
valid_time = datetime(2024, 4, 12, 14, 32, 45)
# at least one value wrong should raise or return False
with tempfile.TemporaryDirectory() as tmpdir:
log_path = Path(tmpdir) / "mess_log.jsonl"
setattr(core, "LOG_FILE_PATH", log_path)
with pytest.raises((TypeError, ValueError)):
core.log_timestamps(invalid_time, valid_time, valid_time)
def test_log_timestamps_file_writing_failure(monkeypatch):
# simulate unwritable file path
unwritable_path = Path("/root/forbidden.jsonl")
monkeypatch.setattr(core, "LOG_FILE_PATH", unwritable_path, raising=False)
t_publish = datetime(2024, 4, 12, 14, 32, 45)
t_gate_read = datetime(2024, 4, 12, 14, 34, 1)
t_index_visible = datetime(2024, 4, 12, 14, 36, 33)
result = core.log_timestamps(t_publish, t_gate_read, t_index_visible)
assert result is False