Debian Codegraph @

tests/test_integration.py

raw
1 # SPDX-License-Identifier: MIT
2
3 from __future__ import annotations
4
5 import contextlib
6 import importlib.util
7 import os
8 import os.path
9 import re
10 import shutil
11 import subprocess
12 import sys
13 import tarfile
14 import urllib.request
15
16 from pathlib import Path
17
18 import filelock
19 import pytest
20 import pytest_mock
21
22 import build.__main__
23
24
25 IS_WINDOWS = sys.platform.startswith('win')
26 IS_PYPY = sys.implementation.name == 'pypy'
27 MISSING_UV = not shutil.which('uv')
28
29
30 INTEGRATION_SOURCES = {
31 'dateutil': ('dateutil/dateutil', '2.9.0'),
32 'pip': ('pypa/pip', '25.0.1'),
33 'Solaar': ('pwr-Solaar/Solaar', '1.1.14'),
34 'flit': ('pypa/flit', '3.12.0'),
35 }
36
37 _SDIST = re.compile('.*.tar.gz')
38 _WHEEL = re.compile('.*.whl')
39 ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
40
41 EXCL = frozenset(['.tox', 'dist', '.git', '__pycache__', '.integration-sources', '.github', 'tests', 'docs'])
42
43
44 def get_project(name: str, tmp_path: Path) -> Path:
45 dest = tmp_path / name
46 if name == 'build':
47 # our own project is available in-source, just ignore development files
48
49 def _ignore_folder(base: str, filenames: list[str]) -> list[str]:
50 ignore = [
51 n for n in filenames if n in EXCL or n.endswith(('_cache', '.egg-info', '.pyc')) or n.startswith('.coverage')
52 ]
53 if os.path.basename(base) == ROOT and 'build' in filenames: # ignore build only at root (our module is build too)
54 ignore.append('build')
55 return ignore
56
57 shutil.copytree(ROOT, str(dest), ignore=_ignore_folder)
58 return dest
59
60 # for other projects download from github and cache it
61 tar_store = os.path.join(ROOT, '.integration-sources')
62 # Checking with exists is not parallel safe so just ignore,
63 # if the creation failed we will have another failure soon
64 # that will notify the user.
65 with contextlib.suppress(OSError):
66 os.makedirs(tar_store)
67
68 github_org_repo, version = INTEGRATION_SOURCES[name]
69 tar_filename = f'{name}-{version}.tar.gz'
70 tarball = os.path.join(tar_store, tar_filename)
71 with filelock.FileLock(os.path.join(tar_store, f'{tar_filename}.lock')):
72 if not os.path.exists(tarball):
73 url = f'https://github.com/{github_org_repo}/archive/{version}.tar.gz'
74 with urllib.request.urlopen(url) as request, open(tarball, 'wb') as file_handler:
75 shutil.copyfileobj(request, file_handler)
76 with tarfile.open(tarball, 'r:gz') as tar_handler:
77 tar_handler.extractall(str(dest))
78 return dest / f'{name}-{version}'
79
80
81 @pytest.mark.network
82 @pytest.mark.parametrize(
83 'call',
84 [
85 None, # via code
86 [sys.executable, '-m', 'build'], # module
87 ['pyproject-build'], # entrypoint
88 ],
89 ids=['code', 'module', 'entrypoint'],
90 )
91 @pytest.mark.parametrize(
92 'args',
93 [
94 [],
95 pytest.param(
96 ['--installer', 'uv'],
97 marks=pytest.mark.skipif(MISSING_UV, reason='uv executable not found'),
98 ),
99 ['-x', '--no-isolation'],
100 ],
101 ids=['isolated_pip', 'isolated_uv', 'no_isolation'],
102 )
103 @pytest.mark.parametrize(
104 'project',
105 [
106 'build',
107 'pip',
108 'dateutil',
109 'Solaar',
110 'flit',
111 ],
112 )
113 @pytest.mark.isolated
114 def test_build(
115 request: pytest.FixtureRequest, # noqa: ARG001
116 monkeypatch: pytest.MonkeyPatch,
117 project: str,
118 args: list[str],
119 call: list[str] | None,
120 tmp_path: Path,
121 ) -> None:
122 if args == ['--installer', 'uv'] and IS_WINDOWS and IS_PYPY:
123 pytest.xfail('uv cannot find PyPy executable')
124 if project in {'build', 'flit'} and '--no-isolation' in args:
125 pytest.xfail(f"can't build {project} without isolation due to missing dependencies")
126 if project == 'Solaar' and IS_WINDOWS and IS_PYPY:
127 pytest.xfail('Solaar fails building wheels via sdists on Windows on PyPy 3')
128
129 monkeypatch.chdir(tmp_path)
130 monkeypatch.setenv('SETUPTOOLS_SCM_PRETEND_VERSION', '0+dummy') # for the projects that use setuptools_scm
131
132 if call and call[0] == 'pyproject-build':
133 exe_name = f'pyproject-build{".exe" if sys.platform.startswith("win") else ""}'
134 exe = os.path.join(os.path.dirname(sys.executable), exe_name)
135 if os.path.exists(exe):
136 call[0] = exe
137 else:
138 pytest.skip('Running via PYTHONPATH, so the pyproject-build entrypoint is not available')
139 path = get_project(project, tmp_path)
140 pkgs = tmp_path / 'pkgs'
141 args = [str(path), '-o', str(pkgs), *args]
142
143 if call is None:
144 build.__main__.main(args)
145 else:
146 subprocess.check_call(call + args)
147
148 pkg_names = os.listdir(str(pkgs))
149 assert list(filter(_SDIST.match, pkg_names))
150 assert list(filter(_WHEEL.match, pkg_names))
151
152
153 def test_isolation(tmp_dir: str, package_test_flit: str, mocker: pytest_mock.MockerFixture) -> None:
154 if importlib.util.find_spec('flit_core'):
155 pytest.xfail('flit_core is available -- we want it missing!') # pragma: no cover
156
157 error = mocker.patch('build.__main__._error')
158
159 build.__main__.main([package_test_flit, '-o', tmp_dir, '--no-isolation'])
160 error.assert_called_with("Backend 'flit_core.buildapi' is not available.")