| 1 |
# SPDX-License-Identifier: MIT |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import contextlib |
| 6 |
import hashlib |
| 7 |
import io |
| 8 |
import json |
| 9 |
import os |
| 10 |
import pathlib |
| 11 |
import re |
| 12 |
import subprocess |
| 13 |
import sys |
| 14 |
import tarfile |
| 15 |
import unittest.mock |
| 16 |
import venv |
| 17 |
import zipfile |
| 18 |
|
| 19 |
from collections.abc import Callable, Iterator, Mapping, Sequence |
| 20 |
from typing import TYPE_CHECKING, Protocol, TypedDict |
| 21 |
|
| 22 |
import pytest |
| 23 |
import pytest_mock |
| 24 |
|
| 25 |
import build |
| 26 |
import build.__main__ |
| 27 |
import build._ctx |
| 28 |
import build.env |
| 29 |
|
| 30 |
from build._compat import importlib as _importlib |
| 31 |
|
| 32 |
|
| 33 |
if TYPE_CHECKING: |
| 34 |
from conftest import SubTests |
| 35 |
|
| 36 |
|
| 37 |
class CapturedRunner(Protocol): |
| 38 |
def __call__(self, cmd: Sequence[str], cwd: str | None = ..., extra_environ: Mapping[str, str] | None = ...) -> None: ... |
| 39 |
|
| 40 |
|
| 41 |
pytestmark = pytest.mark.contextvars |
| 42 |
|
| 43 |
|
| 44 |
build_open_owner = 'builtins' |
| 45 |
|
| 46 |
cwd = os.getcwd() |
| 47 |
out = os.path.join(cwd, 'dist') |
| 48 |
|
| 49 |
ANSI_STRIP = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') |
| 50 |
|
| 51 |
JSONValue = str | int | list['JSONValue'] | dict[str, 'JSONValue'] |
| 52 |
|
| 53 |
|
| 54 |
class BuildKwargs(TypedDict): |
| 55 |
distributions: list[str] |
| 56 |
config_settings: dict[str, JSONValue] |
| 57 |
isolation: bool |
| 58 |
skip_dependency_check: bool |
| 59 |
dependency_constraints_txt: str | None |
| 60 |
installer: str |
| 61 |
env_dir: str | None |
| 62 |
|
| 63 |
|
| 64 |
def make_kwargs( |
| 65 |
*, |
| 66 |
distributions: list[str] | None = None, |
| 67 |
config_settings: dict[str, JSONValue] | None = None, |
| 68 |
isolation: bool = True, |
| 69 |
skip_dependency_check: bool = False, |
| 70 |
dependency_constraints_txt: str | None = None, |
| 71 |
installer: str = 'pip', |
| 72 |
env_dir: str | None = None, |
| 73 |
) -> BuildKwargs: |
| 74 |
return { |
| 75 |
'distributions': distributions if distributions is not None else ['wheel'], |
| 76 |
'config_settings': config_settings if config_settings is not None else {}, |
| 77 |
'isolation': isolation, |
| 78 |
'skip_dependency_check': skip_dependency_check, |
| 79 |
'dependency_constraints_txt': dependency_constraints_txt, |
| 80 |
'installer': installer, |
| 81 |
'env_dir': env_dir, |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
@pytest.mark.parametrize( |
| 86 |
('cli_args', 'build_args', 'build_kwargs', 'hook'), |
| 87 |
[ |
| 88 |
pytest.param([], (cwd, out), make_kwargs(), 'build_package_via_sdist', id='defaults'), |
| 89 |
pytest.param(['-n'], (cwd, out), make_kwargs(isolation=False), 'build_package_via_sdist', id='no-isolation'), |
| 90 |
pytest.param(['-s'], (cwd, out), make_kwargs(distributions=['sdist']), 'build_package', id='sdist'), |
| 91 |
pytest.param(['-w'], (cwd, out), make_kwargs(), 'build_package', id='wheel'), |
| 92 |
pytest.param( |
| 93 |
['-s', '-w'], (cwd, out), make_kwargs(distributions=['sdist', 'wheel']), 'build_package', id='sdist-and-wheel' |
| 94 |
), |
| 95 |
pytest.param( |
| 96 |
['source'], ('source', os.path.join('source', 'dist')), make_kwargs(), 'build_package_via_sdist', id='srcdir' |
| 97 |
), |
| 98 |
pytest.param(['-o', 'out'], (cwd, 'out'), make_kwargs(), 'build_package_via_sdist', id='outdir'), |
| 99 |
pytest.param(['source', '-o', 'out'], ('source', 'out'), make_kwargs(), 'build_package_via_sdist', id='srcdir-outdir'), |
| 100 |
pytest.param( |
| 101 |
['-x'], (cwd, out), make_kwargs(skip_dependency_check=True), 'build_package_via_sdist', id='skip-dependency-check' |
| 102 |
), |
| 103 |
pytest.param( |
| 104 |
['--installer', 'uv'], (cwd, out), make_kwargs(installer='uv'), 'build_package_via_sdist', id='installer' |
| 105 |
), |
| 106 |
pytest.param( |
| 107 |
['-C--flag1=', '-C--flag2='], |
| 108 |
(cwd, out), |
| 109 |
make_kwargs(config_settings={'--flag1': '', '--flag2': ''}), |
| 110 |
'build_package_via_sdist', |
| 111 |
id='config-empty-values', |
| 112 |
), |
| 113 |
pytest.param( |
| 114 |
['-C--flag=value'], |
| 115 |
(cwd, out), |
| 116 |
make_kwargs(config_settings={'--flag': 'value'}), |
| 117 |
'build_package_via_sdist', |
| 118 |
id='config-single', |
| 119 |
), |
| 120 |
pytest.param( |
| 121 |
['-C--flag1=value', '-C--flag2=other_value', '-C--flag2=extra_value'], |
| 122 |
(cwd, out), |
| 123 |
make_kwargs(config_settings={'--flag1': 'value', '--flag2': ['other_value', 'extra_value']}), |
| 124 |
'build_package_via_sdist', |
| 125 |
id='config-repeated', |
| 126 |
), |
| 127 |
pytest.param( |
| 128 |
['--config-json={"one": 1, "two": [2, 3], "three": {"in": "out"}}'], |
| 129 |
(cwd, out), |
| 130 |
make_kwargs(config_settings={'one': 1, 'two': [2, 3], 'three': {'in': 'out'}}), |
| 131 |
'build_package_via_sdist', |
| 132 |
id='config-json', |
| 133 |
), |
| 134 |
pytest.param( |
| 135 |
['--config-json', '{"outer": {"inner": {"deeper": 2}}}'], |
| 136 |
(cwd, out), |
| 137 |
make_kwargs(config_settings={'outer': {'inner': {'deeper': 2}}}), |
| 138 |
'build_package_via_sdist', |
| 139 |
id='config-json-nested', |
| 140 |
), |
| 141 |
pytest.param(['--config-json', '{}'], (cwd, out), make_kwargs(), 'build_package_via_sdist', id='config-json-empty'), |
| 142 |
pytest.param( |
| 143 |
['--dependency-constraints-txt', 'contraints.txt'], |
| 144 |
(cwd, out), |
| 145 |
make_kwargs(dependency_constraints_txt='contraints.txt'), |
| 146 |
'build_package_via_sdist', |
| 147 |
id='dependency-constraints-txt', |
| 148 |
), |
| 149 |
pytest.param( |
| 150 |
['--env-dir', 'build-env'], |
| 151 |
(cwd, out), |
| 152 |
make_kwargs(env_dir='build-env'), |
| 153 |
'build_package_via_sdist', |
| 154 |
id='env-dir', |
| 155 |
), |
| 156 |
], |
| 157 |
) |
| 158 |
def test_parse_args( |
| 159 |
mocker: pytest_mock.MockerFixture, |
| 160 |
cli_args: list[str], |
| 161 |
build_args: tuple[str, str], |
| 162 |
build_kwargs: BuildKwargs, |
| 163 |
hook: str, |
| 164 |
) -> None: |
| 165 |
build_package = mocker.patch('build.__main__.build_package', autospec=True, return_value=['something']) |
| 166 |
build_package_via_sdist = mocker.patch('build.__main__.build_package_via_sdist', autospec=True, return_value=['something']) |
| 167 |
|
| 168 |
build.__main__.main(cli_args) |
| 169 |
|
| 170 |
if hook == 'build_package': |
| 171 |
build_package.assert_called_with(*build_args, **build_kwargs) |
| 172 |
elif hook == 'build_package_via_sdist': |
| 173 |
build_package_via_sdist.assert_called_with(*build_args, **build_kwargs, sdist_extract_dir=None) |
| 174 |
else: # pragma: no cover |
| 175 |
msg = f'Unknown hook {hook}' |
| 176 |
raise ValueError(msg) |
| 177 |
|
| 178 |
|
| 179 |
def test_env_dir_flag_forwarded(mocker: pytest_mock.MockerFixture) -> None: |
| 180 |
build_package_via_sdist = mocker.patch('build.__main__.build_package_via_sdist', return_value=['something']) |
| 181 |
|
| 182 |
build.__main__.main(['--env-dir', 'build-env']) |
| 183 |
|
| 184 |
assert build_package_via_sdist.call_args.kwargs['env_dir'] == 'build-env' |
| 185 |
|
| 186 |
|
| 187 |
def test_env_dir_conflicts_with_no_isolation(capsys: pytest.CaptureFixture[str]) -> None: |
| 188 |
with pytest.raises(SystemExit): |
| 189 |
build.__main__.main(['--env-dir', 'build-env', '--no-isolation']) |
| 190 |
|
| 191 |
assert '--env-dir: not allowed with --no-isolation' in capsys.readouterr().err |
| 192 |
|
| 193 |
|
| 194 |
def test_prog() -> None: |
| 195 |
out = io.StringIO() |
| 196 |
|
| 197 |
with pytest.raises(SystemExit), contextlib.redirect_stdout(out): |
| 198 |
build.__main__.main(['--help'], prog='something') |
| 199 |
|
| 200 |
assert out.getvalue().startswith('usage: something [-h]') |
| 201 |
|
| 202 |
|
| 203 |
def test_version(capsys: pytest.CaptureFixture[str]) -> None: |
| 204 |
with pytest.raises(SystemExit): |
| 205 |
build.__main__.main(['--version']) |
| 206 |
out, _ = capsys.readouterr() |
| 207 |
assert out.startswith(f'build {build.__version__}') |
| 208 |
|
| 209 |
|
| 210 |
@pytest.mark.isolated |
| 211 |
def test_build_isolated(mocker: pytest_mock.MockerFixture, package_test_flit: str) -> None: |
| 212 |
build_cmd = mocker.patch('build.ProjectBuilder.build', return_value='something') |
| 213 |
required_cmd = mocker.patch( |
| 214 |
'build.ProjectBuilder.get_requires_for_build', |
| 215 |
side_effect=[ |
| 216 |
{'dep1', 'dep2'}, |
| 217 |
], |
| 218 |
) |
| 219 |
mocker.patch('build.__main__._error') |
| 220 |
install = mocker.patch('build.env.DefaultIsolatedEnv.install') |
| 221 |
|
| 222 |
build.__main__.build_package(package_test_flit, '.', ['sdist']) |
| 223 |
|
| 224 |
install.assert_any_call({'flit_core >=2,<4'}, _fresh=True) |
| 225 |
|
| 226 |
required_cmd.assert_called_with('sdist', None) |
| 227 |
install.assert_any_call({'dep1', 'dep2'}) |
| 228 |
|
| 229 |
build_cmd.assert_called_with('sdist', '.', None) |
| 230 |
|
| 231 |
|
| 232 |
def test_build_no_isolation_check_deps_empty(mocker: pytest_mock.MockerFixture, package_test_flit: str) -> None: |
| 233 |
# check_dependencies = [] |
| 234 |
build_cmd = mocker.patch('build.ProjectBuilder.build', return_value='something') |
| 235 |
mocker.patch('build.ProjectBuilder.check_dependencies', return_value=[]) |
| 236 |
|
| 237 |
build.__main__.build_package(package_test_flit, '.', ['sdist'], isolation=False) |
| 238 |
|
| 239 |
build_cmd.assert_called_with('sdist', '.', None) |
| 240 |
|
| 241 |
|
| 242 |
def test_build_package_passes_config_settings_to_build(mocker: pytest_mock.MockerFixture, package_test_flit: str) -> None: |
| 243 |
build_cmd = mocker.patch( |
| 244 |
'build.__main__._build', |
| 245 |
autospec=True, |
| 246 |
side_effect=[ |
| 247 |
os.path.join('dist', 'test_flit-1.0.0.tar.gz'), |
| 248 |
os.path.join('dist', 'test_flit-1.0.0-py3-none-any.whl'), |
| 249 |
], |
| 250 |
) |
| 251 |
config_settings = {'--flag': 'value'} |
| 252 |
|
| 253 |
built = build.__main__.build_package( |
| 254 |
package_test_flit, |
| 255 |
'.', |
| 256 |
['sdist', 'wheel'], |
| 257 |
config_settings=config_settings, |
| 258 |
isolation=False, |
| 259 |
skip_dependency_check=True, |
| 260 |
dependency_constraints_txt=pathlib.Path('constraints.txt'), |
| 261 |
installer='uv', |
| 262 |
) |
| 263 |
|
| 264 |
assert built == ['test_flit-1.0.0.tar.gz', 'test_flit-1.0.0-py3-none-any.whl'] |
| 265 |
build_cmd.assert_has_calls( |
| 266 |
[ |
| 267 |
unittest.mock.call( |
| 268 |
False, package_test_flit, '.', 'sdist', config_settings, True, pathlib.Path('constraints.txt'), 'uv', None |
| 269 |
), |
| 270 |
unittest.mock.call( |
| 271 |
False, package_test_flit, '.', 'wheel', config_settings, True, pathlib.Path('constraints.txt'), 'uv', None |
| 272 |
), |
| 273 |
] |
| 274 |
) |
| 275 |
|
| 276 |
|
| 277 |
def test_build_package_via_sdist_passes_config_settings_to_build(mocker: pytest_mock.MockerFixture) -> None: |
| 278 |
build_cmd = mocker.patch( |
| 279 |
'build.__main__._build', |
| 280 |
autospec=True, |
| 281 |
side_effect=[ |
| 282 |
os.path.join('dist', 'demo-1.0.0.tar.gz'), |
| 283 |
os.path.join('dist', 'demo-1.0.0-py3-none-any.whl'), |
| 284 |
], |
| 285 |
) |
| 286 |
mocker.patch('build.__main__.tempfile.mkdtemp', return_value='temp-sdist-dir') |
| 287 |
rmtree = mocker.patch('build.__main__.shutil.rmtree') |
| 288 |
tar_open = mocker.patch('build.__main__.tar_open') |
| 289 |
mocker.patch('build.__main__._validate_sdist_archive', return_value='demo-1.0.0') |
| 290 |
mocker.patch('build.__main__._ctx.log') |
| 291 |
config_settings = {'--flag': 'value'} |
| 292 |
|
| 293 |
built = build.__main__.build_package_via_sdist( |
| 294 |
'src', |
| 295 |
'dist', |
| 296 |
['wheel'], |
| 297 |
config_settings=config_settings, |
| 298 |
isolation=False, |
| 299 |
skip_dependency_check=True, |
| 300 |
dependency_constraints_txt=pathlib.Path('constraints.txt'), |
| 301 |
installer='uv', |
| 302 |
) |
| 303 |
|
| 304 |
assert built == ['demo-1.0.0.tar.gz', 'demo-1.0.0-py3-none-any.whl'] |
| 305 |
extractall = tar_open.return_value.__enter__.return_value.extractall |
| 306 |
extractall.assert_called_once() |
| 307 |
assert extractall.call_args.args[0] == 'temp-sdist-dir' |
| 308 |
build_cmd.assert_has_calls( |
| 309 |
[ |
| 310 |
unittest.mock.call( |
| 311 |
False, 'src', 'dist', 'sdist', config_settings, True, pathlib.Path('constraints.txt'), 'uv', None |
| 312 |
), |
| 313 |
unittest.mock.call( |
| 314 |
False, |
| 315 |
os.path.join('temp-sdist-dir', 'demo-1.0.0'), |
| 316 |
'dist', |
| 317 |
'wheel', |
| 318 |
config_settings, |
| 319 |
True, |
| 320 |
pathlib.Path('constraints.txt'), |
| 321 |
'uv', |
| 322 |
None, |
| 323 |
), |
| 324 |
] |
| 325 |
) |
| 326 |
rmtree.assert_called_once_with('temp-sdist-dir', ignore_errors=True) |
| 327 |
|
| 328 |
|
| 329 |
def test_build_no_isolation_check_deps_not_installed(mocker: pytest_mock.MockerFixture, package_test_flit: str) -> None: |
| 330 |
error = mocker.patch('build.__main__._error') |
| 331 |
build_cmd = mocker.patch('build.ProjectBuilder.build', return_value='something') |
| 332 |
mocker.patch('build.ProjectBuilder.check_dependencies', return_value=[('foo>=1.0',)]) |
| 333 |
mocker.patch('build._compat.importlib.metadata.distribution', side_effect=_importlib.metadata.PackageNotFoundError) |
| 334 |
|
| 335 |
build.__main__.build_package(package_test_flit, '.', ['sdist'], isolation=False) |
| 336 |
|
| 337 |
build_cmd.assert_called_with('sdist', '.', None) |
| 338 |
error.assert_called_once_with( |
| 339 |
f'Unmet dependencies (checked against {sys.executable}):\n\tfoo>=1.0\n\t\twanted: >=1.0\n\t\tfound: not installed' |
| 340 |
) |
| 341 |
|
| 342 |
|
| 343 |
def test_build_no_isolation_check_deps_version_mismatch(mocker: pytest_mock.MockerFixture, package_test_flit: str) -> None: |
| 344 |
error = mocker.patch('build.__main__._error') |
| 345 |
mocker.patch('build.ProjectBuilder.build', return_value='something') |
| 346 |
mocker.patch('build.ProjectBuilder.check_dependencies', return_value=[('bar>=2.0',)]) |
| 347 |
mocker.patch('build._compat.importlib.metadata.distribution', return_value=mocker.MagicMock(version='1.0.0')) |
| 348 |
|
| 349 |
build.__main__.build_package(package_test_flit, '.', ['sdist'], isolation=False) |
| 350 |
|
| 351 |
error.assert_called_once_with( |
| 352 |
f'Unmet dependencies (checked against {sys.executable}):\n\tbar>=2.0\n\t\twanted: >=2.0\n\t\tfound: 1.0.0' |
| 353 |
) |
| 354 |
|
| 355 |
|
| 356 |
def test_build_no_isolation_check_deps_chain_without_specifier( |
| 357 |
mocker: pytest_mock.MockerFixture, package_test_flit: str |
| 358 |
) -> None: |
| 359 |
error = mocker.patch('build.__main__._error') |
| 360 |
mocker.patch('build.ProjectBuilder.build', return_value='something') |
| 361 |
mocker.patch('build.ProjectBuilder.check_dependencies', return_value=[('matplotlib>=2.2', 'kiwisolver')]) |
| 362 |
mocker.patch('build._compat.importlib.metadata.distribution', side_effect=_importlib.metadata.PackageNotFoundError) |
| 363 |
|
| 364 |
build.__main__.build_package(package_test_flit, '.', ['sdist'], isolation=False) |
| 365 |
|
| 366 |
error.assert_called_once_with( |
| 367 |
f'Unmet dependencies (checked against {sys.executable}):' |
| 368 |
'\n\tmatplotlib>=2.2 -> kiwisolver\n\t\twanted: any\n\t\tfound: not installed' |
| 369 |
) |
| 370 |
|
| 371 |
|
| 372 |
@pytest.mark.parametrize( |
| 373 |
('cli_args', 'err_msg'), |
| 374 |
[ |
| 375 |
(['-Cone=1', '--config-json={"two": 2}'], 'not allowed with argument'), |
| 376 |
(['--config-json={"two": 2'], 'Invalid JSON in --config-json'), |
| 377 |
(['--config-json=[1]'], '--config-json must contain a JSON object'), |
| 378 |
], |
| 379 |
) |
| 380 |
def test_config_json_errors(cli_args: list[str], err_msg: str, capsys: pytest.CaptureFixture[str]) -> None: |
| 381 |
with pytest.raises(SystemExit): |
| 382 |
build.__main__.main(cli_args) |
| 383 |
|
| 384 |
outerr = capsys.readouterr() |
| 385 |
assert err_msg in outerr.out or err_msg in outerr.err |
| 386 |
|
| 387 |
|
| 388 |
@pytest.mark.isolated |
| 389 |
def test_build_raises_build_exception(mocker: pytest_mock.MockerFixture, package_test_flit: str) -> None: |
| 390 |
mocker.patch('build.ProjectBuilder.get_requires_for_build', side_effect=build.BuildException) |
| 391 |
mocker.patch('build.env.DefaultIsolatedEnv.install') |
| 392 |
|
| 393 |
with pytest.raises(build.BuildException): |
| 394 |
build.__main__.build_package(package_test_flit, '.', ['sdist']) |
| 395 |
|
| 396 |
|
| 397 |
@pytest.mark.isolated |
| 398 |
def test_build_raises_build_backend_exception(mocker: pytest_mock.MockerFixture, package_test_flit: str) -> None: |
| 399 |
mocker.patch('build.ProjectBuilder.get_requires_for_build', side_effect=build.BuildBackendException(Exception('a'))) |
| 400 |
mocker.patch('build.env.DefaultIsolatedEnv.install') |
| 401 |
|
| 402 |
msg = f"Backend operation failed: Exception('a'{',' if sys.version_info < (3, 7) else ''})" |
| 403 |
with pytest.raises(build.BuildBackendException, match=re.escape(msg)): |
| 404 |
build.__main__.build_package(package_test_flit, '.', ['sdist']) |
| 405 |
|
| 406 |
|
| 407 |
@pytest.mark.network |
| 408 |
@pytest.mark.pypy3323bug |
| 409 |
def test_build_package(tmp_dir: str, package_test_setuptools: str) -> None: |
| 410 |
build.__main__.build_package(package_test_setuptools, tmp_dir, ['sdist', 'wheel']) |
| 411 |
|
| 412 |
assert sorted(os.listdir(tmp_dir)) == [ |
| 413 |
'test_setuptools-1.0.0-py3-none-any.whl', |
| 414 |
'test_setuptools-1.0.0.tar.gz', |
| 415 |
] |
| 416 |
|
| 417 |
|
| 418 |
@pytest.mark.network |
| 419 |
@pytest.mark.pypy3323bug |
| 420 |
def test_build_package_via_sdist(tmp_dir: str, package_test_setuptools: str) -> None: |
| 421 |
build.__main__.build_package_via_sdist(package_test_setuptools, tmp_dir, ['wheel']) |
| 422 |
|
| 423 |
assert sorted(os.listdir(tmp_dir)) == [ |
| 424 |
'test_setuptools-1.0.0-py3-none-any.whl', |
| 425 |
'test_setuptools-1.0.0.tar.gz', |
| 426 |
] |
| 427 |
|
| 428 |
|
| 429 |
@pytest.mark.pypy3323bug |
| 430 |
def test_build_package_via_sdist_incomplete_sdist(tmp_dir: str, package_test_cant_build_via_sdist: str) -> None: |
| 431 |
# The backend produces an sdist without a PKG-INFO, so it is rejected up front rather than |
| 432 |
# failing later when the wheel build cannot find its missing source file. |
| 433 |
with pytest.raises(build.BuildException, match='PKG-INFO'): |
| 434 |
build.__main__.build_package_via_sdist(package_test_cant_build_via_sdist, tmp_dir, ['wheel']) |
| 435 |
|
| 436 |
|
| 437 |
def test_build_package_via_sdist_invalid_distribution(tmp_dir: str, package_test_setuptools: str) -> None: |
| 438 |
with pytest.raises(ValueError, match='Only binary distributions are allowed but sdist was specified'): |
| 439 |
build.__main__.build_package_via_sdist(package_test_setuptools, tmp_dir, ['sdist']) |
| 440 |
|
| 441 |
|
| 442 |
@pytest.mark.isolated |
| 443 |
def test_build_package_with_constraints( |
| 444 |
mocker: pytest_mock.MockerFixture, tmp_path: pathlib.Path, package_test_flit: str |
| 445 |
) -> None: |
| 446 |
install = mocker.patch('build.env.DefaultIsolatedEnv.install') |
| 447 |
|
| 448 |
constraints_txt_path = tmp_path.joinpath('constraints.txt') |
| 449 |
constraints_txt_path.write_text( |
| 450 |
"""\ |
| 451 |
flit-core==12.34 |
| 452 |
foo==wot |
| 453 |
""", |
| 454 |
encoding='utf-8', |
| 455 |
) |
| 456 |
|
| 457 |
with pytest.raises(build.BuildBackendException, match=re.escape("Backend 'flit_core.buildapi' is not available.")): |
| 458 |
build.__main__.build_package(package_test_flit, tmp_path, ['wheel'], dependency_constraints_txt=constraints_txt_path) |
| 459 |
|
| 460 |
install.assert_any_call({'flit_core >=2,<4'}, constraints={'flit-core==12.34', 'foo==wot'}, _fresh=True) |
| 461 |
|
| 462 |
|
| 463 |
@pytest.mark.pypy3323bug |
| 464 |
@pytest.mark.parametrize( |
| 465 |
('args', 'output'), |
| 466 |
[ |
| 467 |
pytest.param( |
| 468 |
[], |
| 469 |
[ |
| 470 |
'* Creating isolated environment: venv+pip...', |
| 471 |
'* Installing packages in isolated environment:', |
| 472 |
' - setuptools >= 42.0.0', |
| 473 |
'* Getting build dependencies for sdist...', |
| 474 |
'* Building sdist...', |
| 475 |
'* Building wheel from sdist', |
| 476 |
'* Creating isolated environment: venv+pip...', |
| 477 |
'* Installing packages in isolated environment:', |
| 478 |
' - setuptools >= 42.0.0', |
| 479 |
'* Getting build dependencies for wheel...', |
| 480 |
'* Building wheel...', |
| 481 |
'Successfully built test_setuptools-1.0.0.tar.gz and test_setuptools-1.0.0-py3-none-any.whl', |
| 482 |
], |
| 483 |
id='via-sdist-isolation', |
| 484 |
marks=[pytest.mark.network, pytest.mark.isolated], |
| 485 |
), |
| 486 |
pytest.param( |
| 487 |
['--no-isolation'], |
| 488 |
[ |
| 489 |
'* Getting build dependencies for sdist...', |
| 490 |
'* Building sdist...', |
| 491 |
'* Building wheel from sdist', |
| 492 |
'* Getting build dependencies for wheel...', |
| 493 |
'* Building wheel...', |
| 494 |
'Successfully built test_setuptools-1.0.0.tar.gz and test_setuptools-1.0.0-py3-none-any.whl', |
| 495 |
], |
| 496 |
id='via-sdist-no-isolation', |
| 497 |
), |
| 498 |
pytest.param( |
| 499 |
['--wheel'], |
| 500 |
[ |
| 501 |
'* Creating isolated environment: venv+pip...', |
| 502 |
'* Installing packages in isolated environment:', |
| 503 |
' - setuptools >= 42.0.0', |
| 504 |
'* Getting build dependencies for wheel...', |
| 505 |
'* Building wheel...', |
| 506 |
'Successfully built test_setuptools-1.0.0-py3-none-any.whl', |
| 507 |
], |
| 508 |
id='wheel-direct-isolation', |
| 509 |
marks=[pytest.mark.network, pytest.mark.isolated], |
| 510 |
), |
| 511 |
pytest.param( |
| 512 |
['--wheel', '--no-isolation'], |
| 513 |
[ |
| 514 |
'* Getting build dependencies for wheel...', |
| 515 |
'* Building wheel...', |
| 516 |
'Successfully built test_setuptools-1.0.0-py3-none-any.whl', |
| 517 |
], |
| 518 |
id='wheel-direct-no-isolation', |
| 519 |
), |
| 520 |
pytest.param( |
| 521 |
['--sdist', '--no-isolation'], |
| 522 |
[ |
| 523 |
'* Getting build dependencies for sdist...', |
| 524 |
'* Building sdist...', |
| 525 |
'Successfully built test_setuptools-1.0.0.tar.gz', |
| 526 |
], |
| 527 |
id='sdist-direct-no-isolation', |
| 528 |
), |
| 529 |
pytest.param( |
| 530 |
['--sdist', '--wheel', '--no-isolation'], |
| 531 |
[ |
| 532 |
'* Getting build dependencies for sdist...', |
| 533 |
'* Building sdist...', |
| 534 |
'* Getting build dependencies for wheel...', |
| 535 |
'* Building wheel...', |
| 536 |
'Successfully built test_setuptools-1.0.0.tar.gz and test_setuptools-1.0.0-py3-none-any.whl', |
| 537 |
], |
| 538 |
id='sdist-and-wheel-direct-no-isolation', |
| 539 |
), |
| 540 |
pytest.param( |
| 541 |
['--metadata'], |
| 542 |
[ |
| 543 |
'* Creating isolated environment: venv+pip...', |
| 544 |
'* Getting metadata for wheel...', |
| 545 |
'* Getting build dependencies for wheel...', |
| 546 |
'* Installing packages in isolated environment:', |
| 547 |
' - setuptools >= 42.0.0', |
| 548 |
], |
| 549 |
id='metadata-isolation', |
| 550 |
marks=[pytest.mark.network, pytest.mark.isolated], |
| 551 |
), |
| 552 |
pytest.param( |
| 553 |
['--metadata', '--no-isolation'], |
| 554 |
[ |
| 555 |
'* Getting build dependencies for wheel...', |
| 556 |
'* Getting metadata for wheel...', |
| 557 |
], |
| 558 |
id='metadata-no-isolation', |
| 559 |
), |
| 560 |
], |
| 561 |
) |
| 562 |
@pytest.mark.flaky(reruns=5) |
| 563 |
def test_logging_output( |
| 564 |
package_test_setuptools: str, tmp_dir: str, capsys: pytest.CaptureFixture[str], args: list[str], output: list[str] |
| 565 |
) -> None: |
| 566 |
build.__main__.main([package_test_setuptools, '-o', tmp_dir, *args]) |
| 567 |
_, stderr = capsys.readouterr() |
| 568 |
# the installed-version step lists dynamic versions, exercised in its own test below |
| 569 |
version_pin = re.compile(r' {2}- \S+==\S+') |
| 570 |
lines = [ |
| 571 |
line |
| 572 |
for line in stderr.splitlines() |
| 573 |
if line != '* Installed build dependency versions:' and not version_pin.fullmatch(line) |
| 574 |
] |
| 575 |
assert set(lines) <= set(output) |
| 576 |
|
| 577 |
|
| 578 |
@pytest.mark.network |
| 579 |
@pytest.mark.isolated |
| 580 |
@pytest.mark.flaky(reruns=5) |
| 581 |
def test_logging_output_backend_versions( |
| 582 |
package_test_setuptools: str, tmp_dir: str, capsys: pytest.CaptureFixture[str] |
| 583 |
) -> None: |
| 584 |
build.__main__.main([package_test_setuptools, '-o', tmp_dir, '--wheel']) |
| 585 |
_, stderr = capsys.readouterr() |
| 586 |
assert '* Installed build dependency versions:' in stderr.splitlines() |
| 587 |
assert any(re.fullmatch(r' {2}- setuptools==\d[\w.]*', line) for line in stderr.splitlines()) |
| 588 |
|
| 589 |
|
| 590 |
@pytest.mark.pypy3323bug |
| 591 |
@pytest.mark.parametrize( |
| 592 |
('color', 'stderr_error', 'stderr_body'), |
| 593 |
[ |
| 594 |
( |
| 595 |
False, |
| 596 |
'ERROR ', |
| 597 |
[ |
| 598 |
'* Creating isolated environment: venv+pip...', |
| 599 |
'* Installing packages in isolated environment:', |
| 600 |
' - setuptools >= 42.0.0', |
| 601 |
' - this is invalid', |
| 602 |
], |
| 603 |
), |
| 604 |
( |
| 605 |
True, |
| 606 |
'\33[91mERROR\33[0m ', |
| 607 |
[ |
| 608 |
'\33[1m* Creating isolated environment: venv+pip...\33[0m', |
| 609 |
'\33[1m* Installing packages in isolated environment:\33[0m', |
| 610 |
' - setuptools >= 42.0.0', |
| 611 |
' - this is invalid', |
| 612 |
], |
| 613 |
), |
| 614 |
], |
| 615 |
ids=['no-color', 'color'], |
| 616 |
) |
| 617 |
@pytest.mark.usefixtures('local_pip') |
| 618 |
def test_logging_output_env_subprocess_error( |
| 619 |
mocker: pytest_mock.MockerFixture, |
| 620 |
monkeypatch: pytest.MonkeyPatch, |
| 621 |
package_test_invalid_requirements: str, |
| 622 |
tmp_dir: str, |
| 623 |
capsys: pytest.CaptureFixture[str], |
| 624 |
color: bool, |
| 625 |
stderr_body: list[str], |
| 626 |
stderr_error: str, |
| 627 |
) -> None: |
| 628 |
with contextlib.suppress(ModuleNotFoundError): # colorama might not be available |
| 629 |
# do not inject hook to have clear output on capsys |
| 630 |
mocker.patch('colorama.init') |
| 631 |
|
| 632 |
monkeypatch.delenv('NO_COLOR', raising=False) |
| 633 |
monkeypatch.setenv('FORCE_COLOR' if color else 'NO_COLOR', '') |
| 634 |
|
| 635 |
with pytest.raises(SystemExit): |
| 636 |
build.__main__.main([package_test_invalid_requirements, '-o', tmp_dir]) |
| 637 |
outerr = capsys.readouterr() |
| 638 |
stderr = outerr.err.splitlines() |
| 639 |
|
| 640 |
assert stderr[:4] == stderr_body |
| 641 |
assert stderr[-1].startswith(stderr_error) |
| 642 |
|
| 643 |
# Newer versions of pip also color stderr - strip them if present |
| 644 |
assert any(ANSI_STRIP.sub('', e).strip().startswith('< ERROR: Invalid requirement: ') for e in stderr) |
| 645 |
|
| 646 |
|
| 647 |
@pytest.mark.parametrize( |
| 648 |
('stdout_tty', 'stderr_tty', 'env', 'stdout_colors', 'stderr_colors'), |
| 649 |
[ |
| 650 |
(False, False, {}, build.__main__._NO_COLORS, build.__main__._NO_COLORS), |
| 651 |
(True, True, {}, build.__main__._COLORS, build.__main__._COLORS), |
| 652 |
# regression: color support must be decided per-stream, not solely from stdout. |
| 653 |
(False, True, {}, build.__main__._NO_COLORS, build.__main__._COLORS), |
| 654 |
(True, False, {}, build.__main__._COLORS, build.__main__._NO_COLORS), |
| 655 |
(False, False, {'NO_COLOR': ''}, build.__main__._NO_COLORS, build.__main__._NO_COLORS), |
| 656 |
(True, True, {'NO_COLOR': ''}, build.__main__._NO_COLORS, build.__main__._NO_COLORS), |
| 657 |
(False, False, {'FORCE_COLOR': ''}, build.__main__._COLORS, build.__main__._COLORS), |
| 658 |
(True, True, {'FORCE_COLOR': ''}, build.__main__._COLORS, build.__main__._COLORS), |
| 659 |
], |
| 660 |
) |
| 661 |
def test_colors( |
| 662 |
mocker: pytest_mock.MockerFixture, |
| 663 |
monkeypatch: pytest.MonkeyPatch, |
| 664 |
stdout_tty: bool, |
| 665 |
stderr_tty: bool, |
| 666 |
env: dict[str, str], |
| 667 |
stdout_colors: dict[str, object], |
| 668 |
stderr_colors: dict[str, object], |
| 669 |
) -> None: |
| 670 |
mocker.patch('sys.stdout.isatty', return_value=stdout_tty) |
| 671 |
mocker.patch('sys.stderr.isatty', return_value=stderr_tty) |
| 672 |
monkeypatch.delenv('NO_COLOR', raising=False) |
| 673 |
monkeypatch.delenv('FORCE_COLOR', raising=False) |
| 674 |
for key, value in env.items(): |
| 675 |
monkeypatch.setenv(key, value) |
| 676 |
|
| 677 |
build.__main__._init_colors() |
| 678 |
|
| 679 |
styles = build.__main__._styles.get() |
| 680 |
assert styles['stdout'] == stdout_colors |
| 681 |
assert styles['stderr'] == stderr_colors |
| 682 |
|
| 683 |
|
| 684 |
def test_colors_conflict(monkeypatch: pytest.MonkeyPatch) -> None: |
| 685 |
with monkeypatch.context() as m: |
| 686 |
m.setenv('NO_COLOR', '') |
| 687 |
m.setenv('FORCE_COLOR', '') |
| 688 |
|
| 689 |
with pytest.warns( |
| 690 |
UserWarning, |
| 691 |
match='Both NO_COLOR and FORCE_COLOR environment variables are set, disabling color', |
| 692 |
): |
| 693 |
build.__main__._init_colors() |
| 694 |
|
| 695 |
styles = build.__main__._styles.get() |
| 696 |
assert styles['stdout'] == build.__main__._NO_COLORS |
| 697 |
assert styles['stderr'] == build.__main__._NO_COLORS |
| 698 |
|
| 699 |
|
| 700 |
def test_cprint_selects_style_per_stream(mocker: pytest_mock.MockerFixture, monkeypatch: pytest.MonkeyPatch) -> None: |
| 701 |
"""stderr output is colored independently of stdout, based on its own tty-ness.""" |
| 702 |
monkeypatch.delenv('NO_COLOR', raising=False) |
| 703 |
monkeypatch.delenv('FORCE_COLOR', raising=False) |
| 704 |
|
| 705 |
# stdout is not a tty (e.g. redirected to a log file), stderr is a tty. |
| 706 |
mocker.patch('sys.stdout.isatty', return_value=False) |
| 707 |
mocker.patch('sys.stderr.isatty', return_value=True) |
| 708 |
build.__main__._init_colors() |
| 709 |
|
| 710 |
assert build.__main__._styles.get()['stdout'] == build.__main__._NO_COLORS |
| 711 |
assert build.__main__._styles.get()['stderr'] == build.__main__._COLORS |
| 712 |
|
| 713 |
# the inverse: stdout is a tty, stderr is redirected. |
| 714 |
mocker.patch('sys.stdout.isatty', return_value=True) |
| 715 |
mocker.patch('sys.stderr.isatty', return_value=False) |
| 716 |
build.__main__._init_colors() |
| 717 |
|
| 718 |
assert build.__main__._styles.get()['stdout'] == build.__main__._COLORS |
| 719 |
assert build.__main__._styles.get()['stderr'] == build.__main__._NO_COLORS |
| 720 |
|
| 721 |
|
| 722 |
def test_warning_goes_to_stderr(capsys: pytest.CaptureFixture[str]) -> None: |
| 723 |
build.__main__._showwarning('a warning', UserWarning, 'f.py', 1) |
| 724 |
|
| 725 |
out, err = capsys.readouterr() |
| 726 |
|
| 727 |
assert out == '' |
| 728 |
assert 'WARNING' in err |
| 729 |
assert 'a warning' in err |
| 730 |
|
| 731 |
|
| 732 |
def test_logging_output_venv_failure( |
| 733 |
monkeypatch: pytest.MonkeyPatch, package_test_flit: str, tmp_dir: str, capsys: pytest.CaptureFixture[str] |
| 734 |
) -> None: |
| 735 |
def raise_called_process_err(*_args: object, **_kwargs: object) -> None: |
| 736 |
raise subprocess.CalledProcessError(1, ['test', 'args'], b'stdoutput', b'stderror') |
| 737 |
|
| 738 |
monkeypatch.setattr(venv.EnvBuilder, 'create', raise_called_process_err) |
| 739 |
monkeypatch.setenv('NO_COLOR', '') |
| 740 |
|
| 741 |
with pytest.raises(SystemExit): |
| 742 |
build.__main__.main([package_test_flit, '-o', tmp_dir]) |
| 743 |
|
| 744 |
_, stderr = capsys.readouterr() |
| 745 |
|
| 746 |
assert ( |
| 747 |
stderr |
| 748 |
== """\ |
| 749 |
* Creating isolated environment: venv+pip... |
| 750 |
> test args |
| 751 |
< stdoutput |
| 752 |
< stderror |
| 753 |
ERROR Failed to create venv. Maybe try installing virtualenv. |
| 754 |
""" |
| 755 |
) |
| 756 |
|
| 757 |
|
| 758 |
@pytest.mark.contextvars |
| 759 |
@pytest.mark.network |
| 760 |
def test_verbose_logging_output( |
| 761 |
subtests: SubTests, |
| 762 |
capfd: pytest.CaptureFixture[str], |
| 763 |
monkeypatch: pytest.MonkeyPatch, |
| 764 |
tmp_dir: str, |
| 765 |
package_test_setuptools: str, |
| 766 |
) -> None: |
| 767 |
monkeypatch.setenv('NO_COLOR', '') |
| 768 |
|
| 769 |
no_of_lines = -1 |
| 770 |
|
| 771 |
for verbosity in range(-2, 3): |
| 772 |
with subtests.test(verbosity=verbosity): |
| 773 |
cmd = [package_test_setuptools, '-w', '-o', tmp_dir] |
| 774 |
if verbosity: |
| 775 |
cmd.insert(0, f'-{("v" if verbosity > 0 else "q") * abs(verbosity)}') |
| 776 |
|
| 777 |
build.__main__.main(cmd) |
| 778 |
|
| 779 |
new_no_of_lines = sum(1 for s in capfd.readouterr() for i in s.splitlines()) |
| 780 |
assert new_no_of_lines > no_of_lines |
| 781 |
no_of_lines = new_no_of_lines |
| 782 |
|
| 783 |
|
| 784 |
def test_metadata_json_output( |
| 785 |
capsys: pytest.CaptureFixture[str], |
| 786 |
package_test_setuptools: str, |
| 787 |
) -> None: |
| 788 |
build.__main__.main([package_test_setuptools, '--metadata', '-n']) |
| 789 |
|
| 790 |
stdout = capsys.readouterr().out |
| 791 |
metadata = json.loads(stdout) |
| 792 |
# Name normalised in old versions of setuptools. |
| 793 |
assert metadata['name'] in {'test_setuptools', 'test-setuptools'} |
| 794 |
assert metadata['version'] == '1.0.0' |
| 795 |
|
| 796 |
|
| 797 |
def test_setup_cli_windows_colorama_available(mocker: pytest_mock.MockerFixture) -> None: |
| 798 |
mocker.patch('platform.system', return_value='Windows') |
| 799 |
colorama = mocker.MagicMock() |
| 800 |
mocker.patch.dict('sys.modules', {'colorama': colorama}) |
| 801 |
build.__main__._setup_cli(verbosity=0) |
| 802 |
colorama.init.assert_called_once() |
| 803 |
|
| 804 |
|
| 805 |
def test_setup_cli_windows_colorama_missing(mocker: pytest_mock.MockerFixture) -> None: |
| 806 |
mocker.patch('platform.system', return_value='Windows') |
| 807 |
mocker.patch.dict('sys.modules', {'colorama': None}) |
| 808 |
build.__main__._setup_cli(verbosity=0) |
| 809 |
|
| 810 |
|
| 811 |
def test_setup_cli_non_windows(mocker: pytest_mock.MockerFixture) -> None: |
| 812 |
mocker.patch('platform.system', return_value='Linux') |
| 813 |
build.__main__._setup_cli(verbosity=0) |
| 814 |
|
| 815 |
|
| 816 |
def test_metadata_with_distributions_error() -> None: |
| 817 |
with pytest.raises(SystemExit): |
| 818 |
build.__main__.main(['--metadata', '--sdist']) |
| 819 |
|
| 820 |
|
| 821 |
def test_entrypoint(mocker: pytest_mock.MockerFixture) -> None: |
| 822 |
main = mocker.patch('build.__main__.main') |
| 823 |
build.__main__.entrypoint() |
| 824 |
main.assert_called_once_with(sys.argv[1:]) |
| 825 |
|
| 826 |
|
| 827 |
def test_handle_build_error_build_backend_exception(mocker: pytest_mock.MockerFixture) -> None: |
| 828 |
mocker.patch('build.__main__._error', side_effect=SystemExit(1)) |
| 829 |
|
| 830 |
exc = ValueError('test error') |
| 831 |
try: |
| 832 |
raise exc |
| 833 |
except ValueError: |
| 834 |
exc_info = sys.exc_info() |
| 835 |
|
| 836 |
with pytest.raises(SystemExit), build.__main__._handle_build_error(env_dir=None, sdist_extract_dir=None): |
| 837 |
raise build.BuildBackendException(exc, exc_info=exc_info) |
| 838 |
|
| 839 |
|
| 840 |
def test_handle_build_error_prints_debug_tip_on_subprocess_failure( |
| 841 |
mocker: pytest_mock.MockerFixture, |
| 842 |
capsys: pytest.CaptureFixture[str], |
| 843 |
) -> None: |
| 844 |
mocker.patch('build.__main__._error', side_effect=SystemExit(1)) |
| 845 |
|
| 846 |
exc = subprocess.CalledProcessError(1, ['backend']) |
| 847 |
with pytest.raises(SystemExit), build.__main__._handle_build_error(env_dir=None, sdist_extract_dir=None): |
| 848 |
raise build.BuildBackendException(exc, 'Backend subprocess exited') |
| 849 |
|
| 850 |
err = ANSI_STRIP.sub('', capsys.readouterr().err) |
| 851 |
assert 'TIP' in err |
| 852 |
assert 'pass --env-dir and --sdist-extract-dir' in err |
| 853 |
assert 'troubleshooting.html#debug-a-failed-build' in err |
| 854 |
|
| 855 |
|
| 856 |
@pytest.mark.parametrize( |
| 857 |
('env_dir', 'sdist_extract_dir', 'expected'), |
| 858 |
[ |
| 859 |
pytest.param(None, None, 'pass --env-dir and --sdist-extract-dir to keep', id='none-pinned'), |
| 860 |
pytest.param('env', None, 'inspect the build environment at env', id='env-only'), |
| 861 |
pytest.param(None, 'src', 'inspect the extracted sources at src', id='sdist-only'), |
| 862 |
pytest.param('env', 'src', 'inspect the build environment at env and the extracted sources at src', id='both'), |
| 863 |
], |
| 864 |
) |
| 865 |
def test_build_failure_hint(env_dir: str | None, sdist_extract_dir: str | None, expected: str) -> None: |
| 866 |
hint = build.__main__._build_failure_hint(env_dir, sdist_extract_dir) |
| 867 |
|
| 868 |
assert expected in hint |
| 869 |
assert hint.endswith('troubleshooting.html#debug-a-failed-build for help debugging a failed build') |
| 870 |
|
| 871 |
|
| 872 |
def test_log_unknown_kind(mocker: pytest_mock.MockerFixture) -> None: |
| 873 |
mocker.patch('build.__main__._cprint') |
| 874 |
log = build.__main__._make_logger() |
| 875 |
log('message', kind=('unknown',)) |
| 876 |
|
| 877 |
|
| 878 |
def test_log_dependency_versions(mocker: pytest_mock.MockerFixture) -> None: |
| 879 |
env = mocker.create_autospec(build.env.DefaultIsolatedEnv, instance=True) |
| 880 |
env.installed_versions.return_value = {'wheel': '0.45.1', 'setuptools': '80.9.0'} |
| 881 |
log = mocker.patch('build.__main__._ctx.log') |
| 882 |
|
| 883 |
build.__main__._log_dependency_versions(env, {'setuptools', 'wheel'}) |
| 884 |
|
| 885 |
log.assert_called_once_with( |
| 886 |
'Installed build dependency versions:\n- setuptools==80.9.0\n- wheel==0.45.1', |
| 887 |
kind=('step',), |
| 888 |
) |
| 889 |
|
| 890 |
|
| 891 |
def test_log_dependency_versions_none(mocker: pytest_mock.MockerFixture) -> None: |
| 892 |
env = mocker.create_autospec(build.env.DefaultIsolatedEnv, instance=True) |
| 893 |
env.installed_versions.return_value = {} |
| 894 |
log = mocker.patch('build.__main__._ctx.log') |
| 895 |
|
| 896 |
build.__main__._log_dependency_versions(env, set()) |
| 897 |
|
| 898 |
log.assert_not_called() |
| 899 |
|
| 900 |
|
| 901 |
def test_bootstrap_build_env_logs_versions(mocker: pytest_mock.MockerFixture) -> None: |
| 902 |
env = mocker.create_autospec(build.env.DefaultIsolatedEnv, instance=True) |
| 903 |
env.__enter__.return_value = env |
| 904 |
mocker.patch('build.__main__.DefaultIsolatedEnv', return_value=env) |
| 905 |
builder = mocker.create_autospec(build.ProjectBuilder, instance=True) |
| 906 |
builder.build_system_requires = {'setuptools'} |
| 907 |
builder.get_requires_for_build.return_value = {'wheel'} |
| 908 |
mocker.patch('build.ProjectBuilder.from_isolated_env', return_value=builder) |
| 909 |
log_versions = mocker.patch('build.__main__._log_dependency_versions') |
| 910 |
|
| 911 |
with build.__main__._bootstrap_build_env( |
| 912 |
isolation=True, |
| 913 |
srcdir='src', |
| 914 |
distribution='wheel', |
| 915 |
config_settings=None, |
| 916 |
skip_dependency_check=False, |
| 917 |
dependency_constraints_txt=None, |
| 918 |
installer='pip', |
| 919 |
) as result: |
| 920 |
assert result is builder |
| 921 |
|
| 922 |
env.install.assert_any_call({'setuptools'}, _fresh=True) |
| 923 |
env.install.assert_any_call({'wheel'}) |
| 924 |
log_versions.assert_called_once_with(env, {'setuptools', 'wheel'}) |
| 925 |
|
| 926 |
|
| 927 |
def test_build_no_isolation_skip_dependency_check(mocker: pytest_mock.MockerFixture, package_test_flit: str) -> None: |
| 928 |
build_cmd = mocker.patch('build.ProjectBuilder.build', return_value='something') |
| 929 |
build.__main__.build_package(package_test_flit, '.', ['sdist'], isolation=False, skip_dependency_check=True) |
| 930 |
build_cmd.assert_called_with('sdist', '.', None) |
| 931 |
|
| 932 |
|
| 933 |
def test_build_package_via_sdist_empty_distributions(mocker: pytest_mock.MockerFixture) -> None: |
| 934 |
mocker.patch( |
| 935 |
'build.__main__._build', |
| 936 |
return_value=os.path.join('dist', 'demo-1.0.0.tar.gz'), |
| 937 |
) |
| 938 |
result = build.__main__.build_package_via_sdist('src', 'dist', []) |
| 939 |
assert result == ['demo-1.0.0.tar.gz'] |
| 940 |
|
| 941 |
|
| 942 |
def test_parse_config_settings_triple_duplicate() -> None: |
| 943 |
result = build.__main__._parse_config_settings(['--flag=a', '--flag=b', '--flag=c']) |
| 944 |
assert result == {'--flag': ['a', 'b', 'c']} |
| 945 |
|
| 946 |
|
| 947 |
@pytest.mark.parametrize( |
| 948 |
('arg', 'value', 'warns'), |
| 949 |
[ |
| 950 |
pytest.param('--flag', '', True, id='bare-key-warns'), |
| 951 |
pytest.param('--flag=', '', False, id='empty-value'), |
| 952 |
pytest.param('--flag=value', 'value', False, id='with-value'), |
| 953 |
], |
| 954 |
) |
| 955 |
def test_parse_config_settings_pip_compatibility(arg: str, value: str, warns: bool, recwarn: pytest.WarningsRecorder) -> None: |
| 956 |
assert build.__main__._parse_config_settings([arg]) == {'--flag': value} |
| 957 |
|
| 958 |
messages = [str(warning.message) for warning in recwarn] |
| 959 |
config_warnings = [m for m in messages if "Config setting '--flag' was passed without a value" in m] |
| 960 |
assert messages == config_warnings # no unrelated warnings are emitted either way |
| 961 |
assert bool(config_warnings) == warns |
| 962 |
|
| 963 |
|
| 964 |
def test_build_metadata_runner_without_extra_environ( |
| 965 |
mocker: pytest_mock.MockerFixture, |
| 966 |
tmp_path: pathlib.Path, |
| 967 |
package_test_setuptools: str, |
| 968 |
) -> None: |
| 969 |
captured_runners: list[CapturedRunner] = [] |
| 970 |
|
| 971 |
@contextlib.contextmanager |
| 972 |
def fake_bootstrap(*_args: object, runner: CapturedRunner, **_kwargs: object) -> Iterator[unittest.mock.MagicMock]: |
| 973 |
captured_runners.append(runner) |
| 974 |
builder = mocker.MagicMock() |
| 975 |
metadata_dir = tmp_path / 'metadata' |
| 976 |
metadata_dir.mkdir() |
| 977 |
(metadata_dir / 'METADATA').write_bytes(b'Metadata-Version: 2.2\nName: test\nVersion: 1.0\n') |
| 978 |
builder.metadata_path.return_value = str(metadata_dir) |
| 979 |
yield builder |
| 980 |
|
| 981 |
mocker.patch('build.__main__._bootstrap_build_env', side_effect=fake_bootstrap) |
| 982 |
ctx_run = mocker.patch('build.__main__._ctx.run_subprocess') |
| 983 |
|
| 984 |
build.__main__._build_metadata(package_test_setuptools, '.', ['wheel'], isolation=False, skip_dependency_check=True) |
| 985 |
|
| 986 |
assert captured_runners |
| 987 |
captured_runners[0](['echo', 'test']) |
| 988 |
ctx_run.assert_called_once_with(['echo', 'test'], None, mocker.ANY) |
| 989 |
|
| 990 |
|
| 991 |
class WriteSdist(Protocol): |
| 992 |
def __call__( |
| 993 |
self, path: pathlib.Path, top_level: str, *, with_pkg_info: bool = ..., extra: dict[str, str] | None = ... |
| 994 |
) -> None: ... |
| 995 |
|
| 996 |
|
| 997 |
@pytest.fixture |
| 998 |
def write_sdist() -> WriteSdist: |
| 999 |
def _write( |
| 1000 |
path: pathlib.Path, |
| 1001 |
top_level: str, |
| 1002 |
*, |
| 1003 |
with_pkg_info: bool = True, |
| 1004 |
extra: dict[str, str] | None = None, |
| 1005 |
) -> None: |
| 1006 |
pkg_info = b'Metadata-Version: 2.2\nName: demo\nVersion: 1.0.0\n' |
| 1007 |
with tarfile.open(path, 'w:gz') as tar: |
| 1008 |
if with_pkg_info: |
| 1009 |
info = tarfile.TarInfo(name=f'{top_level}/PKG-INFO') |
| 1010 |
info.size = len(pkg_info) |
| 1011 |
tar.addfile(info, io.BytesIO(pkg_info)) |
| 1012 |
body = b'[build-system]\nrequires = []\nbuild-backend = "noop"\n' |
| 1013 |
info = tarfile.TarInfo(name=f'{top_level}/pyproject.toml') |
| 1014 |
info.size = len(body) |
| 1015 |
tar.addfile(info, io.BytesIO(body)) |
| 1016 |
for member_name, member_body in (extra or {}).items(): |
| 1017 |
data = member_body.encode() |
| 1018 |
info = tarfile.TarInfo(name=member_name) |
| 1019 |
info.size = len(data) |
| 1020 |
tar.addfile(info, io.BytesIO(data)) |
| 1021 |
|
| 1022 |
return _write |
| 1023 |
|
| 1024 |
|
| 1025 |
@pytest.fixture |
| 1026 |
def sdist(tmp_path: pathlib.Path, write_sdist: WriteSdist) -> pathlib.Path: |
| 1027 |
archive = tmp_path / 'demo-1.0.0.tar.gz' |
| 1028 |
write_sdist(archive, 'demo-1.0.0') |
| 1029 |
return archive |
| 1030 |
|
| 1031 |
|
| 1032 |
def test_validate_sdist_archive_happy(sdist: pathlib.Path) -> None: |
| 1033 |
assert build.__main__._validate_sdist_archive(str(sdist)) == 'demo-1.0.0' |
| 1034 |
|
| 1035 |
|
| 1036 |
def test_validate_sdist_archive_top_level_name_mismatch(tmp_path: pathlib.Path, write_sdist: WriteSdist) -> None: |
| 1037 |
archive = tmp_path / 'demo-1.0.0.tar.gz' |
| 1038 |
write_sdist(archive, 'something-else-1.0') |
| 1039 |
assert build.__main__._validate_sdist_archive(str(archive)) == 'something-else-1.0' |
| 1040 |
|
| 1041 |
|
| 1042 |
def _invalid_filename(tmp_path: pathlib.Path, write: WriteSdist) -> str: |
| 1043 |
archive = tmp_path / 'noversion.tar.gz' |
| 1044 |
write(archive, 'noversion') |
| 1045 |
return str(archive) |
| 1046 |
|
| 1047 |
|
| 1048 |
def _invalid_version(tmp_path: pathlib.Path, write: WriteSdist) -> str: |
| 1049 |
archive = tmp_path / 'demo-not_a_version.tar.gz' |
| 1050 |
write(archive, 'demo-not_a_version') |
| 1051 |
return str(archive) |
| 1052 |
|
| 1053 |
|
| 1054 |
def _corrupt_tar(tmp_path: pathlib.Path, _write: WriteSdist) -> str: |
| 1055 |
archive = tmp_path / 'demo-1.0.0.tar.gz' |
| 1056 |
archive.write_bytes(b'not a real tar.gz') |
| 1057 |
return str(archive) |
| 1058 |
|
| 1059 |
|
| 1060 |
def _multiple_top_level(tmp_path: pathlib.Path, write: WriteSdist) -> str: |
| 1061 |
archive = tmp_path / 'demo-1.0.0.tar.gz' |
| 1062 |
write(archive, 'demo-1.0.0', extra={'other-1.0.0/PKG-INFO': 'x'}) |
| 1063 |
return str(archive) |
| 1064 |
|
| 1065 |
|
| 1066 |
def _missing_pkg_info(tmp_path: pathlib.Path, write: WriteSdist) -> str: |
| 1067 |
archive = tmp_path / 'demo-1.0.0.tar.gz' |
| 1068 |
write(archive, 'demo-1.0.0', with_pkg_info=False) |
| 1069 |
return str(archive) |
| 1070 |
|
| 1071 |
|
| 1072 |
_REJECT_CASES: dict[str, Callable[[pathlib.Path, WriteSdist], str]] = { |
| 1073 |
'invalid-filename': _invalid_filename, |
| 1074 |
'invalid-version': _invalid_version, |
| 1075 |
'corrupt-tar': _corrupt_tar, |
| 1076 |
'multiple-top-level': _multiple_top_level, |
| 1077 |
'missing-pkg-info': _missing_pkg_info, |
| 1078 |
} |
| 1079 |
|
| 1080 |
|
| 1081 |
@pytest.mark.parametrize( |
| 1082 |
('case', 'match'), |
| 1083 |
[ |
| 1084 |
pytest.param('invalid-filename', 'does not look like a source distribution', id='invalid-filename'), |
| 1085 |
pytest.param('invalid-version', 'does not look like a source distribution', id='invalid-version'), |
| 1086 |
pytest.param('corrupt-tar', 'failed to read source distribution', id='corrupt-tar'), |
| 1087 |
pytest.param('multiple-top-level', 'single top-level directory', id='multiple-top-level'), |
| 1088 |
pytest.param('missing-pkg-info', 'does not contain demo-1.0.0/PKG-INFO', id='missing-pkg-info'), |
| 1089 |
], |
| 1090 |
) |
| 1091 |
def test_validate_sdist_archive_rejects( |
| 1092 |
tmp_path: pathlib.Path, |
| 1093 |
write_sdist: WriteSdist, |
| 1094 |
case: str, |
| 1095 |
match: str, |
| 1096 |
) -> None: |
| 1097 |
archive = _REJECT_CASES[case](tmp_path, write_sdist) |
| 1098 |
with pytest.raises(build.BuildException, match=match): |
| 1099 |
build.__main__._validate_sdist_archive(archive) |
| 1100 |
|
| 1101 |
|
| 1102 |
def test_extract_sdist_yields_top_level(sdist: pathlib.Path) -> None: |
| 1103 |
with build.__main__._extract_sdist(str(sdist), 'demo-1.0.0') as extracted: |
| 1104 |
assert os.path.isdir(extracted) |
| 1105 |
assert os.path.isfile(os.path.join(extracted, 'PKG-INFO')) |
| 1106 |
extract_root = os.path.dirname(extracted) |
| 1107 |
assert not os.path.exists(extract_root) |
| 1108 |
|
| 1109 |
|
| 1110 |
def _raise_inside_extract(sdist: pathlib.Path) -> None: |
| 1111 |
with build.__main__._extract_sdist(str(sdist), 'demo-1.0.0') as extracted: |
| 1112 |
msg = 'boom' |
| 1113 |
raise RuntimeError(msg, os.path.dirname(extracted)) |
| 1114 |
|
| 1115 |
|
| 1116 |
def test_extract_sdist_cleans_up_on_error(sdist: pathlib.Path) -> None: |
| 1117 |
with pytest.raises(RuntimeError, match='boom') as exc_info: |
| 1118 |
_raise_inside_extract(sdist) |
| 1119 |
_, extract_root = exc_info.value.args |
| 1120 |
assert not os.path.exists(extract_root) |
| 1121 |
|
| 1122 |
|
| 1123 |
def test_extract_sdist_rejects_path_traversal(tmp_path: pathlib.Path) -> None: |
| 1124 |
archive = tmp_path / 'demo-1.0.0.tar.gz' |
| 1125 |
body = b'evil\n' |
| 1126 |
with tarfile.open(archive, 'w:gz') as tar: |
| 1127 |
info = tarfile.TarInfo(name='../evil.txt') |
| 1128 |
info.size = len(body) |
| 1129 |
tar.addfile(info, io.BytesIO(body)) |
| 1130 |
|
| 1131 |
cm = build.__main__._extract_sdist(str(archive), 'demo-1.0.0') |
| 1132 |
with pytest.raises(tarfile.TarError): |
| 1133 |
cm.__enter__() |
| 1134 |
assert not (tmp_path / 'evil.txt').exists() |
| 1135 |
|
| 1136 |
|
| 1137 |
def test_extract_sdist_rejects_absolute_symlink(tmp_path: pathlib.Path) -> None: |
| 1138 |
archive = tmp_path / 'demo-1.0.0.tar.gz' |
| 1139 |
with tarfile.open(archive, 'w:gz') as tar: |
| 1140 |
info = tarfile.TarInfo(name='demo-1.0.0/evil') |
| 1141 |
info.type = tarfile.SYMTYPE |
| 1142 |
info.linkname = '/etc/passwd' |
| 1143 |
tar.addfile(info) |
| 1144 |
|
| 1145 |
cm = build.__main__._extract_sdist(str(archive), 'demo-1.0.0') |
| 1146 |
with pytest.raises(tarfile.TarError): |
| 1147 |
cm.__enter__() |
| 1148 |
|
| 1149 |
|
| 1150 |
def test_extract_sdist_fixed_dir_is_deterministic_and_kept(sdist: pathlib.Path, tmp_path: pathlib.Path) -> None: |
| 1151 |
extract_dir = tmp_path / 'extract' |
| 1152 |
with build.__main__._extract_sdist(str(sdist), 'demo-1.0.0', extract_dir=str(extract_dir)) as extracted: |
| 1153 |
assert extracted == str(extract_dir / 'demo-1.0.0') |
| 1154 |
assert os.path.isfile(os.path.join(extracted, 'PKG-INFO')) |
| 1155 |
assert (extract_dir / 'demo-1.0.0' / 'PKG-INFO').is_file() |
| 1156 |
|
| 1157 |
|
| 1158 |
def test_extract_sdist_fixed_dir_clears_stale_before_extract(sdist: pathlib.Path, tmp_path: pathlib.Path) -> None: |
| 1159 |
extract_dir = tmp_path / 'extract' |
| 1160 |
stale = extract_dir / 'demo-1.0.0' / 'stale.txt' |
| 1161 |
stale.parent.mkdir(parents=True) |
| 1162 |
stale.write_text('old', encoding='utf-8') |
| 1163 |
|
| 1164 |
with build.__main__._extract_sdist(str(sdist), 'demo-1.0.0', extract_dir=str(extract_dir)) as extracted: |
| 1165 |
assert extracted == str(extract_dir / 'demo-1.0.0') |
| 1166 |
assert not stale.exists() |
| 1167 |
assert os.path.isfile(os.path.join(extracted, 'PKG-INFO')) |
| 1168 |
|
| 1169 |
|
| 1170 |
@pytest.mark.parametrize( |
| 1171 |
('extra_args', 'expected'), |
| 1172 |
[ |
| 1173 |
pytest.param([], None, id='default-temp-dir'), |
| 1174 |
pytest.param(['--sdist-extract-dir', 'extract-here'], 'extract-here', id='fixed-dir'), |
| 1175 |
], |
| 1176 |
) |
| 1177 |
def test_main_via_sdist_forwards_extract_dir( |
| 1178 |
tmp_path: pathlib.Path, |
| 1179 |
mocker: pytest_mock.MockerFixture, |
| 1180 |
extra_args: list[str], |
| 1181 |
expected: str | None, |
| 1182 |
) -> None: |
| 1183 |
via_sdist = mocker.patch('build.__main__.build_package_via_sdist', autospec=True, return_value=['something']) |
| 1184 |
|
| 1185 |
build.__main__.main([str(tmp_path), *extra_args]) |
| 1186 |
|
| 1187 |
assert via_sdist.call_args.kwargs['sdist_extract_dir'] == expected |
| 1188 |
|
| 1189 |
|
| 1190 |
def test_main_sdist_input_forwards_extract_dir( |
| 1191 |
sdist: pathlib.Path, |
| 1192 |
tmp_path: pathlib.Path, |
| 1193 |
mocker: pytest_mock.MockerFixture, |
| 1194 |
) -> None: |
| 1195 |
extract = mocker.patch('build.__main__._extract_sdist', autospec=True) |
| 1196 |
extract.return_value.__enter__.return_value = str(tmp_path / 'demo-1.0.0') |
| 1197 |
mocker.patch('build.__main__.build_package', return_value=['demo-1.0.0-py3-none-any.whl']) |
| 1198 |
|
| 1199 |
build.__main__.main([str(sdist), '--wheel', '-o', str(tmp_path), '--sdist-extract-dir', 'extract-here']) |
| 1200 |
|
| 1201 |
assert extract.call_args.kwargs['extract_dir'] == 'extract-here' |
| 1202 |
|
| 1203 |
|
| 1204 |
@pytest.mark.parametrize( |
| 1205 |
('extra_args', 'expected_distributions', 'expected_outdir'), |
| 1206 |
[ |
| 1207 |
pytest.param([], ['wheel'], None, id='no-flag'), |
| 1208 |
pytest.param(['--wheel'], ['wheel'], None, id='wheel-long'), |
| 1209 |
pytest.param(['-w'], ['wheel'], None, id='wheel-short'), |
| 1210 |
pytest.param(['--wheel', '-o', 'custom-out'], ['wheel'], 'custom-out', id='custom-outdir'), |
| 1211 |
], |
| 1212 |
) |
| 1213 |
def test_main_sdist_input_wheel_dispatch( |
| 1214 |
sdist: pathlib.Path, |
| 1215 |
mocker: pytest_mock.MockerFixture, |
| 1216 |
extra_args: list[str], |
| 1217 |
expected_distributions: list[str], |
| 1218 |
expected_outdir: str | None, |
| 1219 |
) -> None: |
| 1220 |
build_package = mocker.patch('build.__main__.build_package', return_value=['demo-1.0.0-py3-none-any.whl']) |
| 1221 |
via_sdist = mocker.patch('build.__main__.build_package_via_sdist') |
| 1222 |
|
| 1223 |
build.__main__.main([str(sdist), *extra_args]) |
| 1224 |
|
| 1225 |
via_sdist.assert_not_called() |
| 1226 |
args, kwargs = build_package.call_args |
| 1227 |
extracted_srcdir, outdir = args |
| 1228 |
assert os.path.basename(extracted_srcdir) == 'demo-1.0.0' |
| 1229 |
assert kwargs['distributions'] == expected_distributions |
| 1230 |
expected = expected_outdir if expected_outdir is not None else os.path.dirname(os.path.abspath(sdist)) |
| 1231 |
assert outdir == expected |
| 1232 |
|
| 1233 |
|
| 1234 |
def test_main_sdist_input_metadata(sdist: pathlib.Path, mocker: pytest_mock.MockerFixture) -> None: |
| 1235 |
build_metadata = mocker.patch('build.__main__._build_metadata', return_value=[]) |
| 1236 |
|
| 1237 |
build.__main__.main([str(sdist), '--metadata']) |
| 1238 |
|
| 1239 |
args, kwargs = build_metadata.call_args |
| 1240 |
extracted_srcdir, _outdir = args |
| 1241 |
assert os.path.basename(extracted_srcdir) == 'demo-1.0.0' |
| 1242 |
assert kwargs['distributions'] == ['wheel'] |
| 1243 |
|
| 1244 |
|
| 1245 |
@pytest.mark.parametrize( |
| 1246 |
'flags', |
| 1247 |
[ |
| 1248 |
pytest.param(['--sdist'], id='sdist-only'), |
| 1249 |
pytest.param(['--sdist', '--wheel'], id='sdist-and-wheel'), |
| 1250 |
], |
| 1251 |
) |
| 1252 |
def test_main_sdist_input_rejects_sdist_flag( |
| 1253 |
sdist: pathlib.Path, |
| 1254 |
capsys: pytest.CaptureFixture[str], |
| 1255 |
flags: list[str], |
| 1256 |
) -> None: |
| 1257 |
with pytest.raises(SystemExit): |
| 1258 |
build.__main__.main([str(sdist), *flags]) |
| 1259 |
assert 'cannot build a source distribution from a source distribution' in capsys.readouterr().err |
| 1260 |
|
| 1261 |
|
| 1262 |
def test_main_sdist_input_validation_error_surfaced( |
| 1263 |
tmp_path: pathlib.Path, |
| 1264 |
write_sdist: WriteSdist, |
| 1265 |
capsys: pytest.CaptureFixture[str], |
| 1266 |
) -> None: |
| 1267 |
archive = tmp_path / 'demo-1.0.0.tar.gz' |
| 1268 |
write_sdist(archive, 'demo-1.0.0', with_pkg_info=False) |
| 1269 |
|
| 1270 |
with pytest.raises(SystemExit): |
| 1271 |
build.__main__.main([str(archive), '--wheel']) |
| 1272 |
|
| 1273 |
assert 'PKG-INFO' in capsys.readouterr().err |
| 1274 |
|
| 1275 |
|
| 1276 |
def test_main_sdist_input_passes_kwargs(sdist: pathlib.Path, mocker: pytest_mock.MockerFixture) -> None: |
| 1277 |
build_package = mocker.patch('build.__main__.build_package', return_value=['demo-1.0.0-py3-none-any.whl']) |
| 1278 |
|
| 1279 |
build.__main__.main([str(sdist), '--wheel', '-n', '-x', '-Cflag=value']) |
| 1280 |
|
| 1281 |
_args, kwargs = build_package.call_args |
| 1282 |
assert kwargs['isolation'] is False |
| 1283 |
assert kwargs['skip_dependency_check'] is True |
| 1284 |
assert kwargs['config_settings'] == {'flag': 'value'} |
| 1285 |
assert kwargs['installer'] == 'pip' |
| 1286 |
|
| 1287 |
|
| 1288 |
def test_main_sdist_input_end_to_end(tmp_path: pathlib.Path, package_test_setuptools: str) -> None: |
| 1289 |
sdist_dir = tmp_path / 'dist' |
| 1290 |
sdist_dir.mkdir() |
| 1291 |
build.__main__.build_package(package_test_setuptools, str(sdist_dir), ['sdist']) |
| 1292 |
archive = next(sdist_dir.glob('*.tar.gz')) |
| 1293 |
|
| 1294 |
out_dir = tmp_path / 'out' |
| 1295 |
build.__main__.main([str(archive), '--wheel', '-n', '-o', str(out_dir)]) |
| 1296 |
|
| 1297 |
wheels = list(out_dir.glob('*.whl')) |
| 1298 |
assert len(wheels) == 1 |
| 1299 |
assert wheels[0].name.startswith('test_setuptools-1.0.0') |
| 1300 |
|
| 1301 |
|
| 1302 |
def test_main_sdist_input_default_outdir_is_archive_parent( |
| 1303 |
tmp_path: pathlib.Path, |
| 1304 |
sdist: pathlib.Path, |
| 1305 |
mocker: pytest_mock.MockerFixture, |
| 1306 |
) -> None: |
| 1307 |
build_package = mocker.patch('build.__main__.build_package', return_value=['demo-1.0.0-py3-none-any.whl']) |
| 1308 |
|
| 1309 |
build.__main__.main([str(sdist)]) |
| 1310 |
|
| 1311 |
_, outdir = build_package.call_args.args |
| 1312 |
assert outdir == str(tmp_path) |
| 1313 |
|
| 1314 |
|
| 1315 |
def test_main_non_archive_file_treated_as_directory(tmp_path: pathlib.Path, mocker: pytest_mock.MockerFixture) -> None: |
| 1316 |
archive = tmp_path / 'demo-1.0.0.zip' |
| 1317 |
archive.write_bytes(b'') |
| 1318 |
via_sdist = mocker.patch('build.__main__.build_package_via_sdist', return_value=['something']) |
| 1319 |
|
| 1320 |
build.__main__.main([str(archive)]) |
| 1321 |
|
| 1322 |
via_sdist.assert_called_once() |
| 1323 |
|
| 1324 |
|
| 1325 |
@pytest.fixture |
| 1326 |
def built_dist(tmp_path: pathlib.Path) -> tuple[pathlib.Path, list[str]]: |
| 1327 |
outdir = tmp_path / 'dist' |
| 1328 |
outdir.mkdir() |
| 1329 |
names = ['test_pkg-1.0.0.tar.gz', 'test_pkg-1.0.0-py3-none-any.whl'] |
| 1330 |
for name in names: |
| 1331 |
(outdir / name).write_bytes(f'contents of {name}'.encode()) |
| 1332 |
return outdir, names |
| 1333 |
|
| 1334 |
|
| 1335 |
def test_report_written( |
| 1336 |
mocker: pytest_mock.MockerFixture, |
| 1337 |
tmp_path: pathlib.Path, |
| 1338 |
built_dist: tuple[pathlib.Path, list[str]], |
| 1339 |
) -> None: |
| 1340 |
outdir, names = built_dist |
| 1341 |
mocker.patch('build.__main__.build_package_via_sdist', autospec=True, return_value=names) |
| 1342 |
report = tmp_path / 'report.json' |
| 1343 |
|
| 1344 |
build.__main__.main([str(tmp_path), '-o', str(outdir), '--report', str(report)]) |
| 1345 |
|
| 1346 |
payload = json.loads(report.read_text(encoding='utf-8')) |
| 1347 |
assert payload['version'] == '1.0' |
| 1348 |
assert [artifact['name'] for artifact in payload['artifacts']] == names |
| 1349 |
for artifact, name in zip(payload['artifacts'], names, strict=True): |
| 1350 |
path = outdir / name |
| 1351 |
assert artifact['path'] == os.path.join(str(outdir), name) |
| 1352 |
assert artifact['kind'] == ('sdist' if name.endswith('.tar.gz') else 'wheel') |
| 1353 |
assert artifact['size'] == path.stat().st_size |
| 1354 |
assert artifact['hashes'] == {'sha256': hashlib.sha256(path.read_bytes()).hexdigest()} |
| 1355 |
|
| 1356 |
|
| 1357 |
def test_report_requires_path(capsys: pytest.CaptureFixture[str]) -> None: |
| 1358 |
with pytest.raises(SystemExit): |
| 1359 |
build.__main__.main(['--report']) |
| 1360 |
|
| 1361 |
assert '--report: expected one argument' in capsys.readouterr().err |
| 1362 |
|
| 1363 |
|
| 1364 |
def test_write_report_is_atomic(tmp_path: pathlib.Path, built_dist: tuple[pathlib.Path, list[str]]) -> None: |
| 1365 |
outdir, names = built_dist |
| 1366 |
report = tmp_path / 'report.json' |
| 1367 |
|
| 1368 |
build.__main__._write_report(report, str(outdir), names) |
| 1369 |
|
| 1370 |
assert not list(tmp_path.glob('*.tmp')) |
| 1371 |
assert not list(outdir.glob('*.tmp')) |
| 1372 |
|
| 1373 |
|
| 1374 |
def test_write_report_cleans_tmp_on_failure( |
| 1375 |
mocker: pytest_mock.MockerFixture, tmp_path: pathlib.Path, built_dist: tuple[pathlib.Path, list[str]] |
| 1376 |
) -> None: |
| 1377 |
outdir, names = built_dist |
| 1378 |
mocker.patch('build.__main__.os.replace', side_effect=OSError('boom')) |
| 1379 |
|
| 1380 |
with pytest.raises(OSError, match='boom'): |
| 1381 |
build.__main__._write_report(tmp_path / 'report.json', str(outdir), names) |
| 1382 |
|
| 1383 |
assert not list(tmp_path.glob('*.tmp')) |
| 1384 |
|
| 1385 |
|
| 1386 |
def test_report_not_allowed_with_metadata(capsys: pytest.CaptureFixture[str]) -> None: |
| 1387 |
with pytest.raises(SystemExit): |
| 1388 |
build.__main__.main(['--report', 'r.json', '--metadata']) |
| 1389 |
|
| 1390 |
assert '--report: not allowed with --metadata' in capsys.readouterr().err |
| 1391 |
|
| 1392 |
|
| 1393 |
@pytest.fixture |
| 1394 |
def wheel(tmp_path: pathlib.Path) -> pathlib.Path: |
| 1395 |
path = tmp_path / 'demo-1.0.0-py3-none-any.whl' |
| 1396 |
with zipfile.ZipFile(path, 'w') as archive: |
| 1397 |
archive.writestr('demo-1.0.0.dist-info/METADATA', 'Metadata-Version: 2.1\nName: demo\nVersion: 1.0.0\n\n') |
| 1398 |
return path |
| 1399 |
|
| 1400 |
|
| 1401 |
def test_metadata_read_from_wheel(wheel: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: |
| 1402 |
build.__main__.main([str(wheel), '--metadata']) |
| 1403 |
|
| 1404 |
metadata = json.loads(capsys.readouterr().out) |
| 1405 |
assert metadata['name'] == 'demo' |
| 1406 |
assert metadata['version'] == '1.0.0' |
| 1407 |
|
| 1408 |
|
| 1409 |
def test_wheel_input_requires_metadata(wheel: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: |
| 1410 |
with pytest.raises(SystemExit): |
| 1411 |
build.__main__.main([str(wheel)]) |
| 1412 |
|
| 1413 |
assert 'a wheel can only be used with --metadata' in capsys.readouterr().err |
| 1414 |
|
| 1415 |
|
| 1416 |
def test_metadata_from_wheel_without_dist_info(tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str]) -> None: |
| 1417 |
path = tmp_path / 'broken-1.0.0-py3-none-any.whl' |
| 1418 |
with zipfile.ZipFile(path, 'w') as archive: |
| 1419 |
archive.writestr('demo/__init__.py', '') |
| 1420 |
|
| 1421 |
with pytest.raises(SystemExit): |
| 1422 |
build.__main__.main([str(path), '--metadata']) |
| 1423 |
|
| 1424 |
assert 'is not a valid wheel' in capsys.readouterr().err |