"""Unit tests for `src.app` handler selection and sentry init.""" import importlib import sys def test_spotifyapi(monkeypatch): """Instantiates SpotifyAPI with credentials in non-DEV env.""" import src.app as app monkeypatch.setattr(app.config, 'ENVIRONMENT', 'qa') monkeypatch.setattr(app.config, 'SPOTIFY_CLIENT_ID', 'cid') monkeypatch.setattr(app.config, 'SPOTIFY_CLIENT_SECRET', 'csecret') captured = {} class FakeSpotify: def __init__(self, cid, secret): captured['args'] = (cid, secret) monkeypatch.setattr(app, 'SpotifyAPI', FakeSpotify) def fake_handle_event(event, api): captured['api'] = api monkeypatch.setattr(app, 'handle_event', fake_handle_event) ev = {'records': []} result = app.handler(ev, None) assert result == {'status': 'OK'} assert captured['args'] == ('cid', 'csecret') assert isinstance(captured['api'], FakeSpotify) def test_handler_calls_handle_event_with_spotify_api(monkeypatch): """Handler should instantiate SpotifyAPI and call handle_event.""" import src.app as app monkeypatch.setattr(app.config, 'SPOTIFY_CLIENT_ID', 'test_cid') monkeypatch.setattr(app.config, 'SPOTIFY_CLIENT_SECRET', 'test_secret') captured = {} class FakeSpotify: def __init__(self, cid, secret): captured['cid'] = cid captured['secret'] = secret monkeypatch.setattr(app, 'SpotifyAPI', FakeSpotify) def fake_handle_event(event, api): captured['handle_event_called'] = True captured['api'] = api monkeypatch.setattr(app, 'handle_event', fake_handle_event) result = app.handler({'test': 'event'}, None) assert result == {'status': 'OK'} assert captured['cid'] == 'test_cid' assert captured['secret'] == 'test_secret' assert captured['handle_event_called'] is True assert isinstance(captured['api'], FakeSpotify) def test_sentry_init_on_module_reload(monkeypatch): """Reloading module when SENTRY_DSN is set should call sentry.init.""" # Inject a fake top-level config module so reloading src.app triggers init orig = sys.modules.get('config') from types import SimpleNamespace fake_config = SimpleNamespace( SENTRY_DSN='dsn://123', DEV_ENVIRONMENT='dev', ENVIRONMENT='dev', SPOTIFY_CLIENT_ID='cid', SPOTIFY_CLIENT_SECRET='csecret', ) sys.modules['config'] = fake_config try: sentry_sdk = importlib.import_module('sentry_sdk') called = {} def fake_init(dsn, integrations=None): called['called'] = True called['dsn'] = dsn monkeypatch.setattr(sentry_sdk, 'init', fake_init) # reload app to trigger top-level init import src.app as appmod importlib.reload(appmod) assert called.get('called') is True assert called.get('dsn') == 'dsn://123' finally: if orig is None: del sys.modules['config'] else: sys.modules['config'] = orig