-
-
Notifications
You must be signed in to change notification settings - Fork 35.1k
Expand file tree
/
Copy pathtest_venv.py
More file actions
1402 lines (1265 loc) · 57.6 KB
/
Copy pathtest_venv.py
File metadata and controls
1402 lines (1265 loc) · 57.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Test harness for the venv module.
Copyright (C) 2011-2012 Vinay Sajip.
Licensed to the PSF under a contributor agreement.
"""
import contextlib
import ensurepip
import os
import os.path
import pathlib
import re
import shlex
import shutil
import subprocess
import sys
import sysconfig
import tempfile
from test.support import (captured_stdout, captured_stderr,
skip_if_broken_multiprocessing_synchronize, verbose,
requires_subprocess, is_android, is_apple_mobile,
is_wasm32,
requires_venv_with_pip, TEST_HOME_DIR,
requires_resource, copy_python_src_ignore)
from test.support.os_helper import (can_symlink, EnvironmentVarGuard, rmtree,
TESTFN, FakePath)
import unittest
import venv
from unittest.mock import patch, Mock
try:
import ctypes
except ImportError:
ctypes = None
# Platforms that set sys._base_executable can create venvs from within
# another venv, so no need to skip tests that require venv.create().
requireVenvCreate = unittest.skipUnless(
sys.prefix == sys.base_prefix
or sys._base_executable != sys.executable,
'cannot run venv.create from within a venv on this platform')
if is_android or is_apple_mobile or is_wasm32:
raise unittest.SkipTest("venv is not available on this platform")
@requires_subprocess()
def check_output(cmd, encoding=None):
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env={**os.environ, "PYTHONHOME": ""})
out, err = p.communicate()
if p.returncode:
if verbose and err:
print(err.decode(encoding or 'utf-8', 'backslashreplace'))
raise subprocess.CalledProcessError(
p.returncode, cmd, out, err)
if encoding:
return (
out.decode(encoding, 'backslashreplace'),
err.decode(encoding, 'backslashreplace'),
)
return out, err
class BaseTest(unittest.TestCase):
"""Base class for venv tests."""
maxDiff = 80 * 50
def setUp(self):
self.env_dir = os.path.realpath(tempfile.mkdtemp())
if os.name == 'nt':
self.bindir = 'Scripts'
self.lib = ('Lib',)
self.include = 'Include'
else:
self.bindir = 'bin'
self.lib = ('lib', f'python{sysconfig._get_python_version_abi()}')
self.include = 'include'
executable = sys._base_executable
self.exe = os.path.split(executable)[-1]
if (sys.platform == 'win32'
and os.path.lexists(executable)
and not os.path.exists(executable)):
self.cannot_link_exe = True
else:
self.cannot_link_exe = False
def tearDown(self):
rmtree(self.env_dir)
def envpy(self, *, real_env_dir=False):
if real_env_dir:
env_dir = os.path.realpath(self.env_dir)
else:
env_dir = self.env_dir
return os.path.join(env_dir, self.bindir, self.exe)
def run_with_capture(self, func, *args, **kwargs):
with captured_stdout() as output:
with captured_stderr() as error:
func(*args, **kwargs)
return output.getvalue(), error.getvalue()
def get_env_file(self, *args):
return os.path.join(self.env_dir, *args)
def get_text_file_contents(self, *args, encoding='utf-8'):
with open(self.get_env_file(*args), 'r', encoding=encoding) as f:
result = f.read()
return result
class BasicTest(BaseTest):
"""Test venv module functionality."""
def isdir(self, *args):
fn = self.get_env_file(*args)
self.assertTrue(os.path.isdir(fn))
def test_defaults_with_str_path(self):
"""
Test the create function with default arguments and a str path.
"""
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir)
self._check_output_of_default_create()
def test_defaults_with_pathlike(self):
"""
Test the create function with default arguments and a path-like path.
"""
rmtree(self.env_dir)
self.run_with_capture(venv.create, FakePath(self.env_dir))
self._check_output_of_default_create()
def _check_output_of_default_create(self):
self.isdir(self.bindir)
self.isdir(self.include)
self.isdir(*self.lib)
p = self.get_env_file('lib64')
if os.path.exists(p):
self.assertFalse(os.path.islink(p))
data = self.get_text_file_contents('pyvenv.cfg')
executable = sys._base_executable
path = os.path.dirname(executable)
self.assertIn('home = %s' % path, data)
self.assertIn('executable = %s' %
os.path.realpath(sys.executable), data)
copies = '' if os.name=='nt' else ' --copies'
cmd = (f'command = {sys.executable} -m venv{copies} --without-pip '
f'--without-scm-ignore-files {self.env_dir}')
self.assertIn(cmd, data)
fn = self.get_env_file(self.bindir, self.exe)
if not os.path.exists(fn): # diagnostics for Windows buildbot failures
bd = self.get_env_file(self.bindir)
print('Contents of %r:' % bd)
print(' %r' % os.listdir(bd))
self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
def test_config_file_command_key(self):
options = [
(None, None, None), # Default case.
('--copies', 'symlinks', False),
('--without-pip', 'with_pip', False),
('--system-site-packages', 'system_site_packages', True),
('--clear', 'clear', True),
('--upgrade', 'upgrade', True),
('--upgrade-deps', 'upgrade_deps', True),
('--prompt="foobar"', 'prompt', 'foobar'),
('--without-scm-ignore-files', 'scm_ignore_files', frozenset()),
]
for opt, attr, value in options:
with self.subTest(opt=opt, attr=attr, value=value):
rmtree(self.env_dir)
if not attr:
kwargs = {}
else:
kwargs = {attr: value}
b = venv.EnvBuilder(**kwargs)
b.upgrade_dependencies = Mock() # avoid pip command to upgrade deps
b._setup_pip = Mock() # avoid pip setup
self.run_with_capture(b.create, self.env_dir)
data = self.get_text_file_contents('pyvenv.cfg')
if not attr or opt.endswith('git'):
for opt in ('--system-site-packages', '--clear', '--upgrade',
'--upgrade-deps', '--prompt'):
self.assertNotRegex(data, rf'command = .* {opt}')
elif os.name=='nt' and attr=='symlinks':
pass
else:
self.assertRegex(data, rf'command = .* {opt}')
def test_prompt(self):
env_name = os.path.split(self.env_dir)[1]
rmtree(self.env_dir)
builder = venv.EnvBuilder()
self.run_with_capture(builder.create, self.env_dir)
context = builder.ensure_directories(self.env_dir)
data = self.get_text_file_contents('pyvenv.cfg')
self.assertEqual(context.prompt, env_name)
self.assertNotIn("prompt = ", data)
rmtree(self.env_dir)
builder = venv.EnvBuilder(prompt='My prompt')
self.run_with_capture(builder.create, self.env_dir)
context = builder.ensure_directories(self.env_dir)
data = self.get_text_file_contents('pyvenv.cfg')
self.assertEqual(context.prompt, 'My prompt')
self.assertIn("prompt = 'My prompt'\n", data)
rmtree(self.env_dir)
builder = venv.EnvBuilder(prompt='.')
cwd = os.path.basename(os.getcwd())
self.run_with_capture(builder.create, self.env_dir)
context = builder.ensure_directories(self.env_dir)
data = self.get_text_file_contents('pyvenv.cfg')
self.assertEqual(context.prompt, cwd)
self.assertIn("prompt = '%s'\n" % cwd, data)
def test_upgrade_dependencies(self):
builder = venv.EnvBuilder()
bin_path = 'bin'
python_exe = os.path.split(sys.executable)[1]
expected_exe = os.path.basename(sys._base_executable)
if sys.platform == 'win32':
bin_path = 'Scripts'
if os.path.normcase(os.path.splitext(python_exe)[0]).endswith('_d'):
expected_exe = 'python_d'
else:
expected_exe = 'python'
python_exe = expected_exe + '.exe'
with tempfile.TemporaryDirectory() as fake_env_dir:
expect_exe = os.path.normcase(
os.path.join(fake_env_dir, bin_path, expected_exe)
)
if sys.platform == 'win32':
expect_exe = os.path.normcase(os.path.realpath(expect_exe))
def pip_cmd_checker(cmd, **kwargs):
self.assertEqual(
cmd[1:],
[
'-m',
'pip',
'install',
'--upgrade',
'pip',
]
)
exe_dir = os.path.normcase(os.path.dirname(cmd[0]))
expected_dir = os.path.normcase(os.path.dirname(expect_exe))
self.assertEqual(exe_dir, expected_dir)
fake_context = builder.ensure_directories(fake_env_dir)
with patch('venv.subprocess.check_output', pip_cmd_checker):
builder.upgrade_dependencies(fake_context)
@requireVenvCreate
def test_prefixes(self):
"""
Test that the prefix values are as expected.
"""
# check a venv's prefixes
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir)
cmd = [self.envpy(), '-c', None]
for prefix, expected in (
('prefix', self.env_dir),
('exec_prefix', self.env_dir),
('base_prefix', sys.base_prefix),
('base_exec_prefix', sys.base_exec_prefix)):
cmd[2] = 'import sys; print(sys.%s)' % prefix
out, err = check_output(cmd)
self.assertEqual(pathlib.Path(out.strip().decode()),
pathlib.Path(expected), prefix)
@requireVenvCreate
def test_sysconfig(self):
"""
Test that the sysconfig functions work in a virtual environment.
"""
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir, symlinks=False)
cmd = [self.envpy(), '-c', None]
for call, expected in (
# installation scheme
('get_preferred_scheme("prefix")', 'venv'),
('get_default_scheme()', 'venv'),
# build environment
('is_python_build()', str(sysconfig.is_python_build())),
('get_makefile_filename()', sysconfig.get_makefile_filename()),
('get_config_h_filename()', sysconfig.get_config_h_filename()),
('get_config_var("Py_GIL_DISABLED")',
str(sysconfig.get_config_var("Py_GIL_DISABLED")))):
with self.subTest(call):
cmd[2] = 'import sysconfig; print(sysconfig.%s)' % call
out, err = check_output(cmd, encoding='utf-8')
self.assertEqual(out.strip(), expected, err)
for attr, expected in (
('executable', self.envpy()),
# Usually compare to sys.prefix, but if we're running in our own
# venv then we really need to compare to our base prefix
('base_prefix', sys.base_prefix),
):
with self.subTest(attr):
cmd[2] = f'import sys; print(sys.{attr})'
out, err = check_output(cmd, encoding='utf-8')
self.assertEqual(out.strip(), expected, err)
@requireVenvCreate
def test_version_mismatch_warning(self):
"""
Test that a warning is emitted when running a venv created for a
different minor Python version.
"""
rmtree(self.env_dir)
wrong_minor = sys.version_info.minor + 1
self.run_with_capture(venv.create, self.env_dir, with_pip=False)
cfg_path = self.get_env_file('pyvenv.cfg')
with open(cfg_path, 'r', encoding='utf-8') as f:
cfg_content = f.read()
new_version = f"{sys.version_info.major}.{wrong_minor}"
if 'version =' in cfg_content:
cfg_content = re.sub(r'version = \d+\.\d+', f'version = {new_version}', cfg_content)
cfg_content += f'\nversion_info = {new_version}\n'
with open(cfg_path, 'w', encoding='utf-8') as f:
f.write(cfg_content)
envpy = self.envpy(real_env_dir=True)
proc = subprocess.run(
[envpy, '-c', 'import sys; print("done")'],
capture_output=True,
text=True,
env={**os.environ, "PYTHONHOME": ""}
)
self.assertIn(f"Python {sys.version_info.major}.{wrong_minor}", proc.stderr)
self.assertIn("Consider running `python -m venv --upgrade`", proc.stderr)
@requireVenvCreate
def test_version_info_mismatch_warning(self):
"""
Test that a warning is emitted when version_info (used by virtualenv)
indicates a different minor version.
"""
rmtree(self.env_dir)
wrong_minor = sys.version_info.minor + 1
self.run_with_capture(venv.create, self.env_dir, with_pip=False)
cfg_path = self.get_env_file('pyvenv.cfg')
with open(cfg_path, 'r', encoding='utf-8') as f:
cfg_content = f.read()
# Add only version_info, don't modify version
new_version = f"{sys.version_info.major}.{wrong_minor}"
cfg_content += f'\nversion_info = {new_version}\n'
with open(cfg_path, 'w', encoding='utf-8') as f:
f.write(cfg_content)
envpy = self.envpy(real_env_dir=True)
proc = subprocess.run(
[envpy, '-c', 'import sys; print("done")'],
capture_output=True,
text=True,
env={**os.environ, "PYTHONHOME": ""}
)
self.assertIn(f"Python {sys.version_info.major}.{wrong_minor}", proc.stderr)
self.assertIn("Consider running `python -m venv --upgrade`", proc.stderr)
@requireVenvCreate
def test_version_match_no_warning(self):
"""
Test that no warning is emitted when the venv version matches.
"""
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir, with_pip=False)
cfg_path = self.get_env_file('pyvenv.cfg')
with open(cfg_path, 'r', encoding='utf-8') as f:
cfg_content = f.read()
expected_version = f"{sys.version_info.major}.{sys.version_info.minor}"
with open(cfg_path, 'w', encoding='utf-8') as f:
f.write(cfg_content)
envpy = self.envpy(real_env_dir=True)
proc = subprocess.run(
[envpy, '-c', 'import sys; print("done")'],
capture_output=True,
text=True,
env={**os.environ, "PYTHONHOME": ""}
)
self.assertNotIn("Consider running `python -m venv --upgrade`", proc.stderr)
@requireVenvCreate
def test_malformed_version_warning(self):
"""
Test that a warning is emitted on malformed version string
in pyenv.cfg
"""
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir, with_pip=False)
cfg_path = self.get_env_file('pyvenv.cfg')
with open(cfg_path, 'r', encoding='utf-8') as f:
cfg_content = f.read()
malformed_version = "not.a.version"
if 'version =' in cfg_content:
cfg_content = re.sub(r'version = .+', f'version = {malformed_version}', cfg_content)
with open(cfg_path, 'w', encoding='utf-8') as f:
f.write(cfg_content)
envpy = self.envpy(real_env_dir=True)
proc = subprocess.run(
[envpy, '-c', 'import sys; print("done")'],
capture_output=True,
text=True,
env={**os.environ, "PYTHONHOME": ""}
)
self.assertIn("Malformed version string", proc.stderr)
self.assertIn(malformed_version, proc.stderr)
@requireVenvCreate
def test_malformed_version_info_warning(self):
"""
Test that a warning is emitted on malformed version_info string
in pyenv.cfg
"""
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir, with_pip=False)
cfg_path = self.get_env_file('pyvenv.cfg')
with open(cfg_path, 'r', encoding='utf-8') as f:
cfg_content = f.read()
malformed_version = "invalid.version"
cfg_content += f'\nversion_info = {malformed_version}\n'
with open(cfg_path, 'w', encoding='utf-8') as f:
f.write(cfg_content)
envpy = self.envpy(real_env_dir=True)
proc = subprocess.run(
[envpy, '-c', 'import sys; print("done")'],
capture_output=True,
text=True,
env={**os.environ, "PYTHONHOME": ""}
)
self.assertIn("Malformed version_info string", proc.stderr)
self.assertIn(malformed_version, proc.stderr)
@requireVenvCreate
def test_conflicting_version_fields(self):
"""
Test behavior when both version and version_info are present
but contain different values. Should warn based on first mismatch found.
"""
rmtree(self.env_dir)
wrong_minor = sys.version_info.minor + 1
self.run_with_capture(venv.create, self.env_dir, with_pip=False)
cfg_path = self.get_env_file('pyvenv.cfg')
with open(cfg_path, 'r', encoding='utf-8') as f:
cfg_content = f.read()
version_wrong = f"{sys.version_info.major}.{wrong_minor}"
if 'version =' in cfg_content:
cfg_content = re.sub(r'version = \d+\.\d+', f'version = {version_wrong}', cfg_content)
version_info_wrong = f"{sys.version_info.major}.{wrong_minor + 1}"
cfg_content += f'\nversion_info = {version_info_wrong}\n'
with open(cfg_path, 'w', encoding='utf-8') as f:
f.write(cfg_content)
envpy = self.envpy(real_env_dir=True)
proc = subprocess.run(
[envpy, '-c', 'import sys; print("done")'],
capture_output=True,
text=True,
env={**os.environ, "PYTHONHOME": ""}
)
self.assertIn("Consider running `python -m venv --upgrade`", proc.stderr)
self.assertEqual(proc.stderr.count("Consider running `python -m venv --upgrade`"), 1)
@requireVenvCreate
def test_different_major_version_no_warning(self):
"""
Test that no warning is emitted when major version differs.
The warning should only trigger for same major, different minor.
"""
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir, with_pip=False)
cfg_path = self.get_env_file('pyvenv.cfg')
with open(cfg_path, 'r', encoding='utf-8') as f:
cfg_content = f.read()
different_major = sys.version_info.major + 1
new_version = f"{different_major}.{sys.version_info.minor}"
if 'version =' in cfg_content:
cfg_content = re.sub(r'version = \d+\.\d+', f'version = {new_version}', cfg_content)
with open(cfg_path, 'w', encoding='utf-8') as f:
f.write(cfg_content)
envpy = self.envpy(real_env_dir=True)
proc = subprocess.run(
[envpy, '-c', 'import sys; print("done")'],
capture_output=True,
text=True,
env={**os.environ, "PYTHONHOME": ""}
)
self.assertNotIn("Consider running `python -m venv --upgrade`", proc.stderr)
@requireVenvCreate
@unittest.skipUnless(can_symlink(), 'Needs symlinks')
def test_sysconfig_symlinks(self):
"""
Test that the sysconfig functions work in a virtual environment.
"""
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir, symlinks=True)
cmd = [self.envpy(), '-c', None]
for call, expected in (
# installation scheme
('get_preferred_scheme("prefix")', 'venv'),
('get_default_scheme()', 'venv'),
# build environment
('is_python_build()', str(sysconfig.is_python_build())),
('get_makefile_filename()', sysconfig.get_makefile_filename()),
('get_config_h_filename()', sysconfig.get_config_h_filename()),
('get_config_var("Py_GIL_DISABLED")',
str(sysconfig.get_config_var("Py_GIL_DISABLED")))):
with self.subTest(call):
cmd[2] = 'import sysconfig; print(sysconfig.%s)' % call
out, err = check_output(cmd, encoding='utf-8')
self.assertEqual(out.strip(), expected, err)
for attr, expected in (
('executable', self.envpy()),
# Usually compare to sys.executable, but if we're running in our own
# venv then we really need to compare to our base executable
# HACK: Test fails on POSIX with unversioned binary (PR gh-113033)
#('_base_executable', sys._base_executable),
):
with self.subTest(attr):
cmd[2] = f'import sys; print(sys.{attr})'
out, err = check_output(cmd, encoding='utf-8')
self.assertEqual(out.strip(), expected, err)
if sys.platform == 'win32':
ENV_SUBDIRS = (
('Scripts',),
('Include',),
('Lib',),
('Lib', 'site-packages'),
)
else:
ENV_SUBDIRS = (
('bin',),
('include',),
('lib',),
('lib', 'python%d.%d' % sys.version_info[:2]),
('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
)
def create_contents(self, paths, filename):
"""
Create some files in the environment which are unrelated
to the virtual environment.
"""
for subdirs in paths:
d = os.path.join(self.env_dir, *subdirs)
os.mkdir(d)
fn = os.path.join(d, filename)
with open(fn, 'wb') as f:
f.write(b'Still here?')
@unittest.skipUnless(hasattr(os, 'listxattr'), 'test requires os.listxattr')
def test_install_scripts_selinux(self):
"""
gh-145417: Test that install_scripts does not copy SELinux context
when copying scripts.
"""
with patch('os.listxattr') as listxattr_mock:
venv.create(self.env_dir)
listxattr_mock.assert_not_called()
def test_overwrite_existing(self):
"""
Test creating environment in an existing directory.
"""
self.create_contents(self.ENV_SUBDIRS, 'foo')
venv.create(self.env_dir)
for subdirs in self.ENV_SUBDIRS:
fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
self.assertTrue(os.path.exists(fn))
with open(fn, 'rb') as f:
self.assertEqual(f.read(), b'Still here?')
builder = venv.EnvBuilder(clear=True)
builder.create(self.env_dir)
for subdirs in self.ENV_SUBDIRS:
fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
self.assertFalse(os.path.exists(fn))
def clear_directory(self, path):
for fn in os.listdir(path):
fn = os.path.join(path, fn)
if os.path.islink(fn) or os.path.isfile(fn):
os.remove(fn)
elif os.path.isdir(fn):
rmtree(fn)
def test_unoverwritable_fails(self):
#create a file clashing with directories in the env dir
for paths in self.ENV_SUBDIRS[:3]:
fn = os.path.join(self.env_dir, *paths)
with open(fn, 'wb') as f:
f.write(b'')
self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
self.clear_directory(self.env_dir)
def test_upgrade(self):
"""
Test upgrading an existing environment directory.
"""
# See Issue #21643: the loop needs to run twice to ensure
# that everything works on the upgrade (the first run just creates
# the venv).
for upgrade in (False, True):
builder = venv.EnvBuilder(upgrade=upgrade)
self.run_with_capture(builder.create, self.env_dir)
self.isdir(self.bindir)
self.isdir(self.include)
self.isdir(*self.lib)
fn = self.get_env_file(self.bindir, self.exe)
if not os.path.exists(fn):
# diagnostics for Windows buildbot failures
bd = self.get_env_file(self.bindir)
print('Contents of %r:' % bd)
print(' %r' % os.listdir(bd))
self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
def test_isolation(self):
"""
Test isolation from system site-packages
"""
for ssp, s in ((True, 'true'), (False, 'false')):
builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
builder.create(self.env_dir)
data = self.get_text_file_contents('pyvenv.cfg')
self.assertIn('include-system-site-packages = %s\n' % s, data)
@unittest.skipUnless(can_symlink(), 'Needs symlinks')
def test_symlinking(self):
"""
Test symlinking works as expected
"""
for usl in (False, True):
builder = venv.EnvBuilder(clear=True, symlinks=usl)
builder.create(self.env_dir)
fn = self.get_env_file(self.bindir, self.exe)
# Don't test when False, because e.g. 'python' is always
# symlinked to 'python3.3' in the env, even when symlinking in
# general isn't wanted.
if usl:
if self.cannot_link_exe:
# Symlinking is skipped when our executable is already a
# special app symlink
self.assertFalse(os.path.islink(fn))
else:
self.assertTrue(os.path.islink(fn))
# If a venv is created from a source build and that venv is used to
# run the test, the pyvenv.cfg in the venv created in the test will
# point to the venv being used to run the test, and we lose the link
# to the source build - so Python can't initialise properly.
@requireVenvCreate
def test_executable(self):
"""
Test that the sys.executable value is as expected.
"""
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir)
envpy = self.envpy(real_env_dir=True)
out, err = check_output([envpy, '-c',
'import sys; print(sys.executable)'])
self.assertEqual(out.strip(), envpy.encode())
@unittest.skipUnless(can_symlink(), 'Needs symlinks')
def test_executable_symlinks(self):
"""
Test that the sys.executable value is as expected.
"""
rmtree(self.env_dir)
builder = venv.EnvBuilder(clear=True, symlinks=True)
builder.create(self.env_dir)
envpy = self.envpy(real_env_dir=True)
out, err = check_output([envpy, '-c',
'import sys; print(sys.executable)'])
self.assertEqual(out.strip(), envpy.encode())
# gh-124651: test quoted strings
@unittest.skipIf(os.name == 'nt', 'contains invalid characters on Windows')
@unittest.skipIf(sys.platform == 'cygwin', 'fail to locate cygpython DLL')
def test_special_chars_bash(self):
"""
Test that the template strings are quoted properly (bash)
"""
rmtree(self.env_dir)
bash = shutil.which('bash')
if bash is None:
self.skipTest('bash required for this test')
env_name = '"\';&&$e|\'"'
env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
builder = venv.EnvBuilder(clear=True)
builder.create(env_dir)
activate = os.path.join(env_dir, self.bindir, 'activate')
test_script = os.path.join(self.env_dir, 'test_special_chars.sh')
with open(test_script, "w") as f:
f.write(f'source {shlex.quote(activate)}\n'
'python -c \'import sys; print(sys.executable)\'\n'
'python -c \'import os; print(os.environ["VIRTUAL_ENV"])\'\n'
'deactivate\n')
out, err = check_output([bash, test_script])
lines = out.splitlines()
self.assertTrue(env_name.encode() in lines[0])
self.assertEndsWith(lines[1], env_name.encode())
# gh-124651: test quoted strings
@unittest.skipIf(os.name == 'nt', 'contains invalid characters on Windows')
@unittest.skipIf(sys.platform.startswith('netbsd'),
"NetBSD csh fails with quoted special chars; see gh-139308")
def test_special_chars_csh(self):
"""
Test that the template strings are quoted properly (csh)
"""
rmtree(self.env_dir)
csh = shutil.which('tcsh') or shutil.which('csh')
if csh is None:
self.skipTest('csh required for this test')
env_name = '"\';&&$e|\'"'
env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
builder = venv.EnvBuilder(clear=True)
builder.create(env_dir)
activate = os.path.join(env_dir, self.bindir, 'activate.csh')
test_script = os.path.join(self.env_dir, 'test_special_chars.csh')
with open(test_script, "w") as f:
f.write(f'source {shlex.quote(activate)}\n'
'python -c \'import sys; print(sys.executable)\'\n'
'python -c \'import os; print(os.environ["VIRTUAL_ENV"])\'\n'
'deactivate\n')
out, err = check_output([csh, test_script])
lines = out.splitlines()
self.assertTrue(env_name.encode() in lines[0])
self.assertEndsWith(lines[1], env_name.encode())
# gh-140006: the fish prompt override must keep working when a user
# function shadows a builtin it relies on.
@unittest.skipIf(os.name == 'nt', 'fish is not available on Windows')
def test_fish_activate_shadowed_builtins(self):
"""
The fish prompt override restores the exit status through `source` and
prints through `printf`/`echo`/`set_color`. A user function that
shadows one of those builtins (a common pattern for `.`-style directory
navigators) must not hijack the prompt or break status restoration.
"""
# Some systems have an unrelated "fish" game (see fish(6)), which
# can precede the fish shell in PATH.
for dirname in None, *os.get_exec_path():
fish = shutil.which('fish', path=dirname)
if fish is not None and subprocess.run(
[fish, '-c', 'echo $FISH_VERSION'],
stdin=subprocess.DEVNULL,
capture_output=True).stdout.strip():
break
else:
self.skipTest('fish required for this test')
rmtree(self.env_dir)
builder = venv.EnvBuilder(clear=True)
builder.create(self.env_dir)
activate = os.path.join(self.env_dir, self.bindir, 'activate.fish')
test_script = os.path.join(self.env_dir, 'test_shadowed_builtins.fish')
with open(test_script, "w") as f:
f.write(
# The pre-existing prompt reports the status it receives;
# activation copies it to _old_fish_prompt.
'function fish_prompt; builtin echo "OLDSTATUS=$status"; end\n'
f'source {shlex.quote(activate)}\n'
# Shadow every builtin the override uses. A dot-navigator that
# lists the directory is the reported failure.
'function .; builtin echo DOT_LEAK; end\n'
'function source; builtin echo SOURCE_LEAK; end\n'
'function echo; command echo ECHO_LEAK; end\n'
'function printf; command printf PRINTF_LEAK; end\n'
'function set_color; command true; end\n'
'function _exit7; return 7; end\n'
'_exit7\n'
'fish_prompt\n'
)
out, err = check_output([fish, '--no-config', test_script])
text = out.decode()
self.assertNotIn('LEAK', text)
self.assertIn('OLDSTATUS=7', text)
# gh-124651: test quoted strings on Windows
@unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
def test_special_chars_windows(self):
"""
Test that the template strings are quoted properly on Windows
"""
rmtree(self.env_dir)
env_name = "'&&^$e"
env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
builder = venv.EnvBuilder(clear=True)
builder.create(env_dir)
activate = os.path.join(env_dir, self.bindir, 'activate.bat')
test_batch = os.path.join(self.env_dir, 'test_special_chars.bat')
with open(test_batch, "w") as f:
f.write('@echo off\n'
f'"{activate}" & '
f'{self.exe} -c "import sys; print(sys.executable)" & '
f'{self.exe} -c "import os; print(os.environ[\'VIRTUAL_ENV\'])" & '
'deactivate')
out, err = check_output([test_batch])
lines = out.splitlines()
self.assertTrue(env_name.encode() in lines[0])
self.assertEndsWith(lines[1], env_name.encode())
@unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
def test_unicode_in_batch_file(self):
"""
Test handling of Unicode paths
"""
rmtree(self.env_dir)
env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
builder = venv.EnvBuilder(clear=True)
builder.create(env_dir)
activate = os.path.join(env_dir, self.bindir, 'activate.bat')
out, err = check_output(
[activate, '&', self.exe, '-c', 'print(0)'],
encoding='oem',
)
self.assertEqual(out.strip(), '0')
@unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
def test_activate_bat_respects_disable_prompt(self):
rmtree(self.env_dir)
env_dir = os.path.join(os.path.realpath(self.env_dir), 'venv')
builder = venv.EnvBuilder(clear=True)
builder.create(env_dir)
activate = os.path.join(env_dir, self.bindir, 'activate.bat')
test_batch = os.path.join(self.env_dir, 'test_disable_prompt.bat')
with open(test_batch, "w") as f:
f.write('@echo off\n'
'set "PROMPT=base$G"\n'
'set "VIRTUAL_ENV_DISABLE_PROMPT=1"\n'
f'call "{activate}"\n'
'echo ACTIVE_PROMPT:%PROMPT%\n'
'echo VIRTUAL_ENV:%VIRTUAL_ENV%\n'
'set "PROMPT=changed$G"\n'
'call deactivate\n'
'echo FINAL_PROMPT:%PROMPT%\n')
out, err = check_output([test_batch])
lines = out.splitlines()
self.assertEqual(lines[0], b'ACTIVE_PROMPT:base$G')
self.assertEndsWith(lines[1], os.fsencode(env_dir))
self.assertEqual(lines[2], b'FINAL_PROMPT:changed$G')
@unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
def test_activate_bat_prefixes_prompt_by_default(self):
rmtree(self.env_dir)
env_dir = os.path.join(os.path.realpath(self.env_dir), 'venv')
builder = venv.EnvBuilder(clear=True)
builder.create(env_dir)
activate = os.path.join(env_dir, self.bindir, 'activate.bat')
test_batch = os.path.join(self.env_dir, 'test_enable_prompt.bat')
with open(test_batch, "w") as f:
f.write('@echo off\n'
'set "PROMPT=base) $G"\n'
'set "VIRTUAL_ENV_DISABLE_PROMPT="\n'
f'call "{activate}"\n'
'echo ACTIVE_PROMPT:%PROMPT%\n'
'call deactivate\n'
'echo FINAL_PROMPT:%PROMPT%\n')
out, err = check_output([test_batch])
lines = out.splitlines()
self.assertEqual(lines[0], b'ACTIVE_PROMPT:(venv) base) $G')
self.assertEqual(lines[1], b'FINAL_PROMPT:base) $G')
@unittest.skipUnless(os.name == 'nt' and can_symlink(),
'symlinks on Windows')
def test_failed_symlink(self):
"""
Test handling of failed symlinks on Windows.
"""
rmtree(self.env_dir)
env_dir = os.path.join(os.path.realpath(self.env_dir), 'venv')
with patch('os.symlink') as mock_symlink:
mock_symlink.side_effect = OSError()
builder = venv.EnvBuilder(clear=True, symlinks=True)
_, err = self.run_with_capture(builder.create, env_dir)
filepath_regex = r"'[A-Z]:\\\\(?:[^\\\\]+\\\\)*[^\\\\]+'"
self.assertRegex(err, rf"Unable to symlink {filepath_regex} to {filepath_regex}")
@requireVenvCreate
def test_multiprocessing(self):
"""
Test that the multiprocessing is able to spawn.
"""
# bpo-36342: Instantiation of a Pool object imports the
# multiprocessing.synchronize module. Skip the test if this module
# cannot be imported.
skip_if_broken_multiprocessing_synchronize()
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir)
out, err = check_output([self.envpy(real_env_dir=True), '-c',
'from multiprocessing import Pool; '
'pool = Pool(1); '
'print(pool.apply_async("Python".lower).get(3)); '
'pool.terminate()'])
self.assertEqual(out.strip(), "python".encode())
@requireVenvCreate
def test_multiprocessing_recursion(self):
"""
Test that the multiprocessing is able to spawn itself
"""
skip_if_broken_multiprocessing_synchronize()
rmtree(self.env_dir)
self.run_with_capture(venv.create, self.env_dir)
script = os.path.join(TEST_HOME_DIR, '_test_venv_multiprocessing.py')
subprocess.check_call([self.envpy(real_env_dir=True), "-I", script])
@unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
def test_deactivate_with_strict_bash_opts(self):
bash = shutil.which("bash")
if bash is None:
self.skipTest("bash required for this test")
rmtree(self.env_dir)
builder = venv.EnvBuilder(clear=True)
builder.create(self.env_dir)
activate = os.path.join(self.env_dir, self.bindir, "activate")
test_script = os.path.join(self.env_dir, "test_strict.sh")
with open(test_script, "w") as f:
f.write("set -euo pipefail\n"
f"source {activate}\n"
"deactivate\n")
out, err = check_output([bash, test_script])
self.assertEqual(out, "".encode())
self.assertEqual(err, "".encode())
# gh-149701: Test exit code is zero even when hashing is disabled
@unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
def test_deactivate_with_strict_bash_opts_and_hashing_disabled(self):
bash = shutil.which("bash")
if bash is None:
self.skipTest("bash required for this test")
rmtree(self.env_dir)
builder = venv.EnvBuilder(clear=True)
builder.create(self.env_dir)
activate = os.path.join(self.env_dir, self.bindir, "activate")
test_script = os.path.join(self.env_dir, "test_hash_disabled.sh")
with open(test_script, "w") as f:
f.write("set -euo pipefail\n"
"set +h\n" # disable hashing
f"source {activate}\n"
"deactivate")
out, err = check_output([bash, test_script])
self.assertEqual(out, "".encode())
self.assertEqual(err, "".encode())
@unittest.skipUnless(sys.platform == 'darwin', 'only relevant on macOS')
def test_macos_env(self):
rmtree(self.env_dir)
builder = venv.EnvBuilder()
builder.create(self.env_dir)
out, err = check_output([self.envpy(real_env_dir=True), '-c',