radiowellen_experiment/data_logging/tests/test_core.py

60 lines
No EOL
1.9 KiB
Python

import json
import os
import tempfile
from pathlib import Path
import pytest
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from data_logging import core
def test_log_data_creates_and_appends_valid_json(tmp_path, monkeypatch):
log_file = tmp_path / 'log_data.json'
# Patch the target output path in the function if it uses fixed path
monkeypatch.setattr(core, 'Path', lambda p=None: tmp_path if p is None else Path(p))
data_points = [
{"timestamp": "2024-06-01T12:00:00Z", "temperature": 22.5, "signal_noise_ratio": 35.1},
{"timestamp": "2024-06-01T12:05:00Z", "temperature": 22.7, "signal_noise_ratio": 34.8}
]
for dp in data_points:
core.log_data(dp['timestamp'], dp['temperature'], dp['signal_noise_ratio'])
assert log_file.exists(), 'Log file should be created by log_data()'
with open(log_file, 'r', encoding='utf-8') as f:
content = f.read().strip()
assert content, 'Log file must not be empty.'
# Interpret as JSON lines
lines = content.splitlines()
parsed = [json.loads(l) for l in lines]
assert all(isinstance(p, dict) for p in parsed)
expected_keys = {'timestamp', 'temperature', 'signal_noise_ratio'}
for p in parsed:
assert expected_keys.issubset(p.keys())
assert isinstance(p['timestamp'], str)
assert isinstance(p['temperature'], (float, int))
assert isinstance(p['signal_noise_ratio'], (float, int))
# Check append behavior
assert len(parsed) == len(data_points)
def test_log_data_handles_invalid_input(tmp_path):
log_file = tmp_path / 'log_data.json'
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
# Expect that invalid temperature type raises an error
with pytest.raises((TypeError, ValueError)):
core.log_data('2024-06-01T12:00:00Z', 'invalid', 34.2)
assert not log_file.exists(), 'Invalid input should not create a file.'