Add data_logger/tests/test_core.py
This commit is contained in:
parent
3fa3637d98
commit
be51d20a2b
1 changed files with 59 additions and 0 deletions
59
data_logger/tests/test_core.py
Normal file
59
data_logger/tests/test_core.py
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import csv
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from data_logger import core
|
||||
|
||||
|
||||
def make_sample_data():
|
||||
return [
|
||||
core.SensorData('2024-01-01T12:00:00', 23.5, 0.12, 45.0),
|
||||
core.SensorData('2024-01-01T12:01:00', 24.0, 0.10, 46.5)
|
||||
]
|
||||
|
||||
|
||||
def test_sensor_data_initialization():
|
||||
data = core.SensorData('2024-01-01T12:00:00', 22.1, 0.15, 50.0)
|
||||
assert data.timestamp == '2024-01-01T12:00:00'
|
||||
assert isinstance(data.temperature, float)
|
||||
assert isinstance(data.vibration_amplitude, float)
|
||||
assert isinstance(data.humidity, float)
|
||||
|
||||
|
||||
def test_log_sensor_data_creates_csv():
|
||||
data_list = make_sample_data()
|
||||
tmpdir = Path(tempfile.mkdtemp())
|
||||
output_path = tmpdir / 'logged_data.csv'
|
||||
|
||||
# call function
|
||||
csv_path = core.log_sensor_data(data_list)
|
||||
|
||||
assert isinstance(csv_path, str)
|
||||
out_file = Path(csv_path)
|
||||
assert out_file.exists()
|
||||
|
||||
# check CSV content
|
||||
with out_file.open('r', newline='') as f:
|
||||
reader = csv.DictReader(f)
|
||||
rows = list(reader)
|
||||
|
||||
assert len(rows) == len(data_list)
|
||||
for i, row in enumerate(rows):
|
||||
assert set(row.keys()) == {'timestamp', 'temperature', 'vibration_amplitude', 'humidity'}
|
||||
assert float(row['temperature']) == pytest.approx(data_list[i].temperature, rel=1e-6)
|
||||
assert float(row['vibration_amplitude']) == pytest.approx(data_list[i].vibration_amplitude, rel=1e-6)
|
||||
assert float(row['humidity']) == pytest.approx(data_list[i].humidity, rel=1e-6)
|
||||
|
||||
|
||||
def test_log_sensor_data_empty_list(tmp_path):
|
||||
with pytest.raises((AssertionError, ValueError, TypeError)):
|
||||
core.log_sensor_data([])
|
||||
|
||||
|
||||
def test_invalid_sensor_data_type(tmp_path):
|
||||
invalid_data = [
|
||||
{'timestamp': '2024-01-01T12:00:00', 'temperature': 22.0, 'vibration_amplitude': 0.1, 'humidity': 40.0}
|
||||
]
|
||||
with pytest.raises((AssertionError, AttributeError, TypeError)):
|
||||
core.log_sensor_data(invalid_data)
|
||||
Loading…
Reference in a new issue