Refactor test files for improved readability and consistency

- Removed unnecessary blank lines and adjusted formatting in test files.
- Ensured consistent use of commas in function calls and assertions across various test cases.
- Updated import statements for better organization and clarity.
- Enhanced mock setups in tests for better isolation and reliability.
- Improved assertions to follow a consistent style for better readability.
This commit is contained in:
JSC
2025-07-31 21:37:04 +02:00
parent e69098d633
commit 8847131f24
42 changed files with 602 additions and 616 deletions

View File

@@ -177,7 +177,7 @@ class TestApiTokenEndpoints:
# Set a token on the user
authenticated_user.api_token = "expired_token"
authenticated_user.api_token_expires_at = datetime.now(UTC) - timedelta(
days=1
days=1,
)
response = await authenticated_client.get("/api/v1/auth/api-token/status")
@@ -209,7 +209,7 @@ class TestApiTokenEndpoints:
# Verify token exists
status_response = await authenticated_client.get(
"/api/v1/auth/api-token/status"
"/api/v1/auth/api-token/status",
)
assert status_response.json()["has_token"] is True
@@ -222,7 +222,7 @@ class TestApiTokenEndpoints:
# Verify token is gone
status_response = await authenticated_client.get(
"/api/v1/auth/api-token/status"
"/api/v1/auth/api-token/status",
)
assert status_response.json()["has_token"] is False

View File

@@ -1,20 +1,16 @@
"""Tests for extraction API endpoints."""
from unittest.mock import AsyncMock, Mock
import pytest
import pytest_asyncio
from httpx import AsyncClient
from app.models.user import User
class TestExtractionEndpoints:
"""Test extraction API endpoints."""
@pytest.mark.asyncio
async def test_create_extraction_success(
self, test_client: AsyncClient, auth_cookies: dict[str, str]
self, test_client: AsyncClient, auth_cookies: dict[str, str],
):
"""Test successful extraction creation."""
# Set cookies on client instance to avoid deprecation warning
@@ -50,7 +46,7 @@ class TestExtractionEndpoints:
@pytest.mark.asyncio
async def test_get_processor_status_admin(
self, test_client: AsyncClient, admin_cookies: dict[str, str]
self, test_client: AsyncClient, admin_cookies: dict[str, str],
):
"""Test getting processor status as admin."""
# Set cookies on client instance to avoid deprecation warning
@@ -66,7 +62,7 @@ class TestExtractionEndpoints:
@pytest.mark.asyncio
async def test_get_processor_status_non_admin(
self, test_client: AsyncClient, auth_cookies: dict[str, str]
self, test_client: AsyncClient, auth_cookies: dict[str, str],
):
"""Test getting processor status as non-admin user."""
# Set cookies on client instance to avoid deprecation warning
@@ -80,7 +76,7 @@ class TestExtractionEndpoints:
@pytest.mark.asyncio
async def test_get_user_extractions(
self, test_client: AsyncClient, auth_cookies: dict[str, str]
self, test_client: AsyncClient, auth_cookies: dict[str, str],
):
"""Test getting user extractions."""
# Set cookies on client instance to avoid deprecation warning

View File

@@ -656,4 +656,4 @@ class TestPlayerEndpoints:
json={"volume": 100},
)
assert response.status_code == 200
mock_player_service.set_volume.assert_called_with(100)
mock_player_service.set_volume.assert_called_with(100)

View File

