|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +import builtins |
| 4 | +import functools |
3 | 5 | import inspect |
4 | 6 | import sys |
5 | 7 | from pathlib import Path |
| 8 | +from typing import TYPE_CHECKING, Any, Callable |
6 | 9 |
|
7 | 10 | import pytest |
8 | 11 |
|
9 | 12 | import platformdirs |
10 | 13 | from platformdirs.android import Android |
11 | 14 |
|
| 15 | +builtin_import = builtins.__import__ |
| 16 | + |
| 17 | + |
| 18 | +if TYPE_CHECKING: |
| 19 | + from types import ModuleType |
| 20 | + |
12 | 21 |
|
13 | 22 | def test_package_metadata() -> None: |
14 | 23 | assert hasattr(platformdirs, "__version__") |
@@ -80,3 +89,34 @@ def test_android_active( # noqa: PLR0913 |
80 | 89 | assert platformdirs._set_platform_dir_class() is Android # noqa: SLF001 |
81 | 90 | else: |
82 | 91 | assert platformdirs._set_platform_dir_class() is not Android # noqa: SLF001 |
| 92 | + |
| 93 | + |
| 94 | +def _fake_import(name: str, *args: Any, **kwargs: Any) -> ModuleType: # noqa: ANN401 |
| 95 | + if name == "ctypes": |
| 96 | + raise ModuleNotFoundError("No module named %s" % name) |
| 97 | + return builtin_import(name, *args, **kwargs) |
| 98 | + |
| 99 | + |
| 100 | +def mock_import(func: Callable[[], None]) -> Callable[[], None]: |
| 101 | + @functools.wraps(func) |
| 102 | + def wrap() -> None: |
| 103 | + platformdirs_module_items = [item for item in sys.modules.items() if item[0].startswith("platformdirs")] |
| 104 | + try: |
| 105 | + builtins.__import__ = _fake_import |
| 106 | + for name, _ in platformdirs_module_items: |
| 107 | + del sys.modules[name] |
| 108 | + return func() |
| 109 | + finally: |
| 110 | + # restore original modules |
| 111 | + builtins.__import__ = builtin_import |
| 112 | + for name, module in platformdirs_module_items: |
| 113 | + sys.modules[name] = module |
| 114 | + |
| 115 | + return wrap |
| 116 | + |
| 117 | + |
| 118 | +@mock_import |
| 119 | +def test_no_ctypes() -> None: |
| 120 | + import platformdirs # noqa: PLC0415 |
| 121 | + |
| 122 | + assert platformdirs |
0 commit comments