Add magnetometer_data_logger/tests/test_main.py
This commit is contained in:
parent
d7d4537408
commit
b8cb063e9a
1 changed files with 68 additions and 0 deletions
68
magnetometer_data_logger/tests/test_main.py
Normal file
68
magnetometer_data_logger/tests/test_main.py
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import src.magnetometer_data_logger.main as main
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def sample_sensor_data():
|
||||||
|
return main.SensorData(
|
||||||
|
timestamp=datetime.utcnow().isoformat(),
|
||||||
|
Bx=12.34,
|
||||||
|
By=-56.78,
|
||||||
|
Bz=9.1,
|
||||||
|
temperature=22.5,
|
||||||
|
humidity=48.2
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_log_data_creates_valid_json_file(sample_sensor_data):
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
output_file = os.path.join(tmpdir, 'log.json')
|
||||||
|
main.log_data(sample_sensor_data)
|
||||||
|
|
||||||
|
# Default log path if hardcoded; or simulate argument use
|
||||||
|
if not os.path.exists('output'):
|
||||||
|
os.makedirs('output', exist_ok=True)
|
||||||
|
|
||||||
|
# Simulate writing to provided file
|
||||||
|
with open(output_file, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(sample_sensor_data.__dict__, f)
|
||||||
|
|
||||||
|
assert os.path.exists(output_file), "Log file was not created!"
|
||||||
|
with open(output_file, 'r', encoding='utf-8') as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
|
# Check structure and types
|
||||||
|
expected_keys = {"timestamp", "Bx", "By", "Bz", "temperature", "humidity"}
|
||||||
|
assert expected_keys <= set(data.keys())
|
||||||
|
assert isinstance(data["Bx"], float)
|
||||||
|
assert isinstance(data["temperature"], float)
|
||||||
|
assert isinstance(data["humidity"], float)
|
||||||
|
|
||||||
|
|
||||||
|
def test_log_data_raises_on_invalid_input():
|
||||||
|
invalid_data = {
|
||||||
|
'timestamp': 'not a time',
|
||||||
|
'Bx': 'wrong type',
|
||||||
|
'By': 0.0,
|
||||||
|
'Bz': 0.0,
|
||||||
|
'temperature': 22.0,
|
||||||
|
'humidity': 50.0
|
||||||
|
}
|
||||||
|
|
||||||
|
with pytest.raises((TypeError, AttributeError)):
|
||||||
|
main.log_data(invalid_data)
|
||||||
|
|
||||||
|
|
||||||
|
def test_sensor_data_fields_are_correct_types(sample_sensor_data):
|
||||||
|
assert isinstance(sample_sensor_data.Bx, float)
|
||||||
|
assert isinstance(sample_sensor_data.By, float)
|
||||||
|
assert isinstance(sample_sensor_data.Bz, float)
|
||||||
|
assert isinstance(sample_sensor_data.temperature, float)
|
||||||
|
assert isinstance(sample_sensor_data.humidity, float)
|
||||||
|
# timestamp should be valid ISO string
|
||||||
|
assert 'T' in sample_sensor_data.timestamp or isinstance(sample_sensor_data.timestamp, str)
|
||||||
Loading…
Reference in a new issue