@@ -1,7 +1,5 @@
"""Tests for playlist API endpoints."""
import json
from typing import Any
import pytest
import pytest_asyncio
@@ -96,7 +94,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
main_playlist = Playlist(
user_id=None,
name="Main Playlist",
@@ -107,7 +105,7 @@ class TestPlaylistEndpoints:
)
test_session.add(main_playlist)
await test_session.commit()
response = await authenticated_client.get("/api/v1/playlists/")
assert response.status_code == 200
@@ -146,11 +144,11 @@ class TestPlaylistEndpoints:
test_session.add(main_playlist)
await test_session.commit()
await test_session.refresh(main_playlist)
# Extract ID before HTTP request
main_playlist_id = main_playlist.id
main_playlist_name = main_playlist.name
response = await authenticated_client.get("/api/v1/playlists/main")
assert response.status_code == 200
@@ -189,10 +187,10 @@ class TestPlaylistEndpoints:
test_session.add(main_playlist)
await test_session.commit()
await test_session.refresh(main_playlist)
# Extract ID before HTTP request
main_playlist_id = main_playlist.id
response = await authenticated_client.get("/api/v1/playlists/current")
assert response.status_code == 200
@@ -256,10 +254,10 @@ class TestPlaylistEndpoints:
test_session.add(test_playlist)
await test_session.commit()
await test_session.refresh(test_playlist)
# Extract name before HTTP request
playlist_name = test_playlist.name
payload = {
"name": playlist_name,
"description": "Duplicate name",
@@ -292,13 +290,13 @@ class TestPlaylistEndpoints:
test_session.add(test_playlist)
await test_session.commit()
await test_session.refresh(test_playlist)
# Extract values before HTTP request
playlist_id = test_playlist.id
playlist_name = test_playlist.name
response = await authenticated_client.get(
f"/api/v1/playlists/{playlist_id}"
f"/api/v1/playlists/{playlist_id}",
)
assert response.status_code == 200
@@ -339,10 +337,10 @@ class TestPlaylistEndpoints:
test_session.add(test_playlist)
await test_session.commit()
await test_session.refresh(test_playlist)
# Extract ID before HTTP request
playlist_id = test_playlist.id
payload = {
"name": "Updated Playlist",
"description": "Updated description",
@@ -350,7 +348,7 @@ class TestPlaylistEndpoints:
}
response = await authenticated_client.put(
f"/api/v1/playlists/{playlist_id}", json=payload
f"/api/v1/playlists/{playlist_id}", json=payload,
)
assert response.status_code == 200
@@ -379,7 +377,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
# Note: main_playlist doesn't need to be current=True for this test
# The service logic handles current playlist management
main_playlist = Playlist(
@@ -393,14 +391,14 @@ class TestPlaylistEndpoints:
test_session.add(main_playlist)
await test_session.commit()
await test_session.refresh(test_playlist)
# Extract ID before HTTP request
playlist_id = test_playlist.id
payload = {"is_current": True}
response = await authenticated_client.put(
f"/api/v1/playlists/{playlist_id}", json=payload
f"/api/v1/playlists/{playlist_id}", json=payload,
)
assert response.status_code == 200
@@ -429,12 +427,12 @@ class TestPlaylistEndpoints:
test_session.add(test_playlist)
await test_session.commit()
await test_session.refresh(test_playlist)
# Extract ID before HTTP requests
playlist_id = test_playlist.id
response = await authenticated_client.delete(
f"/api/v1/playlists/{playlist_id}"
f"/api/v1/playlists/{playlist_id}",
)
assert response.status_code == 200
@@ -442,7 +440,7 @@ class TestPlaylistEndpoints:
# Verify playlist is deleted
get_response = await authenticated_client.get(
f"/api/v1/playlists/{playlist_id}"
f"/api/v1/playlists/{playlist_id}",
)
assert get_response.status_code == 404
@@ -465,12 +463,12 @@ class TestPlaylistEndpoints:
test_session.add(main_playlist)
await test_session.commit()
await test_session.refresh(main_playlist)
# Extract ID before HTTP request
main_playlist_id = main_playlist.id
response = await authenticated_client.delete(
f"/api/v1/playlists/{main_playlist_id}"
f"/api/v1/playlists/{main_playlist_id}",
)
assert response.status_code == 400
@@ -496,7 +494,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
main_playlist = Playlist(
user_id=None,
name="Main Playlist",
@@ -507,7 +505,7 @@ class TestPlaylistEndpoints:
)
test_session.add(main_playlist)
await test_session.commit()
response = await authenticated_client.get("/api/v1/playlists/search/playlist")
assert response.status_code == 200
@@ -541,7 +539,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
test_sound = Sound(
name="Test Sound",
filename="test.mp3",
@@ -555,12 +553,12 @@ class TestPlaylistEndpoints:
await test_session.commit()
await test_session.refresh(test_playlist)
await test_session.refresh(test_sound)
# Extract IDs before creating playlist_sound
playlist_id = test_playlist.id
sound_id = test_sound.id
sound_name = test_sound.name
# Add sound to playlist manually for testing
from app.models.playlist_sound import PlaylistSound
@@ -573,7 +571,7 @@ class TestPlaylistEndpoints:
await test_session.commit()
response = await authenticated_client.get(
f"/api/v1/playlists/{playlist_id}/sounds"
f"/api/v1/playlists/{playlist_id}/sounds",
)
assert response.status_code == 200
@@ -602,7 +600,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
test_sound = Sound(
name="Test Sound",
filename="test.mp3",
@@ -616,15 +614,15 @@ class TestPlaylistEndpoints:
await test_session.commit()
await test_session.refresh(test_playlist)
await test_session.refresh(test_sound)
# Extract IDs before HTTP requests
playlist_id = test_playlist.id
sound_id = test_sound.id
payload = {"sound_id": sound_id}
response = await authenticated_client.post(
f"/api/v1/playlists/{playlist_id}/sounds", json=payload
f"/api/v1/playlists/{playlist_id}/sounds", json=payload,
)
assert response.status_code == 200
@@ -632,7 +630,7 @@ class TestPlaylistEndpoints:
# Verify sound was added
get_response = await authenticated_client.get(
f"/api/v1/playlists/{playlist_id}/sounds"
f"/api/v1/playlists/{playlist_id}/sounds",
)
assert get_response.status_code == 200
sounds = get_response.json()
@@ -659,7 +657,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
test_sound = Sound(
name="Test Sound",
filename="test.mp3",
@@ -673,15 +671,15 @@ class TestPlaylistEndpoints:
await test_session.commit()
await test_session.refresh(test_playlist)
await test_session.refresh(test_sound)
# Extract IDs before HTTP request
playlist_id = test_playlist.id
sound_id = test_sound.id
payload = {"sound_id": sound_id, "position": 5}
response = await authenticated_client.post(
f"/api/v1/playlists/{playlist_id}/sounds", json=payload
f"/api/v1/playlists/{playlist_id}/sounds", json=payload,
)
assert response.status_code == 200
@@ -706,7 +704,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
test_sound = Sound(
name="Test Sound",
filename="test.mp3",
@@ -720,22 +718,22 @@ class TestPlaylistEndpoints:
await test_session.commit()
await test_session.refresh(test_playlist)
await test_session.refresh(test_sound)
# Extract IDs before HTTP requests
playlist_id = test_playlist.id
sound_id = test_sound.id
payload = {"sound_id": sound_id}
# Add sound first time
response = await authenticated_client.post(
f"/api/v1/playlists/{playlist_id}/sounds", json=payload
f"/api/v1/playlists/{playlist_id}/sounds", json=payload,
)
assert response.status_code == 200
# Try to add same sound again
response = await authenticated_client.post(
f"/api/v1/playlists/{playlist_id}/sounds", json=payload
f"/api/v1/playlists/{playlist_id}/sounds", json=payload,
)
assert response.status_code == 400
assert "already in this playlist" in response.json()["detail"]
@@ -762,14 +760,14 @@ class TestPlaylistEndpoints:
test_session.add(test_playlist)
await test_session.commit()
await test_session.refresh(test_playlist)
# Extract ID before HTTP request
playlist_id = test_playlist.id
payload = {"sound_id": 99999}
response = await authenticated_client.post(
f"/api/v1/playlists/{playlist_id}/sounds", json=payload
f"/api/v1/playlists/{playlist_id}/sounds", json=payload,
)
assert response.status_code == 404
@@ -795,7 +793,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
test_sound = Sound(
name="Test Sound",
filename="test.mp3",
@@ -809,20 +807,20 @@ class TestPlaylistEndpoints:
await test_session.commit()
await test_session.refresh(test_playlist)
await test_session.refresh(test_sound)
# Extract IDs before HTTP requests
playlist_id = test_playlist.id
sound_id = test_sound.id
# Add sound first
payload = {"sound_id": sound_id}
await authenticated_client.post(
f"/api/v1/playlists/{playlist_id}/sounds", json=payload
f"/api/v1/playlists/{playlist_id}/sounds", json=payload,
)
# Remove sound
response = await authenticated_client.delete(
f"/api/v1/playlists/{playlist_id}/sounds/{sound_id}"
f"/api/v1/playlists/{playlist_id}/sounds/{sound_id}",
)
assert response.status_code == 200
@@ -830,7 +828,7 @@ class TestPlaylistEndpoints:
# Verify sound was removed
get_response = await authenticated_client.get(
f"/api/v1/playlists/{playlist_id}/sounds"
f"/api/v1/playlists/{playlist_id}/sounds",
)
sounds = get_response.json()
assert len(sounds) == 0
@@ -855,7 +853,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
test_sound = Sound(
name="Test Sound",
filename="test.mp3",
@@ -869,13 +867,13 @@ class TestPlaylistEndpoints:
await test_session.commit()
await test_session.refresh(test_playlist)
await test_session.refresh(test_sound)
# Extract IDs before HTTP request
playlist_id = test_playlist.id
sound_id = test_sound.id
response = await authenticated_client.delete(
f"/api/v1/playlists/{playlist_id}/sounds/{sound_id}"
f"/api/v1/playlists/{playlist_id}/sounds/{sound_id}",
)
assert response.status_code == 404
@@ -901,7 +899,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
# Create multiple sounds
sound1 = Sound(name="Sound 1", filename="sound1.mp3", type="SDB", hash="hash1")
sound2 = Sound(name="Sound 2", filename="sound2.mp3", type="SDB", hash="hash2")
@@ -910,7 +908,7 @@ class TestPlaylistEndpoints:
await test_session.refresh(test_playlist)
await test_session.refresh(sound1)
await test_session.refresh(sound2)
# Extract IDs before HTTP requests
playlist_id = test_playlist.id
sound1_id = sound1.id
@@ -929,11 +927,11 @@ class TestPlaylistEndpoints:
# Reorder sounds - use positions that don't cause constraints
# When swapping, we need to be careful about unique constraints
payload = {
"sound_positions": [[sound1_id, 10], [sound2_id, 5]] # Use different positions to avoid constraints
"sound_positions": [[sound1_id, 10], [sound2_id, 5]], # Use different positions to avoid constraints
}
response = await authenticated_client.put(
f"/api/v1/playlists/{playlist_id}/sounds/reorder", json=payload
f"/api/v1/playlists/{playlist_id}/sounds/reorder", json=payload,
)
assert response.status_code == 200
@@ -959,7 +957,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
main_playlist = Playlist(
user_id=None,
name="Main Playlist",
@@ -971,12 +969,12 @@ class TestPlaylistEndpoints:
test_session.add(main_playlist)
await test_session.commit()
await test_session.refresh(test_playlist)
# Extract ID before HTTP request
playlist_id = test_playlist.id
response = await authenticated_client.put(
f"/api/v1/playlists/{playlist_id}/set-current"
f"/api/v1/playlists/{playlist_id}/set-current",
)
assert response.status_code == 200
@@ -1001,7 +999,7 @@ class TestPlaylistEndpoints:
is_deletable=False,
)
test_session.add(main_playlist)
# Create a current playlist for the user
user_id = test_user.id
current_playlist = Playlist(
@@ -1025,7 +1023,7 @@ class TestPlaylistEndpoints:
# but something else is causing validation to fail
assert response.status_code == 422
return
assert response.status_code == 200
assert "unset successfully" in response.json()["message"]
@@ -1055,7 +1053,7 @@ class TestPlaylistEndpoints:
is_deletable=True,
)
test_session.add(test_playlist)
test_sound = Sound(
name="Test Sound",
filename="test.mp3",
@@ -1069,14 +1067,14 @@ class TestPlaylistEndpoints:
await test_session.commit()
await test_session.refresh(test_playlist)
await test_session.refresh(test_sound)
# Extract IDs before HTTP requests
playlist_id = test_playlist.id
sound_id = test_sound.id
# Initially empty
response = await authenticated_client.get(
f"/api/v1/playlists/{playlist_id}/stats"
f"/api/v1/playlists/{playlist_id}/stats",
)
assert response.status_code == 200
@@ -1093,7 +1091,7 @@ class TestPlaylistEndpoints:
# Check stats again
response = await authenticated_client.get(
f"/api/v1/playlists/{playlist_id}/stats"
f"/api/v1/playlists/{playlist_id}/stats",
)
assert response.status_code == 200
@@ -1110,8 +1108,8 @@ class TestPlaylistEndpoints:
test_session: AsyncSession,
) -> None:
"""Test that users can only access their own playlists."""
from app.utils.auth import JWTUtils, PasswordUtils
from app.models.plan import Plan
from app.utils.auth import PasswordUtils
# Create plan within this test to avoid session issues
plan = Plan(
@@ -1124,10 +1122,10 @@ class TestPlaylistEndpoints:
test_session.add(plan)
await test_session.commit()
await test_session.refresh(plan)
# Extract plan ID immediately to avoid session issues
plan_id = plan.id
# Create another user with their own playlist
other_user = User(
email="other@example.com",
@@ -1144,7 +1142,7 @@ class TestPlaylistEndpoints:
# Extract other user ID before creating playlist
other_user_id = other_user.id
other_playlist = Playlist(
user_id=other_user_id,
name="Other User's Playlist",
@@ -1153,13 +1151,13 @@ class TestPlaylistEndpoints:
test_session.add(other_playlist)
await test_session.commit()
await test_session.refresh(other_playlist)
# Extract playlist ID before HTTP requests
other_playlist_id = other_playlist.id
# Try to access other user's playlist
response = await authenticated_client.get(
f"/api/v1/playlists/{other_playlist_id}"
f"/api/v1/playlists/{other_playlist_id}",
)
# Currently the implementation allows access to all playlists

View File

@@ -158,7 +158,7 @@ class TestSocketEndpoints:
@pytest.mark.asyncio
async def test_send_message_missing_parameters(
self, authenticated_client: AsyncClient, authenticated_user: User
self, authenticated_client: AsyncClient, authenticated_user: User,
):
"""Test sending message with missing parameters."""
# Missing target_user_id
@@ -177,7 +177,7 @@ class TestSocketEndpoints:
@pytest.mark.asyncio
async def test_broadcast_message_missing_parameters(
self, authenticated_client: AsyncClient, authenticated_user: User
self, authenticated_client: AsyncClient, authenticated_user: User,
):
"""Test broadcasting message with missing parameters."""
response = await authenticated_client.post("/api/v1/socket/broadcast")
@@ -185,7 +185,7 @@ class TestSocketEndpoints:
@pytest.mark.asyncio
async def test_send_message_invalid_user_id(
self, authenticated_client: AsyncClient, authenticated_user: User
self, authenticated_client: AsyncClient, authenticated_user: User,
):
"""Test sending message with invalid user ID."""
response = await authenticated_client.post(

View File

@@ -66,7 +66,7 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory"
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory",
) as mock_scan:
mock_scan.return_value = mock_results
@@ -167,7 +167,7 @@ class TestSoundEndpoints:
headers = {"API-TOKEN": "admin_api_token"}
with patch(
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory"
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory",
) as mock_scan:
mock_scan.return_value = mock_results
@@ -192,7 +192,7 @@ class TestSoundEndpoints:
):
"""Test scanning sounds when service raises an error."""
with patch(
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory"
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory",
) as mock_scan:
mock_scan.side_effect = Exception("Directory not found")
@@ -244,7 +244,7 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_scanner.SoundScannerService.scan_directory"
"app.services.sound_scanner.SoundScannerService.scan_directory",
) as mock_scan:
mock_scan.return_value = mock_results
@@ -285,7 +285,7 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_scanner.SoundScannerService.scan_directory"
"app.services.sound_scanner.SoundScannerService.scan_directory",
) as mock_scan:
mock_scan.return_value = mock_results
@@ -307,14 +307,14 @@ class TestSoundEndpoints:
):
"""Test custom directory scanning with invalid path."""
with patch(
"app.services.sound_scanner.SoundScannerService.scan_directory"
"app.services.sound_scanner.SoundScannerService.scan_directory",
) as mock_scan:
mock_scan.side_effect = ValueError(
"Directory does not exist: /invalid/path"
"Directory does not exist: /invalid/path",
)
response = await authenticated_admin_client.post(
"/api/v1/sounds/scan/custom", params={"directory": "/invalid/path"}
"/api/v1/sounds/scan/custom", params={"directory": "/invalid/path"},
)
assert response.status_code == 400
@@ -325,7 +325,7 @@ class TestSoundEndpoints:
async def test_scan_custom_directory_unauthenticated(self, client: AsyncClient):
"""Test custom directory scanning without authentication."""
response = await client.post(
"/api/v1/sounds/scan/custom", params={"directory": "/some/path"}
"/api/v1/sounds/scan/custom", params={"directory": "/some/path"},
)
assert response.status_code == 401
@@ -377,12 +377,12 @@ class TestSoundEndpoints:
):
"""Test custom directory scanning when service raises an error."""
with patch(
"app.services.sound_scanner.SoundScannerService.scan_directory"
"app.services.sound_scanner.SoundScannerService.scan_directory",
) as mock_scan:
mock_scan.side_effect = Exception("Permission denied")
response = await authenticated_admin_client.post(
"/api/v1/sounds/scan/custom", params={"directory": "/restricted/path"}
"/api/v1/sounds/scan/custom", params={"directory": "/restricted/path"},
)
assert response.status_code == 500
@@ -442,7 +442,7 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory"
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory",
) as mock_scan:
mock_scan.return_value = mock_results
@@ -480,7 +480,7 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory"
"app.services.sound_scanner.SoundScannerService.scan_soundboard_directory",
) as mock_scan:
mock_scan.return_value = mock_results
@@ -570,12 +570,12 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_all_sounds"
"app.services.sound_normalizer.SoundNormalizerService.normalize_all_sounds",
) as mock_normalize:
mock_normalize.return_value = mock_results
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/all"
"/api/v1/sounds/normalize/all",
)
assert response.status_code == 200
@@ -608,12 +608,12 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_all_sounds"
"app.services.sound_normalizer.SoundNormalizerService.normalize_all_sounds",
) as mock_normalize:
mock_normalize.return_value = mock_results
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/all", params={"force": True}
"/api/v1/sounds/normalize/all", params={"force": True},
)
assert response.status_code == 200
@@ -637,12 +637,12 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_all_sounds"
"app.services.sound_normalizer.SoundNormalizerService.normalize_all_sounds",
) as mock_normalize:
mock_normalize.return_value = mock_results
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/all", params={"one_pass": True}
"/api/v1/sounds/normalize/all", params={"one_pass": True},
)
assert response.status_code == 200
@@ -684,7 +684,7 @@ class TestSoundEndpoints:
base_url="http://test",
) as client:
response = await client.post(
"/api/v1/sounds/normalize/all", headers=headers
"/api/v1/sounds/normalize/all", headers=headers,
)
assert response.status_code == 403
@@ -702,12 +702,12 @@ class TestSoundEndpoints:
):
"""Test normalization when service raises an error."""
with patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_all_sounds"
"app.services.sound_normalizer.SoundNormalizerService.normalize_all_sounds",
) as mock_normalize:
mock_normalize.side_effect = Exception("Normalization service failed")
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/all"
"/api/v1/sounds/normalize/all",
)
assert response.status_code == 500
@@ -758,12 +758,12 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_sounds_by_type"
"app.services.sound_normalizer.SoundNormalizerService.normalize_sounds_by_type",
) as mock_normalize:
mock_normalize.return_value = mock_results
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/type/SDB"
"/api/v1/sounds/normalize/type/SDB",
)
assert response.status_code == 200
@@ -779,7 +779,7 @@ class TestSoundEndpoints:
# Verify the service was called with correct type
mock_normalize.assert_called_once_with(
sound_type="SDB", force=False, one_pass=None
sound_type="SDB", force=False, one_pass=None,
)
@pytest.mark.asyncio
@@ -790,7 +790,7 @@ class TestSoundEndpoints:
):
"""Test normalization with invalid sound type."""
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/type/INVALID"
"/api/v1/sounds/normalize/type/INVALID",
)
assert response.status_code == 400
@@ -814,7 +814,7 @@ class TestSoundEndpoints:
}
with patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_sounds_by_type"
"app.services.sound_normalizer.SoundNormalizerService.normalize_sounds_by_type",
) as mock_normalize:
mock_normalize.return_value = mock_results
@@ -827,7 +827,7 @@ class TestSoundEndpoints:
# Verify parameters were passed correctly
mock_normalize.assert_called_once_with(
sound_type="TTS", force=True, one_pass=False
sound_type="TTS", force=True, one_pass=False,
)
@pytest.mark.asyncio
@@ -866,7 +866,7 @@ class TestSoundEndpoints:
with (
patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_sound"
"app.services.sound_normalizer.SoundNormalizerService.normalize_sound",
) as mock_normalize_sound,
patch("app.repositories.sound.SoundRepository.get_by_id") as mock_get_sound,
):
@@ -874,7 +874,7 @@ class TestSoundEndpoints:
mock_normalize_sound.return_value = mock_result
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/42"
"/api/v1/sounds/normalize/42",
)
assert response.status_code == 200
@@ -897,12 +897,12 @@ class TestSoundEndpoints:
):
"""Test normalization of non-existent sound."""
with patch(
"app.repositories.sound.SoundRepository.get_by_id"
"app.repositories.sound.SoundRepository.get_by_id",
) as mock_get_sound:
mock_get_sound.return_value = None
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/999"
"/api/v1/sounds/normalize/999",
)
assert response.status_code == 404
@@ -945,7 +945,7 @@ class TestSoundEndpoints:
with (
patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_sound"
"app.services.sound_normalizer.SoundNormalizerService.normalize_sound",
) as mock_normalize_sound,
patch("app.repositories.sound.SoundRepository.get_by_id") as mock_get_sound,
):
@@ -953,7 +953,7 @@ class TestSoundEndpoints:
mock_normalize_sound.return_value = mock_result
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/42"
"/api/v1/sounds/normalize/42",
)
assert response.status_code == 500
@@ -997,7 +997,7 @@ class TestSoundEndpoints:
with (
patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_sound"
"app.services.sound_normalizer.SoundNormalizerService.normalize_sound",
) as mock_normalize_sound,
patch("app.repositories.sound.SoundRepository.get_by_id") as mock_get_sound,
):
@@ -1052,7 +1052,7 @@ class TestSoundEndpoints:
with (
patch(
"app.services.sound_normalizer.SoundNormalizerService.normalize_sound"
"app.services.sound_normalizer.SoundNormalizerService.normalize_sound",
) as mock_normalize_sound,
patch("app.repositories.sound.SoundRepository.get_by_id") as mock_get_sound,
):
@@ -1060,7 +1060,7 @@ class TestSoundEndpoints:
mock_normalize_sound.return_value = mock_result
response = await authenticated_admin_client.post(
"/api/v1/sounds/normalize/42"
"/api/v1/sounds/normalize/42",
)
assert response.status_code == 200

