Commit 080cb8b6 authored by Aryan Noshirvani's avatar Aryan Noshirvani

Add real functional test coverage for every API endpoint

Every existing test file mostly covered validation-shape (missing
fields -> 422, unknown id -> 404) but not the actual success path with
real dummy data, and auth.py's one "success" test just accepted any of
[200, 400, 422, 500] since it hit the real Telegram API unmocked - not
really testing anything. Went through every router and added the
missing success-path coverage:

- auth.py: mock telegram_auth/telegram_sync instead of hitting real
  Telegram; test request_code and login (including that login actually
  creates a User row), chats and chat-music with a real session header
  (previously only the 401-no-token cases existed).
- discovery.py: /listen success path (mocked identify_audio, asserts
  a DiscoveredSong row is actually created) and the no-match case;
  /swipe success path (asserts `liked` is actually persisted, not just
  that invalid ids 404).
- library.py: /library/stream and /library/lyrics had zero test
  coverage at all - added success + 404 + (for stream) file-missing-
  on-disk cases; /playlists/{id}/add success path (asserts the
  PlaylistTrack row actually exists, not just that invalid ids 404).
- music.py: /music/upload success path - generates a real minimal MP3
  at test time (mutagen rejects garbage bytes, so a fake byte string
  isn't enough here), mocks identify_audio, verifies the response
  metadata and that the tagged file actually lands in downloads/.
- social.py: added the one endpoint with no test at all,
  /social/posts/{id}/tree (both the 404 and the with-children case).

44 tests total (up from 24), full run still ~1s since everything
external is mocked - no real network calls anywhere in the suite.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent 13247d86
def test_auth_request_code(client):
from src.api.routers import auth as auth_router
from src.core.database import SessionLocal, User
async def _fake_request_code_ok(phone_number):
return {"phone_code_hash": "fake_hash_123", "is_registered": True}
async def _fake_request_code_fail(phone_number):
raise Exception("Telegram rejected the phone number")
async def _fake_login_ok(phone_number, phone_code_hash, code):
return {"session_string": "fake_session_string", "user_id": 424242}
async def _fake_login_fail(phone_number, phone_code_hash, code):
raise Exception("Session expired or not found. Please request a new code.")
async def _fake_get_chats(session_string):
return [{"id": 1, "title": "Test Chat", "type": "private"}]
async def _fake_get_chat_music(session_string, chat_id, limit=50):
return [{"message_id": 1, "title": "Song", "artist": "Someone", "duration": 180, "file_name": "song.mp3"}]
def test_auth_request_code_success(client, monkeypatch):
monkeypatch.setattr(auth_router.telegram_auth, "request_code", _fake_request_code_ok)
response = client.post("/auth/request_code", json={"phone_number": "+1234567890"})
assert response.status_code in [200, 400, 422, 500]
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert body["data"]["phone_code_hash"] == "fake_hash_123"
def test_auth_request_code_upstream_failure(client, monkeypatch):
monkeypatch.setattr(auth_router.telegram_auth, "request_code", _fake_request_code_fail)
response = client.post("/auth/request_code", json={"phone_number": "+1234567890"})
assert response.status_code == 400
assert "rejected" in response.json()["detail"]
def test_auth_request_code_missing_field(client):
response = client.post("/auth/request_code", json={})
assert response.status_code == 422
def test_auth_login_success_creates_user(client, monkeypatch):
monkeypatch.setattr(auth_router.telegram_auth, "login", _fake_login_ok)
response = client.post("/auth/login", json={
"phone_number": "+1234567890", "phone_code_hash": "fake_hash_123", "code": "00000",
})
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert body["access_token"] == "fake_session_string"
assert body["user_id"] == 424242
db = SessionLocal()
try:
user = db.query(User).filter(User.id == 424242).first()
assert user is not None
assert user.username == "+1234567890"
finally:
db.close()
def test_auth_login_upstream_failure(client, monkeypatch):
monkeypatch.setattr(auth_router.telegram_auth, "login", _fake_login_fail)
response = client.post("/auth/login", json={
"phone_number": "+1234567890", "phone_code_hash": "wrong_hash", "code": "00000",
})
assert response.status_code == 400
assert "expired" in response.json()["detail"]
def test_auth_login_missing_fields(client):
response = client.post("/auth/login", json={"phone_number": "+1234567890"})
assert response.status_code == 422 # Unprocessable Entity
assert response.status_code == 422
def test_auth_chats_no_token(client):
response = client.get("/auth/chats")
assert response.status_code == 401
def test_auth_chats_with_token(client, monkeypatch):
monkeypatch.setattr(auth_router.telegram_sync, "get_chats", _fake_get_chats)
response = client.get("/auth/chats", headers={"session-string": "fake_session_string"})
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert body["chats"] == [{"id": 1, "title": "Test Chat", "type": "private"}]
def test_auth_chats_music_no_token(client):
response = client.get("/auth/chats/123/music")
assert response.status_code == 401
def test_auth_chats_music_with_token(client, monkeypatch):
monkeypatch.setattr(auth_router.telegram_sync, "get_chat_music", _fake_get_chat_music)
response = client.get("/auth/chats/123/music", headers={"session-string": "fake_session_string"})
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert len(body["music"]) == 1
assert body["music"][0]["title"] == "Song"
import io
from src.api.routers import discovery as discovery_router
from src.core.database import SessionLocal, DiscoveredSong
async def _fake_identify_hit(path):
return [{"title": "Dummy Song", "artist": "Dummy Artist", "genre": "Pop", "coverart": "http://example.com/art.jpg"}]
async def _fake_identify_miss(path):
return []
def _dummy_audio_file():
return ("clip.mp3", io.BytesIO(b"not-real-audio-bytes-but-thats-fine-for-this-mock"), "audio/mpeg")
def test_discovery_history(client):
response = client.get("/discovery/history")
assert response.status_code == 200
......@@ -5,10 +23,63 @@ def test_discovery_history(client):
assert "history" in response.json()
assert isinstance(response.json()["history"], list)
def test_discovery_listen_no_file(client):
response = client.post("/discovery/listen")
assert response.status_code == 422
def test_discovery_listen_success_creates_row(client, monkeypatch):
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_hit)
response = client.post("/discovery/listen", files={"file": _dummy_audio_file()})
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert body["detected"]["title"] == "Dummy Song"
discovery_id = body["discovery_id"]
db = SessionLocal()
try:
row = db.query(DiscoveredSong).filter(DiscoveredSong.id == discovery_id).first()
assert row is not None
assert row.title == "Dummy Song"
assert row.artist == "Dummy Artist"
finally:
db.close()
def test_discovery_listen_no_match(client, monkeypatch):
monkeypatch.setattr(discovery_router, "identify_audio", _fake_identify_miss)
response = client.post("/discovery/listen", files={"file": _dummy_audio_file()})
assert response.status_code == 200
body = response.json()
assert body["status"] == "error"
assert "message" in body
def test_discovery_swipe_invalid_song(client):
response = client.post("/discovery/99999/swipe", data={"liked": True})
assert response.status_code == 404
def test_discovery_swipe_success_updates_liked(client):
db = SessionLocal()
try:
song = DiscoveredSong(title="Swipe Me", artist="Someone", genre="Rock")
db.add(song)
db.commit()
db.refresh(song)
song_id = song.id
finally:
db.close()
response = client.post(f"/discovery/{song_id}/swipe", data={"liked": True})
assert response.status_code == 200
assert response.json()["status"] == "success"
db = SessionLocal()
try:
updated = db.query(DiscoveredSong).filter(DiscoveredSong.id == song_id).first()
assert updated.liked is True
finally:
db.close()
import os
import tempfile
from src.core.database import SessionLocal, LibrarySong, Playlist, PlaylistTrack
def _make_library_song(**overrides):
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes for stream test")
defaults = dict(title="Test Song", artist="Test Artist", album="Test Album", genre="Pop", lyrics="la la la", file_path=path)
defaults.update(overrides)
db = SessionLocal()
try:
song = LibrarySong(**defaults)
db.add(song)
db.commit()
db.refresh(song)
return song.id, path
finally:
db.close()
def test_library_endpoints(client):
response = client.get("/library")
assert response.status_code == 200
......@@ -5,11 +30,70 @@ def test_library_endpoints(client):
assert "library" in response.json()
assert isinstance(response.json()["library"], list)
def test_library_search(client):
response = client.post("/library/search", data={"query": "test"})
assert response.status_code == 200
assert "results" in response.json()
def test_library_search_finds_match(client):
song_id, path = _make_library_song(title="Unique Searchable Title Xyzzy")
try:
response = client.post("/library/search", data={"query": "Xyzzy"})
assert response.status_code == 200
results = response.json()["results"]
assert any(r["id"] == song_id for r in results)
finally:
os.remove(path)
def test_library_stream_success(client):
song_id, path = _make_library_song()
try:
response = client.get(f"/library/stream/{song_id}")
assert response.status_code == 200
assert response.content == b"fake mp3 bytes for stream test"
assert response.headers["content-type"] == "audio/mpeg"
finally:
os.remove(path)
def test_library_stream_unknown_id(client):
response = client.get("/library/stream/99999")
assert response.status_code == 404
def test_library_stream_missing_file_on_disk(client):
db = SessionLocal()
try:
song = LibrarySong(title="Ghost Song", artist="Nobody", file_path="/tmp/does_not_exist_xyz.mp3")
db.add(song)
db.commit()
db.refresh(song)
song_id = song.id
finally:
db.close()
response = client.get(f"/library/stream/{song_id}")
assert response.status_code == 404
def test_library_lyrics_success(client):
song_id, path = _make_library_song(lyrics="these are the test lyrics")
try:
response = client.get(f"/library/lyrics/{song_id}")
assert response.status_code == 200
assert response.json()["lyrics"] == "these are the test lyrics"
finally:
os.remove(path)
def test_library_lyrics_unknown_id(client):
response = client.get("/library/lyrics/99999")
assert response.status_code == 404
def test_playlists_endpoints(client):
response = client.get("/playlists")
assert response.status_code == 200
......@@ -29,6 +113,37 @@ def test_playlists_endpoints(client):
playlists = response.json()["playlists"]
assert any(p["id"] == playlist_id for p in playlists)
def test_playlist_add_invalid(client):
response = client.post("/playlists/99999/add", data={"song_id": 99999})
assert response.status_code == 404
def test_playlist_add_success(client):
song_id, path = _make_library_song()
try:
pl_response = client.post("/playlists", json={"name": "Add Test Playlist"})
playlist_id = pl_response.json()["playlist"]["id"]
response = client.post(f"/playlists/{playlist_id}/add", data={"song_id": song_id})
assert response.status_code == 200
assert response.json()["status"] == "success"
db = SessionLocal()
try:
track = db.query(PlaylistTrack).filter(
PlaylistTrack.playlist_id == playlist_id, PlaylistTrack.song_id == song_id
).first()
assert track is not None
finally:
db.close()
finally:
os.remove(path)
def test_playlist_add_song_not_found(client):
pl_response = client.post("/playlists", json={"name": "Another Playlist"})
playlist_id = pl_response.json()["playlist"]["id"]
response = client.post(f"/playlists/{playlist_id}/add", data={"song_id": 99999})
assert response.status_code == 404
import io
import os
from src.api.routers import music as music_router
def _real_tiny_mp3_bytes():
from pydub.generators import Sine
tone = Sine(440).to_audio_segment(duration=300).apply_gain(-6)
buf = io.BytesIO()
tone.export(buf, format="mp3", bitrate="64k")
buf.seek(0)
return buf.read()
async def _fake_identify_hit(path):
return [{
"title": "Fully Known Song", "artist": "Known Artist", "album": "Known Album",
"year": "2024", "genre": "Synthwave", "track_number": "1/1",
"source": "Shazam", "coverart": None, "lyrics": "known lyrics already present",
}]
def test_music_tag(client):
response = client.post("/music/tag", json={"chat_id": 1, "message_id": 2, "language_preference": "native"})
assert response.status_code == 200
assert response.json()["status"] == "success"
def test_music_tag_missing_fields(client):
response = client.post("/music/tag", json={"chat_id": 1})
assert response.status_code == 422
def test_music_upload_no_file(client):
response = client.post("/music/upload")
assert response.status_code == 422
def test_music_upload_success(client, monkeypatch):
monkeypatch.setattr(music_router, "identify_audio", _fake_identify_hit)
response = client.post(
"/music/upload",
files={"file": ("raw_upload.mp3", io.BytesIO(_real_tiny_mp3_bytes()), "audio/mpeg")},
)
assert response.status_code == 200
body = response.json()
assert body["status"] == "success"
assert body["metadata"]["title"] == "Fully Known Song"
assert body["metadata"]["artist"] == "Known Artist"
assert body["metadata"]["genre"] == "Synthwave"
assert body["metadata"]["has_lyrics"] is True
assert body["download_url"].endswith(".mp3")
downloaded_filename = body["download_url"].rsplit("/", 1)[-1]
from urllib.parse import unquote
downloaded_path = os.path.join("/root/antigrav-stax-audio/downloads", unquote(downloaded_filename))
assert os.path.exists(downloaded_path)
os.remove(downloaded_path)
......@@ -46,3 +46,23 @@ def test_get_active_rooms():
response = client.get("/social/rooms")
assert response.status_code == 200
assert isinstance(response.json(), list)
def test_remix_tree_not_found():
response = client.get("/social/posts/999999/tree")
assert response.status_code == 404
def test_remix_tree_with_children():
root_res = client.post("/social/posts", json={"user_id": 1, "song_id": 1, "caption": "root post"})
root_id = root_res.json()["id"]
child_res = client.post("/social/posts", json={
"user_id": 2, "song_id": 1, "parent_post_id": root_id, "caption": "a remix of the root"
})
assert child_res.status_code == 201
response = client.get(f"/social/posts/{root_id}/tree")
assert response.status_code == 200
body = response.json()
assert body["post"]["id"] == root_id
assert len(body["children"]) == 1
assert body["children"][0]["caption"] == "a remix of the root"
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment