Add data_logging/tests/test_core.py
This commit is contained in:
parent
88010939cc
commit
4565979dbc
1 changed files with 60 additions and 0 deletions
60
data_logging/tests/test_core.py
Normal file
60
data_logging/tests/test_core.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import pytest
|
||||
import csv
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from pydantic import ValidationError
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Sicherstellen, dass das src-Paket importiert werden kann
|
||||
ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||
SRC_DIR = ROOT_DIR / 'src'
|
||||
sys.path.insert(0, str(SRC_DIR))
|
||||
|
||||
from data_logging.core import LogEntry, log_data
|
||||
|
||||
def make_sample_entries():
|
||||
return [
|
||||
LogEntry(timestamp=datetime(2024, 1, 1, 12, 0, 0), value=-0.5, status='valid'),
|
||||
LogEntry(timestamp=datetime(2024, 1, 1, 12, 5, 0), value=-1.2, status='error')
|
||||
]
|
||||
|
||||
def test_log_data_creates_csv_successfully(tmp_path: Path):
|
||||
data = make_sample_entries()
|
||||
output_file = tmp_path / 'test_log.csv'
|
||||
success = log_data(data, str(output_file))
|
||||
|
||||
assert success is True
|
||||
assert output_file.exists(), 'CSV wurde nicht erstellt'
|
||||
|
||||
with open(output_file, newline='') as f:
|
||||
reader = csv.DictReader(f)
|
||||
rows = list(reader)
|
||||
|
||||
assert len(rows) == len(data)
|
||||
# Validieren von Feldern
|
||||
for row, entry in zip(rows, data):
|
||||
assert row['timestamp'] == entry.timestamp.isoformat()
|
||||
assert float(row['value']) == pytest.approx(entry.value)
|
||||
assert row['status'] == entry.status
|
||||
|
||||
def test_log_entry_invalid_fields_raise_validation_error():
|
||||
# Ungültiger Timestamp
|
||||
with pytest.raises(ValidationError):
|
||||
LogEntry(timestamp='not-a-date', value=-2.3, status='valid')
|
||||
# Ungültiger Typ für Value
|
||||
with pytest.raises(ValidationError):
|
||||
LogEntry(timestamp=datetime.now(), value='NaN', status='valid')
|
||||
|
||||
|
||||
def test_log_data_handles_empty_list(tmp_path: Path):
|
||||
output_file = tmp_path / 'empty.csv'
|
||||
success = log_data([], str(output_file))
|
||||
assert success is True
|
||||
assert output_file.exists()
|
||||
with open(output_file) as f:
|
||||
content = f.read()
|
||||
# Bei leerer Eingabe sollte nur Header geschrieben werden
|
||||
assert 'timestamp' in content
|
||||
assert content.count('\n') == 1
|
||||
Loading…
Reference in a new issue