Debian Codegraph @

tests/conftest.py

raw
1 # SPDX-License-Identifier: MIT
2
3 from __future__ import annotations
4
5 import contextlib
6 import contextvars
7 import importlib.metadata
8 import os
9 import os.path
10 import shutil
11 import stat
12 import sys
13 import sysconfig
14 import tempfile
15
16 from collections.abc import Callable, Generator
17 from functools import partial, update_wrapper
18 from pathlib import Path
19 from typing import Protocol
20
21 import pytest
22
23 import build.env
24
25 from build._compat import tomllib
26
27
28 class SubTests(Protocol):
29 def test(self, msg: str | None = ..., **kwargs: object) -> contextlib.AbstractContextManager[None]: ...
30
31
32 def pytest_addoption(parser: pytest.Parser) -> None:
33 os.environ['PYTHONWARNINGS'] = 'ignore:DEPRECATION::pip._internal.cli.base_command' # for when not run within tox
34 os.environ['PIP_DISABLE_PIP_VERSION_CHECK'] = '1' # do not pollute stderr with upgrade advisory
35 parser.addoption('--run-integration', action='store_true', help='run the integration tests')
36 parser.addoption('--only-integration', action='store_true', help='only run the integration tests')
37
38
39 PYPY3_WIN_VENV_BAD = (
40 sys.implementation.name == 'pypy' and sys.implementation.version < (7, 3, 9) and sys.platform.startswith('win')
41 )
42 PYPY3_WIN_M = 'https://foss.heptapod.net/pypy/pypy/-/issues/3323 and https://foss.heptapod.net/pypy/pypy/-/issues/3321'
43
44
45 def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
46 skip_int = pytest.mark.skip(reason='integration tests not run (no --run-integration flag)')
47 skip_other = pytest.mark.skip(reason='only integration tests are run (got --only-integration flag)')
48
49 if config.getoption('--run-integration') and config.getoption('--only-integration'): # pragma: no cover
50 msg = "--run-integration and --only-integration can't be used together, choose one"
51 raise pytest.UsageError(msg)
52
53 if len(items) == 1: # do not require flags if called directly
54 return
55 for item in items:
56 is_integration_file = is_integration(item)
57 if PYPY3_WIN_VENV_BAD and item.get_closest_marker('pypy3323bug') and os.environ.get('PYPY3323BUG', None):
58 item.add_marker(pytest.mark.xfail(reason=PYPY3_WIN_M, strict=False))
59 if (
60 PYPY3_WIN_VENV_BAD
61 and item.get_closest_marker('isolated')
62 and _xfail_isolated_strict(item, is_integration_file=is_integration_file)
63 ):
64 item.add_marker(pytest.mark.xfail(reason=PYPY3_WIN_M, strict=True))
65 if is_integration_file: # pragma: no cover
66 if not config.getoption('--run-integration') and not config.getoption('--only-integration'):
67 item.add_marker(skip_int)
68 elif config.getoption('--only-integration'): # pragma: no cover
69 item.add_marker(skip_other)
70 # run integration tests after unit tests
71 items.sort(key=lambda i: 1 if is_integration(i) else 0)
72
73
74 def _xfail_isolated_strict(item: pytest.Item, *, is_integration_file: bool) -> bool:
75 if isinstance(item, pytest.Function) and hasattr(item, 'callspec'):
76 args = item.callspec.params.get('args', [])
77 if isinstance(args, (list, tuple)) and '--no-isolation' not in args:
78 return True
79 is_test_build = is_integration_file and isinstance(item, pytest.Function) and item.originalname == 'test_build'
80 return not is_test_build
81
82
83 def is_integration(item: pytest.Item) -> bool:
84 # item.location is typically a (path, lineno) tuple; cast to str for typing
85 return os.path.basename(str(item.location[0])) == 'test_integration.py'
86
87
88 def pytest_runtest_call(item: pytest.Item) -> None:
89 if item.get_closest_marker('contextvars'):
90 if isinstance(item, pytest.Function):
91 wrapped_function = partial(contextvars.copy_context().run, item.obj)
92 item.obj = update_wrapper(wrapped_function, item.obj)
93 else:
94 msg = 'cannot rewrap non-function item'
95 raise RuntimeError(msg)
96
97
98 @pytest.fixture
99 def local_pip(monkeypatch: pytest.MonkeyPatch) -> None:
100 monkeypatch.setattr(build.env._PipBackend, '_has_valid_outer_pip', None)
101
102
103 @pytest.fixture(autouse=True)
104 def avoid_constraints(monkeypatch: pytest.MonkeyPatch) -> None:
105 monkeypatch.delenv('PIP_CONSTRAINT', raising=False)
106 monkeypatch.delenv('PIP_KEYRING_PROVIDER', raising=False)
107 monkeypatch.delenv('UV_CONSTRAINT', raising=False)
108 monkeypatch.delenv('UV_KEYRING_PROVIDER', raising=False)
109
110
111 @pytest.fixture(autouse=True)
112 def _clear_keyring_cache() -> Generator[None, None, None]:
113 build.env._has_keyring_cli.cache_clear()
114 yield
115 build.env._has_keyring_cli.cache_clear()
116
117
118 @pytest.fixture(autouse=True, params=[False])
119 def has_virtualenv(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> None:
120 if request.param is not None:
121 monkeypatch.setattr(build.env._PipBackend, '_has_virtualenv', request.param)
122
123
124 @pytest.fixture(scope='session', autouse=True)
125 def ensure_syconfig_vars_created() -> None:
126 # the config vars are globally cached and may use get_path, make sure they are created
127 sysconfig.get_config_vars()
128
129
130 @pytest.fixture
131 def packages_path() -> str:
132 return os.path.realpath(os.path.join(__file__, '..', 'packages'))
133
134
135 def is_setuptools(package_path: Path) -> bool:
136 if package_path.joinpath('setup.py').is_file():
137 return True
138 pyproject = package_path / 'pyproject.toml'
139 try:
140 with pyproject.open('rb') as f:
141 pp = tomllib.load(f)
142 except (FileNotFoundError, ValueError):
143 return True
144 return 'setuptools' in pp.get('build-system', {}).get('build-backend', 'setuptools')
145
146
147 def generate_package_path_fixture(package_name: str) -> Callable[[str, Path], str]:
148 @pytest.fixture
149 def fixture(packages_path: str, tmp_path: Path) -> str:
150 package_path = Path(packages_path) / package_name
151 if not is_setuptools(package_path):
152 return str(package_path)
153
154 new_path = tmp_path / package_name
155 shutil.copytree(package_path, new_path)
156 return str(new_path)
157
158 return fixture
159
160
161 # Generate path fixtures dynamically.
162 package_names = os.listdir(os.path.join(os.path.dirname(__file__), 'packages'))
163 for package_name in package_names:
164 normalized_name = package_name.replace('-', '_')
165 fixture_name = f'package_{normalized_name}'
166 globals()[fixture_name] = generate_package_path_fixture(package_name)
167
168
169 @pytest.fixture
170 def test_no_permission(packages_path: str) -> Generator[str, None, None]:
171 path = os.path.join(packages_path, 'test-no-permission')
172 file = os.path.join(path, 'pyproject.toml')
173 orig_stat = os.stat(file).st_mode
174
175 os.chmod(file, ~stat.S_IRWXU)
176
177 yield os.path.join(packages_path, 'test-no-permission')
178
179 os.chmod(file, orig_stat)
180
181
182 @pytest.fixture
183 def tmp_dir() -> Generator[str, None, None]:
184 path = tempfile.mkdtemp(prefix='python-build-test-')
185
186 yield path
187
188 shutil.rmtree(path)
189
190
191 def pytest_report_header() -> str:
192 interesting_packages = [
193 'build',
194 'colorama',
195 'coverage',
196 'filelock',
197 'packaging',
198 'pip',
199 'pyproject_hooks',
200 'setuptools',
201 'tomli',
202 'virtualenv',
203 'wheel',
204 ]
205 valid = []
206 for package in interesting_packages:
207 # Old versions of importlib_metadata made this FileNotFoundError
208 with contextlib.suppress(ModuleNotFoundError, FileNotFoundError):
209 valid.append(f'{package}=={importlib.metadata.version(package)}')
210 reqs = ' '.join(valid)
211 return f'installed packages of interest: {reqs}'
212
213
214 @pytest.fixture
215 def subtests(request: pytest.FixtureRequest) -> SubTests:
216 try:
217 existing: SubTests = request.getfixturevalue('subtests')
218 except pytest.FixtureLookupError:
219
220 class Subtests:
221 @staticmethod
222 @contextlib.contextmanager
223 def test(msg: str | None = None, **_kwargs: object) -> Generator[None, None, None]: # noqa: ARG004
224 yield
225
226 return Subtests()
227 return existing