Add logger/tests/test_core.py

This commit is contained in:
Mika 2026-03-29 03:07:27 +00:00
parent d415d20b5d
commit d5c6e60057

75
logger/tests/test_core.py Normal file
View file

@ -0,0 +1,75 @@
import json
import os
import time
from pathlib import Path
import pytest
# Import the module under test from the logger package
import src.logger.core as core
def test_logentry_to_dict():
ts = time.time()
entry = core.LogEntry(
timestamp=ts,
led_id="LED_A1",
lumens=123.4,
peak_wavelength=540.2,
latitude=48.8566,
longitude=2.3522,
)
data = entry.to_dict()
assert isinstance(data, dict)
assert set(data.keys()) == {
"timestamp",
"led_id",
"lumens",
"peak_wavelength",
"latitude",
"longitude",
}
assert data["led_id"] == "LED_A1"
assert pytest.approx(data["lumens"], 0.01) == 123.4
def test_start_logging_creates_json_file(tmp_path):
log_path = tmp_path / "session_log.json"
# Monkeypatch output path in the core module if required
# but since the API returns a file path, we test the returned path object exists
result_path = core.start_logging(interval=0.1, duration=0.3)
# Ensure a valid path string is returned
assert isinstance(result_path, str)
# Wait briefly to ensure file system flush
time.sleep(0.1)
# The generated log file should exist
path_obj = Path(result_path)
assert path_obj.exists(), f"Expected log file {path_obj} to exist"
# JSON should be a list of LogEntries
with open(path_obj, "r", encoding="utf-8") as f:
data = json.load(f)
assert isinstance(data, list)
assert len(data) >= 1
sample = data[0]
for key in ["timestamp", "led_id", "lumens", "peak_wavelength", "latitude", "longitude"]:
assert key in sample
def test_start_logging_invalid_parameters():
# Negative interval should raise an assertion or error
with pytest.raises(Exception):
core.start_logging(interval=-1, duration=1)
# Zero duration should still produce a file but likely empty data
path = core.start_logging(interval=0.1, duration=0)
assert isinstance(path, str)
if os.path.exists(path):
with open(path, 'r', encoding='utf-8') as f:
data = json.load(f)
assert isinstance(data, list)