59 lines
No EOL
2 KiB
Python
59 lines
No EOL
2 KiB
Python
import json
|
|
import tempfile
|
|
import os
|
|
import pytest
|
|
from pathlib import Path
|
|
|
|
import src.sensor_logging.main as main
|
|
|
|
|
|
def test_sensor_data_to_json_structure():
|
|
s = main.SensorData(voltage=123.4, temperature=22.1, humidity=55.2)
|
|
data = s.to_json()
|
|
assert isinstance(data, dict)
|
|
assert set(data.keys()) == {"timestamp", "voltage", "temperature", "humidity"}
|
|
assert isinstance(data["timestamp"], str)
|
|
assert data["voltage"] == pytest.approx(123.4)
|
|
assert data["temperature"] == pytest.approx(22.1)
|
|
assert data["humidity"] == pytest.approx(55.2)
|
|
|
|
|
|
def test_log_sensor_data_creates_file_and_appends():
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
logfile = Path(tmpdir) / "sensor_log.json"
|
|
|
|
# First log entry
|
|
main.log_sensor_data(1.0, 2.0, 3.0)
|
|
# Override output path temporarily
|
|
orig_path = getattr(main, "DEFAULT_OUTPUT_PATH", None)
|
|
try:
|
|
main.DEFAULT_OUTPUT_PATH = logfile
|
|
main.log_sensor_data(4.5, 6.7, 8.9)
|
|
finally:
|
|
if orig_path is not None:
|
|
main.DEFAULT_OUTPUT_PATH = orig_path
|
|
|
|
assert logfile.exists()
|
|
content = logfile.read_text().strip().splitlines()
|
|
# Assuming each line is separate JSON object
|
|
parsed = [json.loads(line) for line in content]
|
|
assert len(parsed) >= 1
|
|
for p in parsed:
|
|
assert set(p.keys()) == {"timestamp", "voltage", "temperature", "humidity"}
|
|
assert isinstance(p["voltage"], (int, float))
|
|
|
|
|
|
def test_log_sensor_data_invalid_inputs_raises(tmp_path):
|
|
# Invalid voltage type
|
|
with pytest.raises((TypeError, ValueError)):
|
|
main.log_sensor_data("bad", 25.0, 40.0)
|
|
|
|
with pytest.raises((TypeError, ValueError)):
|
|
main.log_sensor_data(2.0, None, 50.0)
|
|
|
|
|
|
def test_sensor_data_timestamp_format():
|
|
s = main.SensorData(voltage=2.2, temperature=3.3, humidity=4.4)
|
|
t = s.to_json()["timestamp"]
|
|
# Basic ISO8601 pattern validation
|
|
assert "T" in t and t.endswith("Z") |