Skip to content

Commit

Permalink
test(utils): fix test_utils to actually work
Browse files Browse the repository at this point in the history
also centralize some more test code, fix linting, and fix formatting
  • Loading branch information
soehlert committed Dec 27, 2024
1 parent 558bb95 commit c3db4cb
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 49 deletions.
17 changes: 17 additions & 0 deletions backend/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from unittest.mock import MagicMock, patch

import pytest
from plexapi.audio import Track

mock_env = {
"PLEX_BASE_URL": "http://fake-plex:32400",
Expand All @@ -23,6 +24,22 @@ def mock_settings():
yield settings


@pytest.fixture
def mock_plex_track():
"""Create a mock Plex Track object with test attributes.
Returns:
MagicMock: Simulated Plex Track object
"""
mock_track = MagicMock(spec=Track)
mock_track.ratingKey = "12345"
mock_track.title = "Test Song"
mock_track.duration = 180
mock_track.thumb = "http://example.com/album_art.jpg"
mock_track.grandparentTitle = "Test Artist"
return mock_track


@pytest.fixture
def mock_redis(mocker, mock_settings):
"""Mock Redis clients to avoid actual Redis connection.
Expand Down
3 changes: 1 addition & 2 deletions backend/tests/test_redis.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
"""Test redis functionality."""

import json
from unittest.mock import patch

import pytest

from unittest.mock import patch

from backend.services.redis import (
add_to_queue_redis,
cache_data,
Expand Down
67 changes: 23 additions & 44 deletions backend/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,6 @@
)


@pytest.fixture
def mock_redis(mocker):
"""Mock Redis client to avoid actual Redis connection.
Returns a MagicMock object that simulates Redis client behavior.
"""
mock_redis_queue = MagicMock()
mocker.patch("backend.utils.get_redis_queue_client", return_value=mock_redis_queue)
return mock_redis_queue


@pytest.fixture
def mock_plex_track():
"""Create a mock Plex Track object with standard test attributes.
Returns a MagicMock object simulating a Plex Track.
"""
track = MagicMock()
track.ratingKey = "12345"
track.title = "Mock Song"
track.artist = "Mock Artist"
track.duration = 180
return track


@pytest.fixture
def tracker():
"""Create a fresh TrackTimeTracker instance for testing.
Expand Down Expand Up @@ -71,37 +46,41 @@ def test_is_track_object():

def test_song_found_in_queue(mock_redis, mock_plex_track):
"""Test when a song exists in the queue."""
mock_redis.lrange.return_value = ['{"item_id": "12345", "title": "Mock Song", "artist": "Mock Artist"}']
assert is_song_in_queue(mock_plex_track) is True
mock_redis.lrange.assert_called_once_with("playback_queue", 0, -1)
mock_redis_queue, _ = mock_redis
with patch("backend.utils.get_redis_queue_client", return_value=mock_redis_queue):
mock_redis_queue.lrange.return_value = ['{"item_id": "12345", "title": "Mock Song", "artist": "Mock Artist"}']
assert is_song_in_queue(mock_plex_track) is True
mock_redis_queue.lrange.assert_called_once_with("playback_queue", 0, -1)


def test_song_not_in_queue(mock_redis, mock_plex_track):
"""Test when a song is not in the queue."""
mock_redis.lrange.return_value = ['{"item_id": "67890", "title": "Different Song", "artist": "Different Artist"}']
assert is_song_in_queue(mock_plex_track) is False
mock_redis_queue, _ = mock_redis
with patch("backend.utils.get_redis_queue_client", return_value=mock_redis_queue):
mock_redis_queue.lrange.return_value = [
'{"item_id": "67890", "title": "Different Song", "artist": "Different Artist"}'
]
assert is_song_in_queue(mock_plex_track) is False


def test_empty_queue(mock_redis, mock_plex_track):
"""Test behavior with an empty queue."""
mock_redis.lrange.return_value = []
assert is_song_in_queue(mock_plex_track) is False


def test_redis_exception_handling(mock_redis, mock_plex_track):
"""Test exception handling for Redis failures."""
mock_redis.lrange.side_effect = Exception("Redis connection failed")
assert is_song_in_queue(mock_plex_track) is False
mock_redis_queue, _ = mock_redis
with patch("backend.utils.get_redis_queue_client", return_value=mock_redis_queue):
mock_redis_queue.lrange.return_value = []
assert is_song_in_queue(mock_plex_track) is False


def test_multiple_items_in_queue(mock_redis, mock_plex_track):
"""Test with multiple items in the queue."""
mock_redis.lrange.return_value = [
'{"item_id": "11111", "title": "Song 1"}',
'{"item_id": "12345", "title": "Mock Song"}',
'{"item_id": "22222", "title": "Song 2"}',
]
assert is_song_in_queue(mock_plex_track) is True
mock_redis_queue, _ = mock_redis
with patch("backend.utils.get_redis_queue_client", return_value=mock_redis_queue):
mock_redis_queue.lrange.return_value = [
'{"item_id": "11111", "title": "Song 1"}',
'{"item_id": "12345", "title": "Mock Song"}',
'{"item_id": "22222", "title": "Song 2"}',
]
assert is_song_in_queue(mock_plex_track) is True


def test_tracker_start(tracker):
Expand Down
2 changes: 1 addition & 1 deletion backend/tests/test_websockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ async def receive_text(self):
try:
message = await self.receive_queue.get()
if message == "__DISCONNECT__":
logger .debug("MockWebSocket: Simulating disconnect")
logger.debug("MockWebSocket: Simulating disconnect")
raise WebSocketDisconnect
except asyncio.QueueEmpty:
logger.debug("MockWebSocket: Queue is empty, raising WebSocketDisconnect")
Expand Down
6 changes: 4 additions & 2 deletions backend/websockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ async def send_queue():
await send_to_specific_client(session_id, message, "queue_update")
# ruff: noqa: BLE001
except Exception as e:
logger.error("Failed to send to session %s: %s", session_id, e)
# ruff: noqa: TRY401
logger.exception("Failed to send to session %s: %s", session_id, e)
active_connections["queue_update"].pop(session_id, None)


Expand Down Expand Up @@ -77,7 +78,8 @@ async def send_current_playing():
logger.debug("Sending current track to connection %s", session_id)
await send_to_specific_client(session_id, message, "music_control")
except Exception as e:
logger.error(f"Failed to send to session %s: %s", session_id, e)
# ruff: noqa: TRY401
logger.exception("Failed to send to session %s: %s", session_id, e)
active_connections["music_control"].pop(session_id, None)
else:
logger.warning("No current track found.")
Expand Down

0 comments on commit c3db4cb

Please sign in to comment.