File size: 10,084 Bytes
47a6c2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""
Unit tests for dados.gov.br API client.
"""

import pytest
from unittest.mock import AsyncMock, patch, MagicMock
import httpx

from src.tools.dados_gov_api import DadosGovAPIClient, DadosGovAPIError


@pytest.fixture
def api_client():
    """Create API client instance for testing"""
    return DadosGovAPIClient(api_key="test-key")


@pytest.fixture
def mock_httpx_client():
    """Create mock httpx client"""
    mock = AsyncMock()
    mock.aclose = AsyncMock()
    return mock


class TestDadosGovAPIClient:
    """Test suite for dados.gov.br API client"""
    
    @pytest.mark.asyncio
    async def test_client_initialization(self):
        """Test client initialization with and without API key"""
        # With API key
        client = DadosGovAPIClient(api_key="test-key")
        assert client.api_key == "test-key"
        
        # Without API key
        client = DadosGovAPIClient()
        assert client.api_key is None
        
    @pytest.mark.asyncio
    async def test_search_datasets_success(self, api_client, mock_httpx_client):
        """Test successful dataset search"""
        # Mock response
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {
            "count": 2,
            "results": [
                {
                    "id": "dataset1",
                    "name": "test-dataset-1",
                    "title": "Test Dataset 1",
                },
                {
                    "id": "dataset2",
                    "name": "test-dataset-2",
                    "title": "Test Dataset 2",
                },
            ],
        }
        
        mock_httpx_client.request.return_value = mock_response
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            result = await api_client.search_datasets(
                query="test",
                limit=10,
            )
            
        assert result["count"] == 2
        assert len(result["results"]) == 2
        assert result["results"][0]["id"] == "dataset1"
        
        # Verify request parameters
        mock_httpx_client.request.assert_called_once()
        call_args = mock_httpx_client.request.call_args
        assert call_args[0][0] == "GET"
        assert call_args[0][1] == "package_search"
        assert call_args[1]["params"]["q"] == "test"
        assert call_args[1]["params"]["rows"] == 10
        
    @pytest.mark.asyncio
    async def test_search_datasets_with_filters(self, api_client, mock_httpx_client):
        """Test dataset search with filters"""
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {"count": 0, "results": []}
        
        mock_httpx_client.request.return_value = mock_response
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            result = await api_client.search_datasets(
                organization="test-org",
                tags=["tag1", "tag2"],
                format="csv",
            )
            
        # Verify filters in request
        call_args = mock_httpx_client.request.call_args
        params = call_args[1]["params"]
        assert params["fq"] == "organization:test-org"
        assert params["tags"] == "tag1,tag2"
        assert params["res_format"] == "csv"
        
    @pytest.mark.asyncio
    async def test_get_dataset(self, api_client, mock_httpx_client):
        """Test getting dataset details"""
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {
            "result": {
                "id": "test-dataset",
                "name": "test-dataset",
                "title": "Test Dataset",
                "resources": [
                    {
                        "id": "resource1",
                        "format": "CSV",
                        "url": "http://example.com/data.csv",
                    }
                ],
            }
        }
        
        mock_httpx_client.request.return_value = mock_response
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            result = await api_client.get_dataset("test-dataset")
            
        assert result["result"]["id"] == "test-dataset"
        assert len(result["result"]["resources"]) == 1
        
    @pytest.mark.asyncio
    async def test_error_handling_401(self, api_client, mock_httpx_client):
        """Test authentication error handling"""
        mock_response = MagicMock()
        mock_response.status_code = 401
        
        mock_httpx_client.request.return_value = mock_response
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            with pytest.raises(DadosGovAPIError) as exc_info:
                await api_client.search_datasets()
                
        assert "Authentication failed" in str(exc_info.value)
        assert exc_info.value.status_code == 401
        
    @pytest.mark.asyncio
    async def test_error_handling_403(self, api_client, mock_httpx_client):
        """Test access forbidden error handling"""
        mock_response = MagicMock()
        mock_response.status_code = 403
        
        mock_httpx_client.request.return_value = mock_response
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            with pytest.raises(DadosGovAPIError) as exc_info:
                await api_client.search_datasets()
                
        assert "Access forbidden" in str(exc_info.value)
        assert exc_info.value.status_code == 403
        
    @pytest.mark.asyncio
    async def test_error_handling_404(self, api_client, mock_httpx_client):
        """Test not found error handling"""
        mock_response = MagicMock()
        mock_response.status_code = 404
        
        mock_httpx_client.request.return_value = mock_response
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            with pytest.raises(DadosGovAPIError) as exc_info:
                await api_client.get_dataset("nonexistent")
                
        assert "Resource not found" in str(exc_info.value)
        assert exc_info.value.status_code == 404
        
    @pytest.mark.asyncio
    async def test_rate_limit_handling(self, api_client, mock_httpx_client):
        """Test rate limit handling with retry"""
        # First response: rate limited
        mock_response_429 = MagicMock()
        mock_response_429.status_code = 429
        mock_response_429.headers = {"Retry-After": "1"}
        
        # Second response: success
        mock_response_200 = MagicMock()
        mock_response_200.status_code = 200
        mock_response_200.json.return_value = {"count": 0, "results": []}
        
        mock_httpx_client.request.side_effect = [
            mock_response_429,
            mock_response_200,
        ]
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            with patch("asyncio.sleep", new_callable=AsyncMock) as mock_sleep:
                result = await api_client.search_datasets()
                
        assert result["count"] == 0
        mock_sleep.assert_called_once_with(1)
        assert mock_httpx_client.request.call_count == 2
        
    @pytest.mark.asyncio
    async def test_connection_error_retry(self, api_client, mock_httpx_client):
        """Test connection error with retry logic"""
        # First two attempts fail, third succeeds
        mock_httpx_client.request.side_effect = [
            httpx.ConnectError("Connection failed"),
            httpx.TimeoutException("Timeout"),
            MagicMock(
                status_code=200,
                json=MagicMock(return_value={"count": 0, "results": []})
            ),
        ]
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            with patch("asyncio.sleep", new_callable=AsyncMock):
                result = await api_client.search_datasets()
                
        assert result["count"] == 0
        assert mock_httpx_client.request.call_count == 3
        
    @pytest.mark.asyncio
    async def test_connection_error_max_retries(self, api_client, mock_httpx_client):
        """Test connection error exhausting retries"""
        mock_httpx_client.request.side_effect = httpx.ConnectError("Connection failed")
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            with patch("asyncio.sleep", new_callable=AsyncMock):
                with pytest.raises(DadosGovAPIError) as exc_info:
                    await api_client.search_datasets()
                    
        assert "Failed to connect" in str(exc_info.value)
        assert mock_httpx_client.request.call_count == 3  # MAX_RETRIES
        
    @pytest.mark.asyncio
    async def test_list_organizations(self, api_client, mock_httpx_client):
        """Test listing organizations"""
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {
            "result": [
                {"id": "org1", "title": "Organization 1"},
                {"id": "org2", "title": "Organization 2"},
            ]
        }
        
        mock_httpx_client.request.return_value = mock_response
        
        with patch.object(api_client, "_get_client", return_value=mock_httpx_client):
            result = await api_client.list_organizations(limit=50)
            
        assert len(result["result"]) == 2
        assert result["result"][0]["id"] == "org1"
        
    @pytest.mark.asyncio
    async def test_client_cleanup(self, api_client):
        """Test client cleanup on close"""
        mock_client = AsyncMock()
        api_client._client = mock_client
        
        await api_client.close()
        
        mock_client.aclose.assert_called_once()
        assert api_client._client is None