diff --git a/donau_listener/tests/test_core.py b/donau_listener/tests/test_core.py new file mode 100644 index 0000000..bfb3e69 --- /dev/null +++ b/donau_listener/tests/test_core.py @@ -0,0 +1,85 @@ +import json +import os +import pytest +from pathlib import Path +from unittest import mock + +import donau_listener.core as core + +@pytest.fixture +def mock_output_path(tmp_path): + output_file = tmp_path / "recording_log.json" + yield output_file + +@pytest.fixture +def sample_recording_data(): + return { + "timestamp": "2024-05-15T12:00:00Z", + "water_level": 0.85, + "ground_vibration": 0.12, + "ai_label": "wave" + } + +def test_start_recording_valid(monkeypatch): + # Mock audio library to avoid real recording + with mock.patch("donau_listener.core.sd") as mock_sd: + mock_stream = mock.Mock() + mock_sd.InputStream.return_value.__enter__.return_value = mock_stream + result = core.start_recording(0.8, 0.03) + assert isinstance(result, str) + assert "started" in result.lower() or "recording" in result.lower() + mock_sd.InputStream.assert_called() + +def test_start_recording_invalid_gain(): + # Gain outside valid range should raise ValueError + with pytest.raises(ValueError): + core.start_recording(-0.5, 0.02) + + with pytest.raises(ValueError): + core.start_recording(1.5, 0.02) + +def test_start_recording_invalid_threshold(): + with pytest.raises(ValueError): + core.start_recording(0.5, -0.1) + + +def test_log_data_creates_file(monkeypatch, mock_output_path, sample_recording_data): + # Patch output path in module + monkeypatch.setattr(core, "OUTPUT_PATH", mock_output_path) + + success = core.log_data(**sample_recording_data) + assert success is True + assert mock_output_path.exists() + + # Validate JSON structure + with open(mock_output_path, 'r', encoding='utf-8') as f: + data = json.load(f) + + assert isinstance(data, list) + assert data[0]["timestamp"] == sample_recording_data["timestamp"] + assert isinstance(data[0]["water_level"], float) + assert data[0]["ai_label"] == "wave" + +def test_log_data_appends_entries(monkeypatch, mock_output_path, sample_recording_data): + monkeypatch.setattr(core, "OUTPUT_PATH", mock_output_path) + + core.log_data(**sample_recording_data) + second_entry = { + "timestamp": "2024-05-15T12:01:00Z", + "water_level": 0.9, + "ground_vibration": 0.11, + "ai_label": "boat" + } + core.log_data(**second_entry) + + with open(mock_output_path, 'r', encoding='utf-8') as f: + data = json.load(f) + + assert len(data) == 2 + assert data[1]["ai_label"] == "boat" + + +def test_log_data_invalid_input(monkeypatch, mock_output_path): + monkeypatch.setattr(core, "OUTPUT_PATH", mock_output_path) + with pytest.raises(ValueError): + core.log_data(timestamp="not-a-time", water_level="abc", ground_vibration=0.1, ai_label="test") \ No newline at end of file