Debian Codegraph @

tests/test_projectbuilder.py

raw
1 # SPDX-License-Identifier: MIT
2
3 from __future__ import annotations
4
5 import copy
6 import logging
7 import os
8 import pathlib
9 import sys
10 import textwrap
11 import typing
12 import zipfile
13
14 from collections.abc import Callable
15 from typing import TYPE_CHECKING, NoReturn
16
17 import pyproject_hooks
18 import pytest
19 import pytest_mock
20
21 import build
22 import build._builder
23
24 from build._compat import importlib as _importlib
25
26
27 if TYPE_CHECKING:
28 from collections.abc import Mapping
29
30 from build._builder import BuildSystemTable, TOMLValue
31
32
33 build_open_owner = 'builtins'
34
35
36 DEFAULT_BACKEND = {
37 'build-backend': 'setuptools.build_meta:__legacy__',
38 'requires': ['setuptools >= 40.8.0'],
39 }
40
41
42 class MockDistribution(_importlib.metadata.Distribution):
43 _metadata: str = ''
44
45 def locate_file(self, path: str | os.PathLike[str]) -> _importlib.metadata.SimplePath: # pragma: no cover
46 raise NotImplementedError
47
48 def read_text(self, filename: str) -> str:
49 if filename == 'METADATA':
50 return self._metadata
51 return ''
52
53 @classmethod
54 def from_name(cls, name: str) -> MockDistribution:
55 registry: dict[str, type[MockDistribution]] = {
56 'extras_dep': ExtraMockDistribution,
57 'requireless_dep': RequirelessMockDistribution,
58 'recursive_dep': RecursiveMockDistribution,
59 'prerelease_dep': PrereleaseMockDistribution,
60 'circular_dep': CircularMockDistribution,
61 'nested_circular_dep': NestedCircularMockDistribution,
62 }
63 if (dist_cls := registry.get(name)) is not None:
64 return dist_cls()
65 raise _importlib.metadata.PackageNotFoundError
66
67
68 class ExtraMockDistribution(MockDistribution):
69 _metadata = textwrap.dedent("""\
70 Metadata-Version: 2.2
71 Name: extras_dep
72 Version: 1.0.0
73 Provides-Extra: extra-without-associated-deps
74 Provides-Extra: extra-with_unmet-deps
75 Requires-Dist: unmet_dep; extra == 'extra-with-unmet-deps'
76 Provides-Extra: extra-with-met-deps
77 Requires-Dist: extras_dep; extra == 'extra-with-met-deps'
78 Provides-Extra: recursive-extra-with-unmet-deps
79 Requires-Dist: recursive_dep; extra == 'recursive-extra-with-unmet-deps'""")
80
81
82 class RequirelessMockDistribution(MockDistribution):
83 _metadata = textwrap.dedent("""\
84 Metadata-Version: 2.2
85 Name: requireless_dep
86 Version: 1.0.0""")
87
88
89 class RecursiveMockDistribution(MockDistribution):
90 _metadata = textwrap.dedent("""\
91 Metadata-Version: 2.2
92 Name: recursive_dep
93 Version: 1.0.0
94 Requires-Dist: recursive_unmet_dep""")
95
96
97 class PrereleaseMockDistribution(MockDistribution):
98 _metadata = textwrap.dedent("""\
99 Metadata-Version: 2.2
100 Name: prerelease_dep
101 Version: 1.0.1a0""")
102
103
104 class CircularMockDistribution(MockDistribution):
105 _metadata = textwrap.dedent("""\
106 Metadata-Version: 2.2
107 Name: circular_dep
108 Version: 1.0.0
109 Requires-Dist: nested_circular_dep""")
110
111
112 class NestedCircularMockDistribution(MockDistribution):
113 _metadata = textwrap.dedent("""\
114 Metadata-Version: 2.2
115 Name: nested_circular_dep
116 Version: 1.0.0
117 Requires-Dist: circular_dep""")
118
119
120 @pytest.mark.parametrize(
121 ('requirement_string', 'expected'),
122 [
123 ('extras_dep', None),
124 ('missing_dep', ('missing_dep',)),
125 ('requireless_dep', None),
126 ('extras_dep[undefined_extra]', None),
127 # would the wheel builder filter this out?
128 ('extras_dep[extra-without-associated-deps]', None),
129 (
130 'extras_dep[extra-with-unmet-deps]',
131 ('extras_dep[extra-with-unmet-deps]', 'unmet_dep; extra == "extra-with-unmet-deps"'),
132 ),
133 (
134 'extras_dep[recursive-extra-with-unmet-deps]',
135 (
136 'extras_dep[recursive-extra-with-unmet-deps]',
137 'recursive_dep; extra == "recursive-extra-with-unmet-deps"',
138 'recursive_unmet_dep',
139 ),
140 ),
141 ('extras_dep[extra-with-met-deps]', None),
142 ('missing_dep; python_version>"10"', None),
143 ('missing_dep; python_version<="1"', None),
144 ('missing_dep; python_version>="1"', ('missing_dep; python_version >= "1"',)),
145 ('extras_dep == 1.0.0', None),
146 ('extras_dep == 2.0.0', ('extras_dep==2.0.0',)),
147 ('extras_dep[extra-without-associated-deps] == 1.0.0', None),
148 ('extras_dep[extra-without-associated-deps] == 2.0.0', ('extras_dep[extra-without-associated-deps]==2.0.0',)),
149 ('prerelease_dep >= 1.0.0', None),
150 ('circular_dep', None),
151 ],
152 )
153 def test_check_dependency(monkeypatch: pytest.MonkeyPatch, requirement_string: str, expected: tuple[str, ...] | None) -> None:
154 monkeypatch.setattr(_importlib.metadata, 'Distribution', MockDistribution)
155 assert next(build.check_dependency(requirement_string), None) == expected
156
157
158 def test_check_dependency_diamond_visits_each_once(monkeypatch: pytest.MonkeyPatch) -> None:
159 # A→B,C; B→D; C→D. The shared subtree (D) must be verified at most once,
160 # not once per path, otherwise dense graphs blow up exponentially.
161 graph = {
162 'diamond_a': 'Requires-Dist: diamond_b\nRequires-Dist: diamond_c',
163 'diamond_b': 'Requires-Dist: diamond_d',
164 'diamond_c': 'Requires-Dist: diamond_d',
165 'diamond_d': '',
166 }
167 lookups: dict[str, int] = {}
168
169 class DiamondDistribution(MockDistribution):
170 _name = ''
171
172 def read_text(self, filename: str) -> str:
173 if filename == 'METADATA':
174 return f'Metadata-Version: 2.2\nName: {self._name}\nVersion: 1.0.0\n{graph[self._name]}'
175 return ''
176
177 @classmethod
178 def from_name(cls, name: str) -> DiamondDistribution:
179 # everything looked up is in the graph, so no not-found branch needed
180 lookups[name] = lookups.get(name, 0) + 1
181 dist = cls()
182 dist._name = name
183 return dist
184
185 monkeypatch.setattr(_importlib.metadata, 'Distribution', DiamondDistribution)
186
187 assert list(build.check_dependency('diamond_a')) == []
188 assert lookups == {'diamond_a': 1, 'diamond_b': 1, 'diamond_c': 1, 'diamond_d': 1}
189
190
191 @pytest.mark.parametrize(
192 ('requirement_string', 'expected'),
193 [
194 ('extras_dep == 2.0.0', [('extras_dep==2.0.0',)]),
195 ('recursive_dep', [('recursive_dep', 'recursive_unmet_dep')]),
196 ],
197 )
198 def test_check_dependency_exhausted(
199 monkeypatch: pytest.MonkeyPatch, requirement_string: str, expected: list[tuple[str, ...]]
200 ) -> None:
201 # Unlike ``next``-based checks, exhausting the generator runs the code past
202 # each yield, including the unsatisfied-subtree exit.
203 monkeypatch.setattr(_importlib.metadata, 'Distribution', MockDistribution)
204 assert list(build.check_dependency(requirement_string)) == expected
205
206
207 def test_bad_project(package_test_no_project: str) -> None:
208 # Passing a nonexistent project directory
209 with pytest.raises(build.BuildException):
210 build.ProjectBuilder(os.path.join(package_test_no_project, 'does-not-exist'))
211 # Passing a file as a project directory
212 with pytest.raises(build.BuildException):
213 build.ProjectBuilder(os.path.join(package_test_no_project, 'empty.txt'))
214 # Passing a project directory with no pyproject.toml or setup.py
215 with pytest.raises(build.BuildException):
216 build.ProjectBuilder(package_test_no_project)
217
218
219 def test_init(
220 mocker: pytest_mock.MockerFixture,
221 package_test_flit: str,
222 package_legacy: str,
223 package_test_bad_syntax: str,
224 ) -> None:
225 mock_buildcaller = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True)
226
227 # correct flit pyproject.toml
228 builder = build.ProjectBuilder(package_test_flit)
229 mock_buildcaller.assert_called_with(
230 package_test_flit, 'flit_core.buildapi', backend_path=None, python_executable=sys.executable, runner=builder._runner
231 )
232 mock_buildcaller.reset_mock()
233
234 # custom python
235 builder = build.ProjectBuilder(package_test_flit, python_executable='some-python')
236 assert builder.python_executable == 'some-python'
237 mock_buildcaller.assert_called_with(
238 package_test_flit, 'flit_core.buildapi', backend_path=None, python_executable='some-python', runner=builder._runner
239 )
240 mock_buildcaller.reset_mock()
241
242 # FileNotFoundError
243 builder = build.ProjectBuilder(package_legacy)
244 mock_buildcaller.assert_called_with(
245 package_legacy,
246 'setuptools.build_meta:__legacy__',
247 backend_path=None,
248 python_executable=sys.executable,
249 runner=builder._runner,
250 )
251
252 # TomlDecodeError
253 with pytest.raises(build.BuildException):
254 build.ProjectBuilder(package_test_bad_syntax)
255
256
257 @pytest.mark.skipif(sys.platform.startswith('win'), reason="can't correctly set the permissions required for this")
258 def test_init_permission_error(test_no_permission: str) -> None: # pragma: win32 no cover
259 with pytest.raises(build.BuildException):
260 build.ProjectBuilder(test_no_permission)
261
262
263 def test_init_makes_source_dir_absolute(package_test_flit: str) -> None:
264 rel_dir = os.path.relpath(package_test_flit, os.getcwd())
265 assert not os.path.isabs(rel_dir)
266 builder = build.ProjectBuilder(rel_dir)
267 assert os.path.isabs(builder.source_dir)
268
269
270 @pytest.mark.parametrize('distribution', ['wheel', 'sdist'])
271 def test_get_requires_for_build_missing_backend(
272 packages_path: str, distribution: typing.Literal['sdist', 'wheel', 'editable']
273 ) -> None:
274 bad_backend_path = os.path.join(packages_path, 'test-bad-backend')
275 builder = build.ProjectBuilder(bad_backend_path)
276
277 with pytest.raises(build.BuildBackendException):
278 builder.get_requires_for_build(distribution)
279
280
281 @pytest.mark.parametrize('distribution', ['wheel', 'sdist'])
282 def test_get_requires_for_build_missing_optional_hooks(
283 package_test_optional_hooks: str, distribution: typing.Literal['sdist', 'wheel', 'editable']
284 ) -> None:
285 builder = build.ProjectBuilder(package_test_optional_hooks)
286
287 assert builder.get_requires_for_build(distribution) == set()
288
289
290 @pytest.mark.parametrize('distribution', ['wheel', 'sdist'])
291 def test_build_missing_backend(
292 packages_path: str, distribution: typing.Literal['sdist', 'wheel', 'editable'], tmpdir: str
293 ) -> None:
294 bad_backend_path = os.path.join(packages_path, 'test-bad-backend')
295 builder = build.ProjectBuilder(bad_backend_path)
296
297 with pytest.raises(build.BuildBackendException):
298 builder.build(distribution, str(tmpdir))
299
300
301 def _nothing_installed(name: str) -> NoReturn:
302 raise _importlib.metadata.PackageNotFoundError(name)
303
304
305 def test_check_dependencies(
306 mocker: pytest_mock.MockerFixture, package_test_flit: str, monkeypatch: pytest.MonkeyPatch
307 ) -> None:
308 get_requires_sdist = mocker.patch('pyproject_hooks.BuildBackendHookCaller.get_requires_for_build_sdist')
309 get_requires_wheel = mocker.patch('pyproject_hooks.BuildBackendHookCaller.get_requires_for_build_wheel')
310
311 monkeypatch.setattr(_importlib.metadata, 'distribution', _nothing_installed)
312
313 builder = build.ProjectBuilder(package_test_flit)
314
315 side_effects = [
316 [],
317 ['something'],
318 pyproject_hooks.BackendUnavailable,
319 ]
320
321 get_requires_sdist.side_effect = copy.copy(side_effects)
322 get_requires_wheel.side_effect = copy.copy(side_effects)
323
324 # requires = []
325 assert builder.check_dependencies('sdist') == {('flit_core<4,>=2',)}
326 assert builder.check_dependencies('wheel') == {('flit_core<4,>=2',)}
327
328 # requires = ['something']
329 assert builder.check_dependencies('sdist') == {('flit_core<4,>=2',), ('something',)}
330 assert builder.check_dependencies('wheel') == {('flit_core<4,>=2',), ('something',)}
331
332 # BackendUnavailable
333 with pytest.raises(build.BuildBackendException):
334 builder.check_dependencies('sdist')
335 with pytest.raises(build.BuildBackendException):
336 not builder.check_dependencies('wheel')
337
338
339 def test_build(mocker: pytest_mock.MockerFixture, package_test_flit: str, tmp_dir: str) -> None:
340 hook = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True).return_value
341
342 builder = build.ProjectBuilder(package_test_flit)
343
344 hook.build_sdist.side_effect = ['dist.tar.gz', Exception]
345 hook.build_wheel.side_effect = ['dist.whl', Exception]
346
347 assert builder.build('sdist', tmp_dir) == os.path.join(tmp_dir, 'dist.tar.gz')
348 hook.build_sdist.assert_called_with(tmp_dir, None)
349
350 assert builder.build('wheel', tmp_dir) == os.path.join(tmp_dir, 'dist.whl')
351 hook.build_wheel.assert_called_with(tmp_dir, None)
352
353 with pytest.raises(build.BuildBackendException):
354 builder.build('sdist', tmp_dir)
355
356 with pytest.raises(build.BuildBackendException):
357 builder.build('wheel', tmp_dir)
358
359
360 def test_default_backend(mocker: pytest_mock.MockerFixture, package_legacy: str) -> None:
361 mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True)
362
363 builder = build.ProjectBuilder(package_legacy)
364
365 assert builder._build_system == DEFAULT_BACKEND
366
367
368 def test_missing_backend(mocker: pytest_mock.MockerFixture, package_test_no_backend: str) -> None:
369 mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True)
370
371 builder = build.ProjectBuilder(package_test_no_backend)
372
373 assert builder._build_system == {'requires': [], 'build-backend': DEFAULT_BACKEND['build-backend']}
374
375
376 def test_missing_requires(mocker: pytest_mock.MockerFixture, package_test_no_requires: str) -> None:
377 mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True)
378
379 with pytest.raises(build.BuildException):
380 build.ProjectBuilder(package_test_no_requires)
381
382
383 def test_build_system_typo(mocker: pytest_mock.MockerFixture, package_test_typo: str) -> None:
384 mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True)
385
386 with pytest.warns(build.TypoWarning):
387 build.ProjectBuilder(package_test_typo)
388
389
390 def test_missing_outdir(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
391 hook = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True).return_value
392
393 builder = build.ProjectBuilder(package_test_flit)
394 hook.build_sdist.return_value = 'dist.tar.gz'
395 out = os.path.join(tmp_dir, 'out')
396
397 builder.build('sdist', out)
398
399 assert os.path.isdir(out)
400
401
402 def test_relative_outdir(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None: # noqa: ARG001
403 hook = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True).return_value
404
405 builder = build.ProjectBuilder(package_test_flit)
406 hook.build_sdist.return_value = 'dist.tar.gz'
407
408 builder.build('sdist', '.')
409
410 hook.build_sdist.assert_called_with(os.path.abspath('.'), None)
411
412
413 def test_build_not_dir_outdir(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
414 hook = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True).return_value
415
416 builder = build.ProjectBuilder(package_test_flit)
417 hook.build_sdist.return_value = 'dist.tar.gz'
418 out = os.path.join(tmp_dir, 'out')
419
420 open(out, 'a', encoding='utf-8').close() # create empty file
421
422 with pytest.raises(build.BuildException):
423 builder.build('sdist', out)
424
425
426 @pytest.fixture(scope='session')
427 def demo_pkg_inline(tmp_path_factory: pytest.TempPathFactory) -> pathlib.Path:
428 # builds a wheel without any dependencies and with a console script demo-pkg-inline
429 tmp_path = tmp_path_factory.mktemp('demo-pkg-inline')
430 builder = build.ProjectBuilder(source_dir=os.path.join(os.path.dirname(__file__), 'packages', 'inline'))
431 out = tmp_path / 'dist'
432 builder.build('wheel', str(out))
433 return next(out.iterdir())
434
435
436 @pytest.mark.contextvars
437 @pytest.mark.isolated
438 def test_build_with_dep_on_console_script(
439 tmp_path: pathlib.Path, demo_pkg_inline: pathlib.Path, capfd: pytest.CaptureFixture[str], mocker: pytest_mock.MockerFixture
440 ) -> None:
441 """All command-line scripts provided by the build-required packages must be present in the build environment's PATH."""
442 # we first install demo pkg inline as build dependency (as this provides a console script we can check)
443 # to validate backend invocations contain the correct path we use an inline backend that will fail, but first
444 # provides the PATH information (and validates shutil.which is able to discover the executable - as PEP states)
445 toml = textwrap.dedent(
446 """
447 [build-system]
448 requires = ["demo_pkg_inline"]
449 build-backend = "build"
450 backend-path = ["."]
451
452 [project]
453 description = "Factory ⸻ A code generator 🏭"
454 authors = [{name = "Łukasz Langa"}]
455 """
456 )
457 code = textwrap.dedent(
458 """
459 import os
460 import shutil
461 import sys
462 print("BB " + os.environ["PATH"])
463 exe_at = shutil.which("demo-pkg-inline")
464 print("BB " + exe_at)
465 """
466 )
467 (tmp_path / 'pyproject.toml').write_text(toml, encoding='UTF-8')
468 (tmp_path / 'build.py').write_text(code, encoding='utf-8')
469
470 deps = {str(demo_pkg_inline)} # we patch the requires demo_pkg_inline to refer to the wheel -> we don't need index
471 mocker.patch('build.ProjectBuilder.build_system_requires', new_callable=mocker.PropertyMock, return_value=deps)
472 from build.__main__ import main
473
474 with pytest.raises(SystemExit):
475 main(['--wheel', '--outdir', str(tmp_path / 'dist'), str(tmp_path)])
476
477 out, _ = capfd.readouterr()
478 lines = [line[3:] for line in out.splitlines() if line.startswith('BB ')] # filter for our markers
479 path_vars = lines[0].split(os.pathsep)
480 which_detected = lines[1]
481 assert which_detected.startswith(path_vars[0]), out
482
483
484 def test_prepare(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
485 hook = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True).return_value
486
487 builder = build.ProjectBuilder(package_test_flit)
488 hook.prepare_metadata_for_build_wheel.return_value = 'dist-1.0.dist-info'
489
490 assert builder.prepare('wheel', tmp_dir) == os.path.join(tmp_dir, 'dist-1.0.dist-info')
491 hook.prepare_metadata_for_build_wheel.assert_called_with(tmp_dir, None, _allow_fallback=False)
492
493
494 def test_prepare_no_hook(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
495 hook = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True).return_value
496
497 builder = build.ProjectBuilder(package_test_flit)
498 failure = pyproject_hooks.HookMissing('prepare_metadata_for_build_wheel')
499 hook.prepare_metadata_for_build_wheel.side_effect = failure
500
501 assert builder.prepare('wheel', tmp_dir) is None
502
503
504 def test_prepare_error(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
505 hook = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True).return_value
506
507 builder = build.ProjectBuilder(package_test_flit)
508 hook.prepare_metadata_for_build_wheel.side_effect = Exception
509
510 with pytest.raises(build.BuildBackendException, match='Backend operation failed: Exception'):
511 builder.prepare('wheel', tmp_dir)
512
513
514 def test_prepare_not_dir_outdir(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
515 mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True)
516
517 builder = build.ProjectBuilder(package_test_flit)
518
519 out = os.path.join(tmp_dir, 'out')
520 with open(out, 'w', encoding='utf-8') as f:
521 f.write('Not a directory')
522 with pytest.raises(build.BuildException, match=r'Build path .* exists and is not a directory'):
523 builder.prepare('wheel', out)
524
525
526 def test_prepare_not_dir_parent_outdir(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
527 mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True)
528
529 builder = build.ProjectBuilder(package_test_flit)
530
531 parent = os.path.join(tmp_dir, 'parent')
532 with open(parent, 'w', encoding='utf-8') as f:
533 f.write('Not a directory')
534 with pytest.raises(build.BuildException, match=r'Build path .* does not exist and cannot be a directory'):
535 builder.prepare('wheel', os.path.join(parent, 'out'))
536
537
538 def test_no_outdir_single(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
539 mocker.patch('pyproject_hooks.BuildBackendHookCaller.prepare_metadata_for_build_wheel', return_value='')
540
541 builder = build.ProjectBuilder(package_test_flit)
542
543 out = os.path.join(tmp_dir, 'out')
544 builder.prepare('wheel', out)
545
546 assert os.path.isdir(out)
547
548
549 def test_no_outdir_multiple(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
550 mocker.patch('pyproject_hooks.BuildBackendHookCaller.prepare_metadata_for_build_wheel', return_value='')
551
552 builder = build.ProjectBuilder(package_test_flit)
553
554 out = os.path.join(tmp_dir, 'does', 'not', 'exist')
555 builder.prepare('wheel', out)
556
557 assert os.path.isdir(out)
558
559
560 def test_runner_user_specified(tmp_dir: str, package_test_flit: str) -> None:
561 def dummy_runner(
562 cmd: typing.Sequence[str], # noqa: ARG001
563 cwd: str | None = None, # noqa: ARG001
564 extra_environ: typing.Mapping[str, str] | None = None, # noqa: ARG001
565 ) -> None:
566 msg = 'Runner was called'
567 raise RuntimeError(msg)
568
569 builder = build.ProjectBuilder(package_test_flit, runner=dummy_runner)
570 with pytest.raises(build.BuildBackendException, match='Runner was called'):
571 builder.build('wheel', tmp_dir)
572
573
574 def test_metadata_path_no_prepare(tmp_dir: str, package_test_no_prepare: str) -> None:
575 builder = build.ProjectBuilder(package_test_no_prepare)
576
577 metadata = _importlib.metadata.PathDistribution(
578 pathlib.Path(builder.metadata_path(tmp_dir)),
579 ).metadata
580 assert metadata is not None
581
582 assert metadata['name'] == 'test-no-prepare'
583 assert metadata['Version'] == '1.0.0'
584
585
586 def test_metadata_path_with_prepare(tmp_dir: str, package_test_setuptools: str) -> None:
587 builder = build.ProjectBuilder(package_test_setuptools)
588
589 metadata = _importlib.metadata.PathDistribution(
590 pathlib.Path(builder.metadata_path(tmp_dir)),
591 ).metadata
592 assert metadata is not None
593
594 # Setuptools < v69.0.3 (https://github.com/pypa/setuptools/pull/4159) normalized this to dashes
595 assert metadata['name'].replace('-', '_') == 'test_setuptools'
596 assert metadata['Version'] == '1.0.0'
597
598
599 def test_metadata_path_legacy(tmp_dir: str, package_legacy: str) -> None:
600 builder = build.ProjectBuilder(package_legacy)
601
602 metadata = _importlib.metadata.PathDistribution(
603 pathlib.Path(builder.metadata_path(tmp_dir)),
604 ).metadata
605 assert metadata is not None
606
607 assert metadata['name'] == 'legacy'
608 assert metadata['Version'] == '1.0.0'
609
610
611 def test_metadata_invalid_wheel(tmp_dir: str, package_test_bad_wheel: str) -> None:
612 builder = build.ProjectBuilder(package_test_bad_wheel)
613
614 with pytest.raises(build.BuildException, match='Invalid wheel'):
615 builder.metadata_path(tmp_dir)
616
617
618 @pytest.mark.parametrize('distinfo_dirs', [[], ['foo-1.0.dist-info', 'bar-2.0.dist-info']], ids=['zero', 'two'])
619 def test_metadata_path_ambiguous_dist_info(
620 mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str, distinfo_dirs: list[str]
621 ) -> None:
622 # A wheel must contain exactly one dist-info directory; anything else is rejected.
623 hook = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True).return_value
624
625 builder = build.ProjectBuilder(package_test_flit)
626 hook.prepare_metadata_for_build_wheel.side_effect = pyproject_hooks.HookMissing('prepare_metadata_for_build_wheel')
627
628 wheel_name = 'foo-1.0-py3-none-any.whl'
629
630 def fake_build_wheel(outdir: str, config_settings: Mapping[str, str] | None = None) -> str: # noqa: ARG001
631 with zipfile.ZipFile(os.path.join(outdir, wheel_name), 'w') as zf:
632 zf.writestr('foo/__init__.py', '')
633 for distinfo_dir in distinfo_dirs:
634 zf.writestr(f'{distinfo_dir}/METADATA', 'Metadata-Version: 2.1\n')
635 return wheel_name
636
637 hook.build_wheel.side_effect = fake_build_wheel
638
639 with pytest.raises(build.BuildException, match='Invalid wheel'):
640 builder.metadata_path(tmp_dir)
641
642
643 def test_metadata_path_no_prepare_build_tag(mocker: pytest_mock.MockerFixture, tmp_dir: str, package_test_flit: str) -> None:
644 # Regression test for a wheel filename with a build tag (e.g. ``foo-1.0-1-py3-none-any.whl``):
645 # the dist-info directory name must be read from the wheel's contents, not guessed from the
646 # (ambiguous) filename, since ``-1`` could be parsed as either the build tag or part of the version.
647 hook = mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True).return_value
648
649 builder = build.ProjectBuilder(package_test_flit)
650 hook.prepare_metadata_for_build_wheel.side_effect = pyproject_hooks.HookMissing('prepare_metadata_for_build_wheel')
651
652 wheel_name = 'foo-1.0-1-py3-none-any.whl'
653
654 def fake_build_wheel(outdir: str, config_settings: Mapping[str, str] | None = None) -> str: # noqa: ARG001
655 with zipfile.ZipFile(os.path.join(outdir, wheel_name), 'w') as zf:
656 zf.writestr('foo-1.0.dist-info/METADATA', 'Metadata-Version: 2.1\nName: foo\nVersion: 1.0\n')
657 zf.writestr('foo/__init__.py', '')
658 return wheel_name
659
660 hook.build_wheel.side_effect = fake_build_wheel
661
662 metadata_dir = builder.metadata_path(tmp_dir)
663
664 assert os.path.basename(metadata_dir) == 'foo-1.0.dist-info'
665 assert os.path.isdir(metadata_dir)
666 assert os.path.isfile(os.path.join(metadata_dir, 'METADATA'))
667
668
669 def test_log(mocker: pytest_mock.MockerFixture, caplog: pytest.LogCaptureFixture, package_test_flit: str) -> None:
670 mocker.patch('pyproject_hooks.BuildBackendHookCaller', autospec=True)
671 mocker.patch('build.ProjectBuilder._call_backend', return_value='some_path')
672 caplog.set_level(logging.DEBUG)
673
674 builder = build.ProjectBuilder(package_test_flit)
675 builder.get_requires_for_build('sdist')
676 builder.get_requires_for_build('wheel')
677 builder.prepare('wheel', '.')
678 builder.build('sdist', '.')
679 builder.build('wheel', '.')
680
681 assert [(record.levelname, record.message) for record in caplog.records] == [
682 ('INFO', 'Getting build dependencies for sdist...'),
683 ('INFO', 'Getting build dependencies for wheel...'),
684 ('INFO', 'Getting metadata for wheel...'),
685 ('INFO', 'Building sdist...'),
686 ('INFO', 'Building wheel...'),
687 ]
688
689
690 @pytest.mark.parametrize(
691 ('pyproject_toml', 'parse_output'),
692 [
693 (
694 {'build-system': {'requires': ['foo']}},
695 {'requires': ['foo'], 'build-backend': 'setuptools.build_meta:__legacy__'},
696 ),
697 (
698 {'build-system': {'requires': ['foo'], 'build-backend': 'bar'}},
699 {'requires': ['foo'], 'build-backend': 'bar'},
700 ),
701 (
702 {'build-system': {'requires': ['foo'], 'build-backend': 'bar', 'backend-path': ['baz']}},
703 {'requires': ['foo'], 'build-backend': 'bar', 'backend-path': ['baz']},
704 ),
705 ],
706 )
707 def test_parse_valid_build_system_table_type(pyproject_toml: Mapping[str, TOMLValue], parse_output: BuildSystemTable) -> None:
708 assert build._builder._parse_build_system_table(pyproject_toml) == parse_output
709
710
711 def test_parse_default_build_system_table_not_shared() -> None:
712 # A caller mutating the returned default table must not affect later callers.
713 first = build._builder._parse_build_system_table({})
714 first['requires'].append('mutated')
715
716 second = build._builder._parse_build_system_table({})
717 assert second['requires'] == ['setuptools >= 40.8.0']
718
719
720 @pytest.mark.parametrize(
721 ('pyproject_toml', 'error_message'),
722 [
723 (
724 {'build-system': 'not a table'},
725 '`build-system` must be a table',
726 ),
727 (
728 {'build-system': {}},
729 '`requires` is a required property',
730 ),
731 (
732 {'build-system': {'requires': 'not an array'}},
733 '`requires` must be an array of strings',
734 ),
735 (
736 {'build-system': {'requires': [1]}},
737 '`requires` must be an array of strings',
738 ),
739 (
740 {'build-system': {'requires': ['foo'], 'build-backend': ['not a string']}},
741 '`build-backend` must be a string',
742 ),
743 (
744 {'build-system': {'requires': ['foo'], 'backend-path': 'not an array'}},
745 '`backend-path` must be an array of strings',
746 ),
747 (
748 {'build-system': {'requires': ['foo'], 'backend-path': [1]}},
749 '`backend-path` must be an array of strings',
750 ),
751 (
752 {'build-system': {'requires': ['foo'], 'unknown-prop': False}},
753 'Unknown properties: unknown-prop',
754 ),
755 ],
756 )
757 def test_parse_invalid_build_system_table_type(pyproject_toml: Mapping[str, TOMLValue], error_message: str) -> None:
758 with pytest.raises(build.BuildSystemTableValidationError, match=error_message):
759 build._builder._parse_build_system_table(pyproject_toml)
760
761
762 @pytest.mark.parametrize(
763 'setup',
764 [
765 pytest.param(lambda _tmp_path: None, id='nonexistent'),
766 pytest.param(lambda tmp_path: (tmp_path / 'bad').write_text('', encoding='utf-8'), id='file-not-dir'),
767 ],
768 )
769 def test_backend_path_invalid_directory(tmp_path: pathlib.Path, setup: Callable[[pathlib.Path], None]) -> None:
770 (tmp_path / 'pyproject.toml').write_text(
771 textwrap.dedent("""\
772 [build-system]
773 requires = []
774 build-backend = "backend"
775 backend-path = ["bad"]
776 """),
777 encoding='utf-8',
778 )
779 setup(tmp_path)
780 with pytest.raises(build.BuildSystemTableValidationError, match='does not exist or is not a directory'):
781 build.ProjectBuilder(tmp_path)