jrrribeiro commited on
Commit
cdaafcb
·
1 Parent(s): 3038fe7

feat: Add support for local audio validation testing

Browse files

- Add AudioFetchService.fetch_local(local_audio_path) method
- Load audio from local filesystem for testing
- Support for .wav, .mp3, .flac, .ogg, .m4a formats
- Caching via ephemeral cache manager
- Error handling for missing/unsupported files

- Add 4 unit tests for local audio fetch:
- test_fetch_local_loads_local_audio_file
- test_fetch_local_caches_on_second_call
- test_fetch_local_raises_on_nonexistent_file
- test_fetch_local_raises_on_unsupported_format

- Add 5 integration tests for local audio validation workflow:
- test_load_local_audio_segment_and_create_detection
- test_fetch_local_audio_and_validate
- test_validate_multiple_local_audio_segments
- test_validation_table_with_local_segments
- test_local_audio_cache_reuse

Features:
- Local audio fixtures generated in tests
- Full validation workflow tested with local segments
- Cache reuse verified across multiple loads
- Integration with existing detection/validation pipeline

Test coverage: +9 new tests
All 104 tests passing, no regressions.

src/services/audio_fetch_service.py CHANGED
@@ -35,6 +35,35 @@ class AudioFetchService:
35
  local_path = self._cache.put_bytes(cache_key, downloaded_path.read_bytes(), suffix=suffix)
36
  return AudioFetchResult(cache_key=cache_key, local_path=str(local_path), source="remote")
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def cleanup_after_validation(self, cache_key: str) -> None:
39
  self._cache.cleanup_key(cache_key)
40
 
 
35
  local_path = self._cache.put_bytes(cache_key, downloaded_path.read_bytes(), suffix=suffix)
36
  return AudioFetchResult(cache_key=cache_key, local_path=str(local_path), source="remote")
37
 
38
+ def fetch_local(self, local_audio_path: str) -> AudioFetchResult:
39
+ """Load audio from local filesystem (useful for testing with local segments).
40
+
41
+ Args:
42
+ local_audio_path: Full path to local audio file
43
+
44
+ Returns:
45
+ AudioFetchResult with cache_key based on file path
46
+
47
+ Raises:
48
+ FileNotFoundError: If local file doesn't exist or is not a supported audio format
49
+ """
50
+ audio_path = Path(local_audio_path)
51
+ if not audio_path.exists():
52
+ raise FileNotFoundError(f"Local audio file not found: {local_audio_path}")
53
+
54
+ if audio_path.suffix.lower() not in SUPPORTED_AUDIO_EXTENSIONS:
55
+ raise ValueError(f"Unsupported audio format: {audio_path.suffix}. Supported: {SUPPORTED_AUDIO_EXTENSIONS}")
56
+
57
+ cache_key = f"local:{audio_path.name}:{audio_path.stat().st_size}"
58
+ cached_path = self._cache.get(cache_key)
59
+ if cached_path:
60
+ return AudioFetchResult(cache_key=cache_key, local_path=str(cached_path), source="cache")
61
+
62
+ # Cache the local file by copying it into the ephemeral cache
63
+ local_bytes = audio_path.read_bytes()
64
+ cached_path = self._cache.put_bytes(cache_key, local_bytes, suffix=audio_path.suffix)
65
+ return AudioFetchResult(cache_key=cache_key, local_path=str(cached_path), source="local")
66
+
67
  def cleanup_after_validation(self, cache_key: str) -> None:
68
  self._cache.cleanup_key(cache_key)
69
 