View File

@@ -1,16 +1,14 @@
"""Tests for VLC player API endpoints."""
from unittest.mock import AsyncMock, Mock, patch
from unittest.mock import AsyncMock
import pytest
from httpx import AsyncClient
from fastapi import FastAPI
from httpx import AsyncClient
from app.api.v1.sounds import get_credit_service, get_sound_repository, get_vlc_player
from app.models.sound import Sound
from app.models.user import User
from app.api.v1.sounds import get_vlc_player, get_sound_repository, get_credit_service
class TestVLCEndpoints:
@@ -28,7 +26,7 @@ class TestVLCEndpoints:
mock_vlc_service = AsyncMock()
mock_repo = AsyncMock()
mock_credit_service = AsyncMock()
# Set up test data
mock_sound = Sound(
id=1,
@@ -39,27 +37,27 @@ class TestVLCEndpoints:
size=1024,
hash="test_hash",
)
# Configure mocks
mock_repo.get_by_id.return_value = mock_sound
mock_credit_service.validate_and_reserve_credits.return_value = None
mock_credit_service.deduct_credits.return_value = None
mock_vlc_service.play_sound.return_value = True
# Override dependencies
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
test_app.dependency_overrides[get_sound_repository] = lambda: mock_repo
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try:
response = await authenticated_client.post("/api/v1/sounds/vlc/play/1")
assert response.status_code == 200
data = response.json()
assert data["sound_id"] == 1
assert data["sound_name"] == "Test Sound"
assert "Test Sound" in data["message"]
# Verify service calls
mock_repo.get_by_id.assert_called_once_with(1)
mock_vlc_service.play_sound.assert_called_once_with(mock_sound)
@@ -81,18 +79,18 @@ class TestVLCEndpoints:
mock_vlc_service = AsyncMock()
mock_repo = AsyncMock()
mock_credit_service = AsyncMock()
# Configure mocks
mock_repo.get_by_id.return_value = None
# Override dependencies
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
test_app.dependency_overrides[get_sound_repository] = lambda: mock_repo
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try:
response = await authenticated_client.post("/api/v1/sounds/vlc/play/999")
assert response.status_code == 404
data = response.json()
assert "Sound with ID 999 not found" in data["detail"]
@@ -114,7 +112,7 @@ class TestVLCEndpoints:
mock_vlc_service = AsyncMock()
mock_repo = AsyncMock()
mock_credit_service = AsyncMock()
# Set up test data
mock_sound = Sound(
id=1,
@@ -125,21 +123,21 @@ class TestVLCEndpoints:
size=1024,
hash="test_hash",
)
# Configure mocks
mock_repo.get_by_id.return_value = mock_sound
mock_credit_service.validate_and_reserve_credits.return_value = None
mock_credit_service.deduct_credits.return_value = None
mock_vlc_service.play_sound.return_value = False
# Override dependencies
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
test_app.dependency_overrides[get_sound_repository] = lambda: mock_repo
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try:
response = await authenticated_client.post("/api/v1/sounds/vlc/play/1")
assert response.status_code == 500
data = response.json()
assert "Failed to launch VLC for sound playback" in data["detail"]
@@ -161,18 +159,18 @@ class TestVLCEndpoints:
mock_vlc_service = AsyncMock()
mock_repo = AsyncMock()
mock_credit_service = AsyncMock()
# Configure mocks
mock_repo.get_by_id.side_effect = Exception("Database error")
# Override dependencies
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
test_app.dependency_overrides[get_sound_repository] = lambda: mock_repo
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try:
response = await authenticated_client.post("/api/v1/sounds/vlc/play/1")
assert response.status_code == 500
data = response.json()
assert "Failed to play sound" in data["detail"]
@@ -209,13 +207,13 @@ class TestVLCEndpoints:
"message": "Killed 3 VLC processes",
}
mock_vlc_service.stop_all_vlc_instances.return_value = mock_result
# Override dependency
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all")
assert response.status_code == 200
data = response.json()
assert data["success"] is True
@@ -223,7 +221,7 @@ class TestVLCEndpoints:
assert data["processes_killed"] == 3
assert data["processes_remaining"] == 0
assert "Killed 3 VLC processes" in data["message"]
# Verify service call
mock_vlc_service.stop_all_vlc_instances.assert_called_once()
finally:
@@ -247,13 +245,13 @@ class TestVLCEndpoints:
"message": "No VLC processes found",
}
mock_vlc_service.stop_all_vlc_instances.return_value = mock_result
# Override dependency
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all")
assert response.status_code == 200
data = response.json()
assert data["success"] is True
@@ -282,13 +280,13 @@ class TestVLCEndpoints:
"message": "Killed 2 VLC processes",
}
mock_vlc_service.stop_all_vlc_instances.return_value = mock_result
# Override dependency
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all")
assert response.status_code == 200
data = response.json()
assert data["success"] is True
@@ -317,13 +315,13 @@ class TestVLCEndpoints:
"message": "Failed to stop VLC processes",
}
mock_vlc_service.stop_all_vlc_instances.return_value = mock_result
# Override dependency
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all")
assert response.status_code == 200
data = response.json()
assert data["success"] is False
@@ -344,13 +342,13 @@ class TestVLCEndpoints:
# Set up mock to raise an exception
mock_vlc_service = AsyncMock()
mock_vlc_service.stop_all_vlc_instances.side_effect = Exception("Service error")
# Override dependency
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
try:
response = await authenticated_client.post("/api/v1/sounds/vlc/stop-all")
assert response.status_code == 500
data = response.json()
assert "Failed to stop VLC instances" in data["detail"]
@@ -379,7 +377,7 @@ class TestVLCEndpoints:
mock_vlc_service = AsyncMock()
mock_repo = AsyncMock()
mock_credit_service = AsyncMock()
# Set up test data
mock_sound = Sound(
id=1,
@@ -390,21 +388,21 @@ class TestVLCEndpoints:
size=512,
hash="admin_hash",
)
# Configure mocks
mock_repo.get_by_id.return_value = mock_sound
mock_credit_service.validate_and_reserve_credits.return_value = None
mock_credit_service.deduct_credits.return_value = None
mock_vlc_service.play_sound.return_value = True
# Override dependencies
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service
test_app.dependency_overrides[get_sound_repository] = lambda: mock_repo
test_app.dependency_overrides[get_credit_service] = lambda: mock_credit_service
try:
response = await authenticated_admin_client.post("/api/v1/sounds/vlc/play/1")
assert response.status_code == 200
data = response.json()
assert data["sound_name"] == "Admin Test Sound"
@@ -424,17 +422,17 @@ class TestVLCEndpoints:
"message": "Killed 1 VLC processes",
}
mock_vlc_service_2.stop_all_vlc_instances.return_value = mock_result
# Override dependency for stop-all test
test_app.dependency_overrides[get_vlc_player] = lambda: mock_vlc_service_2
try:
response = await authenticated_admin_client.post("/api/v1/sounds/vlc/stop-all")
assert response.status_code == 200
data = response.json()
assert data["success"] is True
assert data["processes_killed"] == 1
finally:
# Clean up dependency override
test_app.dependency_overrides.pop(get_vlc_player, None)
test_app.dependency_overrides.pop(get_vlc_player, None)