Debian Codegraph @

tests/test_env.py

raw
1 # SPDX-License-Identifier: MIT
2 from __future__ import annotations
3
4 import contextlib
5 import importlib.util
6 import logging
7 import os
8 import pathlib
9 import shutil
10 import subprocess
11 import sys
12 import sysconfig
13 import typing
14 import unittest.mock
15
16 from pathlib import Path
17 from types import SimpleNamespace
18
19 import pytest
20 import pytest_mock
21
22 from packaging.version import Version
23
24 import build
25 import build.env
26
27 from build import _ctx
28 from build._compat.importlib import metadata as importlib_metadata
29
30
31 IS_PYPY = sys.implementation.name == 'pypy'
32 IS_WINDOWS = sys.platform.startswith('win')
33
34 MISSING_UV = importlib.util.find_spec('uv') is None and not shutil.which('uv')
35 MISSING_VIRTUALENV = importlib.util.find_spec('virtualenv') is None
36
37
38 def test_make_extra_environ_overrides_pythonpath() -> None:
39 with build.env.DefaultIsolatedEnv() as env:
40 extra = env.make_extra_environ()
41 assert extra['PYTHONPATH'] == ''
42 assert env._env_backend.scripts_dir in extra['PATH']
43
44
45 def test_installed_versions(mocker: pytest_mock.MockerFixture) -> None:
46 env = build.env.DefaultIsolatedEnv()
47 env._env_backend = SimpleNamespace(purelib='/purelib')
48 distributions = mocker.patch(
49 'build._compat.importlib.metadata.distributions',
50 return_value=[
51 SimpleNamespace(name='Setuptools', version='80.9.0'),
52 SimpleNamespace(name='wheel', version='0.45.1'),
53 SimpleNamespace(name='pip', version='25.0'),
54 ],
55 )
56
57 versions = env.installed_versions(['setuptools >= 40.8.0', 'Wheel', '/local/path/pkg.whl'])
58
59 assert versions == {'setuptools': '80.9.0', 'wheel': '0.45.1'}
60 distributions.assert_called_once_with(path=['/purelib'])
61
62
63 @pytest.mark.skipif(MISSING_UV, reason='uv executable not found')
64 def test_uv_install_strips_pythonpath(
65 mocker: pytest_mock.MockerFixture,
66 monkeypatch: pytest.MonkeyPatch,
67 ) -> None:
68 monkeypatch.setenv('PYTHONPATH', '/some/leaky/path')
69 run_subprocess = mocker.patch('build.env.run_subprocess')
70 with build.env.DefaultIsolatedEnv(installer='uv') as env:
71 env.install(['some-package'])
72 (install_call,) = run_subprocess.call_args_list
73 assert 'PYTHONPATH' not in install_call.kwargs['env']
74
75
76 @pytest.mark.isolated
77 def test_isolation(monkeypatch: pytest.MonkeyPatch) -> None:
78 subprocess.check_call([sys.executable, '-c', 'import build.env'])
79 # Test that demonstrates the PYTHONPATH leak issue (issue #1047)
80 # When PYTHONPATH is set to include build, and the subprocess env
81 # is not properly isolated, the import will succeed instead of failing.
82 # Only fails on 3.15+ (due to lazy loading)
83 monkeypatch.setenv('PYTHONPATH', os.path.dirname(os.path.dirname(os.path.abspath(build.__file__))))
84 debug = 'import sys; import os; print(os.linesep.join(sys.path));'
85 with build.env.DefaultIsolatedEnv() as env:
86 isolated_env = {**os.environ, **env.make_extra_environ()}
87 with pytest.raises(subprocess.CalledProcessError):
88 subprocess.check_call(
89 [env.python_executable, '-c', f'{debug} import build.env'],
90 env=isolated_env,
91 )
92
93
94 @pytest.mark.skipif(IS_PYPY, reason='PyPy3 uses get path to create and provision venv')
95 @pytest.mark.skipif(sys.platform != 'darwin', reason='workaround for Apple Python')
96 def test_can_get_venv_paths_with_conflicting_default_scheme( # pragma: no cover -- skipped on PyPy and non-darwin
97 mocker: pytest_mock.MockerFixture,
98 ) -> None:
99 get_scheme_names = mocker.patch('sysconfig.get_scheme_names', return_value=('osx_framework_library',))
100 with build.env.DefaultIsolatedEnv():
101 pass
102 assert get_scheme_names.call_count == 1
103
104
105 SCHEME_NAMES = sysconfig.get_scheme_names()
106
107
108 @pytest.mark.skipif('posix_local' not in SCHEME_NAMES, reason='workaround for Debian/Ubuntu Python')
109 @pytest.mark.skipif('venv' in SCHEME_NAMES, reason='different call if venv is in scheme names')
110 def test_can_get_venv_paths_with_posix_local_default_scheme( # pragma: no cover
111 mocker: pytest_mock.MockerFixture,
112 ) -> None:
113 get_paths = mocker.spy(sysconfig, 'get_paths')
114 # We should never call this, but we patch it to ensure failure if we do
115 get_default_scheme = mocker.patch('sysconfig.get_default_scheme', return_value='posix_local')
116 with build.env.DefaultIsolatedEnv():
117 pass
118 get_paths.assert_called_once_with(scheme='posix_prefix', vars=mocker.ANY)
119 assert get_default_scheme.call_count == 0
120
121
122 def test_venv_executable_missing_post_creation(
123 mocker: pytest_mock.MockerFixture,
124 ) -> None:
125 venv_create = mocker.patch('venv.EnvBuilder.create')
126 with (
127 pytest.raises(RuntimeError, match=r'Virtual environment creation failed, executable .* missing'),
128 build.env.DefaultIsolatedEnv(),
129 ):
130 raise AssertionError
131 assert venv_create.call_count == 1
132
133
134 @typing.no_type_check
135 def test_isolated_env_abstract() -> None:
136 with pytest.raises(TypeError):
137 build.env.IsolatedEnv()
138
139 class PartialEnv(build.env.IsolatedEnv):
140 @property
141 def executable(self) -> None:
142 raise NotImplementedError
143
144 with pytest.raises(TypeError):
145 PartialEnv()
146
147 class PartialEnv2(build.env.IsolatedEnv):
148 def make_extra_environ(self) -> None:
149 raise NotImplementedError
150
151 with pytest.raises(TypeError):
152 PartialEnv2()
153
154
155 @pytest.mark.pypy3323bug
156 def test_isolated_env_log(
157 caplog: pytest.LogCaptureFixture,
158 mocker: pytest_mock.MockerFixture,
159 ) -> None:
160 caplog.set_level(logging.DEBUG)
161 mocker.patch('build.env.run_subprocess')
162
163 with build.env.DefaultIsolatedEnv() as env:
164 env.install(['something'])
165
166 assert [(record.levelname, record.message) for record in caplog.records] == [
167 ('INFO', 'Creating isolated environment: venv+pip...'),
168 ('INFO', 'Installing packages in isolated environment:\n- something'),
169 ]
170
171
172 @pytest.mark.isolated
173 @pytest.mark.usefixtures('local_pip')
174 def test_default_pip_is_never_too_old() -> None:
175 with build.env.DefaultIsolatedEnv() as env:
176 version = subprocess.check_output(
177 [env.python_executable, '-c', 'import pip; print(pip.__version__, end="")'],
178 encoding='utf-8',
179 )
180 assert Version(version) >= Version('19.1')
181
182
183 @pytest.mark.isolated
184 @pytest.mark.parametrize('pip_version', ['20.2.0', '20.3.0', '21.0.0', '21.0.1'])
185 @pytest.mark.parametrize('arch', ['x86_64', 'arm64'])
186 @pytest.mark.usefixtures('local_pip')
187 def test_pip_needs_upgrade_mac_os_11(
188 mocker: pytest_mock.MockerFixture,
189 pip_version: str,
190 arch: str,
191 ) -> None:
192 run_subprocess = mocker.patch('build.env.run_subprocess')
193 mocker.patch('platform.system', return_value='Darwin')
194 mocker.patch('platform.mac_ver', return_value=('11.0', ('', '', ''), arch))
195 mocker.patch('build._compat.importlib.metadata.distributions', return_value=(SimpleNamespace(version=pip_version),))
196
197 min_pip_version = '20.3.0' if arch == 'x86_64' else '21.0.1'
198
199 with build.env.DefaultIsolatedEnv() as env:
200 if Version(pip_version) < Version(min_pip_version):
201 assert run_subprocess.call_args_list == [
202 mocker.call(
203 [env.python_executable, '-Im', 'pip', 'install', '--no-input', f'pip>={min_pip_version}'],
204 env=mocker.ANY,
205 ),
206 mocker.call(
207 [env.python_executable, '-Im', 'pip', 'uninstall', '--no-input', '-y', 'setuptools'],
208 env=mocker.ANY,
209 ),
210 ]
211 else:
212 run_subprocess.assert_called_once_with(
213 [env.python_executable, '-Im', 'pip', 'uninstall', '--no-input', '-y', 'setuptools'],
214 env=mocker.ANY,
215 )
216
217
218 @pytest.mark.parametrize('has_symlink', [True, False] if sys.platform.startswith('win') else [True])
219 def test_venv_symlink(
220 mocker: pytest_mock.MockerFixture,
221 has_symlink: bool,
222 ) -> None:
223 if has_symlink:
224 mocker.patch('os.symlink')
225 mocker.patch('os.unlink')
226 else: # pragma: win32 cover
227 mocker.patch('os.symlink', side_effect=OSError())
228
229 # Cache must be cleared to rerun
230 build.env._fs_supports_symlink.cache_clear()
231 supports_symlink = build.env._fs_supports_symlink()
232 build.env._fs_supports_symlink.cache_clear()
233
234 assert supports_symlink is has_symlink
235
236
237 def test_fs_supports_symlink_windows_dest_is_tmp_file_path(
238 mocker: pytest_mock.MockerFixture,
239 ) -> None:
240 """Regression test for the Windows-only branch of ``_fs_supports_symlink``.
241
242 ``dest`` must be built from ``tmp_file.name``, not from the ``NamedTemporaryFile`` object itself: interpolating the
243 object yields its repr (containing ``<`` and ``>``, which are invalid in Windows filenames), so ``os.symlink`` would
244 always fail and the function would always report symlinks as unsupported, even when Windows Developer Mode enables
245 them.
246
247 """
248 mocker.patch('os.name', 'nt')
249
250 # Avoid exercising the real tempfile module: on some platforms tempfile's own
251 # internals branch on os.name, which we're patching to 'nt' above.
252 fake_tmp_file = mocker.MagicMock()
253 fake_tmp_file.name = r'C:\Users\test\AppData\Local\Temp\build-symlink-abc123'
254 fake_tmp_file.__enter__.return_value = fake_tmp_file
255 fake_tmp_file.__exit__.return_value = False
256 mocker.patch('build.env.tempfile.NamedTemporaryFile', return_value=fake_tmp_file)
257
258 recorded_dest = {}
259
260 def fake_symlink(_src: str, dst: str) -> None:
261 recorded_dest['dst'] = dst
262
263 mocker.patch('os.symlink', side_effect=fake_symlink)
264 mocker.patch('os.unlink')
265
266 build.env._fs_supports_symlink.cache_clear()
267 supports_symlink = build.env._fs_supports_symlink()
268 build.env._fs_supports_symlink.cache_clear()
269
270 assert supports_symlink is True
271 assert recorded_dest['dst'] == f'{fake_tmp_file.name}-b'
272
273
274 def test_install_short_circuits(
275 mocker: pytest_mock.MockerFixture,
276 ) -> None:
277 with build.env.DefaultIsolatedEnv() as env:
278 assert env.path
279 install_dependencies = mocker.patch.object(env._env_backend, 'install_dependencies')
280
281 env.install([])
282 install_dependencies.assert_not_called()
283
284 env.install(['foo'])
285 install_dependencies.assert_called_once()
286
287
288 @pytest.mark.parametrize('verbosity', range(3))
289 @pytest.mark.parametrize('constraints', [[], ['foo']])
290 @pytest.mark.parametrize('fresh', [False, True])
291 @pytest.mark.usefixtures('local_pip')
292 def test_default_impl_install_cmd_well_formed(
293 mocker: pytest_mock.MockerFixture,
294 verbosity: int,
295 constraints: list[str],
296 fresh: bool,
297 ) -> None:
298 mocker.patch.object(_ctx, 'verbosity', verbosity)
299
300 with build.env.DefaultIsolatedEnv() as env:
301 run_subprocess = mocker.patch('build.env.run_subprocess')
302
303 env.install(['some', 'requirements'], constraints, _fresh=fresh)
304
305 run_subprocess.assert_called_once_with(
306 [
307 env.python_executable,
308 '-Im',
309 'pip',
310 *([f'-{"v" * (verbosity - 1)}'] if verbosity > 1 else []),
311 'install',
312 *(['--ignore-installed'] if fresh else []),
313 '--use-pep517',
314 '--no-warn-script-location',
315 '--no-compile',
316 '--no-input',
317 '-r',
318 mocker.ANY,
319 *(['-c', mocker.ANY] if constraints else []),
320 ],
321 env=mocker.ANY,
322 )
323
324
325 @pytest.mark.parametrize('verbosity', range(3))
326 @pytest.mark.parametrize('constraints', [[], ['foo']])
327 @pytest.mark.parametrize('fresh', [False, True])
328 @pytest.mark.skipif(IS_PYPY, reason='uv cannot find PyPy executable')
329 @pytest.mark.skipif(MISSING_UV, reason='uv executable not found')
330 def test_uv_impl_install_cmd_well_formed( # pragma: no cover -- uv tests are skipped on PyPy, covered on CPython
331 mocker: pytest_mock.MockerFixture,
332 verbosity: int,
333 constraints: list[str],
334 fresh: bool,
335 ) -> None:
336 mocker.patch.object(_ctx, 'verbosity', verbosity)
337
338 with build.env.DefaultIsolatedEnv(installer='uv') as env:
339 run_subprocess = mocker.patch('build.env.run_subprocess')
340
341 env.install(['some', 'requirements'], constraints, _fresh=fresh)
342
343 run_subprocess.assert_called_once_with(
344 [
345 mocker.ANY,
346 'pip',
347 *(['-vv' if verbosity > 2 else '-v'] if verbosity > 1 else []),
348 'install',
349 'some',
350 'requirements',
351 '--python',
352 mocker.ANY,
353 *(['-c', mocker.ANY] if constraints else []),
354 ],
355 env=mocker.ANY,
356 )
357 (install_call,) = run_subprocess.call_args_list
358 assert install_call.kwargs['env']['VIRTUAL_ENV'] == env.path
359
360
361 @pytest.mark.usefixtures('local_pip')
362 def test_default_impl_install_files_line_endings_not_doubled(mocker: pytest_mock.MockerFixture) -> None:
363 # The requirements/constraints files are opened in text mode, which translates every
364 # '\n' written to os.linesep -- '\r\n' on disk is correct on Windows. Joining with
365 # os.linesep first (instead of '\n') would double-translate there, turning '\r\n' into
366 # '\r\r\n'. Read back as bytes, before the files are deleted by the
367 # install_dependencies() ExitStack, to catch that.
368 written: dict[str, bytes] = {}
369
370 def fake_run_subprocess(cmd: list[str], **_kwargs: object) -> None:
371 args = iter(cmd)
372 for arg in args:
373 if arg == '-r':
374 written['requirements'] = Path(next(args)).read_bytes()
375 elif arg == '-c':
376 written['constraints'] = Path(next(args)).read_bytes()
377
378 with build.env.DefaultIsolatedEnv() as env:
379 mocker.patch('build.env.run_subprocess', side_effect=fake_run_subprocess)
380 env.install(['some', 'requirements'], ['a-constraint', 'b-constraint'])
381
382 assert b'\r\r' not in written['requirements']
383 assert written['requirements'].splitlines() == [b'some', b'requirements']
384 assert b'\r\r' not in written['constraints']
385 assert written['constraints'].splitlines() == [b'a-constraint', b'b-constraint']
386
387
388 @pytest.mark.skipif(IS_PYPY, reason='uv cannot find PyPy executable')
389 @pytest.mark.skipif(MISSING_UV, reason='uv executable not found')
390 def test_uv_impl_install_files_line_endings_not_doubled( # pragma: no cover -- skipped on PyPy, covered on CPython
391 mocker: pytest_mock.MockerFixture,
392 ) -> None:
393 written: dict[str, bytes] = {}
394
395 def fake_run_subprocess(cmd: list[str], **_kwargs: object) -> None:
396 args = iter(cmd)
397 for arg in args:
398 if arg == '-c':
399 written['constraints'] = Path(next(args)).read_bytes()
400
401 with build.env.DefaultIsolatedEnv(installer='uv') as env:
402 mocker.patch('build.env.run_subprocess', side_effect=fake_run_subprocess)
403 env.install(['some', 'requirements'], ['a-constraint', 'b-constraint'])
404
405 assert b'\r\r' not in written['constraints']
406 assert written['constraints'].splitlines() == [b'a-constraint', b'b-constraint']
407
408
409 @pytest.mark.usefixtures('local_pip')
410 @pytest.mark.parametrize(
411 ('installer', 'env_backend_display_name', 'has_virtualenv'),
412 [
413 ('pip', 'venv+pip', False),
414 pytest.param(
415 'pip',
416 'virtualenv+pip',
417 True,
418 marks=pytest.mark.skipif(MISSING_VIRTUALENV, reason='virtualenv not found'),
419 ),
420 pytest.param(
421 'pip',
422 'virtualenv+pip',
423 None,
424 marks=pytest.mark.skipif(MISSING_VIRTUALENV, reason='virtualenv not found'),
425 ), # Fall-through
426 pytest.param(
427 'uv',
428 'venv+uv',
429 None,
430 marks=pytest.mark.skipif(MISSING_UV, reason='uv executable not found'),
431 ),
432 ],
433 indirect=('has_virtualenv',),
434 )
435 def test_venv_creation(
436 installer: build.env.Installer,
437 env_backend_display_name: str,
438 ) -> None:
439 with build.env.DefaultIsolatedEnv(installer=installer) as env:
440 assert env._env_backend.display_name == env_backend_display_name
441
442
443 @pytest.mark.network
444 @pytest.mark.usefixtures('local_pip')
445 @pytest.mark.parametrize(
446 'installer',
447 [
448 'pip',
449 pytest.param(
450 'uv',
451 marks=[
452 pytest.mark.skipif(MISSING_UV, reason='uv executable not found'),
453 ],
454 ),
455 ],
456 )
457 def test_requirement_installation(
458 package_test_flit: str,
459 installer: build.env.Installer,
460 ) -> None:
461 with build.env.DefaultIsolatedEnv(installer=installer) as env:
462 env.install([f'test-flit @ {Path(package_test_flit).as_uri()}'])
463
464
465 @pytest.mark.skipif(MISSING_UV, reason='uv executable not found')
466 def test_external_uv_detection_success(
467 caplog: pytest.LogCaptureFixture,
468 mocker: pytest_mock.MockerFixture,
469 ) -> None:
470 # Ensure INFO logs are captured
471 caplog.set_level(logging.INFO)
472 mocker.patch.dict(sys.modules, {'uv': None})
473
474 with build.env.DefaultIsolatedEnv(installer='uv'):
475 pass
476
477 # Only check that we logged using an external uv binary (do not rely on
478 # which() at assertion time because it can find the environment one).
479 # And .text is used instead of .records so a failure message is helpful.
480 assert 'Using external uv' in caplog.text
481
482
483 def test_external_uv_detection_failure(
484 mocker: pytest_mock.MockerFixture,
485 ) -> None:
486 mocker.patch.dict(sys.modules, {'uv': None})
487 mocker.patch('shutil.which', return_value=None)
488
489 with pytest.raises(RuntimeError, match='uv executable not found'), build.env.DefaultIsolatedEnv(installer='uv'):
490 raise AssertionError
491
492
493 def test_get_minimum_pip_version_non_darwin(
494 mocker: pytest_mock.MockerFixture,
495 ) -> None:
496 mocker.patch('platform.system', return_value='Linux')
497 assert build.env._PipBackend._get_minimum_pip_version_str() == '19.1.0'
498
499
500 def test_get_minimum_pip_version_old_darwin(
501 mocker: pytest_mock.MockerFixture,
502 ) -> None:
503 mocker.patch('platform.system', return_value='Darwin')
504 mocker.patch('platform.mac_ver', return_value=('10.15', ('', '', ''), 'x86_64'))
505 assert build.env._PipBackend._get_minimum_pip_version_str() == '19.1.0'
506
507
508 @pytest.mark.parametrize(
509 ('release', 'machine', 'expected'),
510 [
511 # A dot-less release must not have its last digit truncated.
512 ('15', 'arm64', '21.0.1'),
513 ('15', 'x86_64', '20.3.0'),
514 # The 10.16 backwards-compatibility report maps to the pre-11 minimum.
515 ('10.16', 'x86_64', '19.1.0'),
516 # An empty release must not raise, and falls back to the generic minimum.
517 ('', 'x86_64', '19.1.0'),
518 ],
519 )
520 def test_get_minimum_pip_version_darwin_release_parsing(
521 mocker: pytest_mock.MockerFixture,
522 release: str,
523 machine: str,
524 expected: str,
525 ) -> None:
526 mocker.patch('platform.system', return_value='Darwin')
527 mocker.patch('platform.mac_ver', return_value=(release, ('', '', ''), machine))
528 assert build.env._PipBackend._get_minimum_pip_version_str() == expected
529
530
531 def test_isolated_env_enter_failure_before_path_set(
532 mocker: pytest_mock.MockerFixture,
533 tmp_path: Path,
534 ) -> None:
535 # If setup fails before ``self._path`` is assigned, the original exception must
536 # propagate (not an AttributeError from ``__exit__``), and the temp dir cleaned up.
537 class _DistinctError(Exception):
538 pass
539
540 env_dir = tmp_path / 'build-env'
541 env_dir.mkdir()
542 mocker.patch('build.env.tempfile.mkdtemp', return_value=str(env_dir))
543 mocker.patch('build.env.os.path.realpath', side_effect=_DistinctError('boom'))
544
545 with pytest.raises(_DistinctError, match='boom'):
546 build.env.DefaultIsolatedEnv().__enter__()
547
548 assert not env_dir.exists()
549
550
551 @pytest.mark.parametrize(
552 ('version', 'has_no_wheel'),
553 [
554 pytest.param('20.30.0', True, id='old'),
555 pytest.param('20.31.0', False, id='new'),
556 ],
557 )
558 def test_virtualenv_no_wheel_flag(
559 mocker: pytest_mock.MockerFixture,
560 version: str,
561 has_no_wheel: bool,
562 ) -> None:
563 mocker.patch.object(build.env._PipBackend, '_has_valid_outer_pip', None)
564 mocker.patch.object(build.env._PipBackend, '_has_virtualenv', True)
565
566 mocker.patch('build._compat.importlib.metadata.version', return_value=version)
567 cli_run = mocker.patch('virtualenv.cli_run')
568 cli_run.return_value = SimpleNamespace(
569 creator=SimpleNamespace(exe=Path('/fake/python'), script_dir=Path('/fake/scripts'), purelib=Path('/fake/purelib'))
570 )
571
572 backend = build.env._PipBackend()
573 backend.create('/some/path')
574
575 call_args = cli_run.call_args[0][0]
576 assert ('--no-wheel' in call_args) is has_no_wheel
577
578
579 def test_install_dependencies_with_outer_pip(
580 mocker: pytest_mock.MockerFixture,
581 ) -> None:
582 mocker.patch.object(build.env._PipBackend, '_has_valid_outer_pip', True)
583
584 run_subprocess = mocker.patch('build.env.run_subprocess')
585
586 with build.env.DefaultIsolatedEnv() as env:
587 env.install(['some-package'])
588
589 cmd = run_subprocess.call_args_list[-1][0][0]
590 assert cmd[:4] == [sys.executable, '-m', 'pip', '--python']
591
592
593 def test_find_executable_osx_framework_scheme(
594 mocker: pytest_mock.MockerFixture,
595 ) -> None:
596 mocker.patch('sysconfig.get_scheme_names', return_value=('osx_framework_library', 'posix_prefix'))
597 get_paths = mocker.patch(
598 'sysconfig.get_paths',
599 return_value={
600 'scripts': '/fake/bin',
601 'purelib': '/fake/lib',
602 },
603 )
604 mocker.patch('os.path.exists', return_value=True)
605
606 _exe, scripts, _purelib = build.env._find_executable_and_scripts('/fake/venv')
607
608 get_paths.assert_called_once_with(scheme='posix_prefix', vars=mocker.ANY)
609 assert scripts == '/fake/bin'
610
611
612 def test_find_executable_posix_local_scheme(
613 mocker: pytest_mock.MockerFixture,
614 ) -> None:
615 mocker.patch('sysconfig.get_scheme_names', return_value=('posix_local', 'posix_prefix'))
616 get_paths = mocker.patch(
617 'sysconfig.get_paths',
618 return_value={
619 'scripts': '/fake/bin',
620 'purelib': '/fake/lib',
621 },
622 )
623 mocker.patch('os.path.exists', return_value=True)
624
625 _exe, scripts, _purelib = build.env._find_executable_and_scripts('/fake/venv')
626
627 get_paths.assert_called_once_with(scheme='posix_prefix', vars=mocker.ANY)
628 assert scripts == '/fake/bin'
629
630
631 def test_find_executable_fallback_scheme(
632 mocker: pytest_mock.MockerFixture,
633 ) -> None:
634 mocker.patch('sysconfig.get_scheme_names', return_value=('posix_prefix',))
635 get_paths = mocker.patch(
636 'sysconfig.get_paths',
637 return_value={
638 'scripts': '/fake/bin',
639 'purelib': '/fake/lib',
640 },
641 )
642 mocker.patch('os.path.exists', return_value=True)
643
644 _exe, scripts, _purelib = build.env._find_executable_and_scripts('/fake/venv')
645
646 get_paths.assert_called_once_with(vars=mocker.ANY)
647 assert scripts == '/fake/bin'
648
649
650 def test_has_dependency_missing() -> None:
651 assert build.env._has_dependency('nonexistent_package_xyz_123') is None
652
653
654 @pytest.mark.usefixtures('local_pip')
655 def test_venv_creation_no_setuptools(
656 mocker: pytest_mock.MockerFixture,
657 ) -> None:
658 original = build.env._has_dependency
659
660 def no_setuptools(name: str, min_ver: str | None = None, /, **kwargs: list[str]) -> importlib_metadata.Distribution | None:
661 if name == 'setuptools':
662 return None
663 return original(name, min_ver, **kwargs)
664
665 mocker.patch('build.env._has_dependency', side_effect=no_setuptools)
666 run_subprocess = mocker.patch('build.env.run_subprocess')
667
668 with build.env.DefaultIsolatedEnv() as env:
669 assert env.python_executable
670
671 assert all('setuptools' not in str(c) for c in run_subprocess.call_args_list)
672
673
674 def test_has_keyring_cli_found(mocker: pytest_mock.MockerFixture) -> None:
675 mocker.patch('shutil.which', return_value='/usr/bin/keyring')
676 assert build.env._has_keyring_cli() is True
677
678
679 def test_has_keyring_cli_missing(mocker: pytest_mock.MockerFixture) -> None:
680 mocker.patch('shutil.which', return_value=None)
681 assert build.env._has_keyring_cli() is False
682
683
684 def test_pip_env_with_keyring(mocker: pytest_mock.MockerFixture) -> None:
685 mocker.patch('shutil.which', return_value='/usr/bin/keyring')
686
687 result = build.env._pip_env()
688
689 assert result is not None
690 assert result['PIP_KEYRING_PROVIDER'] == 'subprocess'
691
692
693 def test_pip_env_without_keyring(mocker: pytest_mock.MockerFixture) -> None:
694 mocker.patch('shutil.which', return_value=None)
695 assert build.env._pip_env() is None
696
697
698 def test_pip_env_respects_existing_env_var(
699 mocker: pytest_mock.MockerFixture,
700 monkeypatch: pytest.MonkeyPatch,
701 ) -> None:
702 mocker.patch('shutil.which', return_value='/usr/bin/keyring')
703 monkeypatch.setenv('PIP_KEYRING_PROVIDER', 'import')
704 assert build.env._pip_env() is None
705
706
707 @pytest.mark.usefixtures('local_pip')
708 def test_install_dependencies_passes_keyring_env(
709 mocker: pytest_mock.MockerFixture,
710 ) -> None:
711 mocker.patch('shutil.which', return_value='/usr/bin/keyring')
712
713 with build.env.DefaultIsolatedEnv() as env:
714 run_subprocess = mocker.patch('build.env.run_subprocess')
715 env.install(['some-package'])
716
717 (install_call,) = run_subprocess.call_args_list
718 assert install_call.kwargs['env']['PIP_KEYRING_PROVIDER'] == 'subprocess'
719
720
721 @pytest.mark.skipif(IS_PYPY, reason='uv cannot find PyPy executable')
722 @pytest.mark.skipif(MISSING_UV, reason='uv executable not found')
723 def test_uv_install_dependencies_passes_keyring_env( # pragma: no cover -- uv tests are skipped on PyPy
724 mocker: pytest_mock.MockerFixture,
725 ) -> None:
726 mocker.patch('shutil.which', return_value='/usr/bin/keyring')
727
728 with build.env.DefaultIsolatedEnv(installer='uv') as env:
729 run_subprocess = mocker.patch('build.env.run_subprocess')
730 env.install(['some-package'])
731
732 (install_call,) = run_subprocess.call_args_list
733 assert install_call.kwargs['env']['UV_KEYRING_PROVIDER'] == 'subprocess'
734
735
736 @pytest.mark.skipif(IS_PYPY, reason='uv cannot find PyPy executable')
737 @pytest.mark.skipif(MISSING_UV, reason='uv executable not found')
738 def test_uv_install_respects_existing_keyring_env( # pragma: no cover -- uv tests are skipped on PyPy
739 mocker: pytest_mock.MockerFixture,
740 monkeypatch: pytest.MonkeyPatch,
741 ) -> None:
742 mocker.patch('shutil.which', return_value='/usr/bin/keyring')
743 monkeypatch.setenv('UV_KEYRING_PROVIDER', 'disabled')
744
745 with build.env.DefaultIsolatedEnv(installer='uv') as env:
746 run_subprocess = mocker.patch('build.env.run_subprocess')
747 env.install(['some-package'])
748
749 (install_call,) = run_subprocess.call_args_list
750 assert install_call.kwargs['env']['UV_KEYRING_PROVIDER'] == 'disabled'
751
752
753 @pytest.mark.network
754 def test_pythonpath_does_not_interfere_with_outer_pip(
755 monkeypatch: pytest.MonkeyPatch,
756 tmp_path: pathlib.Path,
757 ) -> None:
758 flit_core = tmp_path.joinpath('flit_core-0.0.0.dist-info/')
759 flit_core.mkdir()
760
761 monkeypatch.setenv('PYTHONPATH', str(tmp_path))
762
763 with build.env.DefaultIsolatedEnv(installer='pip') as env:
764 env.install({'flit_core'}, _fresh=True)
765
766 assert subprocess.check_call([env.python_executable, '-c', 'import flit_core']) == 0
767
768
769 @pytest.fixture
770 def mock_env_create(mocker: pytest_mock.MockerFixture) -> unittest.mock.MagicMock:
771 return mocker.patch('build.env._PipBackend.create', autospec=True)
772
773
774 def test_env_dir_created_at_requested_location(
775 mock_env_create: unittest.mock.MagicMock,
776 tmp_path: pathlib.Path,
777 ) -> None:
778 target = tmp_path / 'nested' / 'build-env'
779
780 with build.env.DefaultIsolatedEnv(path=str(target)) as env:
781 assert env.path == os.path.realpath(target)
782 assert os.path.isdir(env.path)
783
784 mock_env_create.assert_called_once()
785
786
787 @pytest.mark.usefixtures('mock_env_create')
788 @pytest.mark.parametrize(
789 ('use_path', 'fail', 'kept_after'),
790 [
791 pytest.param(False, False, False, id='temporary-success-removed'),
792 pytest.param(False, True, False, id='temporary-failure-removed'),
793 pytest.param(True, False, False, id='requested-success-removed'),
794 pytest.param(True, True, True, id='requested-failure-kept'),
795 ],
796 )
797 def test_env_cleanup(
798 tmp_path: pathlib.Path,
799 use_path: bool,
800 fail: bool,
801 kept_after: bool,
802 ) -> None:
803 target = str(tmp_path / 'build-env') if use_path else None
804
805 created_path = ''
806 with contextlib.suppress(RuntimeError), build.env.DefaultIsolatedEnv(path=target) as env:
807 created_path = env.path
808 if fail:
809 msg = 'boom'
810 raise RuntimeError(msg)
811
812 assert os.path.exists(created_path) is kept_after
813
814
815 def test_env_dir_rejects_non_empty_location(tmp_path: pathlib.Path) -> None:
816 tmp_path.joinpath('sentinel').touch()
817
818 with (
819 pytest.raises(build.BuildException, match='Build environment location is not empty'),
820 build.env.DefaultIsolatedEnv(path=str(tmp_path)),
821 ):
822 raise AssertionError
823
824 assert tmp_path.joinpath('sentinel').exists()
825
826
827 def test_env_dir_rejects_file_at_location(tmp_path: pathlib.Path) -> None:
828 file_path = tmp_path / 'env-file'
829 file_path.touch()
830
831 with (
832 pytest.raises(build.BuildException, match='Build environment location is not a directory'),
833 build.env.DefaultIsolatedEnv(path=str(file_path)),
834 ):
835 raise AssertionError
836
837 assert file_path.is_file()
838
839
840 @pytest.mark.usefixtures('mock_env_create')
841 def test_env_dir_accepts_existing_empty_location(tmp_path: pathlib.Path) -> None:
842 with build.env.DefaultIsolatedEnv(path=str(tmp_path)) as env:
843 assert env.path == os.path.realpath(tmp_path)