"""Unit tests for Snowflake SQL executor of Apple Music Source of Stream.""" from unittest.mock import MagicMock from unittest.mock import patch import pytest from snowflake import connector from analytics_aggregation.flows.spotify_sos.snowflake_executor \ import SpotifySOSExecutor from tests.conftest import SubstringMatcher @pytest.fixture def custom_params(): """Fixture returning custom params.""" return { 'db': 'testdb', 'schema': 'testschema', 'start_date': '2017-01-01', 'end_date': '2017-01-02', 'labelids': None} @pytest.fixture(autouse=True) def patch_connector(monkeypatch): """Patch Snowflake connector to prevent real calls.""" connect_mock = MagicMock() monkeypatch.setattr(connector, 'connect', connect_mock) @pytest.yield_fixture def mock_executor(sf_config_mock, monkeypatch): """Yield executor context.""" connect_mock = MagicMock() monkeypatch.setattr(connector, 'connect', connect_mock) executor = SpotifySOSExecutor(sf_config_mock) with patch.object(executor, 'execute', wraps=executor.execute) as \ executor.ex_mock: yield executor @pytest.yield_fixture def fetch_executor(sf_config_mock, monkeypatch): """Yield executor context.""" connect_mock = MagicMock() monkeypatch.setattr(connector, 'connect', connect_mock) executor = SpotifySOSExecutor(sf_config_mock) with patch.object(executor, 'fetchone', wraps=executor.fetchone) as \ executor.ex_mock: yield executor def test_cleanup_staging_sos(mock_executor, custom_params): """Test cleanup_staging_sos method.""" mock_executor.cleanup_staging_sos( params=custom_params, labelids_clause=None) assert mock_executor.ex_mock.call_count == 1 mock_executor.ex_mock.assert_any_call( SubstringMatcher( containing=['DELETE FROM', 'testdb.testschema.staging_sos']), params={ 'start_date': '2017-01-01', 'end_date': '2017-01-02', 'labelids': None}) def test_populate_staging_sos(mock_executor, custom_params): """Test populate_staging_sos method.""" mock_executor.populate_staging_sos( params=custom_params, labelids_clause=None) assert mock_executor.ex_mock.call_count == 1 mock_executor.ex_mock.assert_any_call( SubstringMatcher( containing=['INSERT INTO', 'testdb.testschema.staging_sos']), params={ 'start_date': '2017-01-01', 'end_date': '2017-01-02', 'labelids': None}) def test_get_row_count_from_staging_sos(fetch_executor, custom_params): """Test get_row_count_from_staging_sos method.""" custom_params.pop('start_date') custom_params.pop('end_date') custom_params.pop('labelids') custom_params.update({'storeid': 286, 'date': '2018-03-10'}) fetch_executor.get_row_count_from_staging_sos(params=custom_params) assert fetch_executor.ex_mock.call_count == 1 fetch_executor.ex_mock.assert_any_call( SubstringMatcher( containing=['SELECT COUNT(*)', 'testdb.testschema.staging_sos']), params={'storeid': 286, 'date': '2018-03-10'})