|
| 1 | +"""Pytest configuration for optional dependency heavy modules.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import importlib |
| 6 | +import importlib.util |
| 7 | +from functools import lru_cache |
| 8 | +from pathlib import Path |
| 9 | +from typing import Sequence |
| 10 | + |
| 11 | +from _pytest.config import Config |
| 12 | + |
| 13 | +REPO_ROOT = Path(__file__).resolve().parent |
| 14 | + |
| 15 | +_OPTIONAL_PATHS: Sequence[tuple[frozenset[str], Path]] = ( |
| 16 | + (frozenset({"cv2"}), REPO_ROOT / "computer_vision"), |
| 17 | + (frozenset({"cv2"}), REPO_ROOT / "data_compression" / "peak_signal_to_noise_ratio.py"), |
| 18 | + (frozenset({"cv2"}), REPO_ROOT / "digital_image_processing"), |
| 19 | + (frozenset({"tensorflow"}), REPO_ROOT / "computer_vision" / "cnn_classification.py"), |
| 20 | + (frozenset({"tensorflow"}), REPO_ROOT / "dynamic_programming" / "k_means_clustering_tensorflow.py"), |
| 21 | + (frozenset({"tensorflow", "keras"}), REPO_ROOT / "machine_learning" / "lstm" / "lstm_prediction.py"), |
| 22 | + (frozenset({"tensorflow"}), REPO_ROOT / "neural_network" / "input_data.py"), |
| 23 | + (frozenset({"qiskit"}), REPO_ROOT / "quantum" / "q_fourier_transform.py"), |
| 24 | +) |
| 25 | + |
| 26 | +_ALWAYS_SKIP: Sequence[Path] = (REPO_ROOT / "scripts" / "validate_filenames.py",) |
| 27 | + |
| 28 | + |
| 29 | +@lru_cache |
| 30 | +def _modules_unavailable(modules: frozenset[str]) -> bool: |
| 31 | + for module in modules: |
| 32 | + spec = importlib.util.find_spec(module) |
| 33 | + if spec is None: |
| 34 | + return True |
| 35 | + try: |
| 36 | + importlib.import_module(module) |
| 37 | + except Exception: # pragma: no cover - handled by skipping collection |
| 38 | + return True |
| 39 | + return False |
| 40 | + |
| 41 | + |
| 42 | +def _is_within(path: Path, location: Path) -> bool: |
| 43 | + try: |
| 44 | + path.relative_to(location) |
| 45 | + except ValueError: |
| 46 | + return False |
| 47 | + return True |
| 48 | + |
| 49 | + |
| 50 | +def pytest_ignore_collect(collection_path: Path, config: Config) -> bool: # type: ignore[override] |
| 51 | + candidate = Path(collection_path) |
| 52 | + if not candidate.is_absolute(): |
| 53 | + candidate = REPO_ROOT / candidate |
| 54 | + |
| 55 | + if any(candidate == location or _is_within(candidate, location) for location in _ALWAYS_SKIP): |
| 56 | + return True |
| 57 | + |
| 58 | + for modules, location in _OPTIONAL_PATHS: |
| 59 | + if modules and not _modules_unavailable(modules): |
| 60 | + continue |
| 61 | + |
| 62 | + if location.is_dir() and _is_within(candidate, location): |
| 63 | + return True |
| 64 | + if not location.is_dir() and candidate == location: |
| 65 | + return True |
| 66 | + |
| 67 | + return False |
0 commit comments