Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Clean up synthetic users and recordings after every test run to keep dev DB clean
Murtaza Nasir1c766ff67475
diff --git a/tests/test_admin_hotwords_and_bugfixes.py b/tests/test_admin_hotwords_and_bugfixes.pyindex 5d21d5b8..a99f3e19 100644--- a/tests/test_admin_hotwords_and_bugfixes.py+++ b/tests/test_admin_hotwords_and_bugfixes.py@@ -358,6 +358,21 @@ def test_user_transcription_language():# Main# =============================================================================+def teardown_module(module):+ """Drop synthetic users created by this test file. pytest invokes this+ automatically; the standalone main() also calls it explicitly so the+ cleanup runs whether the file is executed as a script or via pytest.+ """+ from src.app import app, db+ from src.models import User+ with app.app_context():+ for username in ('chat_test_user',):+ user = User.query.filter_by(username=username).first()+ if user:+ db.session.delete(user)+ db.session.commit()++def main():global PASSED, FAILED, ERRORS@@ -365,10 +380,13 @@ def main():print("Recent Fixes Tests (#240, #245, #246, #250)")print("=" * 60)- test_admin_default_hotwords()- test_chat_api_fix()- test_azure_empty_choices()- test_user_transcription_language()+ try:+ test_admin_default_hotwords()+ test_chat_api_fix()+ test_azure_empty_choices()+ test_user_transcription_language()+ finally:+ teardown_module(None)print("\n" + "=" * 60)print(f"RESULTS: {PASSED} passed, {FAILED} failed")diff --git a/tests/test_api_v1_parity.py b/tests/test_api_v1_parity.pyindex 875b42bb..25ed59c7 100644--- a/tests/test_api_v1_parity.py+++ b/tests/test_api_v1_parity.py@@ -137,10 +137,22 @@ def test_list_has_all_new_fields():assert not missing, f"list item missing fields: {missing}"+def cleanup_test_users():+ """Drop every user created by this file so leaked rows do not appear in+ the admin user-management screens or aggregate stats."""+ with app.app_context():+ for u in User.query.filter(User.username.like('v1parity_%')).all():+ db.session.delete(u)+ db.session.commit()++def main():print("=== Issue #274: API v1 parity ===\n")- run("detail endpoint exposes new fields", test_detail_has_all_new_fields)- run("list endpoint exposes new fields", test_list_has_all_new_fields)+ try:+ run("detail endpoint exposes new fields", test_detail_has_all_new_fields)+ run("list endpoint exposes new fields", test_list_has_all_new_fields)+ finally:+ cleanup_test_users()print(f"\nResults: {PASSED} passed, {FAILED} failed")return 0 if FAILED == 0 else 1diff --git a/tests/test_auto_process_tags.py b/tests/test_auto_process_tags.pyindex 011d6986..68ced4df 100644--- a/tests/test_auto_process_tags.py+++ b/tests/test_auto_process_tags.py@@ -85,9 +85,27 @@ class TestTagAutoProcessModel(unittest.TestCase):# Layer 2: API Tests# ---------------------------------------------------------------------------+def _drop_synthetic_users(*usernames):+ """Helper used by class-level teardowns to remove any synthetic users+ created during the test run. Cascades clear their dependent rows so the+ dev database does not accumulate test artifacts that show up in admin+ and user-facing screens.+ """+ with app.app_context():+ for name in usernames:+ row = User.query.filter_by(username=name).first()+ if row:+ db.session.delete(row)+ db.session.commit()++class TestTagAutoProcessAPI(unittest.TestCase):"""Test Tag API endpoints with auto-process."""+ @classmethod+ def tearDownClass(cls):+ _drop_synthetic_users('autotest_user', 'autotest_nonadmin')+def setUp(self):self.app_context = app.app_context()self.app_context.push()@@ -302,6 +320,11 @@ class TestTagAutoProcessAPI(unittest.TestCase):# ---------------------------------------------------------------------------class TestFileMonitorTagSubdirs(unittest.TestCase):+ @classmethod+ def tearDownClass(cls):+ _drop_synthetic_users('autotest_monitor_user')++"""Test file monitor tag subdirectory scanning."""def setUp(self):@@ -494,6 +517,11 @@ class TestFileMonitorTagSubdirs(unittest.TestCase):# ---------------------------------------------------------------------------class TestAutoProcessEdgeCases(unittest.TestCase):+ @classmethod+ def tearDownClass(cls):+ _drop_synthetic_users('autotest_edge_user')++"""Edge case tests for auto-process features."""def setUp(self):diff --git a/tests/test_bugfixes.py b/tests/test_bugfixes.pyindex 1737c1f4..20863808 100644--- a/tests/test_bugfixes.py+++ b/tests/test_bugfixes.py@@ -37,6 +37,18 @@ def _get_or_create_user():return user+def teardown_module(module):+ """Drop the synthetic user created by this test module so it does not+ accumulate in the dev database and surface in admin / user-facing screens.+ pytest auto-calls teardown_module after every test in the file completes.+ """+ with app.app_context():+ user = User.query.filter_by(username="bugfix_test_user").first()+ if user:+ db.session.delete(user)+ db.session.commit()++def _create_recording_with_snippets(user):"""Create a recording that has speaker_snippet records attached."""rec = Recording(diff --git a/tests/test_job_queue_race_condition.py b/tests/test_job_queue_race_condition.pyindex dee58113..ae39b872 100644--- a/tests/test_job_queue_race_condition.py+++ b/tests/test_job_queue_race_condition.py@@ -227,35 +227,38 @@ def test_multiple_jobs_fair_distribution():db.session.rollback()return None- # Each "worker" claims one job- for i in range(num_jobs + 2): # Extra attempts to ensure no double claims- job_id = claim_any_job(i)- if job_id:- claimed_jobs.append(job_id)- print(f" Worker {i} claimed job {job_id}")- else:- print(f" Worker {i} found no available jobs")-- print(f"\nClaimed jobs: {claimed_jobs}")- print(f"Unique jobs claimed: {len(set(claimed_jobs))}")-- # Verify no duplicates- assert len(claimed_jobs) == len(set(claimed_jobs)), "Duplicate job claims detected!"- assert len(claimed_jobs) == num_jobs, f"Expected {num_jobs} claims, got {len(claimed_jobs)}"-- # Cleanup- for job_id in job_ids:- job = db.session.get(ProcessingJob, job_id)- if job:- db.session.delete(job)- for rec_id in recording_ids:- rec = db.session.get(Recording, rec_id)- if rec:- db.session.delete(rec)- db.session.commit()-- print("\n[PASS] All jobs claimed exactly once!")- return True+ try:+ # Each "worker" claims one job+ for i in range(num_jobs + 2): # Extra attempts to ensure no double claims+ job_id = claim_any_job(i)+ if job_id:+ claimed_jobs.append(job_id)+ print(f" Worker {i} claimed job {job_id}")+ else:+ print(f" Worker {i} found no available jobs")++ print(f"\nClaimed jobs: {claimed_jobs}")+ print(f"Unique jobs claimed: {len(set(claimed_jobs))}")++ # Verify no duplicates+ assert len(claimed_jobs) == len(set(claimed_jobs)), "Duplicate job claims detected!"+ assert len(claimed_jobs) == num_jobs, f"Expected {num_jobs} claims, got {len(claimed_jobs)}"++ print("\n[PASS] All jobs claimed exactly once!")+ return True+ finally:+ # Cleanup must run even if the assertions above fail. Without this+ # the synthetic 'Test Distribution Recording N' rows leak into the+ # dev DB and show up in admin and user-facing recording lists.+ for job_id in job_ids:+ job = db.session.get(ProcessingJob, job_id)+ if job:+ db.session.delete(job)+ for rec_id in recording_ids:+ rec = db.session.get(Recording, rec_id)+ if rec:+ db.session.delete(rec)+ db.session.commit()if __name__ == '__main__':diff --git a/tests/test_reprocess_hotwords.py b/tests/test_reprocess_hotwords.pyindex 392f28c4..b707dc06 100644--- a/tests/test_reprocess_hotwords.py+++ b/tests/test_reprocess_hotwords.py@@ -208,13 +208,29 @@ def test_empty_when_nothing_configured():assert params.get("initial_prompt") is None, f"got {params!r}"+def cleanup_test_users():+ """Remove every user created by this test file.++ Tests run against the live dev database, so without an explicit teardown+ the synthesised users would accumulate forever and pollute the admin+ user-management screens.+ """+ with app.app_context():+ for u in User.query.filter(User.username.like('reprocess_test_%')).all():+ db.session.delete(u)+ db.session.commit()++def main():print("=== Issue #265: reprocess hotwords/initial_prompt precedence ===\n")- run("user input wins over all defaults", test_user_input_wins)- run("tag defaults apply when no user input", test_tag_defaults_apply_when_no_user_input)- run("folder defaults apply when no tag", test_folder_defaults_apply_when_no_tag)- run("user account defaults apply as last resort", test_user_defaults_apply_as_last_resort)- run("nothing configured → both None", test_empty_when_nothing_configured)+ try:+ run("user input wins over all defaults", test_user_input_wins)+ run("tag defaults apply when no user input", test_tag_defaults_apply_when_no_user_input)+ run("folder defaults apply when no tag", test_folder_defaults_apply_when_no_tag)+ run("user account defaults apply as last resort", test_user_defaults_apply_as_last_resort)+ run("nothing configured → both None", test_empty_when_nothing_configured)+ finally:+ cleanup_test_users()print(f"\nResults: {PASSED} passed, {FAILED} failed")return 0 if FAILED == 0 else 1diff --git a/tests/test_transcription_model_override.py b/tests/test_transcription_model_override.pyindex 20307f41..0ded8dd8 100644--- a/tests/test_transcription_model_override.py+++ b/tests/test_transcription_model_override.py@@ -279,22 +279,34 @@ def test_effective_model_blank_override_falls_back():# Main# -----------------------------------------------------------------------------+def cleanup_test_users():+ """Drop every user created by this file so leaked rows do not appear in+ the admin user-management screens or aggregate stats."""+ with app.app_context():+ for u in User.query.filter(User.username.like('models_%')).all():+ db.session.delete(u)+ db.session.commit()++def main():print("=== Issue #266: per-upload/tag/folder transcription model ===\n")- print("--- env parsing ---")- run("CSV + labels parses correctly", test_models_csv_parses_with_labels)- run("unset env var → empty options", test_models_csv_unset_means_empty)- print("\n--- precedence chain ---")- run("user input wins over tag/folder", test_user_input_wins_over_defaults)- run("tag default applies when no user input", test_tag_default_applied_when_no_user_input)- run("folder default applies when no tag", test_folder_default_applied_when_no_tag)- run("model outside allowlist dropped", test_user_supplied_model_outside_allowlist_dropped)- run("nothing configured → None", test_no_defaults_means_no_model_in_job_params)- print("\n--- TranscriptionRequest plumbing ---")- run("model field exists", test_transcription_request_has_model_field)- run("override propagates", test_effective_model_uses_override)- run("falls back when no override", test_effective_model_falls_back_to_default)- run("blank override falls back", test_effective_model_blank_override_falls_back)+ try:+ print("--- env parsing ---")+ run("CSV + labels parses correctly", test_models_csv_parses_with_labels)+ run("unset env var → empty options", test_models_csv_unset_means_empty)+ print("\n--- precedence chain ---")+ run("user input wins over tag/folder", test_user_input_wins_over_defaults)+ run("tag default applies when no user input", test_tag_default_applied_when_no_user_input)+ run("folder default applies when no tag", test_folder_default_applied_when_no_tag)+ run("model outside allowlist dropped", test_user_supplied_model_outside_allowlist_dropped)+ run("nothing configured → None", test_no_defaults_means_no_model_in_job_params)+ print("\n--- TranscriptionRequest plumbing ---")+ run("model field exists", test_transcription_request_has_model_field)+ run("override propagates", test_effective_model_uses_override)+ run("falls back when no override", test_effective_model_falls_back_to_default)+ run("blank override falls back", test_effective_model_blank_override_falls_back)+ finally:+ cleanup_test_users()print(f"\nResults: {PASSED} passed, {FAILED} failed")return 0 if FAILED == 0 else 1