Add python_sensor_logger/tests/test_core.py

This commit is contained in:
Mika 2026-04-12 02:07:08 +00:00
parent 5991b59eb8
commit a0ad800ec1

View file

@ -0,0 +1,94 @@
import json
import os
import time
import tempfile
from pathlib import Path
from unittest import mock
import pytest
import src.python_sensor_logger.core as core
def test_read_temperature_returns_float(monkeypatch):
mock_value = 23.456
with mock.patch('src.python_sensor_logger.core.read_temperature', return_value=mock_value):
result = core.read_temperature()
assert isinstance(result, float), 'Rückgabewert sollte float sein'
assert result == pytest.approx(mock_value)
def test_log_temperature_creates_valid_json(tmp_path):
file_path = tmp_path / 'temperature_log.json'
timestamp = time.time()
temperature = 22.5
# Sicherstellen, dass Datei noch nicht existiert
if file_path.exists():
file_path.unlink()
# Funktion aufrufen
with mock.patch('src.python_sensor_logger.core.os.path.exists', return_value=False):
core.log_temperature(timestamp, temperature)
# Wenn Datei nicht vom Mock erstellt, selbst prüfen
if not file_path.exists():
# Versuch, Standardpfad zu prüfen
default_path = Path('output/temperature_log.json')
if default_path.exists():
file_path = default_path
assert file_path.exists(), 'JSON-Datei sollte nach log_temperature existieren'
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# Je nach Implementation: Liste oder einzelner Eintrag
if isinstance(data, list):
entry = data[-1]
else:
entry = data
assert 'timestamp' in entry, 'timestamp-Feld fehlt'
assert 'temperature' in entry, 'temperature-Feld fehlt'
# Validate value types
assert isinstance(entry['timestamp'], float)
assert isinstance(entry['temperature'], float)
assert entry['temperature'] == pytest.approx(temperature)
def test_log_temperature_appends_data(tmp_path):
file_path = tmp_path / 'temp_log.json'
# Erstes Logging
first_ts = time.time()
first_temp = 20.0
core.log_temperature(first_ts, first_temp)
assert os.path.exists('output/temperature_log.json') or file_path.exists()
# Zweites Logging
second_ts = time.time() + 5
second_temp = 21.0
core.log_temperature(second_ts, second_temp)
# Datei überprüfen
path_to_check = Path('output/temperature_log.json') if Path('output/temperature_log.json').exists() else file_path
with open(path_to_check, 'r', encoding='utf-8') as f:
records = json.load(f)
assert isinstance(records, list), 'JSON sollte eine Liste sein'
timestamps = [r['timestamp'] for r in records]
temps = [r['temperature'] for r in records]
assert first_ts in timestamps or pytest.approx(first_ts) in timestamps
assert any(pytest.approx(second_temp, rel=1e-3) == t for t in temps)
def test_temperature_validation():
invalid_inputs = [None, 'NaN', [], {}]
for invalid_temp in invalid_inputs:
with pytest.raises((TypeError, AssertionError)):
core.log_temperature(time.time(), invalid_temp)