"""Tests for the PDP authorization module.""" from unittest.mock import MagicMock, patch from python_pdp_sdk.backends import exceptions from royalties.utils import authorization @patch('royalties.utils.authorization.base') @patch('royalties.utils.authorization.config') def test_pdp_authorize_resource( config_mock: MagicMock, resource_getters_base_mock: MagicMock ) -> None: """Test the pdp_authorize_resource function.""" config_mock.pdp_authorization_backend.is_authorized.return_value = True result = authorization.pdp_authorize_resource(1, 'test_resource') assert result is True config_mock.pdp_authorization_backend.is_authorized.assert_called_once_with( action='view', resource_id=1, resource_type='test_resource', resource_getter=resource_getters_base_mock.ForwardKwargsGetter.return_value, ) @patch('royalties.utils.authorization.g', spec=['log']) @patch('royalties.utils.authorization.base') @patch('royalties.utils.authorization.config') def test_pdp_authorize_resource_unauthorized( config_mock: MagicMock, _resource_getters_base_mock: MagicMock, g_mock: MagicMock, ) -> None: """Test the pdp_authorize_resource function.""" g_mock.request_context = MagicMock(jwt_identity_id='identity-id') config_mock.pdp_authorization_backend.is_authorized.return_value = False result = authorization.pdp_authorize_resource(1, 'test_resource') assert result is False g_mock.log.warn.assert_called_once_with( 'User is forbidden', resources={ 'identity_id': 'identity-id', 'resource_id': 1, 'resource_type': 'test_resource', 'auth_response': False, }, ) @patch('royalties.utils.authorization.config') @patch('royalties.utils.authorization.g') def test_pdp_authorize_many_accounts_error( mock_g: MagicMock, config_mock: MagicMock ) -> None: """Test error handling of pdp_authorize_many_accounts.""" config_mock.pdp_authorization_backend.is_authorized_many.side_effect = ( exceptions.InvalidRequestException('🥶') ) account_ids = [1234, 5678] result = authorization.pdp_authorize_many_accounts(account_ids=account_ids) assert result is False mock_g.log.warn.assert_called_with( 'Caught a PDP InvalidRequestException', resources={ 'identity_id': mock_g.request_context.jwt_identity_id, 'resource_ids': account_ids, 'resource_type': 'account', 'error': '🥶', }, )