"""Unit tests for the top tracks model layer.""" from unittest.mock import MagicMock, patch import pytest from analytics.models import top_tracks MOCK_SQL = '{subaccount_clause}' @pytest.fixture() def mock_snowflake(monkeypatch, mock_config): """Mock for Snowflake database client.""" snowflake_mock = MagicMock() monkeypatch.setattr( 'analytics.models.top_tracks.snowflake_conn', snowflake_mock) return snowflake_mock @pytest.fixture def mock_db_result(): """Mock database result.""" return [ ( 'isrc', 'trackName', 'artistName', 1, 0.5, 123, 'Subaccount 1,Subaccount 2' ) ] @pytest.fixture def mock_db_subaccount_result(): """Mock database result.""" return [ ( 'isrc', 'trackName', 'artistName', 1, 0.5, 123, None ) ] @pytest.fixture def mock_load_query(): """Mock load query.""" with patch('analytics.models.top_tracks.SQLLoader') as sql_loader: load_query = sql_loader.load_query load_query.return_value = MOCK_SQL yield load_query class TestGetTopTracksWithLabel: """Test get_top_tracks with label.""" expected_sql = 'AND subaccountid IS NULL' expected_response = [ { 'isrc': 'isrc', 'track_name': 'trackName', 'artist_name': 'artistName', 'streams': 1, 'growth_percentage': 0.5, 'product_id': 123, 'subaccount_names': 'Subaccount 1,Subaccount 2' } ] @pytest.fixture def top_tracks_response( self, mock_snowflake, mock_load_query, mock_db_result): """Return top tracks.""" labelid = 7123 subaccountid = None limit = 10 mock_snowflake.fetchall.return_value = mock_db_result return top_tracks.get_top_tracks(labelid, subaccountid, limit) def test_succeeds(self, top_tracks_response): """Test successful response.""" assert top_tracks_response == self.expected_response def test_top_tracks_query_is_loaded( self, top_tracks_response, mock_load_query): """Test top tracks query is loaded.""" mock_load_query.assert_called_once_with('get_top_tracks') class TestGetTopTracksWithSubaccount: """Test get_top_tracks with subaccount.""" expected_sql = 'AND subaccountid = :subaccountid' expected_response = [ { 'isrc': 'isrc', 'track_name': 'trackName', 'artist_name': 'artistName', 'streams': 1, 'growth_percentage': 0.5, 'product_id': 123, 'subaccount_names': None } ] @pytest.fixture def top_tracks_response( self, mock_snowflake, mock_load_query, mock_db_subaccount_result): """Return top tracks.""" labelid = 7123 subaccountid = 345 limit = 10 mock_snowflake.fetchall.return_value = mock_db_subaccount_result return top_tracks.get_top_tracks(labelid, subaccountid, limit) def test_succeeds(self, top_tracks_response): """Test successful response.""" assert top_tracks_response == self.expected_response def test_top_tracks_query_is_loaded( self, top_tracks_response, mock_load_query): """Test top tracks query is loaded.""" mock_load_query.assert_called_once_with('get_top_tracks')