Add data_logging/tests/test_core.py

This commit is contained in:
Mika 2026-04-26 02:07:51 +00:00
parent 4e14edeb0a
commit 86928c92b4

View file

@ -0,0 +1,68 @@
import json
import pytest
from pathlib import Path
from io import StringIO
import data_logging.core as core
@pytest.fixture
def temp_output(tmp_path):
file_path = tmp_path / "wifi_log.json"
return file_path
@pytest.fixture
def sample_entry():
return {
"timestamp": "2024-07-10T23:59:59Z",
"frequency": 2.437,
"signal_strength": -67.0
}
def read_json_file(path: Path):
if not path.exists():
pytest.fail(f"Log file {path} does not exist")
with path.open('r', encoding='utf-8') as f:
data = json.load(f)
return data
def test_log_wifi_data_creates_file(temp_output, sample_entry, monkeypatch):
monkeypatch.setattr(core, 'LOG_PATH', temp_output)
core.log_wifi_data(**sample_entry)
assert temp_output.exists(), "JSON Log file should be created."
data = read_json_file(temp_output)
assert isinstance(data, list), "Log file should contain a list of entries."
assert data[-1]['timestamp'] == sample_entry['timestamp']
assert data[-1]['frequency'] == pytest.approx(sample_entry['frequency'])
assert data[-1]['signal_strength'] == pytest.approx(sample_entry['signal_strength'])
def test_log_wifi_data_appends_entries(temp_output, sample_entry, monkeypatch):
monkeypatch.setattr(core, 'LOG_PATH', temp_output)
core.log_wifi_data(**sample_entry)
second_entry = sample_entry.copy()
second_entry['signal_strength'] = -72.5
core.log_wifi_data(**second_entry)
data = read_json_file(temp_output)
assert len(data) == 2, "File should contain two log entries."
assert data[1]['signal_strength'] == pytest.approx(-72.5)
def test_invalid_inputs_raise_error(monkeypatch, temp_output):
monkeypatch.setattr(core, 'LOG_PATH', temp_output)
# missing timestamp
with pytest.raises((TypeError, ValueError)):
core.log_wifi_data(timestamp=None, frequency=2.4, signal_strength=-60.0)
# invalid types
with pytest.raises((TypeError, ValueError)):
core.log_wifi_data(timestamp="2024-01-01T00:00:00Z", frequency="2.4GHz", signal_strength=-60.0)
with pytest.raises((TypeError, ValueError)):
core.log_wifi_data(timestamp="2024-01-01T00:00:00Z", frequency=2.4, signal_strength="strong")
def test_multiple_calls_persist_data(monkeypatch, temp_output, sample_entry):
monkeypatch.setattr(core, 'LOG_PATH', temp_output)
for idx in range(3):
se = sample_entry.copy()
se['signal_strength'] -= idx * 1.5
core.log_wifi_data(**se)
data = read_json_file(temp_output)
signals = [entry['signal_strength'] for entry in data]
assert len(signals) == 3
assert signals == sorted(signals, reverse=True), "Signal strengths should decrease stepwise."