-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_client.py
More file actions
424 lines (343 loc) · 16.8 KB
/
Copy pathtest_client.py
File metadata and controls
424 lines (343 loc) · 16.8 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
"""
Tests for the HTTP client and main Stack0 client
"""
from __future__ import annotations
import warnings
from unittest.mock import MagicMock, patch
import httpx
import pytest
from stack0 import AsyncStack0, Stack0
from stack0._client.http import AsyncHTTPClient, HTTPClient
from stack0._exceptions import (
APIError,
AuthenticationError,
NetworkError,
NotFoundError,
PermissionError,
RateLimitError,
ValidationError,
)
class TestHTTPClient:
"""Tests for synchronous HTTP client"""
def test_initialization(self) -> None:
"""Test HTTP client initialization"""
with patch("httpx.Client") as mock_client:
client = HTTPClient(api_key="test_key")
assert client.api_key == "test_key"
assert client.base_url == "https://api.stack0.dev/v1"
mock_client.assert_called_once()
def test_initialization_custom_base_url(self) -> None:
"""Test HTTP client with custom base URL"""
with patch("httpx.Client") as mock_client:
client = HTTPClient(api_key="test_key", base_url="https://custom.api.dev/v2/")
assert client.base_url == "https://custom.api.dev/v2"
def test_initialization_custom_timeout(self) -> None:
"""Test HTTP client with custom timeout"""
with patch("httpx.Client") as mock_client:
HTTPClient(api_key="test_key", timeout=60.0)
mock_client.assert_called_once()
call_kwargs = mock_client.call_args[1]
assert call_kwargs["timeout"] == 60.0
def test_headers_set_correctly(self) -> None:
"""Test that headers are set correctly"""
with patch("httpx.Client") as mock_client:
HTTPClient(api_key="test_api_key")
call_kwargs = mock_client.call_args[1]
assert call_kwargs["headers"]["Authorization"] == "Bearer test_api_key"
assert call_kwargs["headers"]["Content-Type"] == "application/json"
def test_get_request(self) -> None:
"""Test GET request"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = True
mock_response.status_code = 200
mock_response.json.return_value = {"data": "test"}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
result = client.get("/test")
assert result == {"data": "test"}
mock_client.return_value.request.assert_called_once_with("GET", "/test")
def test_post_request(self) -> None:
"""Test POST request"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = True
mock_response.status_code = 200
mock_response.json.return_value = {"id": "123"}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
result = client.post("/test", {"name": "test"})
assert result == {"id": "123"}
mock_client.return_value.request.assert_called_once_with("POST", "/test", json={"name": "test"})
def test_put_request(self) -> None:
"""Test PUT request"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = True
mock_response.status_code = 200
mock_response.json.return_value = {"updated": True}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
result = client.put("/test", {"name": "updated"})
assert result == {"updated": True}
def test_patch_request(self) -> None:
"""Test PATCH request"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = True
mock_response.status_code = 200
mock_response.json.return_value = {"patched": True}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
result = client.patch("/test", {"field": "value"})
assert result == {"patched": True}
def test_delete_request(self) -> None:
"""Test DELETE request"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = True
mock_response.status_code = 204
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
result = client.delete("/test")
assert result is None
def test_delete_with_body_request(self) -> None:
"""Test DELETE request with body"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = True
mock_response.status_code = 200
mock_response.json.return_value = {"deleted": True}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
result = client.delete_with_body("/test", {"id": "123"})
assert result == {"deleted": True}
def test_context_manager(self) -> None:
"""Test HTTP client as context manager"""
with patch("httpx.Client") as mock_client:
with HTTPClient(api_key="test_key") as client:
assert client is not None
mock_client.return_value.close.assert_called_once()
class TestHTTPClientErrors:
"""Tests for HTTP client error handling"""
def test_authentication_error(self) -> None:
"""Test 401 error raises AuthenticationError"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = False
mock_response.status_code = 401
mock_response.json.return_value = {"message": "Invalid API key", "code": "INVALID_API_KEY"}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="invalid_key")
with pytest.raises(AuthenticationError) as exc_info:
client.get("/test")
assert exc_info.value.status_code == 401
assert exc_info.value.code == "INVALID_API_KEY"
assert "Invalid API key" in str(exc_info.value)
def test_permission_error(self) -> None:
"""Test 403 error raises PermissionError"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = False
mock_response.status_code = 403
mock_response.json.return_value = {"message": "Access denied"}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
with pytest.raises(PermissionError) as exc_info:
client.get("/test")
assert exc_info.value.status_code == 403
def test_not_found_error(self) -> None:
"""Test 404 error raises NotFoundError"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = False
mock_response.status_code = 404
mock_response.json.return_value = {"message": "Resource not found"}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
with pytest.raises(NotFoundError) as exc_info:
client.get("/test/nonexistent")
assert exc_info.value.status_code == 404
def test_rate_limit_error(self) -> None:
"""Test 429 error raises RateLimitError"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = False
mock_response.status_code = 429
mock_response.json.return_value = {"message": "Rate limit exceeded"}
mock_response.headers = {"Retry-After": "60"}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
with pytest.raises(RateLimitError) as exc_info:
client.get("/test")
assert exc_info.value.status_code == 429
assert exc_info.value.retry_after == 60
def test_rate_limit_error_without_retry_after(self) -> None:
"""Test 429 error without Retry-After header"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = False
mock_response.status_code = 429
mock_response.json.return_value = {"message": "Rate limit exceeded"}
mock_response.headers = {}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
with pytest.raises(RateLimitError) as exc_info:
client.get("/test")
assert exc_info.value.retry_after is None
def test_validation_error(self) -> None:
"""Test 400 error raises ValidationError"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = False
mock_response.status_code = 400
mock_response.json.return_value = {
"message": "Invalid request",
"code": "VALIDATION_ERROR",
}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
with pytest.raises(ValidationError) as exc_info:
client.post("/test", {})
assert exc_info.value.status_code == 400
def test_generic_api_error(self) -> None:
"""Test generic server error raises APIError"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = False
mock_response.status_code = 500
mock_response.json.return_value = {"message": "Internal server error"}
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
with pytest.raises(APIError) as exc_info:
client.get("/test")
assert exc_info.value.status_code == 500
def test_network_error_timeout(self) -> None:
"""Test timeout raises NetworkError"""
with patch("httpx.Client") as mock_client:
mock_client.return_value.request.side_effect = httpx.TimeoutException("Request timed out")
client = HTTPClient(api_key="test_key")
with pytest.raises(NetworkError) as exc_info:
client.get("/test")
assert "timed out" in str(exc_info.value)
def test_network_error_connection(self) -> None:
"""Test connection error raises NetworkError"""
with patch("httpx.Client") as mock_client:
mock_client.return_value.request.side_effect = httpx.ConnectError("Connection failed")
client = HTTPClient(api_key="test_key")
with pytest.raises(NetworkError) as exc_info:
client.get("/test")
assert "Network error" in str(exc_info.value)
def test_error_with_non_json_response(self) -> None:
"""Test error handling when response is not JSON"""
with patch("httpx.Client") as mock_client:
mock_response = MagicMock()
mock_response.is_success = False
mock_response.status_code = 500
mock_response.json.side_effect = ValueError("Invalid JSON")
mock_response.text = "Internal Server Error"
mock_response.reason_phrase = "Internal Server Error"
mock_client.return_value.request.return_value = mock_response
client = HTTPClient(api_key="test_key")
with pytest.raises(APIError) as exc_info:
client.get("/test")
assert exc_info.value.status_code == 500
class TestAsyncHTTPClient:
"""Tests for async HTTP client"""
@pytest.mark.asyncio
async def test_initialization(self) -> None:
"""Test async HTTP client initialization"""
with patch("httpx.AsyncClient") as mock_client:
client = AsyncHTTPClient(api_key="test_key")
assert client.api_key == "test_key"
assert client.base_url == "https://api.stack0.dev/v1"
@pytest.mark.asyncio
async def test_async_context_manager(self) -> None:
"""Test async HTTP client as context manager"""
with patch("httpx.AsyncClient") as mock_client:
mock_client.return_value.aclose = MagicMock()
async with AsyncHTTPClient(api_key="test_key") as client:
assert client is not None
class TestStack0Client:
"""Tests for main Stack0 client"""
def test_initialization(self) -> None:
"""Test Stack0 client initialization"""
with patch("stack0._client.http.HTTPClient"):
client = Stack0(api_key="test_key")
assert client.mail is not None
assert client.cdn is not None
assert client.screenshots is not None
assert client.extraction is not None
assert client.integrations is not None
assert client.marketing is not None
def test_initialization_with_custom_options(self) -> None:
"""Test Stack0 client with custom options"""
with patch("stack0._client.http.HTTPClient") as mock_http:
client = Stack0(
api_key="test_key",
base_url="https://custom.api.dev",
cdn_url="https://cdn.custom.dev",
timeout=60.0,
)
assert client._cdn_url == "https://cdn.custom.dev"
def test_webdata_deprecation_warning(self) -> None:
"""Test that webdata property shows deprecation warning"""
with patch("stack0._client.http.HTTPClient"):
client = Stack0(api_key="test_key")
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
_ = client.webdata
assert len(w) == 1
assert issubclass(w[0].category, DeprecationWarning)
assert "deprecated" in str(w[0].message).lower()
def test_context_manager(self) -> None:
"""Test Stack0 client as context manager"""
with patch("stack0._client.http.HTTPClient") as mock_http:
with Stack0(api_key="test_key") as client:
assert client is not None
mock_http.return_value.close.assert_called_once()
class TestAsyncStack0Client:
"""Tests for async Stack0 client"""
def test_initialization(self) -> None:
"""Test AsyncStack0 client initialization"""
with patch("stack0._client.http.AsyncHTTPClient"):
client = AsyncStack0(api_key="test_key")
assert client.mail is not None
assert client.cdn is not None
assert client.screenshots is not None
assert client.extraction is not None
assert client.integrations is not None
assert client.marketing is not None
def test_webdata_deprecation_warning(self) -> None:
"""Test that webdata property shows deprecation warning"""
with patch("stack0._client.http.AsyncHTTPClient"):
client = AsyncStack0(api_key="test_key")
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
_ = client.webdata
assert len(w) == 1
assert issubclass(w[0].category, DeprecationWarning)
@pytest.mark.asyncio
async def test_async_context_manager(self) -> None:
"""Test AsyncStack0 client as context manager"""
with patch("stack0._client.http.AsyncHTTPClient") as mock_http:
async with AsyncStack0(api_key="test_key") as client:
assert client is not None
class TestExceptions:
"""Tests for exception classes"""
def test_api_error_str(self) -> None:
"""Test APIError string representation"""
error = APIError("Test error", 500, "TEST_CODE", {"detail": "info"})
assert "[TEST_CODE]" in str(error)
assert "Test error" in str(error)
assert "500" in str(error)
def test_api_error_without_code(self) -> None:
"""Test APIError without code"""
error = APIError("Test error", 500)
assert "Test error" in str(error)
assert "500" in str(error)
def test_rate_limit_error_retry_after(self) -> None:
"""Test RateLimitError with retry_after"""
error = RateLimitError("Rate limited", 429, None, None, 60)
assert error.retry_after == 60
assert error.status_code == 429