Repository navigation
Expand file tree
/
Copy pathtest_client_errors.py
More file actions
428 lines (321 loc) · 17.2 KB
/
Copy pathtest_client_errors.py
File metadata and controls
428 lines (321 loc) · 17.2 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
425
426
427
428
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from unittest.mock import Mock
import pytest
from werkzeug import Response
from apify_client.errors import (
ApifyApiError,
ConflictError,
ForbiddenError,
InvalidRequestError,
InvalidResponseBodyError,
NotFoundError,
RateLimitError,
ServerError,
UnauthorizedError,
)
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
from pytest_httpserver import HTTPServer
from werkzeug import Request
from apify_client import ApifyClient, ApifyClientAsync
from apify_client.http_clients import HttpClient, HttpClientAsync
pytestmark = pytest.mark.usefixtures('http_client_classes')
_TEST_PATH = '/errors'
_EXPECTED_MESSAGE = 'some_message'
_EXPECTED_TYPE = 'some_type'
_EXPECTED_DATA = {
'invalidItems': {'0': ["should have required property 'name'"], '1': ["should have required property 'name'"]}
}
RAW_ERROR = (
b'{\n'
b' "error": {\n'
b' "type": "insufficient-permissions",\n'
b' "message": "Insufficient permissions for the Actor run. Make sure you\''
b're passing a correct API token and that it has the required permissions."\n'
b' }\n'
b'}'
)
_DATASET_FIXTURE = {
'id': 'ds-1',
'userId': 'u-1',
'createdAt': '2026-01-01T00:00:00.000Z',
'modifiedAt': '2026-01-01T00:00:00.000Z',
'accessedAt': '2026-01-01T00:00:00.000Z',
'itemCount': 0,
'cleanItemCount': 0,
'consoleUrl': 'https://console.apify.com/storage/datasets/ds-1',
}
# Singleton sub-path endpoints — fetch a fixed path under an ID-identified parent (e.g. /schedules/{id}/log). A 404
# always means the parent is missing, so `NotFoundError` propagates instead of collapsing to `None`.
_SINGLETON_SUBPATH_404_CASES = [
pytest.param('/v2/schedules/missing/log', 'GET', lambda c: c.schedule('missing').get_log(), id='schedule_get_log'),
pytest.param('/v2/actor-tasks/missing/input', 'GET', lambda c: c.task('missing').get_input(), id='task_get_input'),
pytest.param(
'/v2/datasets/missing/statistics',
'GET',
lambda c: c.dataset('missing').get_statistics(),
id='dataset_get_statistics',
),
pytest.param('/v2/webhooks/missing/test', 'POST', lambda c: c.webhook('missing').test(), id='webhook_test'),
]
def _not_found_body() -> dict:
return {'error': {'type': 'record-not-found', 'message': 'not found'}}
def streaming_handler(_request: Request) -> Response:
"""Handler for streaming log requests."""
return Response(
response=(RAW_ERROR[i : i + 1] for i in range(len(RAW_ERROR))),
status=403,
mimetype='application/octet-stream',
headers={'Content-Length': str(len(RAW_ERROR))},
)
@pytest.fixture
def test_endpoint(httpserver: HTTPServer) -> str:
httpserver.expect_request(_TEST_PATH).respond_with_json(
{'error': {'message': _EXPECTED_MESSAGE, 'type': _EXPECTED_TYPE, 'data': _EXPECTED_DATA}}, status=400
)
return str(httpserver.url_for(_TEST_PATH))
def test_client_apify_api_error_with_data(test_endpoint: str, http_client_class: type[HttpClient]) -> None:
"""Test that client correctly throws ApifyApiError with error data from response."""
client = http_client_class()
with pytest.raises(ApifyApiError) as exc:
client.call(method='GET', url=test_endpoint)
assert exc.value.message == _EXPECTED_MESSAGE
assert exc.value.type == _EXPECTED_TYPE
assert exc.value.data == _EXPECTED_DATA
async def test_async_client_apify_api_error_with_data(
test_endpoint: str, http_client_async_class: type[HttpClientAsync]
) -> None:
"""Test that async client correctly throws ApifyApiError with error data from response."""
client = http_client_async_class()
with pytest.raises(ApifyApiError) as exc:
await client.call(method='GET', url=test_endpoint)
assert exc.value.message == _EXPECTED_MESSAGE
assert exc.value.type == _EXPECTED_TYPE
assert exc.value.data == _EXPECTED_DATA
def test_client_apify_api_error_streamed(httpserver: HTTPServer, http_client_class: type[HttpClient]) -> None:
"""Test that client correctly throws ApifyApiError when the response has stream."""
error = json.loads(RAW_ERROR.decode())
client = http_client_class()
httpserver.expect_request('/stream_error').respond_with_handler(streaming_handler)
with pytest.raises(ApifyApiError) as exc:
client.call(method='GET', url=httpserver.url_for('/stream_error'), stream=True)
assert exc.value.message == error['error']['message']
assert exc.value.type == error['error']['type']
async def test_async_client_apify_api_error_streamed(
httpserver: HTTPServer, http_client_async_class: type[HttpClientAsync]
) -> None:
"""Test that async client correctly throws ApifyApiError when the response has stream."""
error = json.loads(RAW_ERROR.decode())
client = http_client_async_class()
httpserver.expect_request('/stream_error').respond_with_handler(streaming_handler)
with pytest.raises(ApifyApiError) as exc:
await client.call(method='GET', url=httpserver.url_for('/stream_error'), stream=True)
assert exc.value.message == error['error']['message']
assert exc.value.type == error['error']['type']
def test_apify_api_error_dispatches_to_subclass_for_known_status(
httpserver: HTTPServer, http_client_class: type[HttpClient]
) -> None:
"""Mapped HTTP status codes dispatch to their matching subclass."""
httpserver.expect_request('/dispatch').respond_with_json(
{'error': {'type': 'record-not-found', 'message': 'nope'}}, status=404
)
client = http_client_class()
with pytest.raises(NotFoundError) as exc:
client.call(method='GET', url=str(httpserver.url_for('/dispatch')))
# Still an ApifyApiError, so legacy `except` handlers keep working.
assert isinstance(exc.value, ApifyApiError)
assert exc.value.status_code == 404
assert exc.value.type == 'record-not-found'
def test_apify_api_error_dispatches_streamed_response(
httpserver: HTTPServer, http_client_class: type[HttpClient]
) -> None:
"""Dispatch works even when the response body comes in as a stream (403 → ForbiddenError)."""
httpserver.expect_request('/stream_dispatch').respond_with_handler(streaming_handler)
client = http_client_class()
with pytest.raises(ForbiddenError) as exc:
client.call(method='GET', url=httpserver.url_for('/stream_dispatch'), stream=True)
assert isinstance(exc.value, ApifyApiError)
assert exc.value.status_code == 403
assert exc.value.type == 'insufficient-permissions'
def test_apify_api_error_dispatches_5xx_to_server_error(
httpserver: HTTPServer, http_client_class: type[HttpClient]
) -> None:
"""Any 5xx status falls under the ServerError subclass."""
httpserver.expect_request('/server_error').respond_with_json(
{'error': {'type': 'internal-error', 'message': 'boom'}}, status=503
)
client = http_client_class(max_retries=1)
with pytest.raises(ServerError) as exc:
client.call(method='GET', url=str(httpserver.url_for('/server_error')))
assert isinstance(exc.value, ApifyApiError)
assert exc.value.status_code == 503
def test_apify_api_error_falls_back_for_unmapped_status(
httpserver: HTTPServer, http_client_class: type[HttpClient]
) -> None:
"""Statuses without a dedicated subclass fall back to the base ApifyApiError."""
httpserver.expect_request('/unmapped').respond_with_json(
{'error': {'type': 'whatever', 'message': 'nope'}}, status=418
)
client = http_client_class()
with pytest.raises(ApifyApiError) as exc:
client.call(method='GET', url=str(httpserver.url_for('/unmapped')))
assert type(exc.value) is ApifyApiError
assert exc.value.status_code == 418
assert exc.value.type == 'whatever'
@pytest.mark.parametrize(
('status_code', 'expected_cls'),
[
pytest.param(400, InvalidRequestError, id='400 → InvalidRequestError'),
pytest.param(401, UnauthorizedError, id='401 → UnauthorizedError'),
pytest.param(403, ForbiddenError, id='403 → ForbiddenError'),
pytest.param(404, NotFoundError, id='404 → NotFoundError'),
pytest.param(409, ConflictError, id='409 → ConflictError'),
pytest.param(429, RateLimitError, id='429 → RateLimitError'),
],
)
def test_apify_api_error_dispatches_all_mapped_statuses(
httpserver: HTTPServer,
http_client_class: type[HttpClient],
status_code: int,
expected_cls: type[ApifyApiError],
) -> None:
"""Every status in `_STATUS_TO_CLASS` dispatches to its matching subclass."""
httpserver.expect_request('/dispatch_all').respond_with_json(
{'error': {'type': 'some-type', 'message': 'msg'}}, status=status_code
)
# Use max_retries=1 so retryable statuses (429) don't loop during the test.
client = http_client_class(max_retries=1)
with pytest.raises(expected_cls) as exc:
client.call(method='GET', url=str(httpserver.url_for('/dispatch_all')))
assert type(exc.value) is expected_cls
assert isinstance(exc.value, ApifyApiError)
assert exc.value.status_code == status_code
def test_apify_api_error_subclass_constructed_directly_keeps_its_class() -> None:
"""Only `ApifyApiError` itself dispatches - a subclass constructed directly is never re-dispatched by status."""
response = Mock()
response.status_code = 404
response.json.return_value = {'error': {'type': 'record-not-found', 'message': 'nope'}}
# 404 maps to `NotFoundError`, but the explicit class must win over the status.
error = ServerError(response, 1)
assert type(error) is ServerError
assert error.status_code == 404
assert error.type == 'record-not-found'
def test_apify_api_error_falls_back_for_unparsable_body(
httpserver: HTTPServer, http_client_class: type[HttpClient]
) -> None:
"""When the body can't be parsed, status-based dispatch still applies and `.type` is None."""
httpserver.expect_request('/unparsable').respond_with_data('<not json>', status=418, content_type='text/html')
client = http_client_class(max_retries=1)
with pytest.raises(ApifyApiError) as exc:
client.call(method='GET', url=str(httpserver.url_for('/unparsable')))
assert type(exc.value) is ApifyApiError
assert exc.value.type is None
def test_get_raises_invalid_response_body_error_on_malformed_json(
httpserver: HTTPServer, sync_client: ApifyClient
) -> None:
"""A successful response whose body is not valid JSON raises `InvalidResponseBodyError`."""
httpserver.expect_request('/v2/datasets/ds-1').respond_with_data(b'{"data": ', content_type='application/json')
with pytest.raises(InvalidResponseBodyError):
sync_client.dataset('ds-1').get()
async def test_get_raises_invalid_response_body_error_on_malformed_json_async(
httpserver: HTTPServer, async_client: ApifyClientAsync
) -> None:
"""A successful response whose body is not valid JSON raises `InvalidResponseBodyError`."""
httpserver.expect_request('/v2/datasets/ds-1').respond_with_data(b'{"data": ', content_type='application/json')
with pytest.raises(InvalidResponseBodyError):
await async_client.dataset('ds-1').get()
def test_direct_get_returns_none_on_404(httpserver: HTTPServer, sync_client: ApifyClient) -> None:
httpserver.expect_request('/v2/datasets/missing').respond_with_json(_not_found_body(), status=404)
assert sync_client.dataset('missing').get() is None
async def test_direct_get_returns_none_on_404_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None:
httpserver.expect_request('/v2/datasets/missing').respond_with_json(_not_found_body(), status=404)
assert await async_client.dataset('missing').get() is None
def test_chained_get_raises_on_404(httpserver: HTTPServer, sync_client: ApifyClient) -> None:
httpserver.expect_request('/v2/actor-runs/missing-run/dataset').respond_with_json(_not_found_body(), status=404)
with pytest.raises(NotFoundError):
sync_client.run('missing-run').dataset().get()
async def test_chained_get_raises_on_404_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None:
httpserver.expect_request('/v2/actor-runs/missing-run/dataset').respond_with_json(_not_found_body(), status=404)
with pytest.raises(NotFoundError):
await async_client.run('missing-run').dataset().get()
def test_actor_last_run_dataset_get_raises_on_404(httpserver: HTTPServer, sync_client: ApifyClient) -> None:
"""404 covers missing actor, missing last_run, or missing dataset — all three are indistinguishable from the single
HTTP response (the client only hits the final URL), so `NotFoundError` propagates uniformly.
"""
httpserver.expect_request('/v2/actors/actor-id/runs/last/dataset').respond_with_json(_not_found_body(), status=404)
with pytest.raises(NotFoundError):
sync_client.actor('actor-id').last_run().dataset().get()
async def test_actor_last_run_dataset_get_raises_on_404_async(
httpserver: HTTPServer, async_client: ApifyClientAsync
) -> None:
httpserver.expect_request('/v2/actors/actor-id/runs/last/dataset').respond_with_json(_not_found_body(), status=404)
with pytest.raises(NotFoundError):
await async_client.actor('actor-id').last_run().dataset().get()
def test_actor_last_run_dataset_get_returns_dataset(httpserver: HTTPServer, sync_client: ApifyClient) -> None:
httpserver.expect_request('/v2/actors/actor-id/runs/last/dataset').respond_with_json({'data': _DATASET_FIXTURE})
dataset = sync_client.actor('actor-id').last_run().dataset().get()
assert dataset is not None
assert dataset.id == 'ds-1'
async def test_actor_last_run_dataset_get_returns_dataset_async(
httpserver: HTTPServer, async_client: ApifyClientAsync
) -> None:
httpserver.expect_request('/v2/actors/actor-id/runs/last/dataset').respond_with_json({'data': _DATASET_FIXTURE})
dataset = await async_client.actor('actor-id').last_run().dataset().get()
assert dataset is not None
assert dataset.id == 'ds-1'
def test_direct_delete_swallows_404(httpserver: HTTPServer, sync_client: ApifyClient) -> None:
httpserver.expect_request('/v2/datasets/missing', method='DELETE').respond_with_json(_not_found_body(), status=404)
sync_client.dataset('missing').delete()
async def test_direct_delete_swallows_404_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None:
httpserver.expect_request('/v2/datasets/missing', method='DELETE').respond_with_json(_not_found_body(), status=404)
await async_client.dataset('missing').delete()
def test_chained_delete_raises_on_404(httpserver: HTTPServer, sync_client: ApifyClient) -> None:
httpserver.expect_request('/v2/actor-runs/missing-run/dataset', method='DELETE').respond_with_json(
_not_found_body(), status=404
)
with pytest.raises(NotFoundError):
sync_client.run('missing-run').dataset().delete()
async def test_chained_delete_raises_on_404_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None:
httpserver.expect_request('/v2/actor-runs/missing-run/dataset', method='DELETE').respond_with_json(
_not_found_body(), status=404
)
with pytest.raises(NotFoundError):
await async_client.run('missing-run').dataset().delete()
def test_direct_log_get_returns_none_on_404(httpserver: HTTPServer, sync_client: ApifyClient) -> None:
httpserver.expect_request('/v2/logs/missing').respond_with_json(_not_found_body(), status=404)
assert sync_client.log('missing').get() is None
async def test_direct_log_get_returns_none_on_404_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None:
httpserver.expect_request('/v2/logs/missing').respond_with_json(_not_found_body(), status=404)
assert await async_client.log('missing').get() is None
def test_chained_log_get_raises_on_404(httpserver: HTTPServer, sync_client: ApifyClient) -> None:
httpserver.expect_request('/v2/actor-runs/missing-run/log').respond_with_json(_not_found_body(), status=404)
with pytest.raises(NotFoundError):
sync_client.run('missing-run').log().get()
async def test_chained_log_get_raises_on_404_async(httpserver: HTTPServer, async_client: ApifyClientAsync) -> None:
httpserver.expect_request('/v2/actor-runs/missing-run/log').respond_with_json(_not_found_body(), status=404)
with pytest.raises(NotFoundError):
await async_client.run('missing-run').log().get()
@pytest.mark.parametrize(('path', 'method', 'call'), _SINGLETON_SUBPATH_404_CASES)
def test_singleton_subpath_raises_on_404(
httpserver: HTTPServer,
sync_client: ApifyClient,
path: str,
method: str,
call: Callable[[ApifyClient], Any],
) -> None:
httpserver.expect_request(path, method=method).respond_with_json(_not_found_body(), status=404)
with pytest.raises(NotFoundError):
call(sync_client)
@pytest.mark.parametrize(('path', 'method', 'call'), _SINGLETON_SUBPATH_404_CASES)
async def test_singleton_subpath_raises_on_404_async(
httpserver: HTTPServer,
async_client: ApifyClientAsync,
path: str,
method: str,
call: Callable[[ApifyClientAsync], Awaitable[Any]],
) -> None:
httpserver.expect_request(path, method=method).respond_with_json(_not_found_body(), status=404)
with pytest.raises(NotFoundError):
await call(async_client)