tests/integration/test_local_audio_validation.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Integration tests for validating local audio segments.
2
+
3
+ These tests demonstrate how to load audio from the local filesystem
4
+ and run it through the validation workflow, useful for testing with
5
+ local audio segments instead of remote datasets.
6
+ """
7
+
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ from src.auth.auth_service import AuthService
13
+ from src.cache.ephemeral_cache_manager import EphemeralCacheManager
14
+ from src.domain.models import Detection
15
+ from src.repositories.in_memory_detection_repository import InMemoryDetectionRepository
16
+ from src.repositories.in_memory_validation_repository import InMemoryValidationRepository
17
+ from src.services.audio_fetch_service import AudioFetchService
18
+ from src.services.detection_queue_service import DetectionQueueService
19
+ from src.services.validation_service import ValidationService
20
+
21
+
22
+ @pytest.fixture
23
+ def local_audio_files(tmp_path: Path) -> dict[str, Path]:
24
+ """Create test audio files locally."""
25
+ audio_dir = tmp_path / "audio_segments"
26
+ audio_dir.mkdir()
27
+
28
+ # Create minimal WAV files for testing
29
+ files = {
30
+ "segment_001.wav": audio_dir / "segment_001.wav",
31
+ "segment_002.wav": audio_dir / "segment_002.wav",
32
+ "segment_003.wav": audio_dir / "segment_003.wav",
33
+ }
34
+
35
+ for filename, filepath in files.items():
36
+ # Write minimal WAV header + dummy audio data (16 bytes header + 100 bytes data)
37
+ wav_header = b"RIFF" + (108).to_bytes(4, "little") + b"WAVEfmt " + \
38
+ (16).to_bytes(4, "little") + \
39
+ (1).to_bytes(2, "little") + (1).to_bytes(2, "little") + \
40
+ (16000).to_bytes(4, "little") + (32000).to_bytes(4, "little") + \
41
+ (2).to_bytes(2, "little") + (16).to_bytes(2, "little") + \
42
+ b"data" + (64).to_bytes(4, "little") + (b"\x00" * 64)
43
+ filepath.write_bytes(wav_header)
44
+
45
+ return files
46
+
47
+
48
+ @pytest.fixture
49
+ def auth_service() -> AuthService:
50
+ """Create auth service with test users."""
51
+ service = AuthService()
52
+ service.register_user_project_access(
53
+ username="alice",
54
+ project_access={"birds-local": "validator"}
55
+ )
56
+ return service
57
+
58
+
59
+ @pytest.fixture
60
+ def repositories() -> tuple[InMemoryDetectionRepository, InMemoryValidationRepository]:
61
+ """Create in-memory repositories."""
62
+ detection_repo = InMemoryDetectionRepository()
63
+ validation_repo = InMemoryValidationRepository()
64
+ return detection_repo, validation_repo
65
+
66
+
67
+ @pytest.fixture
68
+ def services(tmp_path: Path, repositories: tuple) -> tuple[AudioFetchService, ValidationService, DetectionQueueService]:
69
+ """Create service instances for local audio testing."""
70
+ detection_repo, validation_repo = repositories
71
+
72
+ cache = EphemeralCacheManager(cache_dir=str(tmp_path / "cache"), ttl_seconds=120, max_files=20)
73
+ audio_service = AudioFetchService(cache)
74
+ validation_service = ValidationService(validation_repo)
75
+ detection_queue = DetectionQueueService(detection_repo)
76
+
77
+ return audio_service, validation_service, detection_queue
78
+
79
+
80
+ def test_load_local_audio_segment_and_create_detection(
81
+ local_audio_files: dict[str, Path],
82
+ repositories: tuple,
83
+ ) -> None:
84
+ """Test loading a local audio file and creating a detection from it."""
85
+ detection_repo, _ = repositories
86
+ segment_path = local_audio_files["segment_001.wav"]
87
+
88
+ # Create a detection object for the local audio segment
89
+ detection = Detection(
90
+ detection_key="LOCAL-SEG-001-ABCD",
91
+ audio_id=segment_path.name,
92
+ scientific_name="Parus major", # Great Tit
93
+ confidence=0.85,
94
+ start_time=0.5,
95
+ end_time=2.5,
96
+ )
97
+
98
+ # Seed the detection into the repository
99
+ detection_repo.seed(project_slug="birds-local", detections=[detection])
100
+
101
+ # Verify detection was stored by listing all detections
102
+ detections = detection_repo.list_detections(
103
+ project_slug="birds-local",
104
+ page=1,
105
+ page_size=10,
106
+ )
107
+ assert len(detections) == 1
108
+ assert detections[0].scientific_name == "Parus major"
109
+ assert detections[0].confidence == 0.85
110
+
111
+
112
+ def test_fetch_local_audio_and_validate(
113
+ local_audio_files: dict[str, Path],
114
+ services: tuple,
115
+ repositories: tuple,
116
+ ) -> None:
117
+ """Test fetching local audio and validating a detection."""
118
+ audio_service, validation_service, _ = services
119
+ detection_repo, _ = repositories
120
+ segment_path = local_audio_files["segment_001.wav"]
121
+
122
+ # Fetch the local audio file
123
+ audio_result = audio_service.fetch_local(str(segment_path))
124
+
125
+ assert audio_result.source == "local"
126
+ assert Path(audio_result.local_path).exists()
127
+
128
+ # Create and seed a detection for this audio
129
+ detection = Detection(
130
+ detection_key="LOCAL-SEG-002-EFGH",
131
+ audio_id=segment_path.name,
132
+ scientific_name="Turdus merula", # European Blackbird
133
+ confidence=0.92,
134
+ start_time=1.0,
135
+ end_time=3.0,
136
+ )
137
+ detection_repo.seed(project_slug="birds-local", detections=[detection])
138
+
139
+ # Validate the detection
140
+ result = validation_service.validate_detection(
141
+ project_slug="birds-local",
142
+ detection_key="LOCAL-SEG-002-EFGH",
143
+ status="confirmed",
144
+ validator="alice",
145
+ notes="Clear call, high confidence",
146
+ corrected_species="Turdus merula",
147
+ )
148
+
149
+ assert result.item.status == "confirmed"
150
+ assert result.item.validator == "alice"
151
+ assert result.item.notes == "Clear call, high confidence"
152
+
153
+
154
+ def test_validate_multiple_local_audio_segments(
155
+ local_audio_files: dict[str, Path],
156
+ services: tuple,
157
+ repositories: tuple,
158
+ ) -> None:
159
+ """Test validating multiple local audio segments in one session."""
160
+ audio_service, validation_service, _ = services
161
+ detection_repo, _ = repositories
162
+ segment_files = [
163
+ (local_audio_files["segment_001.wav"], "species_1"),
164
+ (local_audio_files["segment_002.wav"], "species_2"),
165
+ (local_audio_files["segment_003.wav"], "species_3"),
166
+ ]
167
+
168
+ # Create and seed all detections first
169
+ detections = []
170
+ for idx, (segment_path, species) in enumerate(segment_files):
171
+ detection = Detection(
172
+ detection_key=f"LOCAL-BATCH-{idx:03d}-IJKL",
173
+ audio_id=segment_path.name,
174
+ scientific_name=species,
175
+ confidence=0.80 + (idx * 0.05),
176
+ start_time=0.5,
177
+ end_time=2.5,
178
+ )
179
+ detections.append(detection)
180
+
181
+ detection_repo.seed(project_slug="birds-local", detections=detections)
182
+
183
+ validations = []
184
+
185
+ for idx, (segment_path, species) in enumerate(segment_files):
186
+ # Fetch local audio
187
+ audio_result = audio_service.fetch_local(str(segment_path))
188
+ assert audio_result.source in ("local", "cache")
189
+
190
+ # Validate the detection
191
+ validation_result = validation_service.validate_detection(
192
+ project_slug="birds-local",
193
+ detection_key=f"LOCAL-BATCH-{idx:03d}-IJKL",
194
+ status="confirmed",
195
+ validator=f"validator_{idx}",
196
+ notes=f"Validated segment {idx + 1}",
197
+ )
198
+ validations.append(validation_result)
199
+
200
+ # Verify all validations were created
201
+ assert len(validations) == 3
202
+ for idx, validation in enumerate(validations):
203
+ assert validation.item.status == "confirmed"
204
+ assert validation.item.validator == f"validator_{idx}"
205
+
206
+
207
+ def test_validation_table_with_local_segments(
208
+ local_audio_files: dict[str, Path],
209
+ services: tuple,
210
+ repositories: tuple,
211
+ ) -> None:
212
+ """Test that validation table can display validations for local audio segments."""
213
+ audio_service, validation_service, _ = services
214
+ detection_repo, validation_repo = repositories
215
+
216
+ segment_path = local_audio_files["segment_001.wav"]
217
+
218
+ # 1. Create and seed detection for local audio
219
+ detection = Detection(
220
+ detection_key="LOCAL-UI-TEST-001",
221
+ audio_id=segment_path.name,
222
+ scientific_name="Accipiter nisus", # Eurasian Sparrowhawk
223
+ confidence=0.88,
224
+ start_time=0.0,
225
+ end_time=3.5,
226
+ )
227
+ detection_repo.seed(project_slug="birds-local", detections=[detection])
228
+
229
+ # 2. Fetch the local audio
230
+ audio_result = audio_service.fetch_local(str(segment_path))
231
+ assert audio_result.source in ("local", "cache")
232
+
233
+ # 3. Validate the detection
234
+ validation_result = validation_service.validate_detection(
235
+ project_slug="birds-local",
236
+ detection_key="LOCAL-UI-TEST-001",
237
+ status="confirmed",
238
+ validator="ui_tester",
239
+ notes="UI test validation",
240
+ corrected_species="Accipiter nisus",
241
+ )
242
+
243
+ # 4. Retrieve validation to simulate table display
244
+ project_validations = validation_repo.list_validations(project_slug="birds-local")
245
+
246
+ # Verify the validation appears in the table
247
+ assert len(project_validations) == 1
248
+ assert project_validations[0].detection_key == "LOCAL-UI-TEST-001"
249
+ assert project_validations[0].status == "confirmed"
250
+ assert project_validations[0].corrected_species == "Accipiter nisus"
251
+
252
+
253
+ def test_local_audio_cache_reuse(
254
+ local_audio_files: dict[str, Path],
255
+ services: tuple,
256
+ ) -> None:
257
+ """Test that local audio files are cached efficiently on repeated access."""
258
+ audio_service, _, _ = services
259
+ segment_path = local_audio_files["segment_002.wav"]
260
+
261
+ # First fetch
262
+ result1 = audio_service.fetch_local(str(segment_path))
263
+ assert result1.source == "local"
264
+ path1 = result1.local_path
265
+
266
+ # Second fetch should come from cache
267
+ result2 = audio_service.fetch_local(str(segment_path))
268
+ assert result2.source == "cache"
269
+ assert result2.local_path == path1
270
+ assert result2.cache_key == result1.cache_key
271
+
272
+ # Cleanup
273
+ audio_service.cleanup_after_validation(result1.cache_key)
274
+ # After cleanup, next fetch should load from local again
275
+ result3 = audio_service.fetch_local(str(segment_path))
276
+ assert result3.source == "local"
tests/unit/test_audio_fetch_service.py CHANGED
@@ -78,3 +78,57 @@ def test_cleanup_after_validation_removes_cached_file(tmp_path: Path, monkeypatc
78
 
79
  assert not path_before.exists()
80
  assert cache.get(result.cache_key) is None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
  assert not path_before.exists()
80
  assert cache.get(result.cache_key) is None
81
+
82
+
83
+ def test_fetch_local_loads_local_audio_file(tmp_path: Path) -> None:
84
+ """Test loading audio from local filesystem (useful for testing with local segments)."""
85
+ # Create a local audio file
86
+ local_audio = tmp_path / "local_segment.wav"
87
+ local_audio.write_bytes(b"local-audio-bytes")
88
+
89
+ cache = EphemeralCacheManager(cache_dir=str(tmp_path / "cache"), ttl_seconds=60, max_files=10)
90
+ service = AudioFetchService(cache)
91
+
92
+ result = service.fetch_local(str(local_audio))
93
+
94
+ assert result.source == "local"
95
+ assert Path(result.local_path).exists()
96
+ assert Path(result.local_path).read_bytes() == b"local-audio-bytes"
97
+ assert "local:" in result.cache_key
98
+
99
+
100
+ def test_fetch_local_caches_on_second_call(tmp_path: Path) -> None:
101
+ """Test that local audio is cached after first fetch."""
102
+ local_audio = tmp_path / "segment.wav"
103
+ local_audio.write_bytes(b"segment-bytes")
104
+
105
+ cache = EphemeralCacheManager(cache_dir=str(tmp_path / "cache"), ttl_seconds=60, max_files=10)
106
+ service = AudioFetchService(cache)
107
+
108
+ first = service.fetch_local(str(local_audio))
109
+ second = service.fetch_local(str(local_audio))
110
+
111
+ assert first.source == "local"
112
+ assert second.source == "cache"
113
+ assert first.cache_key == second.cache_key
114
+
115
+
116
+ def test_fetch_local_raises_on_nonexistent_file(tmp_path: Path) -> None:
117
+ """Test that fetch_local raises error for missing files."""
118
+ cache = EphemeralCacheManager(cache_dir=str(tmp_path / "cache"), ttl_seconds=60, max_files=10)
119
+ service = AudioFetchService(cache)
120
+
121
+ with pytest.raises(FileNotFoundError, match="Local audio file not found"):
122
+ service.fetch_local(str(tmp_path / "nonexistent.wav"))
123
+
124
+
125
+ def test_fetch_local_raises_on_unsupported_format(tmp_path: Path) -> None:
126
+ """Test that fetch_local rejects unsupported audio formats."""
127
+ unsupported_file = tmp_path / "audio.xyz"
128
+ unsupported_file.write_bytes(b"not-audio")
129
+
130
+ cache = EphemeralCacheManager(cache_dir=str(tmp_path / "cache"), ttl_seconds=60, max_files=10)
131
+ service = AudioFetchService(cache)
132
+
133
+ with pytest.raises(ValueError, match="Unsupported audio format"):
134
+ service.fetch_local(str(unsupported_file))