Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Strengthen 14 assertion-free smoke tests with return-value and side-effect assertions

Murtaza Nasirab8907754cd8
diff --git a/tests/test_cov_audio_chunking.py b/tests/test_cov_audio_chunking.py
index 44a37493..3593d9e4 100644
--- a/tests/test_cov_audio_chunking.py
+++ b/tests/test_cov_audio_chunking.py
@@ -705,8 +705,14 @@ def test_log_processing_statistics_with_outliers():
{"processing_time": 12, "size_mb": 16, "duration": 300},
{"processing_time": 90, "size_mb": 18, "duration": 300}, # outlier
]
- # Just ensure it runs through the outlier / summary branches without error.
- svc.log_processing_statistics(results)
+ with mock.patch.object(ac, "logger") as mock_logger:
+ ret = svc.log_processing_statistics(results)
+ assert ret is None
+ # The 90s outlier (vs ~37s avg) must trip the performance-outlier warning
+ # branch — proving the outlier path actually ran, not just "didn't crash".
+ assert mock_logger.warning.called
+ warned = " ".join(str(c.args[0]) for c in mock_logger.warning.call_args_list)
+ assert "outlier" in warned.lower()
def test_get_performance_recommendations_empty():
@@ -761,7 +767,12 @@ def test_cleanup_chunks_missing_files_no_error(tmp_path):
svc = AudioChunkingService()
chunks = [{"path": str(tmp_path / "gone.mp3"), "filename": "gone.mp3"}]
# Should not raise even though file doesn't exist.
- svc.cleanup_chunks(chunks, temp_mp3_path=str(tmp_path / "alsogone.mp3"))
+ with mock.patch("os.remove") as mock_remove:
+ ret = svc.cleanup_chunks(chunks, temp_mp3_path=str(tmp_path / "alsogone.mp3"))
+ assert ret is None
+ # Neither the (missing) chunk nor the (missing) temp mp3 exists, so removal
+ # must never be attempted.
+ mock_remove.assert_not_called()
def test_cleanup_chunks_remove_error_swallowed(tmp_path):
@@ -769,8 +780,11 @@ def test_cleanup_chunks_remove_error_swallowed(tmp_path):
f1.write_bytes(b"x")
svc = AudioChunkingService()
chunks = [{"path": str(f1), "filename": "c0.mp3"}]
- with mock.patch("os.remove", side_effect=OSError("denied")):
- svc.cleanup_chunks(chunks) # warning logged, no raise
+ with mock.patch("os.remove", side_effect=OSError("denied")) as mock_remove:
+ ret = svc.cleanup_chunks(chunks) # warning logged, no raise
+ assert ret is None
+ # The file exists, so removal WAS attempted; the OSError was swallowed.
+ mock_remove.assert_called_once_with(str(f1))
# ---------------------------------------------------------------------------
diff --git a/tests/test_cov_file_monitor.py b/tests/test_cov_file_monitor.py
index d6d22a1a..5bab7714 100644
--- a/tests/test_cov_file_monitor.py
+++ b/tests/test_cov_file_monitor.py
@@ -92,8 +92,11 @@ class TestScanDirectoryFiltering(unittest.TestCase):
def test_nonexistent_directory_is_noop(self):
monitor = _make_monitor(self.temp_dir, self.uid)
missing = monitor.base_watch_directory / 'does-not-exist'
- # Should simply return, not raise.
- monitor._scan_directory_for_user(missing, self.uid)
+ monitor._process_file = MagicMock()
+ # Should simply return, not raise, and process nothing.
+ ret = monitor._scan_directory_for_user(missing, self.uid)
+ self.assertIsNone(ret)
+ monitor._process_file.assert_not_called()
def test_hidden_and_processing_and_unsupported_files_skipped(self):
_write_file(os.path.join(self.temp_dir, '.hidden.mp3'))
@@ -315,8 +318,11 @@ class TestModeDispatch(unittest.TestCase):
mode='user_directories')
# base dir was created by __init__, so remove it to hit the not-exists path.
shutil.rmtree(str(monitor.base_watch_directory), ignore_errors=True)
- monitor._scan_directory_for_user = lambda *a, **kw: self.fail("should not scan")
- monitor._scan_user_directories() # returns silently
+ monitor._scan_directory_for_user = MagicMock()
+ ret = monitor._scan_user_directories() # returns silently
+ self.assertIsNone(ret)
+ # Missing base dir -> nothing should be scanned.
+ monitor._scan_directory_for_user.assert_not_called()
def test_single_user_configured(self):
monitor = _make_monitor(self.temp_dir, self.uid, mode='single_user')
@@ -330,17 +336,23 @@ class TestModeDispatch(unittest.TestCase):
def test_single_user_not_configured(self):
monitor = _make_monitor(self.temp_dir, self.uid, mode='single_user')
- monitor._scan_directory_for_user = lambda *a, **kw: self.fail("should not scan")
+ monitor._scan_directory_for_user = MagicMock()
env = {k: v for k, v in os.environ.items() if k != 'AUTO_PROCESS_DEFAULT_USERNAME'}
with patch.dict(os.environ, env, clear=True):
- monitor._scan_single_user_directory()
+ ret = monitor._scan_single_user_directory()
+ self.assertIsNone(ret)
+ # No default username configured -> nothing should be scanned.
+ monitor._scan_directory_for_user.assert_not_called()
def test_single_user_invalid_username(self):
monitor = _make_monitor(self.temp_dir, self.uid, mode='single_user')
monitor._username_to_id = {}
- monitor._scan_directory_for_user = lambda *a, **kw: self.fail("should not scan")
+ monitor._scan_directory_for_user = MagicMock()
with patch.dict(os.environ, {'AUTO_PROCESS_DEFAULT_USERNAME': 'ghost_user'}):
- monitor._scan_single_user_directory()
+ ret = monitor._scan_single_user_directory()
+ self.assertIsNone(ret)
+ # Configured username isn't a valid user -> nothing should be scanned.
+ monitor._scan_directory_for_user.assert_not_called()
# ---------------------------------------------------------------------------
@@ -784,14 +796,19 @@ class TestModuleHelpers(unittest.TestCase):
# Force the query to return an empty list -> early return (line 598-599).
with patch('src.models.Tag') as TagMock:
TagMock.query.filter_by.return_value.all.return_value = []
- _ensure_tag_folders_on_startup(app, self.temp_dir, 'admin_only')
+ ret = _ensure_tag_folders_on_startup(app, self.temp_dir, 'admin_only')
+ self.assertIsNone(ret)
+ # No auto-process tags -> early return, so no folders were created.
+ self.assertEqual(os.listdir(self.temp_dir), [])
def test_ensure_tag_folders_handles_query_error(self):
# Force the inner Tag query to raise; the helper swallows and logs.
with patch('src.models.Tag') as TagMock:
TagMock.query.filter_by.side_effect = RuntimeError("db down")
- # Should not raise.
- _ensure_tag_folders_on_startup(app, self.temp_dir, 'admin_only')
+ # Should swallow the error (not raise) and create no folders.
+ result = _ensure_tag_folders_on_startup(app, self.temp_dir, 'admin_only')
+ assert result is None
+ assert os.listdir(self.temp_dir) == []
if __name__ == '__main__':
diff --git a/tests/test_cov_processing.py b/tests/test_cov_processing.py
index 34d96d81..47f483c0 100644
--- a/tests/test_cov_processing.py
+++ b/tests/test_cov_processing.py
@@ -239,7 +239,12 @@ def test_summary_event_extraction_invoked_when_user_extract_events():
def test_summary_missing_recording_returns_quietly():
with app.app_context():
# An ID that does not exist must not raise.
- proc.generate_summary_only_task(app.app_context(), 99999999)
+ with _patch_llm(content="should never run") as mock_call:
+ ret = proc.generate_summary_only_task(app.app_context(), 99999999)
+ assert ret is None
+ # Missing record -> must bail out before doing any LLM work.
+ mock_call.assert_not_called()
+ assert db.session.get(Recording, 99999999) is None
def test_summary_user_id_viewer_filtering():
@@ -351,7 +356,12 @@ def test_title_client_not_configured_falls_back_to_filename():
def test_title_missing_recording_returns_quietly():
with app.app_context():
- proc.generate_title_task(app.app_context(), 99999999)
+ with _patch_llm(content="should never run") as mock_call:
+ ret = proc.generate_title_task(app.app_context(), 99999999)
+ assert ret is None
+ # Missing record -> must bail out before doing any LLM work.
+ mock_call.assert_not_called()
+ assert db.session.get(Recording, 99999999) is None
def test_title_budget_exceeded_skips_gracefully():
@@ -562,9 +572,14 @@ def test_transcribe_with_connector_missing_recording():
import time as _time
with app.app_context():
# Must return quietly, not raise.
- proc.transcribe_with_connector(
- app.app_context(), 99999999, "/x.mp3", "x.mp3", _time.time(),
- )
+ with patch("src.services.transcription.get_connector") as mock_get_conn:
+ ret = proc.transcribe_with_connector(
+ app.app_context(), 99999999, "/x.mp3", "x.mp3", _time.time(),
+ )
+ assert ret is None
+ # Missing record -> must bail out before resolving any connector.
+ mock_get_conn.assert_not_called()
+ assert db.session.get(Recording, 99999999) is None
def test_transcribe_with_connector_error_reraises():
diff --git a/tests/test_cov_storage_s3.py b/tests/test_cov_storage_s3.py
index 5d01ae91..bea93933 100644
--- a/tests/test_cov_storage_s3.py
+++ b/tests/test_cov_storage_s3.py
@@ -205,7 +205,13 @@ def test_upload_local_file_delete_source_missing_file_ignored():
missing = '/tmp/definitely_not_here_speakr_xyz.mp3'
with patch_client(backend, fake):
# should not raise even though the file doesn't exist
- backend.upload_local_file(missing, 'audio/del.mp3', delete_source=True)
+ result = backend.upload_local_file(missing, 'audio/del.mp3', delete_source=True)
+ # The missing-source deletion is swallowed; the upload still completes and
+ # returns a valid StoredObject pointing at the uploaded key.
+ assert isinstance(result, StoredObject)
+ assert result.locator == 's3://mybucket/audio/del.mp3'
+ assert result.key == 'audio/del.mp3'
+ fake.upload_file.assert_called_once_with(missing, 'mybucket', 'audio/del.mp3')
# ---------------------------------------------------------------------------