"""Unit tests for JIRA client error handling improvements.""" from typing import Any from config import JiraConfig from pytest import MonkeyPatch, raises from requests.exceptions import HTTPError from jira_client import JiraClient class MockResponse: """Simple mock of requests.Response.""" def __init__(self, status_code: int = 200, json_data: Any = None) -> None: """Initialize the mock response.""" self.status_code = status_code self._json_data = json_data or {} def raise_for_status(self) -> None: """Raise HTTPError for non-2xx status codes.""" if not (200 <= self.status_code < 300): raise HTTPError(f'{self.status_code} error', response=self) def json(self) -> dict: """Return the JSON data.""" return self._json_data def make_jira_config() -> JiraConfig: """Create a sample JiraConfig for testing.""" return JiraConfig( jira_base_url='https://jira.example.com', jira_user_email='testuser', jira_api_token='secret-token', ) def test_query_jira_tickets_401_error(monkeypatch: MonkeyPatch) -> None: """Test that 401 errors are handled with specific messaging.""" cfg = make_jira_config() client = JiraClient(cfg) mock_resp = MockResponse(status_code=401, json_data={}) def mock_get(url: str, params: Any = None, timeout: Any = None) -> MockResponse: return mock_resp monkeypatch.setattr(client._session, 'get', mock_get) # Should raise HTTPError with specific handling for 401 with raises(HTTPError) as exc_info: client.query_jira_tickets('project=ABC') # Verify it's the expected error type assert exc_info.value.response.status_code == 401 def test_query_jira_tickets_403_error(monkeypatch: MonkeyPatch) -> None: """Test that 403 errors are handled with specific messaging.""" cfg = make_jira_config() client = JiraClient(cfg) mock_resp = MockResponse(status_code=403, json_data={}) def mock_get(url: str, params: Any = None, timeout: Any = None) -> MockResponse: return mock_resp monkeypatch.setattr(client._session, 'get', mock_get) # Should raise HTTPError with specific handling for 403 with raises(HTTPError) as exc_info: client.query_jira_tickets('project=ABC') # Verify it's the expected error type assert exc_info.value.response.status_code == 403 def test_query_jira_tickets_500_error(monkeypatch: MonkeyPatch) -> None: """Test that 500 errors are properly raised.""" cfg = make_jira_config() client = JiraClient(cfg) mock_resp = MockResponse(status_code=500, json_data={}) def mock_get(url: str, params: Any = None, timeout: Any = None) -> MockResponse: return mock_resp monkeypatch.setattr(client._session, 'get', mock_get) # Should raise HTTPError for 500 status codes (which go through resp.raise_for_status) with raises(HTTPError) as exc_info: client.query_jira_tickets('project=ABC') # Verify it's the expected error type assert exc_info.value.response.status_code == 500