"""Tests for Handlers.""" import json from contextlib import contextmanager from unittest.mock import MagicMock, patch import pytest from flask import g from owsrequest.utils import mock_request from owsresponse import response from playlist.api import app from playlist.constants.handler_constants import ISRC, PLAYLIST_TYPE, STOREFRONT_ENABLED from playlist.services.ows_permissions import ( OWS_PERMISSIONS_PROFILE_URL, OWS_PERMISSIONS_SERVICE_NAME, ) from playlist.utils import handler_utils from playlist.utils.handler_utils import ( get_query_boolean_params, get_query_string_params, ) from tests.integration.consts.permissions import ALL_PERMISSIONS_EMPLOYEE_HEADERS from tests.unit.services.test_ows_permissions import OWS_PERMISSIONS_ALL_ACCESS_RESPONSE @contextmanager def mock_handler( snowflake_db_response={}, permissions_response=OWS_PERMISSIONS_ALL_ACCESS_RESPONSE ): with ( patch( "playlist.connectors.snowflake.SnowflakeQuery.execute", return_value=snowflake_db_response, ) as snowflake, patch( "playlist.queries.fetch_queries.get_max_available_streaming_date", return_value="2021-06-01", ), ): mock_request.get( OWS_PERMISSIONS_SERVICE_NAME, OWS_PERMISSIONS_PROFILE_URL.format( profile_id=ALL_PERMISSIONS_EMPLOYEE_HEADERS["Orchard-Profile-Id"], profile_type=ALL_PERMISSIONS_EMPLOYEE_HEADERS["Orchard-Profile-Type"], ), status=200, response=permissions_response, ) yield snowflake @pytest.fixture def client(): """Return test client.""" test_client = app.test_client() class Ows: def __init__(self): self.correlation_id = "1" class RequestContext: def __init__(self): self.authorization = True self.context_type = "abcdef" with test_client.application.app_context(): g.ows = Ows() g.request_context = RequestContext() yield test_client def test_exception_handler(): with app.app_context(), patch("playlist.utils.handler_utils.g") as mock_g: """Verify exception_Handler returns 500 status code and json payload.""" message = ( "The server encountered an internal error " "and was unable to complete your request." ) mock_error = MagicMock() server_response = handler_utils.exception_handler(mock_error) mock_g.log.exception.assert_called_with(mock_error) # assert status code is 500 assert server_response.status_code == 500 # assert json payload response_message = json.loads(server_response.data.decode()) assert response_message["message"] == message assert response_message["code"] == response.error.ERROR_CODE_INTERNAL_ERROR def test_validation_error(client): # test validation exceptions are caught and returned as errors with mock_handler(): placements_response = client.get( "/placements?isrc=QZK6M1903348&sort_direction=BRUH", headers=ALL_PERMISSIONS_EMPLOYEE_HEADERS, ) assert placements_response.status_code == 400 assert placements_response.json == { "error": {"sort_direction": ["Must be one of: ASC, DESC."]} } def test_get_query_boolean_params(client): """Ensure that get_query_boolean_params returns correct results.""" with client: client.get( "/placements?isrc=QZK6M1903348&storefront_enabled=true", ) query_params = get_query_boolean_params([STOREFRONT_ENABLED]) assert query_params[STOREFRONT_ENABLED] def test_get_query_boolean_params_when_other_query_params_passed(client): """Ensure that get_query_boolean_params works correctly when other query params are passed.""" with client: client.get( "/placements?isrc=QZK6M1903348&storefront_enabled=true&playlist_type=USER_GENERATED", ) query_params = get_query_string_params([ISRC, PLAYLIST_TYPE]) query_params = get_query_boolean_params([STOREFRONT_ENABLED], query_params) expected_query_params_number = 3 assert query_params[STOREFRONT_ENABLED] assert len(query_params.keys()) == expected_query_params_number def test_get_query_boolean_params_raises_value_error(client): """Ensure that get_query_boolean_params raise ValueError when not incorrect value provided.""" with client: client.get( "/placements?isrc=QZK6M1903348&playlist_type=USER_GENERATED&storefront_enabled=tr", ) with pytest.raises(ValueError): get_query_boolean_params([STOREFRONT_ENABLED]) def test_get_query_boolean_params_when_no_params_in_request(client): """Ensure that get_query_boolean_params returns None when parameter is not provided in the request.""" with client: client.get("/placements?isrc=QZK6M1903348") query_params = get_query_boolean_params([STOREFRONT_ENABLED]) assert query_params.get(STOREFRONT_ENABLED) is None