| 1 |
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html |
| 2 |
# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE |
| 3 |
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import contextlib |
| 8 |
import os |
| 9 |
import sys |
| 10 |
from collections.abc import Iterator, Sequence |
| 11 |
from pathlib import Path |
| 12 |
|
| 13 |
from astroid import builder |
| 14 |
from astroid.manager import AstroidManager |
| 15 |
from astroid.nodes.scoped_nodes import Module |
| 16 |
|
| 17 |
DATA_DIR = Path("testdata") / "python3" |
| 18 |
RESOURCE_PATH = Path(__file__).parent / DATA_DIR / "data" |
| 19 |
|
| 20 |
|
| 21 |
def find(name: str) -> str: |
| 22 |
return os.path.normpath(os.path.join(os.path.dirname(__file__), DATA_DIR, name)) |
| 23 |
|
| 24 |
|
| 25 |
def build_file(path: str, modname: str | None = None) -> Module: |
| 26 |
return builder.AstroidBuilder(AstroidManager()).file_build(find(path), modname) |
| 27 |
|
| 28 |
|
| 29 |
class SysPathSetup: |
| 30 |
def setUp(self) -> None: |
| 31 |
sys.path.insert(0, find("")) |
| 32 |
|
| 33 |
def tearDown(self) -> None: |
| 34 |
del sys.path[0] |
| 35 |
datadir = find("") |
| 36 |
for key in list(sys.path_importer_cache): |
| 37 |
if key.startswith(datadir): |
| 38 |
del sys.path_importer_cache[key] |
| 39 |
|
| 40 |
|
| 41 |
def _augment_sys_path(additional_paths: Sequence[str]) -> list[str]: |
| 42 |
original = list(sys.path) |
| 43 |
changes = [] |
| 44 |
seen = set() |
| 45 |
for additional_path in additional_paths: |
| 46 |
if additional_path not in seen: |
| 47 |
changes.append(additional_path) |
| 48 |
seen.add(additional_path) |
| 49 |
|
| 50 |
sys.path[:] = changes + sys.path |
| 51 |
return original |
| 52 |
|
| 53 |
|
| 54 |
@contextlib.contextmanager |
| 55 |
def augmented_sys_path(additional_paths: Sequence[str]) -> Iterator[None]: |
| 56 |
"""Augment 'sys.path' by adding entries from additional_paths.""" |
| 57 |
original = _augment_sys_path(additional_paths) |
| 58 |
try: |
| 59 |
yield |
| 60 |
finally: |
| 61 |
sys.path[:] = original |