Skip to content

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

Python

Close mutation-sweep survivors (batch 2a): storage guards, embeddings chunking, admin share-cleanup/usage, retention global-flag

Murtaza Nasir622e418bbc56
diff --git a/tests/test_cov_admin.py b/tests/test_cov_admin.py
index faed8a02..2dfc95da 100644
--- a/tests/test_cov_admin.py
+++ b/tests/test_cov_admin.py
@@ -18,12 +18,16 @@ Run:
"""
import uuid
+from datetime import datetime
from unittest.mock import patch, MagicMock
import pytest
from src.app import app, db
-from src.models import User, SystemSetting
+from src.models import (
+ User, SystemSetting, Recording, InternalShare,
+ Group, GroupMembership, TranscriptChunk,
+)
app.config['WTF_CSRF_ENABLED'] = False
app.config['TESTING'] = True
@@ -533,3 +537,298 @@ def test_auto_process_trigger_not_running_400(admin_client):
with patch('src.file_monitor.file_monitor', None):
resp = admin_client.post('/admin/auto-process/trigger')
assert resp.status_code == 400
+
+
+# ---------------------------------------------------------------------------
+# MUTATION-TARGETED TESTS
+# Each test below kills a specific surviving mutant in src/api/admin.py.
+# ---------------------------------------------------------------------------
+
+def _mk_recording(user, file_size=None, audio_path=None,
+ audio_deleted_at=None, status='COMPLETED'):
+ r = Recording(user_id=user.id, title='t', status=status,
+ file_size=file_size, audio_path=audio_path,
+ audio_deleted_at=audio_deleted_at)
+ db.session.add(r)
+ db.session.commit()
+ return r
+
+
+def _mk_share(recording, owner, shared_with):
+ s = InternalShare(recording_id=recording.id, owner_id=owner.id,
+ shared_with_user_id=shared_with.id)
+ db.session.add(s)
+ db.session.commit()
+ return s
+
+
+def _delete_all(*objs):
+ for o in objs:
+ if o is None:
+ continue
+ fresh = db.session.get(type(o), o.id)
+ if fresh is not None:
+ db.session.delete(fresh)
+ db.session.commit()
+
+
+# --- line 351: InternalShare cleanup on user delete (owner OR recipient) ----
+
+def test_delete_user_cleans_shares_both_directions_and_spares_others(admin_client):
+ """Deleting a user removes InternalShares where they are owner OR recipient,
+ while leaving shares between unrelated users untouched.
+
+ Kills the `owner_id == user_id` -> `owner_id != user_id` mutant: that
+ mutant would (a) leave the victim's owner-side share behind and
+ (b) wrongly delete an unrelated third-party share whose owner != victim.
+ """
+ victim = _mk_user(is_admin=False)
+ b = _mk_user(is_admin=False)
+ c = _mk_user(is_admin=False)
+ d = _mk_user(is_admin=False)
+
+ rec_a = _mk_recording(victim) # owned by victim
+ rec_b = _mk_recording(b) # owned by b
+ rec_c = _mk_recording(c) # owned by c (no victim involvement)
+
+ share_owner = _mk_share(rec_a, owner=victim, shared_with=b)
+ share_recipient = _mk_share(rec_b, owner=b, shared_with=victim)
+ share_unrelated = _mk_share(rec_c, owner=c, shared_with=d)
+
+ owner_id = share_owner.id
+ recipient_id = share_recipient.id
+ unrelated_id = share_unrelated.id
+ vid = victim.id
+
+ storage = MagicMock()
+ try:
+ with patch('src.services.storage.get_storage_service', return_value=storage):
+ resp = admin_client.delete(f'/admin/users/{vid}')
+ assert resp.status_code == 200, resp.data
+
+ # Victim's owner-side AND recipient-side shares are gone.
+ assert db.session.get(InternalShare, owner_id) is None
+ assert db.session.get(InternalShare, recipient_id) is None
+ # Unrelated third-party share survives (would be wrongly deleted by
+ # the `!=` mutant).
+ assert db.session.get(InternalShare, unrelated_id) is not None
+ finally:
+ _delete_all(share_unrelated, rec_b, rec_c)
+ _delete_all(b, c, d)
+ # victim already deleted by the endpoint (or cleaned if it wasn't)
+ leftover = db.session.get(User, vid)
+ if leftover:
+ _delete_all(leftover)
+
+
+# --- line 344: storage.delete(path, missing_ok=True) on user delete ---------
+
+def test_delete_user_calls_storage_delete_with_missing_ok_true(admin_client):
+ """On user delete, each recording's audio is removed via
+ storage.delete(path, missing_ok=True). Kills the `missing_ok=True` ->
+ `missing_ok=False` mutant.
+ """
+ victim = _mk_user(is_admin=False)
+ audio_path = f"{victim.username}/clip.wav"
+ _mk_recording(victim, audio_path=audio_path)
+ vid = victim.id
+
+ storage = MagicMock()
+ try:
+ with patch('src.services.storage.get_storage_service', return_value=storage):
+ resp = admin_client.delete(f'/admin/users/{vid}')
+ assert resp.status_code == 200, resp.data
+ storage.delete.assert_called_once_with(audio_path, missing_ok=True)
+ finally:
+ leftover = db.session.get(User, vid)
+ if leftover:
+ _delete_all(leftover)
+
+
+# --- line 288: update_user storage_used excludes deleted-audio recordings ----
+
+def test_update_user_storage_used_excludes_deleted_audio(admin_client):
+ """admin_update_user reports storage_used summed only over recordings whose
+ audio is still present. Kills `... and not r.audio_deleted_at` ->
+ `... or not r.audio_deleted_at` (the deleted-audio recording would be
+ wrongly counted, inflating the total).
+ """
+ victim = _mk_user(is_admin=False)
+ rec_live = _mk_recording(victim, file_size=1000, audio_deleted_at=None)
+ rec_dead = _mk_recording(victim, file_size=5000,
+ audio_deleted_at=datetime.utcnow())
+ vid = victim.id
+ try:
+ resp = admin_client.put(f'/admin/users/{vid}', json={'is_admin': False})
+ assert resp.status_code == 200, resp.data
+ assert resp.get_json()['storage_used'] == 1000
+ finally:
+ _delete_all(rec_live, rec_dead)
+ leftover = db.session.get(User, vid)
+ if leftover:
+ _delete_all(leftover)
+
+
+# --- lines 135/142: list_users storage_used aggregation -----------------------
+
+def test_list_users_storage_used_excludes_deleted_audio_and_none_is_zero(admin_client):
+ """The user-list grouped aggregation excludes deleted-audio bytes and
+ reports a user with no stored audio as 0 (not null).
+
+ Kills `sizes_by_uid.get(user.id) or 0` -> `... and 0` (real storage would
+ collapse to 0) and validates the `audio_deleted_at.is_(None)` filter on the
+ SQL sum.
+ """
+ with_storage = _mk_user(is_admin=False)
+ rec_live = _mk_recording(with_storage, file_size=1234, audio_deleted_at=None)
+ rec_dead = _mk_recording(with_storage, file_size=9999,
+ audio_deleted_at=datetime.utcnow())
+ empty = _mk_user(is_admin=False) # no recordings at all
+ sid = with_storage.id
+ eid = empty.id
+ try:
+ resp = admin_client.get('/admin/users')
+ assert resp.status_code == 200
+ rows = {u['id']: u for u in resp.get_json()}
+ # Only the live recording's bytes count.
+ assert rows[sid]['storage_used'] == 1234
+ # No recordings -> 0, not null (the `or 0` fallback).
+ assert rows[eid]['storage_used'] == 0
+ finally:
+ _delete_all(rec_live, rec_dead)
+ _delete_all(db.session.get(User, sid), db.session.get(User, eid))
+
+
+# --- lines 337/358: inquire chunk-count logging guard on user delete ---------
+
+def test_delete_user_no_chunks_skips_chunk_log(admin_client):
+ """With Inquire mode on but the victim owning zero transcript chunks, the
+ "Deleting N transcript chunks" info log must NOT fire. Kills both
+ `if total_chunks > 0:` (line 337) and `if ENABLE_INQUIRE_MODE and
+ total_chunks > 0:` (line 358) when mutated to `>= 0`, which would log at
+ zero chunks.
+ """
+ victim = _mk_user(is_admin=False)
+ vid = victim.id
+ storage = MagicMock()
+ try:
+ with patch('src.api.admin.ENABLE_INQUIRE_MODE', True), \
+ patch('src.services.storage.get_storage_service', return_value=storage), \
+ patch.object(app.logger, 'info') as log_info:
+ resp = admin_client.delete(f'/admin/users/{vid}')
+ assert resp.status_code == 200, resp.data
+ logged = " ".join(str(c.args[0]) for c in log_info.call_args_list if c.args)
+ assert 'transcript chunks' not in logged
+ assert 'embeddings and chunks' not in logged
+ finally:
+ leftover = db.session.get(User, vid)
+ if leftover:
+ _delete_all(leftover)
+
+
+def test_delete_user_with_chunks_logs_chunk_count(admin_client):
+ """Complementary positive case: a victim WITH transcript chunks does fire
+ the chunk-count info logs. Confirms lines 337/358 are reached and the guard
+ is genuinely `> 0` (further pinning the `>= 0` / branch-removal mutants).
+ """
+ victim = _mk_user(is_admin=False)
+ rec = _mk_recording(victim)
+ chunk = TranscriptChunk(recording_id=rec.id, user_id=victim.id,
+ chunk_index=0, content='hello')
+ db.session.add(chunk)
+ db.session.commit()
+ vid = victim.id
+ storage = MagicMock()
+ try:
+ with patch('src.api.admin.ENABLE_INQUIRE_MODE', True), \
+ patch('src.services.storage.get_storage_service', return_value=storage), \
+ patch.object(app.logger, 'info') as log_info:
+ resp = admin_client.delete(f'/admin/users/{vid}')
+ assert resp.status_code == 200, resp.data
+ logged = " ".join(str(c.args[0]) for c in log_info.call_args_list if c.args)
+ assert 'transcript chunks' in logged
+ finally:
+ leftover = db.session.get(User, vid)
+ if leftover:
+ _delete_all(leftover)
+
+
+# --- lines 68/77: /admin gating for team-admins vs global admins -------------
+
+def _mk_team_admin():
+ """Create a non-global user who is admin of a fresh group."""
+ u = _mk_user(is_admin=False)
+ g = Group(name=f"grp_{uuid.uuid4().hex[:8]}")
+ db.session.add(g)
+ db.session.commit()
+ m = GroupMembership(group_id=g.id, user_id=u.id, role='admin')
+ db.session.add(m)
+ db.session.commit()
+ return u, g, m
+
+
+def test_team_admin_redirected_from_admin_to_group_management(ctx):
+ """A team-admin (group role=admin) who is NOT a global admin is redirected
+ from /admin to /group-management. Kills the line-68 guard
+ `if is_team_admin and not current_user.is_admin:`.
+ """
+ u, g, m = _mk_team_admin()
+ try:
+ c = app.test_client()
+ _login(c, u)
+ resp = c.get('/admin')
+ assert resp.status_code == 302
+ assert '/group-management' in resp.headers.get('Location', '')
+ finally:
+ _delete_all(u) # cascades the membership
+ _delete_all(g)
+
+
+def test_global_admin_who_is_also_team_admin_sees_dashboard(admin_user):
+ """A GLOBAL admin who also happens to be a group admin still lands on the
+ full admin dashboard (not redirected to group management). Kills the
+ line-68 `and` -> `or` mutant, and the line-77 `is_group_admin_only=False`
+ mutant (the rendered <title> would flip to "Group Management").
+ """
+ g = Group(name=f"grp_{uuid.uuid4().hex[:8]}")
+ db.session.add(g)
+ db.session.commit()
+ m = GroupMembership(group_id=g.id, user_id=admin_user.id, role='admin')
+ db.session.add(m)
+ db.session.commit()
+ try:
+ c = app.test_client()
+ _login(c, admin_user)
+ resp = c.get('/admin')
+ assert resp.status_code == 200
+ assert b'<title>Admin Dashboard - Speakr</title>' in resp.data
+ assert b'<title>Group Management - Speakr</title>' not in resp.data
+ finally:
+ _delete_all(m, g)
+
+
+# --- line 91: /group-management requires team-admin --------------------------
+
+def test_group_management_requires_team_admin(normal_client):
+ """A plain (non-team, non-global) user is bounced from /group-management.
+ Kills the line-91 `if not is_team_admin:` -> `if is_team_admin:` mutant
+ (which would let the plain user through and render the page).
+ """
+ resp = normal_client.get('/group-management')
+ assert resp.status_code == 302
+ assert '/group-management' not in resp.headers.get('Location', '')
+
+
+def test_group_management_team_admin_gets_page(ctx):
+ """A team-admin (non-global) successfully reaches /group-management.
+ Complements the line-91 mutant kill (the inverted guard would 302 them).
+ """
+ u, g, m = _mk_team_admin()
+ try:
+ c = app.test_client()
+ _login(c, u)
+ resp = c.get('/group-management')
+ assert resp.status_code == 200
+ finally:
+ _delete_all(u)
+ _delete_all(g)
diff --git a/tests/test_cov_embeddings.py b/tests/test_cov_embeddings.py
index 8a0adff4..987a9b89 100644
--- a/tests/test_cov_embeddings.py
+++ b/tests/test_cov_embeddings.py
@@ -172,6 +172,24 @@ def test_chunk_respects_sentence_boundary(local_emb):
assert chunks[0].endswith(".")
+def test_chunk_sentence_boundary_requires_following_space(local_emb):
+ # MUTATION TARGET (line 248): the boundary check is
+ # `i + 1 < len(transcription) and transcription[i + 1].isspace()`
+ # i.e. a '.'/'!'/'?' only counts as a sentence break when the NEXT
+ # character is whitespace. This rejects the dot inside "3.14".
+ #
+ # With max_chunk_length=40 the window scans indices 0..39, which contains
+ # two periods: index 11 ("home.", followed by a space) and index 18 (the
+ # dot in "3.14", followed by '1'). The `and` keeps only the period+space
+ # break at 12, so chunk 0 == "I went home.". If `and` is mutated to `or`,
+ # the bare '3.' dot at 18 also qualifies, pushing the split to index 19 and
+ # making chunk 0 == "I went home. The 3." instead.
+ text = "I went home. The 3.14 value is large and stuff here too."
+ assert len(text) > 40 # ensure it actually splits
+ chunks = local_emb.chunk_transcription(text, max_chunk_length=40, overlap=10)
+ assert chunks[0] == "I went home."
+
+
def test_chunk_no_overlap_infinite_loop_guard(local_emb):
# A single huge token with no sentence boundaries still terminates.
text = "a" * 2000
@@ -251,6 +269,24 @@ def test_get_embedding_model_none_without_local_lib(local_emb):
assert local_emb.get_embedding_model() is None
+def test_get_embedding_model_none_in_api_mode_even_with_local_lib(api_emb):
+ # MUTATION TARGET (line 77): `if USE_API_EMBEDDINGS or not
+ # LOCAL_EMBEDDINGS_AVAILABLE: return None`. In API mode the local
+ # sentence-transformers model must NEVER be loaded, even if the local lib
+ # is present. Force LOCAL_EMBEDDINGS_AVAILABLE True and stub
+ # SentenceTransformer so that, were the guard mutated `or`->`and`
+ # (USE_API_EMBEDDINGS True, not LOCAL == False => the whole guard goes
+ # False), the function would fall through and construct/return a model.
+ # The original short-circuits on USE_API_EMBEDDINGS and returns None.
+ fake_model = MagicMock()
+ with app.app_context():
+ with patch.object(api_emb, "LOCAL_EMBEDDINGS_AVAILABLE", True):
+ with patch.object(api_emb, "SentenceTransformer",
+ MagicMock(return_value=fake_model)):
+ api_emb._embedding_model = None
+ assert api_emb.get_embedding_model() is None
+
+
def test_get_api_client_initialises_and_caches(api_emb):
fake_client = MagicMock()
fake_openai = MagicMock(return_value=fake_client)
@@ -292,6 +328,21 @@ def test_api_embed_empty_texts_returns_empty(api_emb):
assert api_emb._api_embed([]) == []
+def test_api_embed_empty_texts_does_not_call_client(api_emb):
+ # MUTATION TARGET (line 158): `if client is None or not texts:` must
+ # short-circuit on empty `texts` EVEN WHEN a client exists. The earlier
+ # `== []` assertion alone is insufficient: with the `or`->`and` mutation
+ # the function would proceed to call the client (whose MagicMock response
+ # then raises inside the comprehension and is swallowed back to []), so the
+ # result stays [] but the client IS now hit. Asserting the client was never
+ # called is what actually kills the mutation.
+ client = MagicMock()
+ with app.app_context():
+ with patch.object(api_emb, "get_embedding_api_client", return_value=client):
+ assert api_emb._api_embed([]) == []
+ client.embeddings.create.assert_not_called()
+
+
def test_api_embed_no_client_returns_empty(api_emb):
with app.app_context():
with patch.object(api_emb, "get_embedding_api_client", return_value=None):
diff --git a/tests/test_cov_retention.py b/tests/test_cov_retention.py
index 35ff0a79..7dc3c6a3 100644
--- a/tests/test_cov_retention.py
+++ b/tests/test_cov_retention.py
@@ -313,5 +313,80 @@ class TestProcessAutoDeletion(RetentionTestBase):
self.assertIsNotNone(db.session.get(Recording, rec_id))
+# ---------------------------------------------------------------------------
+# process_auto_deletion: the GLOBAL_RETENTION_DAYS > 0 / has_global_retention
+# flag (retention.py lines 94 & 97).
+#
+# `has_global_retention = GLOBAL_RETENTION_DAYS > 0` and the subsequent
+# `if not has_global_retention:` only gate an informational log line. They have
+# no other behavioral effect (actual deletion eligibility is computed per
+# recording by get_retention_days_for_recording). So killing mutations to these
+# lines requires asserting on whether the "No global retention configured" log
+# message is emitted, in addition to pinning the > 0 boundary behaviorally.
+# ---------------------------------------------------------------------------
+
+class TestGlobalRetentionFlag(RetentionTestBase):
+ NO_GLOBAL_MSG = "No global retention configured"
+
+ def _run_capturing_logs(self, global_days, mode='full_recording', storage=None):
+ if storage is None:
+ storage = _make_storage_mock(exists=True)
+ with patch.object(retention, 'ENABLE_AUTO_DELETION', True), \
+ patch.object(retention, 'GLOBAL_RETENTION_DAYS', global_days), \
+ patch.object(retention, 'DELETION_MODE', mode), \
+ patch.object(retention, 'get_storage_service', return_value=storage), \
+ patch('src.services.speaker_cleanup.cleanup_orphaned_speakers',
+ return_value={'speakers_deleted': 0, 'embeddings_removed': 0,
+ 'speakers_evaluated': 0}), \
+ patch.object(app.logger, 'info') as mock_info:
+ stats = retention.process_auto_deletion()
+ logged_no_global = any(
+ c.args and self.NO_GLOBAL_MSG in str(c.args[0])
+ for c in mock_info.call_args_list
+ )
+ return stats, storage, logged_no_global
+
+ def test_global_days_zero_is_no_policy_old_recording_kept_and_logs_no_global(self):
+ # Boundary: GLOBAL_RETENTION_DAYS == 0 means "no global policy", NOT
+ # "delete everything older than 0 days". An old, untagged recording must
+ # survive, and the "No global retention configured" branch must run.
+ rec = self.make_recording(age_days=100, audio_path='user/zero.mp3')
+ rec_id = rec.id
+ stats, storage, logged_no_global = self._run_capturing_logs(global_days=0)
+ # Behavioral: no policy => skipped, nothing deleted, row + bytes intact.
+ self.assertEqual(stats['skipped_no_retention'], 1)
+ self.assertEqual(stats['deleted_full'], 0)
+ self.assertIsNotNone(db.session.get(Recording, rec_id))
+ storage.delete.assert_not_called()
+ # has_global_retention must be False at GLOBAL==0, so the
+ # `if not has_global_retention:` log fires. Inverting line 97 suppresses
+ # this log, breaking the assertion.
+ self.assertTrue(
+ logged_no_global,
+ "Expected 'No global retention configured' log when GLOBAL_RETENTION_DAYS == 0",
+ )
+
+ def test_global_days_positive_makes_old_recording_eligible_and_no_global_log(self):
+ # GLOBAL_RETENTION_DAYS > 0 => a global policy applies. An old recording
+ # is eligible and gets deleted, and the "No global retention configured"
+ # branch must NOT run.
+ rec = self.make_recording(age_days=100, audio_path='user/pos.mp3')
+ rec_id = rec.id
+ stats, storage, logged_no_global = self._run_capturing_logs(global_days=30)
+ # Behavioral: global policy applies => old recording deleted.
+ self.assertEqual(stats['deleted_full'], 1)
+ self.assertEqual(stats['skipped_no_retention'], 0)
+ self.assertIsNone(db.session.get(Recording, rec_id))
+ storage.delete.assert_called_with('user/pos.mp3', missing_ok=True)
+ # has_global_retention must be True at GLOBAL==30, so the no-global log
+ # must NOT fire. Mutating line 94 (> 0 -> < 0) makes it False (log fires);
+ # mutating line 97 (if not -> if) makes it log too. Either breaks this.
+ self.assertFalse(
+ logged_no_global,
+ "Did not expect 'No global retention configured' log when "
+ "GLOBAL_RETENTION_DAYS > 0",
+ )
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/tests/test_cov_storage_locator.py b/tests/test_cov_storage_locator.py
index fb2d2e12..aa72b733 100644
--- a/tests/test_cov_storage_locator.py
+++ b/tests/test_cov_storage_locator.py
@@ -71,3 +71,56 @@ def test_build_locators_normalize():
assert loc.build_local_locator("recordings/x.mp3") == "local://recordings/x.mp3"
assert loc.build_local_locator("/leading/slash") == "local://leading/slash"
assert loc.build_s3_locator("bkt", "k/x.mp3") == "s3://bkt/k/x.mp3"
+
+
+# ---------------------------------------------------------------------------
+# is_probably_windows_abs / is_absolute_local_path
+# Mutation survivors (2026-06-25): the length guard and both return branches
+# in is_probably_windows_abs, plus the return branches of is_absolute_local_path.
+# ---------------------------------------------------------------------------
+
+def test_is_probably_windows_abs_true_cases():
+ assert loc.is_probably_windows_abs("C:\\x") is True
+ assert loc.is_probably_windows_abs("C:/x") is True
+ assert loc.is_probably_windows_abs("D:\\path\\file") is True
+ # exactly len 3 must still be True (kills a `< 3` -> `<= 3` style mutation)
+ assert loc.is_probably_windows_abs("C:\\") is True
+
+
+def test_is_probably_windows_abs_false_cases():
+ # None / empty / too short -> the `not path or len(path) < 3` guard
+ assert loc.is_probably_windows_abs(None) is False
+ assert loc.is_probably_windows_abs("") is False
+ assert loc.is_probably_windows_abs("ab") is False
+ assert loc.is_probably_windows_abs("C:") is False
+ # third char is not a separator -> the final `return ...` evaluates False
+ assert loc.is_probably_windows_abs("C:x") is False
+ # second char is not a colon
+ assert loc.is_probably_windows_abs("abc") is False
+
+
+def test_is_absolute_local_path():
+ # empty -> the `if not value: return False` branch
+ assert loc.is_absolute_local_path("") is False
+ # windows abs -> the `return True` branch (would fall through to
+ # os.path.isabs() and become False on POSIX if that return is broken)
+ assert loc.is_absolute_local_path("C:\\x") is True
+ assert loc.is_absolute_local_path("/abs/path") is True
+ assert loc.is_absolute_local_path("relative/path") is False
+
+
+# ---------------------------------------------------------------------------
+# parse_locator s3 validation (line 64: `if not bucket or not key`)
+# ---------------------------------------------------------------------------
+
+def test_parse_locator_s3_missing_bucket_raises():
+ # empty bucket: `not bucket` is True. An `or`->`and` mutation would let
+ # this through, so it must raise.
+ with pytest.raises(ValueError):
+ loc.parse_locator("s3:///key.mp3")
+
+
+def test_parse_locator_s3_missing_key_raises():
+ # trailing slash leaves an empty key after normalization.
+ with pytest.raises(ValueError):
+ loc.parse_locator("s3://bucket/")
diff --git a/tests/test_cov_storage_s3.py b/tests/test_cov_storage_s3.py
index bea93933..347ac582 100644
--- a/tests/test_cov_storage_s3.py
+++ b/tests/test_cov_storage_s3.py
@@ -12,6 +12,10 @@ import pytest
from botocore.exceptions import ClientError
from src.services.storage.s3 import S3StorageBackend
+from src.services.storage.local import LocalStorageBackend
+from src.services.storage.locator import local_path_from_key
+from src.services.storage.service import StorageService
+from src.services.storage.factory import StorageSettings
from src.services.storage.interfaces import (
MaterializedFile,
ObjectStat,
@@ -420,3 +424,172 @@ def test_get_client_is_cached():
second = backend._get_client()
assert first is second
mock_client.assert_called_once()
+
+
+# ===========================================================================
+# LocalStorageBackend (src/services/storage/local.py)
+# Mutation survivors (2026-06-25): the empty key/path guards in resolve_path,
+# the same-path no-op in upload_local_file, the missing-file delete branch,
+# and the cleanup_required=False flag in materialize.
+# ===========================================================================
+
+def make_local_backend():
+ root = tempfile.mkdtemp(prefix='speakr_local_')
+ return LocalStorageBackend(root), root
+
+
+def _write(path, data=b'x'):
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, 'wb') as f:
+ f.write(data)
+
+
+def test_local_resolve_path_local_scheme_missing_key_raises():
+ backend, _ = make_local_backend()
+ loc = StorageLocator(scheme='local', raw='local://', key='')
+ with pytest.raises(ValueError):
+ backend.resolve_path(loc)
+
+
+def test_local_resolve_path_legacy_abs_missing_path_raises():
+ backend, _ = make_local_backend()
+ loc = StorageLocator(scheme='legacy_local_abs', raw='', path='')
+ with pytest.raises(ValueError):
+ backend.resolve_path(loc)
+
+
+def test_local_resolve_path_legacy_rel_missing_key_raises():
+ backend, _ = make_local_backend()
+ loc = StorageLocator(scheme='legacy_local_rel', raw='', key='')
+ with pytest.raises(ValueError):
+ backend.resolve_path(loc)
+
+
+def test_local_upload_same_path_is_noop():
+ # The source IS the destination. The `src_resolved != dst_resolved` guard
+ # must skip the copy/move (a `!=`->`==` mutation would attempt copy2 on an
+ # identical path and raise SameFileError).
+ backend, root = make_local_backend()
+ key = 'recordings/same.mp3'
+ dst = local_path_from_key(root, key)
+ _write(dst, b'hello')
+ result = backend.upload_local_file(dst, key, delete_source=False)
+ assert os.path.exists(dst)
+ with open(dst, 'rb') as f:
+ assert f.read() == b'hello'
+ assert result.size == 5
+
+
+def test_local_upload_different_path_copies():
+ backend, root = make_local_backend()
+ fd, src = tempfile.mkstemp(prefix='speakr_src_')
+ os.write(fd, b'data123')
+ os.close(fd)
+ try:
+ result = backend.upload_local_file(src, 'recordings/copied.mp3', delete_source=False)
+ assert os.path.exists(src) # copy, not move -> source survives
+ dst = local_path_from_key(root, 'recordings/copied.mp3')
+ assert os.path.exists(dst)
+ assert result.size == 7
+ finally:
+ if os.path.exists(src):
+ os.remove(src)
+
+
+def test_local_delete_missing_returns_missing_ok():
+ backend, root = make_local_backend()
+ loc = StorageLocator(scheme='local', raw='local://nope.mp3', key='nope.mp3')
+ assert backend.delete(loc, missing_ok=True) is True
+ assert backend.delete(loc, missing_ok=False) is False
+
+
+def test_local_delete_existing_returns_true_and_removes():
+ backend, root = make_local_backend()
+ key = 'recordings/del.mp3'
+ dst = local_path_from_key(root, key)
+ _write(dst)
+ loc = StorageLocator(scheme='local', raw=f'local://{key}', key=key)
+ assert backend.delete(loc) is True
+ assert not os.path.exists(dst)
+
+
+def test_local_materialize_does_not_request_cleanup():
+ # A local file is already on disk; materialize must NOT flag it for
+ # deletion (cleanup_required must stay False, else the real file is removed).
+ backend, root = make_local_backend()
+ key = 'recordings/m.mp3'
+ dst = local_path_from_key(root, key)
+ _write(dst)
+ loc = StorageLocator(scheme='local', raw=f'local://{key}', key=key)
+ mat = backend.materialize(loc)
+ assert mat.cleanup_required is False
+ assert mat.local_path == dst
+
+
+# ===========================================================================
+# StorageService (src/services/storage/service.py) without an S3 backend
+# Mutation survivors (2026-06-25): empty-locator guards and the
+# "S3 not configured" RuntimeErrors.
+# ===========================================================================
+
+def make_no_s3_service(backend='local'):
+ root = tempfile.mkdtemp(prefix='speakr_svc_')
+ settings = StorageSettings(
+ backend=backend,
+ local_root=root,
+ key_prefix='recordings',
+ staging_dir=os.path.join(root, 'staging'),
+ presign_ttl_seconds=300,
+ presign_public_ttl_seconds=600,
+ s3_bucket_name=None, # -> build_s3_backend returns None
+ )
+ return StorageService(settings=settings), root
+
+
+def test_service_no_s3_backend_is_none():
+ svc, _ = make_no_s3_service()
+ assert svc.s3 is None
+
+
+def test_service_parse_empty_raises():
+ svc, _ = make_no_s3_service()
+ with pytest.raises(ValueError, match='Empty storage locator'):
+ svc.exists('')
+
+
+def test_service_delete_empty_returns_missing_ok():
+ svc, _ = make_no_s3_service()
+ assert svc.delete('', missing_ok=True) is True
+ assert svc.delete(None, missing_ok=False) is False
+
+
+def test_service_normalize_empty_returns_input_unchanged():
+ svc, _ = make_no_s3_service()
+ assert svc.maybe_normalize_local_legacy_locator('') == ''
+ assert svc.maybe_normalize_local_legacy_locator(None) is None
+
+
+def test_service_normalize_unparseable_returns_input():
+ # whitespace-only -> parse_locator returns None -> the `if not locator`
+ # guard returns the input rather than dereferencing None.
+ svc, _ = make_no_s3_service()
+ assert svc.maybe_normalize_local_legacy_locator(' ') == ' '
+
+
+def test_service_s3_locator_without_backend_raises():
+ # _resolve_backend_for_locator: s3 scheme + no s3 client -> RuntimeError.
+ svc, _ = make_no_s3_service()
+ with pytest.raises(RuntimeError, match='not configured'):
+ svc.exists('s3://bucket/key.mp3')
+
+
+def test_service_build_default_locator_s3_backend_no_client_raises():
+ svc, _ = make_no_s3_service(backend='s3')
+ with pytest.raises(RuntimeError, match='not configured'):
+ svc.build_default_locator('recordings/x.mp3')
+
+
+def test_service_upload_local_file_s3_backend_no_client_raises():
+ svc, _ = make_no_s3_service(backend='s3')
+ with pytest.raises(RuntimeError, match='not configured'):
+ svc.upload_local_file('/tmp/x.mp3', 'recordings/x.mp3')