"""Tests for OwsError helpers.""" import json from unittest.mock import Mock from httpx import HTTPStatusError, Request from royalties.utils.error import OwsError def test_ows_error_initialization(): """Test standard initialization of the OwsError.""" error = OwsError(message='A specific error occurred.', code='test_code', status=418) assert error.message == 'A specific error occurred.' assert error.code == 'test_code' assert error.status == 418 def test_ows_error_initialization_defaults(): """Test initialization of OwsError with default code and status.""" error = OwsError(message='A default error occurred.') assert error.message == 'A default error occurred.' assert error.code == 'bad_request' assert error.status == 400 def test_ows_error_str_representation(): """Test the string representation of the OwsError.""" error = OwsError(message='Test error', code='test_error', status=418) expected_str = 'Status 418: Test error (test_error)' assert str(error) == expected_str def test_create_from_http_status_error_with_response_text(): """Test creation from an HTTPStatusError with a valid response body.""" mock_response = Mock() mock_response.status_code = 403 error_body = {'message': 'Permission denied', 'code': 'forbidden'} mock_response.text = json.dumps(error_body) http_status_error = HTTPStatusError( message='Forbidden', request=Request('GET', 'http://test.com'), response=mock_response, ) ows_error = OwsError.create_from_http_status_error(http_status_error) assert ows_error.status == 403 assert ows_error.message == 'Permission denied' assert ows_error.code == 'forbidden' def test_create_from_http_status_error_without_response_text(): """Test creation from an HTTPStatusError without a response text body.""" mock_response = Mock() mock_response.status_code = 502 mock_response.text = '' http_status_error = HTTPStatusError( message='Bad Gateway', request=Request('GET', 'http://test.com'), response=mock_response, ) ows_error = OwsError.create_from_http_status_error(http_status_error) assert ows_error.status == 502 assert ows_error.message == 'Bad Gateway' assert ows_error.code == 'request_error' def test_create_from_http_status_error_without_response(): """Test creation from an HTTPStatusError without a response body.""" http_status_error = HTTPStatusError( message='Error', request=Request('GET', 'http://test.com'), response=None ) ows_error = OwsError.create_from_http_status_error(http_status_error) assert ows_error.status == 400 assert ows_error.message == 'Error' assert ows_error.code == 'request_error'