Skip to content

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

Python

Close mutation-sweep survivors (batch 2b): audio config flags, file-monitor admin scan, job-queue round-robin/filename, auth registration/SSO-init

Murtaza Nasir9d8d9acf0449
diff --git a/tests/test_cov_audio_chunking.py b/tests/test_cov_audio_chunking.py
index 3593d9e4..c5dc7cc0 100644
--- a/tests/test_cov_audio_chunking.py
+++ b/tests/test_cov_audio_chunking.py
@@ -207,6 +207,54 @@ def test_config_connector_recommended_soft():
assert cfg.source == "connector_recommended"
+# ---------------------------------------------------------------------------
+# get_effective_chunking_config: cfg.enabled assertions
+#
+# These pin the `enabled` flag of the EffectiveChunkingConfig returned by each
+# distinct branch. The mode/limit/source assertions above don't touch `enabled`,
+# so a mutated `enabled=` field in these branches would otherwise go unnoticed.
+# ---------------------------------------------------------------------------
+
+def test_config_connector_hard_size_limit_enabled():
+ # Connector hard size-limit branch (no user override): chunking is REQUIRED,
+ # so enabled must be True.
+ specs = make_specs(max_file_size_bytes=100 * 1024 * 1024)
+ cfg = get_effective_chunking_config(specs)
+ assert cfg.enabled is True
+ assert cfg.source == "connector_limit"
+
+
+def test_config_connector_and_user_size_min_enabled(monkeypatch):
+ # Same hard size-limit return, now via the MIN(user, connector) path: still
+ # a required-chunking branch, enabled must be True.
+ monkeypatch.setenv("CHUNK_LIMIT", "10MB")
+ specs = make_specs(max_file_size_bytes=100 * 1024 * 1024)
+ cfg = get_effective_chunking_config(specs)
+ assert cfg.enabled is True
+ assert cfg.source == "user_and_connector"
+
+
+def test_config_connector_recommended_soft_enabled():
+ # Connector-recommended (soft, no hard limit) branch: chunking is optional
+ # but enabled, so enabled must be True.
+ specs = make_specs(recommended_chunk_seconds=480)
+ cfg = get_effective_chunking_config(specs)
+ assert cfg.enabled is True
+ assert cfg.source == "connector_recommended"
+
+
+def test_config_disabled_branch_enabled_false(monkeypatch):
+ # Disabled-via-env branch (ENABLE_CHUNKING=false) returns the disabled config
+ # with enabled=False, regardless of connector specs (as long as there are no
+ # hard limits and the connector doesn't chunk internally).
+ monkeypatch.setenv("ENABLE_CHUNKING", "false")
+ specs = make_specs(recommended_chunk_seconds=480)
+ cfg = get_effective_chunking_config(specs)
+ assert cfg.enabled is False
+ assert cfg.mode == "none"
+ assert cfg.source == "disabled"
+
+
# ---------------------------------------------------------------------------
# AudioChunkingService construction / needs_chunking
# ---------------------------------------------------------------------------
diff --git a/tests/test_cov_auth.py b/tests/test_cov_auth.py
index 47fe266f..ddc15de9 100644
--- a/tests/test_cov_auth.py
+++ b/tests/test_cov_auth.py
@@ -672,5 +672,104 @@ def test_update_auto_speaker_labelling_persists(cleanup_users):
assert refreshed.auto_speaker_labelling_threshold == 'high'
+# ---------------------------------------------------------------------------
+# Registration-domain parsing edge cases (is_registration_domain_allowed)
+# ---------------------------------------------------------------------------
+
+def test_registration_domain_empty_env_allows_all(app_ctx):
+ # auth.py:112-113 — REGISTRATION_ALLOWED_DOMAINS unset/empty ⇒ no
+ # restriction ⇒ every domain is allowed.
+ with _envset(REGISTRATION_ALLOWED_DOMAINS=''):
+ assert auth_mod.is_registration_domain_allowed('[email protected]') is True
+ assert auth_mod.is_registration_domain_allowed('[email protected]') is True
+
+
+def test_registration_domain_whitespace_env_allows_all(app_ctx):
+ # auth.py:112 — a whitespace-only value strips to nothing ⇒ still no
+ # restriction. (The `or not domains_env.strip()` clause covers this.)
+ with _envset(REGISTRATION_ALLOWED_DOMAINS=' '):
+ assert auth_mod.is_registration_domain_allowed('[email protected]') is True
+
+
+def test_registration_domain_commas_only_allows_all(app_ctx):
+ # auth.py:115-117 — a value with content but no real domains after the
+ # comma split (so `allowed` is empty) ⇒ treated as no restriction ⇒ True.
+ # This reaches line 117 specifically; `return True`->`return False` here
+ # would wrongly reject every registration.
+ with _envset(REGISTRATION_ALLOWED_DOMAINS=', ,'):
+ assert auth_mod.is_registration_domain_allowed('[email protected]') is True
+ assert auth_mod.is_registration_domain_allowed('[email protected]') is True
+
+
+def test_registration_domain_allowlist_in_and_out(app_ctx):
+ # auth.py:119-124 — a real allowlist gates by domain: in-list True,
+ # out-of-list False. Case-insensitive on both env and email side.
+ with _envset(REGISTRATION_ALLOWED_DOMAINS='Example.com, corp.net'):
+ assert auth_mod.is_registration_domain_allowed('[email protected]') is True
+ assert auth_mod.is_registration_domain_allowed('[email protected]') is True
+ assert auth_mod.is_registration_domain_allowed('[email protected]') is False
+
+
+# ---------------------------------------------------------------------------
+# SSO client initialization on the login route (auth.py:243-244)
+# ---------------------------------------------------------------------------
+
+def _sso_enabled_with_config():
+ """SSO enabled + a usable config, WITHOUT patching the client helpers so
+ each test controls get_sso_client / init_sso_client itself."""
+ with mock.patch.object(auth_mod, 'is_sso_enabled', return_value=True), \
+ mock.patch.object(auth_mod, 'get_sso_config',
+ return_value={'provider_name': 'Keycloak',
+ 'redirect_uri': 'https://app/cb'}):
+ yield
+
+
+def test_sso_login_uses_cached_client_without_reinit():
+ # auth.py:243 — when get_sso_client() returns a client, the `or` must
+ # short-circuit and init_sso_client must NOT be called. The `or`->`and`
+ # mutation would call init_sso_client (and use ITS return value instead).
+ oauth = mock.MagicMock()
+ oauth.sso.authorize_redirect.return_value = 'redirecting'
+ with _sso_enabled_with_config(), \
+ mock.patch.object(auth_mod, 'get_sso_client', return_value=oauth), \
+ mock.patch.object(auth_mod, 'init_sso_client') as init_mock:
+ client = app.test_client()
+ resp = client.get('/auth/sso/login')
+ assert resp.status_code == 200
+ init_mock.assert_not_called()
+ oauth.sso.authorize_redirect.assert_called_once()
+
+
+def test_sso_login_inits_client_when_none_cached():
+ # auth.py:243 — get_sso_client() None ⇒ init_sso_client IS invoked and its
+ # client is used. Under `or`->`and`, `None and init_sso_client(...)`
+ # short-circuits, init is never called, and the route bails to /login.
+ oauth = mock.MagicMock()
+ oauth.sso.authorize_redirect.return_value = 'redirecting'
+ with _sso_enabled_with_config(), \
+ mock.patch.object(auth_mod, 'get_sso_client', return_value=None), \
+ mock.patch.object(auth_mod, 'init_sso_client', return_value=oauth) as init_mock:
+ client = app.test_client()
+ resp = client.get('/auth/sso/login')
+ assert resp.status_code == 200
+ init_mock.assert_called_once()
+ oauth.sso.authorize_redirect.assert_called_once()
+
+
+def test_sso_login_bails_to_login_when_client_unavailable():
+ # auth.py:244 — when neither a cached nor a freshly-initialized client is
+ # available (both None), `if not oauth` must redirect to login. The
+ # `if not oauth`->`if oauth` mutation would instead fall through and
+ # dereference None (no 302-to-login).
+ with _sso_enabled_with_config(), \
+ mock.patch.object(auth_mod, 'get_sso_client', return_value=None), \
+ mock.patch.object(auth_mod, 'init_sso_client', return_value=None):
+ client = app.test_client()
+ resp = client.get('/auth/sso/login')
+ assert resp.status_code == 302
+ assert '/login' in resp.headers['Location']
+
+
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-q"]))
diff --git a/tests/test_cov_file_monitor.py b/tests/test_cov_file_monitor.py
index 5bab7714..044f79f1 100644
--- a/tests/test_cov_file_monitor.py
+++ b/tests/test_cov_file_monitor.py
@@ -385,6 +385,80 @@ class TestUpdateUserCache(unittest.TestCase):
self.assertGreater(monitor._last_user_cache_update, 0)
+# ---------------------------------------------------------------------------
+# Admin user selection in _update_user_cache (line 101: is_admin=True)
+# ---------------------------------------------------------------------------
+
+class TestAdminUserSelection(unittest.TestCase):
+ """Guards the admin-directory scan against picking the wrong user.
+
+ _update_user_cache caches the admin via User.query.filter_by(is_admin=True).
+ _scan_admin_directory then processes that cached user's directory. If the
+ query flips to is_admin=False it would cache a NON-admin user, so every
+ assertion below checks that the user driving the admin scan is_admin=True.
+ """
+
+ def setUp(self):
+ self.ctx = app.app_context()
+ self.ctx.push()
+ self.temp_dir = tempfile.mkdtemp()
+ self.admin_username = _uniq('cov_fm_admin')
+ self.normal_username = _uniq('cov_fm_normal')
+ self.admin = User(
+ username=self.admin_username,
+ email=f'{self.admin_username}@test.com',
+ password='fakehash',
+ is_admin=True,
+ )
+ self.normal = User(
+ username=self.normal_username,
+ email=f'{self.normal_username}@test.com',
+ password='fakehash',
+ is_admin=False,
+ )
+ db.session.add_all([self.admin, self.normal])
+ db.session.commit()
+ self.admin_id = self.admin.id
+ self.normal_id = self.normal.id
+
+ def tearDown(self):
+ for uid in (self.admin_id, self.normal_id):
+ u = db.session.get(User, uid)
+ if u:
+ db.session.delete(u)
+ db.session.commit()
+ shutil.rmtree(self.temp_dir, ignore_errors=True)
+ self.ctx.pop()
+
+ def test_admin_scan_targets_an_admin_user_not_a_normal_user(self):
+ monitor = FileMonitor(self.temp_dir, check_interval=30, mode='admin_only')
+ monitor._last_user_cache_update = 0 # force a real refresh
+
+ monitor._update_user_cache()
+
+ # The cached admin id must resolve to a user flagged is_admin=True.
+ # (Shared DB: there may be other admins; we don't assume *which* admin
+ # is picked, only that it IS an admin. The is_admin=True->False mutant
+ # would cache a non-admin user, failing this.)
+ self.assertIsNotNone(monitor._admin_user_id)
+ selected = db.session.get(User, monitor._admin_user_id)
+ self.assertIsNotNone(selected)
+ self.assertTrue(selected.is_admin)
+ # The normal user we created must never be the one selected.
+ self.assertNotEqual(monitor._admin_user_id, self.normal_id)
+
+ # And the admin directory scan drives _process_file with that admin's id.
+ scanned = []
+ monitor._scan_directory_for_user = lambda d, u, **kw: scanned.append(u)
+ monitor._scan_tag_subdirectories = lambda *a, **kw: None
+ monitor._scan_admin_directory()
+
+ self.assertEqual(scanned, [monitor._admin_user_id])
+ scanned_user = db.session.get(User, scanned[0])
+ self.assertTrue(scanned_user.is_admin)
+ self.assertNotEqual(scanned[0], self.normal_id)
+
+
# ---------------------------------------------------------------------------
# Full _process_file flow (heavy externals mocked)
# ---------------------------------------------------------------------------
diff --git a/tests/test_cov_job_queue.py b/tests/test_cov_job_queue.py
index 3ef106db..5b888b9d 100644
--- a/tests/test_cov_job_queue.py
+++ b/tests/test_cov_job_queue.py
@@ -295,6 +295,53 @@ def test_round_robin_across_two_users(track):
assert third.user_id == u1
+def test_round_robin_cursor_advances_across_three_users(track):
+ """The fairness cursor must advance to the user AFTER the last-claimed one.
+
+ Mutation guard for `_claim_next_job` line 188
+ (`if last_user_id is not None and last_user_id in user_ids:`):
+ the `is not None`->`is None` mutation collapses the round-robin to always
+ picking ``user_ids[0]`` (the lowest min(created_at) user). We make the
+ just-claimed user u1 *retain* the globally-oldest queued job so it stays at
+ ``user_ids[0]``; correct round-robin must still skip past it to u2, while the
+ mutant would re-pick u1.
+ """
+ u1 = _make_user(); track.user_ids.append(u1)
+ u2 = _make_user(); track.user_ids.append(u2)
+ u3 = _make_user(); track.user_ids.append(u3)
+ # u1 owns TWO recordings/jobs so it keeps a queued job after the first claim.
+ r1a = _make_recording(u1); track.recording_ids.append(r1a)
+ r1b = _make_recording(u1); track.recording_ids.append(r1b)
+ r2 = _make_recording(u2); track.recording_ids.append(r2)
+ r3 = _make_recording(u3); track.recording_ids.append(r3)
+
+ j1a = job_queue.enqueue(u1, r1a, "transcribe"); track.job_ids.append(j1a)
+ j1b = job_queue.enqueue(u1, r1b, "transcribe"); track.job_ids.append(j1b)
+ j2 = job_queue.enqueue(u2, r2, "transcribe"); track.job_ids.append(j2)
+ j3 = job_queue.enqueue(u3, r3, "transcribe"); track.job_ids.append(j3)
+
+ # Force created_at so the user ordering by min(created_at) is u1 < u2 < u3,
+ # AND u1 still holds the oldest queued job even after one of its jobs is
+ # claimed (both u1 jobs predate u2/u3).
+ now = datetime.utcnow()
+ db.session.get(ProcessingJob, j1a).created_at = now - timedelta(minutes=30)
+ db.session.get(ProcessingJob, j1b).created_at = now - timedelta(minutes=29)
+ db.session.get(ProcessingJob, j2).created_at = now - timedelta(minutes=20)
+ db.session.get(ProcessingJob, j3).created_at = now - timedelta(minutes=10)
+ db.session.commit()
+
+ first = job_queue._claim_next_job(["transcribe"], "transcription")
+ assert first.user_id == u1 # cursor was None -> user_ids[0] == u1
+ assert job_queue._last_user_id_transcription == u1
+
+ second = job_queue._claim_next_job(["transcribe"], "transcription")
+ # u1 still owns the globally-oldest queued job (j1b), so user_ids stays
+ # [u1, u2, u3]. Correct round-robin advances PAST u1 to u2. The mutant
+ # (is None) ignores the cursor and re-picks user_ids[0] == u1.
+ assert second.user_id == u2
+ assert job_queue._last_user_id_transcription == u2
+
+
# --------------------------------------------------------------------------
# _process_job dispatch routing
# --------------------------------------------------------------------------
@@ -338,6 +385,65 @@ def test_process_job_transcribe_dispatches_task_and_completes(track):
assert refreshed.completed_at is not None
+def test_transcribe_uses_original_filename_when_set(track):
+ """When recording.original_filename is set, it is passed to the ASR task.
+
+ Mutation guard for `_run_transcription` line 432
+ (`recording.original_filename or os.path.basename(filepath)`): the
+ `or`->`and` mutation yields `original_filename and basename` == basename
+ whenever original_filename is truthy, wrongly dropping the real filename.
+ The materialized basename ("mat_name.mp3") is deliberately different from
+ the original_filename ("my recording.mp3") so the two are distinguishable.
+ """
+ uid = _make_user(); track.user_ids.append(uid)
+ rid = _make_recording(uid, status="QUEUED",
+ original_filename="my recording.mp3")
+ track.recording_ids.append(rid)
+ jid = job_queue.enqueue(uid, rid, "transcribe"); track.job_ids.append(jid)
+ job = _claim(rid, ["transcribe"], "transcription")
+
+ fake_task = MagicMock()
+ storage = _fake_materialized("/var/tmp/mat_name.mp3")
+ with patch("src.tasks.processing.transcribe_audio_task", fake_task), \
+ patch("src.services.storage.get_storage_service", return_value=storage), \
+ patch("os.path.exists", return_value=True), \
+ patch.object(job_queue, "_emit_started_webhook"), \
+ patch.object(job_queue, "_emit_completion_webhook"):
+ job_queue._process_job(job)
+
+ fake_task.assert_called_once()
+ # positional: app_context, recording_id, filepath, filename_for_asr, start
+ args = fake_task.call_args[0]
+ assert args[3] == "my recording.mp3" # original filename, NOT basename
+
+
+def test_transcribe_falls_back_to_basename_when_no_original_filename(track):
+ """When original_filename is empty, the materialized basename is used.
+
+ Same line-432 guard from the other direction: with an empty
+ original_filename, the correct `or` expression returns
+ basename(filepath); the `and` mutant would return the empty string.
+ """
+ uid = _make_user(); track.user_ids.append(uid)
+ rid = _make_recording(uid, status="QUEUED", original_filename="")
+ track.recording_ids.append(rid)
+ jid = job_queue.enqueue(uid, rid, "transcribe"); track.job_ids.append(jid)
+ job = _claim(rid, ["transcribe"], "transcription")
+
+ fake_task = MagicMock()
+ storage = _fake_materialized("/var/tmp/materialized_basename.mp3")
+ with patch("src.tasks.processing.transcribe_audio_task", fake_task), \
+ patch("src.services.storage.get_storage_service", return_value=storage), \
+ patch("os.path.exists", return_value=True), \
+ patch.object(job_queue, "_emit_started_webhook"), \
+ patch.object(job_queue, "_emit_completion_webhook"):
+ job_queue._process_job(job)
+
+ fake_task.assert_called_once()
+ args = fake_task.call_args[0]
+ assert args[3] == "materialized_basename.mp3" # basename fallback, not ""
+
+
def test_process_job_summarize_dispatches_summary_task(track):
uid = _make_user(); track.user_ids.append(uid)
rid = _make_recording(uid); track.recording_ids.append(rid)