|
3 | 3 | import gzip |
4 | 4 | import io |
5 | 5 | import json |
| 6 | +import sys |
6 | 7 | from base64 import b64decode |
7 | 8 | from datetime import timedelta |
8 | 9 | from http import HTTPStatus |
| 10 | +from types import ModuleType |
9 | 11 | from typing import TYPE_CHECKING, Any |
10 | 12 | from unittest.mock import Mock |
11 | 13 |
|
|
23 | 25 | response_to_list, |
24 | 26 | to_safe_id, |
25 | 27 | ) |
| 28 | +from apify_client._utils.try_import import FailedImport, try_import |
26 | 29 | from apify_client.errors import ApifyApiError, InvalidResponseBodyError |
27 | 30 |
|
28 | 31 | if TYPE_CHECKING: |
|
32 | 35 | _GZIPPED_DATA = gzip.compress(b'buffer data') |
33 | 36 |
|
34 | 37 |
|
| 38 | +def test_try_import_only_handles_the_named_missing_dependency() -> None: |
| 39 | + """Optional-import handling must not hide a broken transitive dependency or module bug.""" |
| 40 | + module_name = 'test_optional_import_module' |
| 41 | + sys.modules[module_name] = ModuleType(module_name) |
| 42 | + try: |
| 43 | + with ( |
| 44 | + pytest.raises(ModuleNotFoundError, match='broken-transitive'), |
| 45 | + try_import(module_name, 'OptionalSymbol', dependency_name='optional-package'), |
| 46 | + ): |
| 47 | + raise ModuleNotFoundError('broken-transitive', name='broken-transitive') |
| 48 | + assert not hasattr(sys.modules[module_name], 'OptionalSymbol') |
| 49 | + finally: |
| 50 | + del sys.modules[module_name] |
| 51 | + |
| 52 | + |
| 53 | +def test_try_import_records_the_named_missing_dependency() -> None: |
| 54 | + """A genuinely missing optional dependency is converted to a failed-import placeholder.""" |
| 55 | + module_name = 'test_missing_optional_import_module' |
| 56 | + sys.modules[module_name] = ModuleType(module_name) |
| 57 | + try: |
| 58 | + with try_import(module_name, 'OptionalSymbol', dependency_name='optional-package') as state: |
| 59 | + raise ModuleNotFoundError("No module named 'optional-package'", name='optional-package') |
| 60 | + assert state.available is False |
| 61 | + assert isinstance(sys.modules[module_name].OptionalSymbol, FailedImport) |
| 62 | + finally: |
| 63 | + del sys.modules[module_name] |
| 64 | + |
| 65 | + |
35 | 66 | def test_to_safe_id() -> None: |
36 | 67 | assert to_safe_id('abc') == 'abc' |
37 | 68 | assert to_safe_id('abc/def') == 'abc~def' |
|
0 commit comments