Repository navigation
Expand file tree
/
Copy pathtest_utils.py
More file actions
527 lines (444 loc) · 21.3 KB
/
Copy pathtest_utils.py
File metadata and controls
527 lines (444 loc) · 21.3 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
from __future__ import annotations
import gzip
import io
import json
import sys
from base64 import b64decode
from datetime import timedelta
from http import HTTPStatus
from types import ModuleType
from typing import TYPE_CHECKING, Any
from unittest.mock import Mock
import impit
import pytest
from apify_client._models import WebhookCondition, WebhookCreate
from apify_client._resource_clients._resource_client import ResourceClientBase
from apify_client._utils.crypto import create_hmac_signature, create_storage_content_signature, encode_base62
from apify_client._utils.encoding import encode_key_value_store_record_value, encode_webhooks_to_base64
from apify_client._utils.errors import catch_not_found_or_throw, is_retryable_error
from apify_client._utils.http import (
is_compressible_content_type,
response_to_dict,
response_to_list,
to_safe_id,
)
from apify_client._utils.try_import import FailedImport, try_import
from apify_client.errors import ApifyApiError, InvalidResponseBodyError
if TYPE_CHECKING:
from apify_client._typeddicts import WebhookRepresentationDict
from apify_client.types import WebhooksList
_GZIPPED_DATA = gzip.compress(b'buffer data')
def test_try_import_only_handles_the_named_missing_dependency() -> None:
"""Optional-import handling must not hide a broken transitive dependency or module bug."""
module_name = 'test_optional_import_module'
sys.modules[module_name] = ModuleType(module_name)
try:
with (
pytest.raises(ModuleNotFoundError, match='broken-transitive'),
try_import(module_name, 'OptionalSymbol', dependency_name='optional-package'),
):
raise ModuleNotFoundError('broken-transitive', name='broken-transitive')
assert not hasattr(sys.modules[module_name], 'OptionalSymbol')
finally:
del sys.modules[module_name]
def test_try_import_records_the_named_missing_dependency() -> None:
"""A genuinely missing optional dependency is converted to a failed-import placeholder."""
module_name = 'test_missing_optional_import_module'
sys.modules[module_name] = ModuleType(module_name)
try:
with try_import(module_name, 'OptionalSymbol', dependency_name='optional-package') as state:
raise ModuleNotFoundError("No module named 'optional-package'", name='optional-package')
assert state.available is False
assert isinstance(sys.modules[module_name].OptionalSymbol, FailedImport)
finally:
del sys.modules[module_name]
def test_to_safe_id() -> None:
assert to_safe_id('abc') == 'abc'
assert to_safe_id('abc/def') == 'abc~def'
assert to_safe_id('abc~def') == 'abc~def'
assert to_safe_id('user/resource/extra') == 'user~resource~extra'
def test_encode_webhooks_to_base64() -> None:
assert encode_webhooks_to_base64([]) is None
assert (
encode_webhooks_to_base64(
[
WebhookCreate(
event_types=['ACTOR.RUN.CREATED'],
condition=WebhookCondition(),
request_url='https://example.com/run-created',
),
WebhookCreate(
event_types=['ACTOR.RUN.SUCCEEDED'],
condition=WebhookCondition(),
request_url='https://example.com/run-succeeded',
payload_template='{"hello": "world", "resource":{{resource}}}',
),
]
)
== 'W3siZXZlbnRUeXBlcyI6IFsiQUNUT1IuUlVOLkNSRUFURUQiXSwgInJlcXVlc3RVcmwiOiAiaHR0cHM6Ly9leGFtcGxlLmNvbS9ydW4tY3JlYXRlZCJ9LCB7ImV2ZW50VHlwZXMiOiBbIkFDVE9SLlJVTi5TVUNDRUVERUQiXSwgInJlcXVlc3RVcmwiOiAiaHR0cHM6Ly9leGFtcGxlLmNvbS9ydW4tc3VjY2VlZGVkIiwgInBheWxvYWRUZW1wbGF0ZSI6ICJ7XCJoZWxsb1wiOiBcIndvcmxkXCIsIFwicmVzb3VyY2VcIjp7e3Jlc291cmNlfX19In1d' # noqa: E501
)
@pytest.mark.parametrize(
'webhooks',
[
pytest.param(
[
WebhookCreate(
event_types=['ACTOR.RUN.SUCCEEDED'],
condition=WebhookCondition(),
request_url='https://example.com/run-succeeded',
idempotency_key='some-key',
ignore_ssl_errors=True,
do_not_retry=True,
),
],
id='webhook-create-model',
),
pytest.param(
[
{
'event_types': ['ACTOR.RUN.SUCCEEDED'],
'request_url': 'https://example.com/run-succeeded',
'idempotency_key': 'some-key',
'ignore_ssl_errors': True,
'do_not_retry': True,
},
],
id='snake-case-dict',
),
pytest.param(
[
{
'eventTypes': ['ACTOR.RUN.SUCCEEDED'],
'requestUrl': 'https://example.com/run-succeeded',
'idempotencyKey': 'some-key',
'ignoreSslErrors': True,
'doNotRetry': True,
},
],
id='camel-case-dict',
),
],
)
def test_encode_webhooks_to_base64_keeps_adhoc_fields(webhooks: WebhooksList) -> None:
"""Test that the idempotency key and the SSL/retry flags survive the projection for every accepted shape."""
result = encode_webhooks_to_base64(webhooks)
assert result is not None
assert json.loads(b64decode(result)) == [
{
'eventTypes': ['ACTOR.RUN.SUCCEEDED'],
'requestUrl': 'https://example.com/run-succeeded',
'idempotencyKey': 'some-key',
'ignoreSslErrors': True,
'doNotRetry': True,
}
]
def test_encode_webhooks_to_base64_from_dicts() -> None:
"""Test that encode_webhooks_to_base64 accepts plain dicts typed as WebhookRepresentationDict."""
webhooks: list[WebhookRepresentationDict] = [
{
'event_types': ['ACTOR.RUN.CREATED'],
'request_url': 'https://example.com/run-created',
},
{
'event_types': ['ACTOR.RUN.SUCCEEDED'],
'request_url': 'https://example.com/run-succeeded',
'payload_template': '{"hello": "world"}',
},
]
result = encode_webhooks_to_base64(webhooks)
assert result is not None
# Also verify round-trip: dicts and WebhookCreate models should produce the same base64
result_from_models = encode_webhooks_to_base64(
[
WebhookCreate(
event_types=['ACTOR.RUN.CREATED'],
condition=WebhookCondition(),
request_url='https://example.com/run-created',
),
WebhookCreate(
event_types=['ACTOR.RUN.SUCCEEDED'],
condition=WebhookCondition(),
request_url='https://example.com/run-succeeded',
payload_template='{"hello": "world"}',
),
]
)
assert result == result_from_models
@pytest.mark.parametrize(
'exc',
[
InvalidResponseBodyError(impit.Response(status_code=200)),
impit.HTTPError('generic http error'),
impit.NetworkError('network error'),
impit.TimeoutException('timeout'),
impit.RemoteProtocolError('remote protocol error'),
impit.ReadError('read error'),
impit.ConnectError('connect error'),
impit.WriteError('write error'),
impit.DecodingError('decoding error'),
],
)
def test__is_retryable_error(exc: Exception) -> None:
assert is_retryable_error(exc) is True
@pytest.mark.parametrize(
'exc',
[
Exception('generic exception'),
ValueError('value error'),
RuntimeError('runtime error'),
],
)
def test__is_not_retryable_error(exc: Exception) -> None:
assert is_retryable_error(exc) is False
@pytest.mark.parametrize(
('status_code', 'error_type', 'should_suppress'),
[
pytest.param(HTTPStatus.NOT_FOUND, 'record-not-found', True, id='404 record-not-found'),
pytest.param(HTTPStatus.NOT_FOUND, 'record-or-token-not-found', True, id='404 token-not-found'),
pytest.param(HTTPStatus.NOT_FOUND, 'some-other-error', True, id='404 other error type'),
pytest.param(HTTPStatus.BAD_REQUEST, 'record-not-found', False, id='400 record-not-found'),
pytest.param(HTTPStatus.INTERNAL_SERVER_ERROR, 'record-not-found', False, id='500 record-not-found'),
],
)
def test_catch_not_found_or_throw(status_code: HTTPStatus, error_type: str, *, should_suppress: bool) -> None:
"""Test that catch_not_found_or_throw suppresses 404 errors correctly."""
mock_response = Mock()
mock_response.status_code = status_code
mock_response.json.return_value = {'error': {'type': error_type, 'message': 'msg'}}
mock_response.text = f'{{"error":{{"type":"{error_type}"}}}}'
error = ApifyApiError(mock_response, 1)
if should_suppress:
catch_not_found_or_throw(error)
else:
with pytest.raises(ApifyApiError):
catch_not_found_or_throw(error)
@pytest.mark.parametrize(
('input_dict', 'expected'),
[
pytest.param({'a': 1, 'b': None, 'c': 3}, {'a': 1, 'c': 3}, id='Simple case'),
pytest.param({'a': {'b': None, 'c': 2}, 'd': None}, {'a': {'c': 2}}, id='Nested dictionaries'),
pytest.param({'a': {'b': {'c': None, 'd': 4}}}, {'a': {'b': {'d': 4}}}, id='Deep nesting'),
pytest.param({'a': None, 'b': None}, {}, id='Empty dict after filtering'),
pytest.param({'a': {'b': None}, 'c': 3}, {'c': 3}, id='Remove empty dicts'),
pytest.param({'a': 0, 'b': '', 'c': False}, {'a': 0, 'b': '', 'c': False}, id='Keep falsy non-None values'),
],
)
def test__clean_json_payload(input_dict: dict, expected: dict) -> None:
"""Test cleaning None values and empty dicts from API request payloads."""
assert ResourceClientBase._clean_json_payload(input_dict) == expected
def test_encode_key_value_store_record_value_dict() -> None:
"""Test that dictionaries are encoded as JSON."""
value, content_type = encode_key_value_store_record_value({'key': 'value'})
assert value == b'{"key": "value"}'
assert content_type == 'application/json; charset=utf-8'
@pytest.mark.parametrize(
('input_value', 'input_content_type', 'expected_value', 'expected_content_type'),
[
pytest.param('hello', None, 'hello', 'text/plain; charset=utf-8', id='String is text/plain'),
pytest.param(b'binary data', None, b'binary data', 'application/octet-stream', id='Bytes is octet-stream'),
pytest.param('hello', 'text/html', 'hello', 'text/html', id='Custom content type is preserved'),
],
)
def test_encode_key_value_store_record_value(
input_value: str | bytes, input_content_type: str | None, expected_value: str | bytes, expected_content_type: str
) -> None:
"""Test encoding of key-value store record values."""
if input_content_type is not None:
value, content_type = encode_key_value_store_record_value(input_value, content_type=input_content_type)
else:
value, content_type = encode_key_value_store_record_value(input_value)
assert value == expected_value
assert content_type == expected_content_type
def test_encode_key_value_store_record_value_bytesio() -> None:
"""Test that BytesIO is read into bytes and encoded as octet-stream."""
buffer = io.BytesIO(b'buffer data')
value, content_type = encode_key_value_store_record_value(buffer)
assert value == b'buffer data'
assert content_type == 'application/octet-stream'
def test_encode_key_value_store_record_value_stringio() -> None:
"""Test that StringIO is read into text and encoded as text/plain."""
buffer = io.StringIO('buffer data')
value, content_type = encode_key_value_store_record_value(buffer)
assert value == 'buffer data'
assert content_type == 'text/plain; charset=utf-8'
def test_encode_key_value_store_record_value_duck_typed_file_like() -> None:
"""Test that a duck-typed file-like value (a callable `read`, not an `io.IOBase`) is read into bytes."""
class Reader:
def read(self) -> bytes:
return b'buffer data'
value, content_type = encode_key_value_store_record_value(Reader())
assert value == b'buffer data'
assert content_type == 'application/octet-stream'
def test_encode_key_value_store_record_value_async_file_like_raises() -> None:
"""Test that an async file-like value is rejected instead of storing the repr of an un-awaited coroutine."""
class AsyncReader:
async def read(self) -> bytes:
return b'buffer data'
with pytest.raises(TypeError, match='Async file-like objects are not supported'):
encode_key_value_store_record_value(AsyncReader())
def test_encode_key_value_store_record_value_non_bytes_read_raises() -> None:
"""Test that a `read` returning neither bytes nor str is rejected instead of being JSON-serialized."""
class EmptyNonBlockingReader:
def read(self) -> None:
"""Mimic a non-blocking raw stream with no data available."""
with pytest.raises(TypeError, match='returned NoneType, expected bytes or str'):
encode_key_value_store_record_value(EmptyNonBlockingReader())
@pytest.mark.parametrize(
('value', 'expected_type_name'),
[
pytest.param('already gzipped, honest', 'str', id='string'),
pytest.param({'a': 1}, 'dict', id='json-serializable object'),
pytest.param(io.StringIO('buffer data'), 'str', id='text-mode file-like'),
],
)
def test_encode_key_value_store_record_value_declared_compression_of_non_bytes_raises(
value: Any, expected_type_name: str
) -> None:
"""A value that cannot be compressed is rejected when the content encoding declares a compression."""
with pytest.raises(TypeError, match=f'Cannot upload a {expected_type_name} value'):
encode_key_value_store_record_value(value, content_encoding='gzip')
@pytest.mark.parametrize(
('value', 'content_encoding', 'expected_value'),
[
pytest.param(_GZIPPED_DATA, 'gzip', _GZIPPED_DATA, id='bytes'),
pytest.param(bytearray(_GZIPPED_DATA), 'gzip', bytearray(_GZIPPED_DATA), id='bytearray'),
pytest.param(io.BytesIO(_GZIPPED_DATA), 'GZip', _GZIPPED_DATA, id='binary file-like, mixed-case encoding'),
pytest.param('buffer data', 'identity', 'buffer data', id='string under identity'),
pytest.param({'a': 1}, ' Identity ', b'{"a": 1}', id='json-serializable object under padded identity'),
],
)
def test_encode_key_value_store_record_value_accepts_declared_encoding(
value: Any, content_encoding: str, expected_value: bytes | bytearray | str
) -> None:
"""A bytes-like value passes the compression guard, and `identity` declares no compression at all."""
encoded, _content_type = encode_key_value_store_record_value(value, content_encoding=content_encoding)
assert encoded == expected_value
def test_encode_key_value_store_record_value_non_encodable_with_explicit_content_type_raises() -> None:
"""Test that a non-bytes-like value with a non-JSON content type is rejected before it reaches the transport."""
with pytest.raises(TypeError, match="Cannot encode a dict value as 'image/png'"):
encode_key_value_store_record_value({'a': 1}, content_type='image/png')
@pytest.mark.parametrize(
('content_type', 'expected'),
[
pytest.param(None, True, id='missing'),
pytest.param('', True, id='empty'),
pytest.param('application/json', True, id='json'),
pytest.param('text/plain; charset=utf-8', True, id='text with parameters'),
pytest.param('application/octet-stream', True, id='unknown binary'),
pytest.param('application/vnd.api+json', True, id='structured json suffix'),
pytest.param('image/svg+xml', True, id='svg under a compressed prefix'),
pytest.param('IMAGE/SVG+XML; charset=utf-8', True, id='svg uppercase with parameters'),
pytest.param('image/bmp', True, id='raw bitmap under a compressed prefix'),
pytest.param('image/tiff', True, id='tiff under a compressed prefix'),
pytest.param('audio/wav', True, id='raw audio under a compressed prefix'),
pytest.param('audio/L24', True, id='raw pcm audio in its registered casing'),
pytest.param('audio/midi', True, id='midi event data under a compressed prefix'),
pytest.param('image/png', False, id='image prefix'),
pytest.param('video/mp4', False, id='video prefix'),
pytest.param('audio/mpeg', False, id='audio prefix'),
pytest.param('application/zip', False, id='archive'),
pytest.param('application/x-gzip', False, id='gzip archive'),
pytest.param('application/x-zip-compressed', False, id='windows zip archive'),
pytest.param('application/epub+zip', False, id='zip container with a suffix'),
pytest.param(
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
False,
id='office open xml document',
),
pytest.param('font/woff2', False, id='web font'),
pytest.param(' Image/PNG ', False, id='surrounding whitespace and mixed case'),
],
)
def test_is_compressible_content_type(content_type: str | None, *, expected: bool) -> None:
"""Already-compressed media types are reported as not worth compressing, everything else as compressible."""
assert is_compressible_content_type(content_type) is expected
def test_response_to_dict() -> None:
"""Test parsing response as dictionary."""
mock_response = Mock()
mock_response.json.return_value = {'key': 'value'}
assert response_to_dict(mock_response) == {'key': 'value'}
@pytest.mark.parametrize(
'json_return_value',
[
pytest.param(['list', 'response'], id='List response'),
pytest.param('string', id='String response'),
],
)
def test_response_to_dict_raises_for_non_dict(json_return_value: object) -> None:
"""Test that response_to_dict raises for non-dict responses."""
mock_response = Mock()
mock_response.json.return_value = json_return_value
with pytest.raises(ValueError, match='The response is not a dictionary'):
response_to_dict(mock_response)
def test_response_to_list() -> None:
"""Test parsing response as list."""
mock_response = Mock()
mock_response.json.return_value = ['item1', 'item2']
assert response_to_list(mock_response) == ['item1', 'item2']
def test_response_to_list_wraps_dict_in_list() -> None:
"""Test that response_to_list wraps a dict response in a list."""
mock_response = Mock()
mock_response.json.return_value = {'dict': 'response'}
assert response_to_list(mock_response) == [{'dict': 'response'}]
def test_response_to_list_raises_for_non_list() -> None:
"""Test that response_to_list raises for non-list, non-dict responses."""
mock_response = Mock()
mock_response.json.return_value = 'string'
with pytest.raises(ValueError, match='The response is not a list'):
response_to_list(mock_response)
@pytest.mark.parametrize(
('input_value', 'expected'),
[
pytest.param(0, '0', id='Zero'),
pytest.param(1, '1', id='One'),
pytest.param(9, '9', id='Last digit'),
pytest.param(10, 'a', id='First lowercase letter'),
pytest.param(35, 'z', id='Last lowercase letter'),
pytest.param(36, 'A', id='First uppercase letter'),
pytest.param(61, 'Z', id='Last uppercase letter'),
pytest.param(62, '10', id='First two-char encoding'),
pytest.param(100, '1C', id='100'),
pytest.param(123456, 'w7e', id='Large number'),
],
)
def test_encode_base62(input_value: int, expected: str) -> None:
"""Test base62 encoding."""
assert encode_base62(input_value) == expected
def test_create_hmac_signature() -> None:
"""Test HMAC signature creation."""
# Test with known values
signature = create_hmac_signature('secret_key', 'test_message')
assert isinstance(signature, str)
assert len(signature) > 0
# Same inputs should produce same output
signature2 = create_hmac_signature('secret_key', 'test_message')
assert signature == signature2
# Different inputs should produce different output
signature3 = create_hmac_signature('different_key', 'test_message')
assert signature != signature3
signature4 = create_hmac_signature('secret_key', 'different_message')
assert signature != signature4
def test_create_storage_signature() -> None:
"""Test storage signature creation."""
# Non-expiring signature
signature = create_storage_content_signature('resource_123', 'secret_key')
assert isinstance(signature, str)
assert len(signature) > 0
# Expiring signature
signature_expiring = create_storage_content_signature(
'resource_123',
'secret_key',
expires_in=timedelta(seconds=60),
)
assert isinstance(signature_expiring, str)
assert len(signature_expiring) > 0
assert signature != signature_expiring # Different because of expiration
# Different resource IDs produce different signatures
signature2 = create_storage_content_signature('resource_456', 'secret_key')
assert signature != signature2
# Same inputs should produce same output (for non-expiring)
signature3 = create_storage_content_signature('resource_123', 'secret_key')
assert signature == signature3
# Test with version parameter
signature_v1 = create_storage_content_signature('resource_123', 'secret_key', version=1)
assert signature != signature_v1