Debian Codegraph @

Lib/test/test_site.py

raw ◀ ▶
1 Debian patch touch this file
1 """Tests for 'site'.
2
3 Tests assume the initial paths in sys.path once the interpreter has begun
4 executing have not been removed.
5
6 """
7 import unittest
8 import test.support
9 from test import support
10 from test.support.script_helper import assert_python_ok
11 from test.support import os_helper
12 from test.support import socket_helper
13 from test.support import captured_stderr
14 from test.support.os_helper import TESTFN, EnvironmentVarGuard
15 from test.support.script_helper import spawn_python, kill_python
16 import ast
17 import builtins
18 import glob
19 import io
20 import os
21 import re
22 import shutil
23 import stat
24 import subprocess
25 import sys
26 import sysconfig
27 import tempfile
28 from textwrap import dedent
29 import urllib.error
30 import urllib.request
31 from unittest import mock
32 from copy import copy
33
34 # These tests are not particularly useful if Python was invoked with -S.
35 # If you add tests that are useful under -S, this skip should be moved
36 # to the class level.
37 if sys.flags.no_site:
38 raise unittest.SkipTest("Python was invoked with -S")
39
40 import site
41
42
43 HAS_USER_SITE = (site.USER_SITE is not None)
44 OLD_SYS_PATH = None
45
46
47 def setUpModule():
48 global OLD_SYS_PATH
49 OLD_SYS_PATH = sys.path[:]
50
51 if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
52 # need to add user site directory for tests
53 try:
54 os.makedirs(site.USER_SITE)
55 # modify sys.path: will be restored by tearDownModule()
56 site.addsitedir(site.USER_SITE)
57 except PermissionError as exc:
58 raise unittest.SkipTest('unable to create user site directory (%r): %s'
59 % (site.USER_SITE, exc))
60
61
62 def tearDownModule():
63 sys.path[:] = OLD_SYS_PATH
64
65
66 class HelperFunctionsTests(unittest.TestCase):
67 """Tests for helper functions.
68 """
69
70 def setUp(self):
71 """Save a copy of sys.path"""
72 self.sys_path = sys.path[:]
73 self.old_base = site.USER_BASE
74 self.old_site = site.USER_SITE
75 self.old_prefixes = site.PREFIXES
76 self.original_vars = sysconfig._CONFIG_VARS
77 self.old_vars = copy(sysconfig._CONFIG_VARS)
78
79 def tearDown(self):
80 """Restore sys.path"""
81 sys.path[:] = self.sys_path
82 site.USER_BASE = self.old_base
83 site.USER_SITE = self.old_site
84 site.PREFIXES = self.old_prefixes
85 sysconfig._CONFIG_VARS = self.original_vars
86 # _CONFIG_VARS is None before get_config_vars() is called
87 if sysconfig._CONFIG_VARS is not None:
88 sysconfig._CONFIG_VARS.clear()
89 sysconfig._CONFIG_VARS.update(self.old_vars)
90
91 def test_makepath(self):
92 # Test makepath() have an absolute path for its first return value
93 # and a case-normalized version of the absolute path for its
94 # second value.
95 path_parts = ("Beginning", "End")
96 original_dir = os.path.join(*path_parts)
97 abs_dir, norm_dir = site.makepath(*path_parts)
98 self.assertEqual(os.path.abspath(original_dir), abs_dir)
99 if original_dir == os.path.normcase(original_dir):
100 self.assertEqual(abs_dir, norm_dir)
101 else:
102 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
103
104 def test_init_pathinfo(self):
105 dir_set = site._init_pathinfo()
106 for entry in [site.makepath(path)[1] for path in sys.path
107 if path and os.path.exists(path)]:
108 self.assertIn(entry, dir_set,
109 "%s from sys.path not found in set returned "
110 "by _init_pathinfo(): %s" % (entry, dir_set))
111
112 def pth_file_tests(self, pth_file):
113 """Contain common code for testing results of reading a .pth file"""
114 self.assertIn(pth_file.imported, sys.modules,
115 "%s not in sys.modules" % pth_file.imported)
116 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
117 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
118
119 def test_addpackage(self):
120 # Make sure addpackage() imports if the line starts with 'import',
121 # adds directories to sys.path for any line in the file that is not a
122 # comment or import that is a valid directory name for where the .pth
123 # file resides; invalid directories are not added
124 pth_file = PthFile()
125 pth_file.cleanup(prep=True) # to make sure that nothing is
126 # pre-existing that shouldn't be
127 try:
128 pth_file.create()
129 site.addpackage(pth_file.base_dir, pth_file.filename, set())
130 self.pth_file_tests(pth_file)
131 finally:
132 pth_file.cleanup()
133
134 def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
135 # Create a .pth file and return its (abspath, basename).
136 pth_dir = os.path.abspath(pth_dir)
137 pth_basename = pth_name + '.pth'
138 pth_fn = os.path.join(pth_dir, pth_basename)
139 with open(pth_fn, 'w', encoding='utf-8') as pth_file:
140 self.addCleanup(lambda: os.remove(pth_fn))
141 pth_file.write(contents)
142 return pth_dir, pth_basename
143
144 def test_addpackage_import_bad_syntax(self):
145 # Issue 10642
146 pth_dir, pth_fn = self.make_pth("import bad-syntax\n")
147 with captured_stderr() as err_out:
148 site.addpackage(pth_dir, pth_fn, set())
149 self.assertRegex(err_out.getvalue(), "line 1")
150 self.assertRegex(err_out.getvalue(),
151 re.escape(os.path.join(pth_dir, pth_fn)))
152 # XXX: the previous two should be independent checks so that the
153 # order doesn't matter. The next three could be a single check
154 # but my regex foo isn't good enough to write it.
155 self.assertRegex(err_out.getvalue(), 'Traceback')
156 self.assertRegex(err_out.getvalue(), r'import bad-syntax')
157 self.assertRegex(err_out.getvalue(), 'SyntaxError')
158
159 def test_addpackage_import_bad_exec(self):
160 # Issue 10642
161 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
162 with captured_stderr() as err_out:
163 site.addpackage(pth_dir, pth_fn, set())
164 self.assertRegex(err_out.getvalue(), "line 2")
165 self.assertRegex(err_out.getvalue(),
166 re.escape(os.path.join(pth_dir, pth_fn)))
167 # XXX: ditto previous XXX comment.
168 self.assertRegex(err_out.getvalue(), 'Traceback')
169 self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError')
170
171 def test_addpackage_empty_lines(self):
172 # Issue 33689
173 pth_dir, pth_fn = self.make_pth("\n\n \n\n")
174 known_paths = site.addpackage(pth_dir, pth_fn, set())
175 self.assertEqual(known_paths, set())
176
177 def test_addpackage_import_bad_pth_file(self):
178 # Issue 5258
179 pth_dir, pth_fn = self.make_pth("abc\x00def\n")
180 with captured_stderr() as err_out:
181 self.assertFalse(site.addpackage(pth_dir, pth_fn, set()))
182 self.maxDiff = None
183 self.assertEqual(err_out.getvalue(), "")
184 for path in sys.path:
185 if isinstance(path, str):
186 self.assertNotIn("abc\x00def", path)
187
188 def test_addsitedir(self):
189 # Same tests for test_addpackage since addsitedir() essentially just
190 # calls addpackage() for every .pth file in the directory
191 pth_file = PthFile()
192 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
193 # that is tested for
194 try:
195 pth_file.create()
196 site.addsitedir(pth_file.base_dir, set())
197 self.pth_file_tests(pth_file)
198 finally:
199 pth_file.cleanup()
200
201 def test_addsitedir_dotfile(self):
202 pth_file = PthFile('.dotfile')
203 pth_file.cleanup(prep=True)
204 try:
205 pth_file.create()
206 site.addsitedir(pth_file.base_dir, set())
207 self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
208 self.assertIn(pth_file.base_dir, sys.path)
209 finally:
210 pth_file.cleanup()
211
212 @unittest.skipUnless(hasattr(os, 'chflags'), 'test needs os.chflags()')
213 def test_addsitedir_hidden_flags(self):
214 pth_file = PthFile()
215 pth_file.cleanup(prep=True)
216 try:
217 pth_file.create()
218 st = os.stat(pth_file.file_path)
219 os.chflags(pth_file.file_path, st.st_flags | stat.UF_HIDDEN)
220 site.addsitedir(pth_file.base_dir, set())
221 self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
222 self.assertIn(pth_file.base_dir, sys.path)
223 finally:
224 pth_file.cleanup()
225
226 @unittest.skipUnless(sys.platform == 'win32', 'test needs Windows')
227 @support.requires_subprocess()
228 def test_addsitedir_hidden_file_attribute(self):
229 pth_file = PthFile()
230 pth_file.cleanup(prep=True)
231 try:
232 pth_file.create()
233 subprocess.check_call(['attrib', '+H', pth_file.file_path])
234 site.addsitedir(pth_file.base_dir, set())
235 self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
236 self.assertIn(pth_file.base_dir, sys.path)
237 finally:
238 pth_file.cleanup()
239
240 # This tests _getuserbase, hence the double underline
241 # to distinguish from a test for getuserbase
242 def test__getuserbase(self):
243 self.assertEqual(site._getuserbase(), sysconfig._getuserbase())
244
245 @unittest.skipUnless(HAS_USER_SITE, 'need user site')
246 def test_get_path(self):
247 if sys.platform == 'darwin' and sys._framework:
248 scheme = 'osx_framework_user'
249 else:
250 scheme = os.name + '_user'
251 self.assertEqual(os.path.normpath(site._get_path(site._getuserbase())),
252 sysconfig.get_path('purelib', scheme))
253
254 @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
255 "user-site (site.ENABLE_USER_SITE)")
256 @support.requires_subprocess()
257 def test_s_option(self):
258 # (ncoghlan) Change this to use script_helper...
259 usersite = os.path.normpath(site.USER_SITE)
260 self.assertIn(usersite, sys.path)
261
262 env = os.environ.copy()
263 rc = subprocess.call([sys.executable, '-c',
264 'import sys; sys.exit(%r in sys.path)' % usersite],
265 env=env)
266 self.assertEqual(rc, 1)
267
268 env = os.environ.copy()
269 rc = subprocess.call([sys.executable, '-s', '-c',
270 'import sys; sys.exit(%r in sys.path)' % usersite],
271 env=env)
272 if usersite == site.getsitepackages()[0]:
273 self.assertEqual(rc, 1)
274 else:
275 self.assertEqual(rc, 0, "User site still added to path with -s")
276
277 env = os.environ.copy()
278 env["PYTHONNOUSERSITE"] = "1"
279 rc = subprocess.call([sys.executable, '-c',
280 'import sys; sys.exit(%r in sys.path)' % usersite],
281 env=env)
282 if usersite == site.getsitepackages()[0]:
283 self.assertEqual(rc, 1)
284 else:
285 self.assertEqual(rc, 0,
286 "User site still added to path with PYTHONNOUSERSITE")
287
288 env = os.environ.copy()
289 env["PYTHONUSERBASE"] = "/tmp"
290 rc = subprocess.call([sys.executable, '-c',
291 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
292 env=env)
293 self.assertEqual(rc, 1,
294 "User base not set by PYTHONUSERBASE")
295
296 @unittest.skipUnless(HAS_USER_SITE, 'need user site')
297 def test_getuserbase(self):
298 site.USER_BASE = None
299 user_base = site.getuserbase()
300
301 # the call sets site.USER_BASE
302 self.assertEqual(site.USER_BASE, user_base)
303
304 # let's set PYTHONUSERBASE and see if it uses it
305 site.USER_BASE = None
306 import sysconfig
307 sysconfig._CONFIG_VARS = None
308
309 with EnvironmentVarGuard() as environ:
310 environ['PYTHONUSERBASE'] = 'xoxo'
311 self.assertTrue(site.getuserbase().startswith('xoxo'),
312 site.getuserbase())
313
314 @unittest.skipUnless(HAS_USER_SITE, 'need user site')
315 def test_getusersitepackages(self):
316 site.USER_SITE = None
317 site.USER_BASE = None
318 user_site = site.getusersitepackages()
319
320 # the call sets USER_BASE *and* USER_SITE
321 self.assertEqual(site.USER_SITE, user_site)
322 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
323 self.assertEqual(site.USER_BASE, site.getuserbase())
324
325 def test_getsitepackages(self):
326 site.PREFIXES = ['xoxo']
327 dirs = site.getsitepackages()
328 if os.sep == '/':
329 # OS X, Linux, FreeBSD, etc
330 if sys.platlibdir != "lib":
•331 self.assertEqual(len(dirs), 3)
332 wanted = os.path.join('xoxo', 'local', 'lib',
333 f'python{sysconfig._get_python_version_abi()}',
•334 'dist-packages')
335 self.assertEqual(dirs[0], wanted)
336 else:
•337 self.assertEqual(len(dirs), 3)
338 wanted = os.path.join('xoxo', 'lib',
339 f'python{sysconfig._get_python_version_abi()}',
•340 'dist-packages')
341 self.assertEqual(dirs[-1], wanted)
342 else:
343 # other platforms
344 self.assertEqual(len(dirs), 2)
345 self.assertEqual(dirs[0], 'xoxo')
346 wanted = os.path.join('xoxo', 'lib', 'site-packages')
347 self.assertEqual(os.path.normcase(dirs[1]),
348 os.path.normcase(wanted))
349
350 @unittest.skipUnless(HAS_USER_SITE, 'need user site')
351 def test_no_home_directory(self):
352 # bpo-10496: getuserbase() and getusersitepackages() must not fail if
353 # the current user has no home directory (if expanduser() returns the
354 # path unchanged).
355 site.USER_SITE = None
356 site.USER_BASE = None
357
358 with EnvironmentVarGuard() as environ, \
359 mock.patch('os.path.expanduser', lambda path: path):
360 environ.unset('PYTHONUSERBASE', 'APPDATA')
361
362 user_base = site.getuserbase()
363 self.assertTrue(user_base.startswith('~' + os.sep),
364 user_base)
365
366 user_site = site.getusersitepackages()
367 self.assertTrue(user_site.startswith(user_base), user_site)
368
369 with mock.patch('os.path.isdir', return_value=False) as mock_isdir, \
370 mock.patch.object(site, 'addsitedir') as mock_addsitedir, \
371 support.swap_attr(site, 'ENABLE_USER_SITE', True):
372
373 # addusersitepackages() must not add user_site to sys.path
374 # if it is not an existing directory
375 known_paths = set()
376 site.addusersitepackages(known_paths)
377
378 mock_isdir.assert_called_once_with(user_site)
379 mock_addsitedir.assert_not_called()
380 self.assertFalse(known_paths)
381
382 def test_gethistoryfile(self):
383 filename = 'file'
384 rc, out, err = assert_python_ok('-c',
385 f'import site; assert site.gethistoryfile() == "{filename}"',
386 PYTHON_HISTORY=filename)
387 self.assertEqual(rc, 0)
388
389 # Check that PYTHON_HISTORY is ignored in isolated mode.
390 rc, out, err = assert_python_ok('-I', '-c',
391 f'import site; assert site.gethistoryfile() != "{filename}"',
392 PYTHON_HISTORY=filename)
393 self.assertEqual(rc, 0)
394
395 def test_trace(self):
396 message = "bla-bla-bla"
397 for verbose, out in (True, message + "\n"), (False, ""):
398 with mock.patch('sys.flags', mock.Mock(verbose=verbose)), \
399 mock.patch('sys.stderr', io.StringIO()):
400 site._trace(message)
401 self.assertEqual(sys.stderr.getvalue(), out)
402
403
404 class PthFile(object):
405 """Helper class for handling testing of .pth files"""
406
407 def __init__(self, filename_base=TESTFN, imported="time",
408 good_dirname="__testdir__", bad_dirname="__bad"):
409 """Initialize instance variables"""
410 self.filename = filename_base + ".pth"
411 self.base_dir = os.path.abspath('')
412 self.file_path = os.path.join(self.base_dir, self.filename)
413 self.imported = imported
414 self.good_dirname = good_dirname
415 self.bad_dirname = bad_dirname
416 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
417 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
418
419 def create(self):
420 """Create a .pth file with a comment, blank lines, an ``import
421 <self.imported>``, a line with self.good_dirname, and a line with
422 self.bad_dirname.
423
424 Creation of the directory for self.good_dir_path (based off of
425 self.good_dirname) is also performed.
426
427 Make sure to call self.cleanup() to undo anything done by this method.
428
429 """
430 FILE = open(self.file_path, 'w')
431 try:
432 print("#import @bad module name", file=FILE)
433 print("\n", file=FILE)
434 print("import %s" % self.imported, file=FILE)
435 print(self.good_dirname, file=FILE)
436 print(self.bad_dirname, file=FILE)
437 finally:
438 FILE.close()
439 os.mkdir(self.good_dir_path)
440
441 def cleanup(self, prep=False):
442 """Make sure that the .pth file is deleted, self.imported is not in
443 sys.modules, and that both self.good_dirname and self.bad_dirname are
444 not existing directories."""
445 if os.path.exists(self.file_path):
446 os.remove(self.file_path)
447 if prep:
448 self.imported_module = sys.modules.get(self.imported)
449 if self.imported_module:
450 del sys.modules[self.imported]
451 else:
452 if self.imported_module:
453 sys.modules[self.imported] = self.imported_module
454 if os.path.exists(self.good_dir_path):
455 os.rmdir(self.good_dir_path)
456 if os.path.exists(self.bad_dir_path):
457 os.rmdir(self.bad_dir_path)
458
459 class ImportSideEffectTests(unittest.TestCase):
460 """Test side-effects from importing 'site'."""
461
462 def setUp(self):
463 """Make a copy of sys.path"""
464 self.sys_path = sys.path[:]
465
466 def tearDown(self):
467 """Restore sys.path"""
468 sys.path[:] = self.sys_path
469
470 def test_abs_paths_cached_None(self):
471 """Test for __cached__ is None.
472
473 Regarding to PEP 3147, __cached__ can be None.
474
475 See also: https://bugs.python.org/issue30167
476 """
477 sys.modules['test'].__cached__ = None
478 site.abs_paths()
479 self.assertIsNone(sys.modules['test'].__cached__)
480
481 def test_no_duplicate_paths(self):
482 # No duplicate paths should exist in sys.path
483 # Handled by removeduppaths()
484 site.removeduppaths()
485 seen_paths = set()
486 for path in sys.path:
487 self.assertNotIn(path, seen_paths)
488 seen_paths.add(path)
489
490 @unittest.skip('test not implemented')
491 def test_add_build_dir(self):
492 # Test that the build directory's Modules directory is used when it
493 # should be.
494 # XXX: implement
495 pass
496
497 def test_setting_quit(self):
498 # 'quit' and 'exit' should be injected into builtins
499 self.assertTrue(hasattr(builtins, "quit"))
500 self.assertTrue(hasattr(builtins, "exit"))
501
502 def test_setting_copyright(self):
503 # 'copyright', 'credits', and 'license' should be in builtins
504 self.assertTrue(hasattr(builtins, "copyright"))
505 self.assertTrue(hasattr(builtins, "credits"))
506 self.assertTrue(hasattr(builtins, "license"))
507
508 def test_setting_help(self):
509 # 'help' should be set in builtins
510 self.assertTrue(hasattr(builtins, "help"))
511
512 def test_sitecustomize_executed(self):
513 # If sitecustomize is available, it should have been imported.
514 if "sitecustomize" not in sys.modules:
515 try:
516 import sitecustomize
517 except ImportError:
518 pass
519 else:
520 self.fail("sitecustomize not imported automatically")
521
522 @support.requires_subprocess()
523 def test_customization_modules_on_startup(self):
524 mod_names = [
525 'sitecustomize'
526 ]
527
528 if site.ENABLE_USER_SITE:
529 mod_names.append('usercustomize')
530
531 temp_dir = tempfile.mkdtemp()
532 self.addCleanup(os_helper.rmtree, temp_dir)
533
534 with EnvironmentVarGuard() as environ:
535 environ['PYTHONPATH'] = temp_dir
536
537 for module_name in mod_names:
538 os_helper.rmtree(temp_dir)
539 os.mkdir(temp_dir)
540
541 customize_path = os.path.join(temp_dir, f'{module_name}.py')
542 eyecatcher = f'EXECUTED_{module_name}'
543
544 with open(customize_path, 'w') as f:
545 f.write(f'print("{eyecatcher}")')
546
547 output = subprocess.check_output([sys.executable, '-c', '""'])
548 self.assertIn(eyecatcher, output.decode('utf-8'))
549
550 # -S blocks any site-packages
551 output = subprocess.check_output([sys.executable, '-S', '-c', '""'])
552 self.assertNotIn(eyecatcher, output.decode('utf-8'))
553
554 # -s blocks user site-packages
555 if 'usercustomize' == module_name:
556 output = subprocess.check_output([sys.executable, '-s', '-c', '""'])
557 self.assertNotIn(eyecatcher, output.decode('utf-8'))
558
559
560 @unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"),
561 'need SSL support to download license')
562 @test.support.requires_resource('network')
563 @test.support.system_must_validate_cert
564 def test_license_exists_at_url(self):
565 # This test is a bit fragile since it depends on the format of the
566 # string displayed by license in the absence of a LICENSE file.
567 url = license._Printer__data.split()[1]
568 req = urllib.request.Request(url, method='HEAD')
569 # Reset global urllib.request._opener
570 self.addCleanup(urllib.request.urlcleanup)
571 try:
572 with socket_helper.transient_internet(url):
573 with urllib.request.urlopen(req) as data:
574 code = data.getcode()
575 except urllib.error.HTTPError as e:
576 code = e.code
577 self.assertEqual(code, 200, msg="Can't find " + url)
578
579
580 class StartupImportTests(unittest.TestCase):
581
582 @support.requires_subprocess()
583 def test_startup_imports(self):
584 # Get sys.path in isolated mode (python3 -I)
585 popen = subprocess.Popen([sys.executable, '-X', 'utf8', '-I',
586 '-c', 'import sys; print(repr(sys.path))'],
587 stdout=subprocess.PIPE,
588 encoding='utf-8',
589 errors='surrogateescape')
590 stdout = popen.communicate()[0]
591 self.assertEqual(popen.returncode, 0, repr(stdout))
592 isolated_paths = ast.literal_eval(stdout)
593
594 # bpo-27807: Even with -I, the site module executes all .pth files
595 # found in sys.path (see site.addpackage()). Skip the test if at least
596 # one .pth file is found.
597 for path in isolated_paths:
598 pth_files = glob.glob(os.path.join(glob.escape(path), "*.pth"))
599 if pth_files:
600 self.skipTest(f"found {len(pth_files)} .pth files in: {path}")
601
602 # This tests checks which modules are loaded by Python when it
603 # initially starts upon startup.
604 popen = subprocess.Popen([sys.executable, '-X', 'utf8', '-I', '-v',
605 '-c', 'import sys; print(set(sys.modules))'],
606 stdout=subprocess.PIPE,
607 stderr=subprocess.PIPE,
608 encoding='utf-8',
609 errors='surrogateescape')
610 stdout, stderr = popen.communicate()
611 self.assertEqual(popen.returncode, 0, (stdout, stderr))
612 modules = ast.literal_eval(stdout)
613
614 self.assertIn('site', modules)
615
616 # http://bugs.python.org/issue19205
617 re_mods = {'re', '_sre', 're._compiler', 're._constants', 're._parser'}
618 self.assertFalse(modules.intersection(re_mods), stderr)
619
620 # http://bugs.python.org/issue9548
621 self.assertNotIn('locale', modules, stderr)
622
623 # http://bugs.python.org/issue19209
624 self.assertNotIn('copyreg', modules, stderr)
625
626 # http://bugs.python.org/issue19218
627 collection_mods = {'_collections', 'collections', 'functools',
628 'heapq', 'itertools', 'keyword', 'operator',
629 'reprlib', 'types', 'weakref'
630 }.difference(sys.builtin_module_names)
631 self.assertFalse(modules.intersection(collection_mods), stderr)
632
633 @support.requires_subprocess()
634 def test_startup_interactivehook(self):
635 r = subprocess.Popen([sys.executable, '-c',
636 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
637 self.assertTrue(r, "'__interactivehook__' not added by site")
638
639 @support.requires_subprocess()
640 def test_startup_interactivehook_isolated(self):
641 # issue28192 readline is not automatically enabled in isolated mode
642 r = subprocess.Popen([sys.executable, '-I', '-c',
643 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
644 self.assertFalse(r, "'__interactivehook__' added in isolated mode")
645
646 @support.requires_subprocess()
647 def test_startup_interactivehook_isolated_explicit(self):
648 # issue28192 readline can be explicitly enabled in isolated mode
649 r = subprocess.Popen([sys.executable, '-I', '-c',
650 'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
651 self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()")
652
653 class _pthFileTests(unittest.TestCase):
654
655 if sys.platform == 'win32':
656 def _create_underpth_exe(self, lines, exe_pth=True):
657 import _winapi
658 temp_dir = tempfile.mkdtemp()
659 self.addCleanup(os_helper.rmtree, temp_dir)
660 exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1])
661 dll_src_file = _winapi.GetModuleFileName(sys.dllhandle)
662 dll_file = os.path.join(temp_dir, os.path.split(dll_src_file)[1])
663 shutil.copy(sys.executable, exe_file)
664 shutil.copy(dll_src_file, dll_file)
665 for fn in glob.glob(os.path.join(os.path.split(dll_src_file)[0], "vcruntime*.dll")):
666 shutil.copy(fn, os.path.join(temp_dir, os.path.split(fn)[1]))
667 if exe_pth:
668 _pth_file = os.path.splitext(exe_file)[0] + '._pth'
669 else:
670 _pth_file = os.path.splitext(dll_file)[0] + '._pth'
671 with open(_pth_file, 'w', encoding='utf8') as f:
672 for line in lines:
673 print(line, file=f)
674 return exe_file
675 else:
676 def _create_underpth_exe(self, lines, exe_pth=True):
677 if not exe_pth:
678 raise unittest.SkipTest("library ._pth file not supported on this platform")
679 temp_dir = tempfile.mkdtemp()
680 self.addCleanup(os_helper.rmtree, temp_dir)
681 exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1])
682 os.symlink(sys.executable, exe_file)
683 _pth_file = exe_file + '._pth'
684 with open(_pth_file, 'w') as f:
685 for line in lines:
686 print(line, file=f)
687 return exe_file
688
689 def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines):
690 sys_path = []
691 for line in lines:
692 if not line or line[0] == '#':
693 continue
694 abs_path = os.path.abspath(os.path.join(sys_prefix, line))
695 sys_path.append(abs_path)
696 return sys_path
697
698 def _get_pth_lines(self, libpath: str, *, import_site: bool):
699 pth_lines = ['fake-path-name']
700 # include 200 lines of `libpath` in _pth lines (or fewer
701 # if the `libpath` is long enough to get close to 32KB
702 # see https://github.com/python/cpython/issues/113628)
703 encoded_libpath_length = len(libpath.encode("utf-8"))
704 repetitions = min(200, 30000 // encoded_libpath_length)
705 if repetitions <= 2:
706 self.skipTest(
707 f"Python stdlib path is too long ({encoded_libpath_length:,} bytes)")
708 pth_lines.extend(libpath for _ in range(repetitions))
709 pth_lines.extend(['', '# comment'])
710 if import_site:
711 pth_lines.append('import site')
712 return pth_lines
713
714 @support.requires_subprocess()
715 def test_underpth_basic(self):
716 pth_lines = ['#.', '# ..', *sys.path, '.', '..']
717 exe_file = self._create_underpth_exe(pth_lines)
718 sys_path = self._calc_sys_path_for_underpth_nosite(
719 os.path.dirname(exe_file),
720 pth_lines)
721
722 output = subprocess.check_output([exe_file, '-X', 'utf8', '-c',
723 'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")'
724 ], encoding='utf-8', errors='surrogateescape')
725 actual_sys_path = output.rstrip().split('\n')
726 self.assertTrue(actual_sys_path, "sys.flags.no_site was False")
727 self.assertEqual(
728 actual_sys_path,
729 sys_path,
730 "sys.path is incorrect"
731 )
732
733 @support.requires_subprocess()
734 def test_underpth_nosite_file(self):
735 libpath = test.support.STDLIB_DIR
736 exe_prefix = os.path.dirname(sys.executable)
737 pth_lines = self._get_pth_lines(libpath, import_site=False)
738 exe_file = self._create_underpth_exe(pth_lines)
739 sys_path = self._calc_sys_path_for_underpth_nosite(
740 os.path.dirname(exe_file),
741 pth_lines)
742
743 env = os.environ.copy()
744 env['PYTHONPATH'] = 'from-env'
745 env['PATH'] = '{}{}{}'.format(exe_prefix, os.pathsep, os.getenv('PATH'))
746 output = subprocess.check_output([exe_file, '-c',
747 'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")'
748 ], env=env, encoding='utf-8', errors='surrogateescape')
749 actual_sys_path = output.rstrip().split('\n')
750 self.assertTrue(actual_sys_path, "sys.flags.no_site was False")
751 self.assertEqual(
752 actual_sys_path,
753 sys_path,
754 "sys.path is incorrect"
755 )
756
757 @support.requires_subprocess()
758 def test_underpth_file(self):
759 libpath = test.support.STDLIB_DIR
760 exe_prefix = os.path.dirname(sys.executable)
761 exe_file = self._create_underpth_exe(
762 self._get_pth_lines(libpath, import_site=True))
763 sys_prefix = os.path.dirname(exe_file)
764 env = os.environ.copy()
765 env['PYTHONPATH'] = 'from-env'
766 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
767 rc = subprocess.call([exe_file, '-c',
768 'import sys; sys.exit(not sys.flags.no_site and '
769 '%r in sys.path and %r in sys.path and %r not in sys.path and '
770 'all("\\r" not in p and "\\n" not in p for p in sys.path))' % (
771 os.path.join(sys_prefix, 'fake-path-name'),
772 libpath,
773 os.path.join(sys_prefix, 'from-env'),
774 )], env=env)
775 self.assertTrue(rc, "sys.path is incorrect")
776
777 @support.requires_subprocess()
778 def test_underpth_dll_file(self):
779 libpath = test.support.STDLIB_DIR
780 exe_prefix = os.path.dirname(sys.executable)
781 exe_file = self._create_underpth_exe(
782 self._get_pth_lines(libpath, import_site=True), exe_pth=False)
783 sys_prefix = os.path.dirname(exe_file)
784 env = os.environ.copy()
785 env['PYTHONPATH'] = 'from-env'
786 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
787 rc = subprocess.call([exe_file, '-c',
788 'import sys; sys.exit(not sys.flags.no_site and '
789 '%r in sys.path and %r in sys.path and %r not in sys.path and '
790 'all("\\r" not in p and "\\n" not in p for p in sys.path))' % (
791 os.path.join(sys_prefix, 'fake-path-name'),
792 libpath,
793 os.path.join(sys_prefix, 'from-env'),
794 )], env=env)
795 self.assertTrue(rc, "sys.path is incorrect")
796
797
798 class CommandLineTests(unittest.TestCase):
799 def exists(self, path):
800 if path is not None and os.path.isdir(path):
801 return "exists"
802 else:
803 return "doesn't exist"
804
805 def get_excepted_output(self, *args):
806 if len(args) == 0:
807 user_base = site.getuserbase()
808 user_site = site.getusersitepackages()
809 output = io.StringIO()
810 output.write("sys.path = [\n")
811 for dir in sys.path:
812 output.write(" %r,\n" % (dir,))
813 output.write("]\n")
814 output.write(f"USER_BASE: {user_base} ({self.exists(user_base)})\n")
815 output.write(f"USER_SITE: {user_site} ({self.exists(user_site)})\n")
816 output.write(f"ENABLE_USER_SITE: {site.ENABLE_USER_SITE}\n")
817 return 0, dedent(output.getvalue()).strip()
818
819 buffer = []
820 if '--user-base' in args:
821 buffer.append(site.getuserbase())
822 if '--user-site' in args:
823 buffer.append(site.getusersitepackages())
824
825 if buffer:
826 return_code = 3
827 if site.ENABLE_USER_SITE:
828 return_code = 0
829 elif site.ENABLE_USER_SITE is False:
830 return_code = 1
831 elif site.ENABLE_USER_SITE is None:
832 return_code = 2
833 output = os.pathsep.join(buffer)
834 return return_code, os.path.normpath(dedent(output).strip())
835 else:
836 return 10, None
837
838 def invoke_command_line(self, *args):
839 cmd_args = []
840 if sys.flags.no_user_site:
841 cmd_args.append("-s")
842 cmd_args.extend(["-m", "site", *args])
843
844 with EnvironmentVarGuard() as env:
845 env["PYTHONUTF8"] = "1"
846 env["PYTHONIOENCODING"] = "utf-8"
847 proc = spawn_python(*cmd_args, text=True, env=env,
848 encoding='utf-8', errors='replace')
849
850 output = kill_python(proc)
851 return_code = proc.returncode
852 return return_code, os.path.normpath(dedent(output).strip())
853
854 @support.requires_subprocess()
855 def test_no_args(self):
856 return_code, output = self.invoke_command_line()
857 excepted_return_code, _ = self.get_excepted_output()
858 self.assertEqual(return_code, excepted_return_code)
859 lines = output.splitlines()
860 self.assertEqual(lines[0], "sys.path = [")
861 self.assertEqual(lines[-4], "]")
862 excepted_base = f"USER_BASE: '{site.getuserbase()}'" +\
863 f" ({self.exists(site.getuserbase())})"
864 self.assertEqual(lines[-3], excepted_base)
865 excepted_site = f"USER_SITE: '{site.getusersitepackages()}'" +\
866 f" ({self.exists(site.getusersitepackages())})"
867 self.assertEqual(lines[-2], excepted_site)
868 self.assertEqual(lines[-1], f"ENABLE_USER_SITE: {site.ENABLE_USER_SITE}")
869
870 @support.requires_subprocess()
871 def test_unknown_args(self):
872 return_code, output = self.invoke_command_line("--unknown-arg")
873 excepted_return_code, _ = self.get_excepted_output("--unknown-arg")
874 self.assertEqual(return_code, excepted_return_code)
875 self.assertIn('[--user-base] [--user-site]', output)
876
877 @support.requires_subprocess()
878 def test_base_arg(self):
879 return_code, output = self.invoke_command_line("--user-base")
880 excepted = self.get_excepted_output("--user-base")
881 excepted_return_code, excepted_output = excepted
882 self.assertEqual(return_code, excepted_return_code)
883 self.assertEqual(output, excepted_output)
884
885 @support.requires_subprocess()
886 def test_site_arg(self):
887 return_code, output = self.invoke_command_line("--user-site")
888 excepted = self.get_excepted_output("--user-site")
889 excepted_return_code, excepted_output = excepted
890 self.assertEqual(return_code, excepted_return_code)
891 self.assertEqual(output, excepted_output)
892
893 @support.requires_subprocess()
894 def test_both_args(self):
895 return_code, output = self.invoke_command_line("--user-base",
896 "--user-site")
897 excepted = self.get_excepted_output("--user-base", "--user-site")
898 excepted_return_code, excepted_output = excepted
899 self.assertEqual(return_code, excepted_return_code)
900 self.assertEqual(output, excepted_output)
901
902
903 if __name__ == "__main__":
904 unittest.main()