blob: 12e357cd9ba695e9643310d8e6dae0bcbe949e7a [file] [log] [blame]
Brett Cannon0096e262004-06-05 01:12:51 +00001"""Tests for 'site'.
2
3Tests assume the initial paths in sys.path once the interpreter has begun
4executing have not been removed.
5
6"""
7import unittest
Senthil Kumaran8ef519b2013-09-07 13:59:17 -07008import test.support
Victor Stinnerf2f45552018-12-05 16:49:35 +01009from test import support
Steve Dowerf14c28f2018-09-20 13:38:34 -070010from test.support import (captured_stderr, TESTFN, EnvironmentVarGuard,
11 change_cwd)
Georg Brandl1a3284e2007-12-02 09:40:06 +000012import builtins
Brett Cannon0096e262004-06-05 01:12:51 +000013import encodings
Victor Stinnerd18de462020-03-18 18:27:32 +010014import glob
15import os
16import re
Steve Dower1da055e2016-10-29 08:50:31 -070017import shutil
Christian Heimes8dc226f2008-05-06 23:45:46 +000018import subprocess
Victor Stinnerd18de462020-03-18 18:27:32 +010019import sys
Tarek Ziadéedacea32010-01-29 11:41:03 +000020import sysconfig
Zachary Wared48214f2017-05-14 15:49:46 -050021import tempfile
Victor Stinnerd18de462020-03-18 18:27:32 +010022import urllib.error
23import urllib.request
Victor Stinnerf2f45552018-12-05 16:49:35 +010024from unittest import mock
Tarek Ziadéedacea32010-01-29 11:41:03 +000025from copy import copy
26
Zachary Ware36193e72013-12-11 16:59:44 -060027# These tests are not particularly useful if Python was invoked with -S.
28# If you add tests that are useful under -S, this skip should be moved
29# to the class level.
30if sys.flags.no_site:
31 raise unittest.SkipTest("Python was invoked with -S")
32
33import site
Brett Cannon0096e262004-06-05 01:12:51 +000034
Victor Stinnerb85c1362017-04-20 13:39:39 +020035
36OLD_SYS_PATH = None
37
38
39def setUpModule():
40 global OLD_SYS_PATH
41 OLD_SYS_PATH = sys.path[:]
42
43 if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
44 # need to add user site directory for tests
45 try:
46 os.makedirs(site.USER_SITE)
47 # modify sys.path: will be restored by tearDownModule()
48 site.addsitedir(site.USER_SITE)
49 except PermissionError as exc:
50 raise unittest.SkipTest('unable to create user site directory (%r): %s'
51 % (site.USER_SITE, exc))
52
53
54def tearDownModule():
55 sys.path[:] = OLD_SYS_PATH
Victor Stinner21d0e1b2016-03-14 17:47:03 +010056
Christian Heimes8dc226f2008-05-06 23:45:46 +000057
Brett Cannon0096e262004-06-05 01:12:51 +000058class HelperFunctionsTests(unittest.TestCase):
59 """Tests for helper functions.
Brett Cannon0096e262004-06-05 01:12:51 +000060 """
61
62 def setUp(self):
63 """Save a copy of sys.path"""
64 self.sys_path = sys.path[:]
Tarek Ziadé4a608c02009-08-20 21:28:05 +000065 self.old_base = site.USER_BASE
66 self.old_site = site.USER_SITE
67 self.old_prefixes = site.PREFIXES
Brett Cannon8ac95ee2012-04-04 17:31:16 -040068 self.original_vars = sysconfig._CONFIG_VARS
Tarek Ziadéedacea32010-01-29 11:41:03 +000069 self.old_vars = copy(sysconfig._CONFIG_VARS)
Brett Cannon0096e262004-06-05 01:12:51 +000070
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000071 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000072 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +000073 sys.path[:] = self.sys_path
Tarek Ziadé4a608c02009-08-20 21:28:05 +000074 site.USER_BASE = self.old_base
75 site.USER_SITE = self.old_site
76 site.PREFIXES = self.old_prefixes
Brett Cannon8ac95ee2012-04-04 17:31:16 -040077 sysconfig._CONFIG_VARS = self.original_vars
78 sysconfig._CONFIG_VARS.clear()
79 sysconfig._CONFIG_VARS.update(self.old_vars)
Raymond Hettingerebd95222004-06-27 03:02:18 +000080
Brett Cannon0096e262004-06-05 01:12:51 +000081 def test_makepath(self):
82 # Test makepath() have an absolute path for its first return value
83 # and a case-normalized version of the absolute path for its
84 # second value.
85 path_parts = ("Beginning", "End")
86 original_dir = os.path.join(*path_parts)
87 abs_dir, norm_dir = site.makepath(*path_parts)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000088 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000089 if original_dir == os.path.normcase(original_dir):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000090 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000091 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000092 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000093
94 def test_init_pathinfo(self):
95 dir_set = site._init_pathinfo()
96 for entry in [site.makepath(path)[1] for path in sys.path
Brett Cannon5f0507d2016-04-08 15:04:28 -070097 if path and os.path.exists(path)]:
Ezio Melottib58e0bd2010-01-23 15:40:09 +000098 self.assertIn(entry, dir_set,
99 "%s from sys.path not found in set returned "
100 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +0000101
Brett Cannonee86a662004-07-13 07:12:25 +0000102 def pth_file_tests(self, pth_file):
103 """Contain common code for testing results of reading a .pth file"""
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000104 self.assertIn(pth_file.imported, sys.modules,
105 "%s not in sys.modules" % pth_file.imported)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000106 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
107 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +0000108
Brett Cannon0096e262004-06-05 01:12:51 +0000109 def test_addpackage(self):
110 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +0000111 # adds directories to sys.path for any line in the file that is not a
112 # comment or import that is a valid directory name for where the .pth
113 # file resides; invalid directories are not added
114 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000115 pth_file.cleanup(prep=True) # to make sure that nothing is
116 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +0000117 try:
Brett Cannon64a84702004-07-10 02:10:45 +0000118 pth_file.create()
119 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000120 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000121 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000122 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000123
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000124 def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
125 # Create a .pth file and return its (abspath, basename).
126 pth_dir = os.path.abspath(pth_dir)
127 pth_basename = pth_name + '.pth'
128 pth_fn = os.path.join(pth_dir, pth_basename)
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200129 with open(pth_fn, 'w', encoding='utf-8') as pth_file:
130 self.addCleanup(lambda: os.remove(pth_fn))
131 pth_file.write(contents)
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000132 return pth_dir, pth_basename
133
134 def test_addpackage_import_bad_syntax(self):
135 # Issue 10642
Serhiy Storchaka94cf3082018-12-17 17:34:14 +0200136 pth_dir, pth_fn = self.make_pth("import bad-syntax\n")
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000137 with captured_stderr() as err_out:
138 site.addpackage(pth_dir, pth_fn, set())
139 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000140 self.assertRegex(err_out.getvalue(),
141 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000142 # XXX: the previous two should be independent checks so that the
143 # order doesn't matter. The next three could be a single check
144 # but my regex foo isn't good enough to write it.
145 self.assertRegex(err_out.getvalue(), 'Traceback')
Serhiy Storchaka94cf3082018-12-17 17:34:14 +0200146 self.assertRegex(err_out.getvalue(), r'import bad-syntax')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000147 self.assertRegex(err_out.getvalue(), 'SyntaxError')
148
149 def test_addpackage_import_bad_exec(self):
150 # Issue 10642
151 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
152 with captured_stderr() as err_out:
153 site.addpackage(pth_dir, pth_fn, set())
154 self.assertRegex(err_out.getvalue(), "line 2")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000155 self.assertRegex(err_out.getvalue(),
156 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000157 # XXX: ditto previous XXX comment.
158 self.assertRegex(err_out.getvalue(), 'Traceback')
Eric Snow46f97b82016-09-07 16:56:15 -0700159 self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000160
161 def test_addpackage_import_bad_pth_file(self):
162 # Issue 5258
163 pth_dir, pth_fn = self.make_pth("abc\x00def\n")
164 with captured_stderr() as err_out:
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300165 self.assertFalse(site.addpackage(pth_dir, pth_fn, set()))
166 self.assertEqual(err_out.getvalue(), "")
167 for path in sys.path:
168 if isinstance(path, str):
169 self.assertNotIn("abc\x00def", path)
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000170
Brett Cannon0096e262004-06-05 01:12:51 +0000171 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +0000172 # Same tests for test_addpackage since addsitedir() essentially just
173 # calls addpackage() for every .pth file in the directory
174 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000175 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
176 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +0000177 try:
Brett Cannonee86a662004-07-13 07:12:25 +0000178 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +0000179 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000180 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000181 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000182 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +0000183
native-api45d8d242019-03-03 19:05:19 +0300184 # This tests _getuserbase, hence the double underline
185 # to distinguish from a test for getuserbase
186 def test__getuserbase(self):
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900187 self.assertEqual(site._getuserbase(), sysconfig._getuserbase())
188
189 def test_get_path(self):
INADA Naokiba9ddb72017-07-28 21:28:19 +0900190 if sys.platform == 'darwin' and sys._framework:
191 scheme = 'osx_framework_user'
192 else:
193 scheme = os.name + '_user'
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900194 self.assertEqual(site._get_path(site._getuserbase()),
INADA Naokiba9ddb72017-07-28 21:28:19 +0900195 sysconfig.get_path('purelib', scheme))
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900196
Ned Deily316f5732011-10-31 16:16:35 -0700197 @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
198 "user-site (site.ENABLE_USER_SITE)")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000199 def test_s_option(self):
Eric Snow6b4be192017-05-22 21:36:03 -0700200 # (ncoghlan) Change this to use script_helper...
Christian Heimes8dc226f2008-05-06 23:45:46 +0000201 usersite = site.USER_SITE
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000202 self.assertIn(usersite, sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000203
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000204 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000205 rc = subprocess.call([sys.executable, '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000206 'import sys; sys.exit(%r in sys.path)' % usersite],
207 env=env)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000208 self.assertEqual(rc, 1)
209
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000210 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000211 rc = subprocess.call([sys.executable, '-s', '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000212 'import sys; sys.exit(%r in sys.path)' % usersite],
213 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200214 if usersite == site.getsitepackages()[0]:
215 self.assertEqual(rc, 1)
216 else:
Eric Snow6b4be192017-05-22 21:36:03 -0700217 self.assertEqual(rc, 0, "User site still added to path with -s")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000218
219 env = os.environ.copy()
220 env["PYTHONNOUSERSITE"] = "1"
221 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000222 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000223 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200224 if usersite == site.getsitepackages()[0]:
225 self.assertEqual(rc, 1)
226 else:
Eric Snow6b4be192017-05-22 21:36:03 -0700227 self.assertEqual(rc, 0,
228 "User site still added to path with PYTHONNOUSERSITE")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000229
230 env = os.environ.copy()
231 env["PYTHONUSERBASE"] = "/tmp"
232 rc = subprocess.call([sys.executable, '-c',
233 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
234 env=env)
Eric Snow6b4be192017-05-22 21:36:03 -0700235 self.assertEqual(rc, 1,
236 "User base not set by PYTHONUSERBASE")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000237
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000238 def test_getuserbase(self):
239 site.USER_BASE = None
240 user_base = site.getuserbase()
241
242 # the call sets site.USER_BASE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000243 self.assertEqual(site.USER_BASE, user_base)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000244
245 # let's set PYTHONUSERBASE and see if it uses it
246 site.USER_BASE = None
Tarek Ziadéedacea32010-01-29 11:41:03 +0000247 import sysconfig
248 sysconfig._CONFIG_VARS = None
249
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000250 with EnvironmentVarGuard() as environ:
251 environ['PYTHONUSERBASE'] = 'xoxo'
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000252 self.assertTrue(site.getuserbase().startswith('xoxo'),
253 site.getuserbase())
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000254
255 def test_getusersitepackages(self):
256 site.USER_SITE = None
257 site.USER_BASE = None
258 user_site = site.getusersitepackages()
259
260 # the call sets USER_BASE *and* USER_SITE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000261 self.assertEqual(site.USER_SITE, user_site)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000262 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
Victor Stinnerf2f45552018-12-05 16:49:35 +0100263 self.assertEqual(site.USER_BASE, site.getuserbase())
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000264
265 def test_getsitepackages(self):
266 site.PREFIXES = ['xoxo']
267 dirs = site.getsitepackages()
Ned Deily763f0942018-01-30 05:14:09 -0500268 if os.sep == '/':
269 # OS X, Linux, FreeBSD, etc
Victor Stinner8510f432020-03-10 09:53:09 +0100270 if sys.platlibdir != "lib":
271 self.assertEqual(len(dirs), 2)
272 wanted = os.path.join('xoxo', sys.platlibdir,
273 'python%d.%d' % sys.version_info[:2],
274 'site-packages')
275 self.assertEqual(dirs[0], wanted)
276 else:
277 self.assertEqual(len(dirs), 1)
Serhiy Storchaka885bdc42016-02-11 13:10:36 +0200278 wanted = os.path.join('xoxo', 'lib',
279 'python%d.%d' % sys.version_info[:2],
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000280 'site-packages')
Victor Stinner8510f432020-03-10 09:53:09 +0100281 self.assertEqual(dirs[-1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000282 else:
Ned Deilyd531b292012-02-06 00:58:18 +0100283 # other platforms
Ezio Melottifc8b2052010-08-17 08:35:41 +0000284 self.assertEqual(len(dirs), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000285 self.assertEqual(dirs[0], 'xoxo')
Tarek Ziadé8c0e2172009-10-27 21:24:21 +0000286 wanted = os.path.join('xoxo', 'lib', 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000287 self.assertEqual(dirs[1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000288
Victor Stinnerf2f45552018-12-05 16:49:35 +0100289 def test_no_home_directory(self):
290 # bpo-10496: getuserbase() and getusersitepackages() must not fail if
291 # the current user has no home directory (if expanduser() returns the
292 # path unchanged).
293 site.USER_SITE = None
294 site.USER_BASE = None
295
296 with EnvironmentVarGuard() as environ, \
297 mock.patch('os.path.expanduser', lambda path: path):
298
299 del environ['PYTHONUSERBASE']
300 del environ['APPDATA']
301
302 user_base = site.getuserbase()
303 self.assertTrue(user_base.startswith('~' + os.sep),
304 user_base)
305
306 user_site = site.getusersitepackages()
307 self.assertTrue(user_site.startswith(user_base), user_site)
308
309 with mock.patch('os.path.isdir', return_value=False) as mock_isdir, \
310 mock.patch.object(site, 'addsitedir') as mock_addsitedir, \
311 support.swap_attr(site, 'ENABLE_USER_SITE', True):
312
313 # addusersitepackages() must not add user_site to sys.path
314 # if it is not an existing directory
315 known_paths = set()
316 site.addusersitepackages(known_paths)
317
318 mock_isdir.assert_called_once_with(user_site)
319 mock_addsitedir.assert_not_called()
320 self.assertFalse(known_paths)
321
322
Brett Cannon64a84702004-07-10 02:10:45 +0000323class PthFile(object):
324 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000325
Brett Cannon64a84702004-07-10 02:10:45 +0000326 def __init__(self, filename_base=TESTFN, imported="time",
327 good_dirname="__testdir__", bad_dirname="__bad"):
328 """Initialize instance variables"""
329 self.filename = filename_base + ".pth"
330 self.base_dir = os.path.abspath('')
331 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000332 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000333 self.good_dirname = good_dirname
334 self.bad_dirname = bad_dirname
335 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
336 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000337
Brett Cannon64a84702004-07-10 02:10:45 +0000338 def create(self):
339 """Create a .pth file with a comment, blank lines, an ``import
340 <self.imported>``, a line with self.good_dirname, and a line with
341 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000342
Brett Cannon64a84702004-07-10 02:10:45 +0000343 Creation of the directory for self.good_dir_path (based off of
344 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000345
Brett Cannon64a84702004-07-10 02:10:45 +0000346 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000347
Brett Cannon64a84702004-07-10 02:10:45 +0000348 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000349 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000350 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000351 print("#import @bad module name", file=FILE)
352 print("\n", file=FILE)
353 print("import %s" % self.imported, file=FILE)
354 print(self.good_dirname, file=FILE)
355 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000356 finally:
357 FILE.close()
358 os.mkdir(self.good_dir_path)
359
Brett Cannonee86a662004-07-13 07:12:25 +0000360 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000361 """Make sure that the .pth file is deleted, self.imported is not in
362 sys.modules, and that both self.good_dirname and self.bad_dirname are
363 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000364 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000365 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000366 if prep:
367 self.imported_module = sys.modules.get(self.imported)
368 if self.imported_module:
369 del sys.modules[self.imported]
370 else:
371 if self.imported_module:
372 sys.modules[self.imported] = self.imported_module
373 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000374 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000375 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000376 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000377
378class ImportSideEffectTests(unittest.TestCase):
379 """Test side-effects from importing 'site'."""
380
381 def setUp(self):
382 """Make a copy of sys.path"""
383 self.sys_path = sys.path[:]
384
385 def tearDown(self):
386 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +0000387 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000388
Barry Warsaw28a691b2010-04-17 00:19:56 +0000389 def test_abs_paths(self):
390 # Make sure all imported modules have their __file__ and __cached__
391 # attributes as absolute paths. Arranging to put the Lib directory on
392 # PYTHONPATH would cause the os module to have a relative path for
393 # __file__ if abs_paths() does not get run. sys and builtins (the
394 # only other modules imported before site.py runs) do not have
395 # __file__ or __cached__ because they are built-in.
Steve Dowerf14c28f2018-09-20 13:38:34 -0700396 try:
397 parent = os.path.relpath(os.path.dirname(os.__file__))
398 cwd = os.getcwd()
399 except ValueError:
400 # Failure to get relpath probably means we need to chdir
401 # to the same drive.
402 cwd, parent = os.path.split(os.path.dirname(os.__file__))
403 with change_cwd(cwd):
404 env = os.environ.copy()
405 env['PYTHONPATH'] = parent
406 code = ('import os, sys',
407 # use ASCII to avoid locale issues with non-ASCII directories
408 'os_file = os.__file__.encode("ascii", "backslashreplace")',
409 r'sys.stdout.buffer.write(os_file + b"\n")',
410 'os_cached = os.__cached__.encode("ascii", "backslashreplace")',
411 r'sys.stdout.buffer.write(os_cached + b"\n")')
412 command = '\n'.join(code)
413 # First, prove that with -S (no 'import site'), the paths are
414 # relative.
415 proc = subprocess.Popen([sys.executable, '-S', '-c', command],
416 env=env,
417 stdout=subprocess.PIPE)
418 stdout, stderr = proc.communicate()
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000419
Steve Dowerf14c28f2018-09-20 13:38:34 -0700420 self.assertEqual(proc.returncode, 0)
421 os__file__, os__cached__ = stdout.splitlines()[:2]
422 self.assertFalse(os.path.isabs(os__file__))
423 self.assertFalse(os.path.isabs(os__cached__))
424 # Now, with 'import site', it works.
425 proc = subprocess.Popen([sys.executable, '-c', command],
426 env=env,
427 stdout=subprocess.PIPE)
428 stdout, stderr = proc.communicate()
429 self.assertEqual(proc.returncode, 0)
430 os__file__, os__cached__ = stdout.splitlines()[:2]
431 self.assertTrue(os.path.isabs(os__file__),
432 "expected absolute path, got {}"
433 .format(os__file__.decode('ascii')))
434 self.assertTrue(os.path.isabs(os__cached__),
435 "expected absolute path, got {}"
436 .format(os__cached__.decode('ascii')))
Brett Cannon0096e262004-06-05 01:12:51 +0000437
INADA Naokid4c76d92018-10-01 21:10:37 +0900438 def test_abs_paths_cached_None(self):
439 """Test for __cached__ is None.
440
441 Regarding to PEP 3147, __cached__ can be None.
442
443 See also: https://bugs.python.org/issue30167
444 """
445 sys.modules['test'].__cached__ = None
446 site.abs_paths()
447 self.assertIsNone(sys.modules['test'].__cached__)
448
Brett Cannon0096e262004-06-05 01:12:51 +0000449 def test_no_duplicate_paths(self):
450 # No duplicate paths should exist in sys.path
451 # Handled by removeduppaths()
452 site.removeduppaths()
453 seen_paths = set()
454 for path in sys.path:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000455 self.assertNotIn(path, seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000456 seen_paths.add(path)
457
Zachary Ware9fe6d862013-12-08 00:20:35 -0600458 @unittest.skip('test not implemented')
Brett Cannon0096e262004-06-05 01:12:51 +0000459 def test_add_build_dir(self):
460 # Test that the build directory's Modules directory is used when it
461 # should be.
462 # XXX: implement
463 pass
464
Brett Cannon0096e262004-06-05 01:12:51 +0000465 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000466 # 'quit' and 'exit' should be injected into builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000467 self.assertTrue(hasattr(builtins, "quit"))
468 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000469
470 def test_setting_copyright(self):
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700471 # 'copyright', 'credits', and 'license' should be in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000472 self.assertTrue(hasattr(builtins, "copyright"))
473 self.assertTrue(hasattr(builtins, "credits"))
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700474 self.assertTrue(hasattr(builtins, "license"))
Brett Cannon0096e262004-06-05 01:12:51 +0000475
476 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000477 # 'help' should be set in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000478 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000479
480 def test_aliasing_mbcs(self):
481 if sys.platform == "win32":
482 import locale
483 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000484 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000485 if value == "mbcs":
486 break
487 else:
488 self.fail("did not alias mbcs")
489
Brett Cannon0096e262004-06-05 01:12:51 +0000490 def test_sitecustomize_executed(self):
491 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000492 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000493 try:
494 import sitecustomize
495 except ImportError:
496 pass
497 else:
498 self.fail("sitecustomize not imported automatically")
499
R David Murray1bc6ceb2013-09-14 13:28:37 -0400500 @test.support.requires_resource('network')
Benjamin Peterson337578b2015-02-01 20:16:59 -0500501 @test.support.system_must_validate_cert
Georg Brandl78abc9d2013-10-27 09:41:57 +0100502 @unittest.skipUnless(sys.version_info[3] == 'final',
503 'only for released versions')
Ned Deily5a507f02014-03-26 23:31:39 -0700504 @unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"),
505 'need SSL support to download license')
R David Murray1bc6ceb2013-09-14 13:28:37 -0400506 def test_license_exists_at_url(self):
Ned Deily944d5972014-03-26 23:43:26 -0700507 # This test is a bit fragile since it depends on the format of the
R David Murray1bc6ceb2013-09-14 13:28:37 -0400508 # string displayed by license in the absence of a LICENSE file.
509 url = license._Printer__data.split()[1]
510 req = urllib.request.Request(url, method='HEAD')
511 try:
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700512 with test.support.transient_internet(url):
R David Murray1bc6ceb2013-09-14 13:28:37 -0400513 with urllib.request.urlopen(req) as data:
514 code = data.getcode()
515 except urllib.error.HTTPError as e:
516 code = e.code
517 self.assertEqual(code, 200, msg="Can't find " + url)
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700518
Brett Cannon0096e262004-06-05 01:12:51 +0000519
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200520class StartupImportTests(unittest.TestCase):
521
522 def test_startup_imports(self):
Victor Stinnerd18de462020-03-18 18:27:32 +0100523 # Get sys.path in isolated mode (python3 -I)
524 popen = subprocess.Popen([sys.executable, '-I', '-c',
525 'import sys; print(repr(sys.path))'],
526 stdout=subprocess.PIPE,
527 encoding='utf-8')
528 stdout = popen.communicate()[0]
529 self.assertEqual(popen.returncode, 0, repr(stdout))
530 isolated_paths = eval(stdout)
531
532 # bpo-27807: Even with -I, the site module executes all .pth files
533 # found in sys.path (see site.addpackage()). Skip the test if at least
534 # one .pth file is found.
535 for path in isolated_paths:
536 pth_files = glob.glob(os.path.join(path, "*.pth"))
537 if pth_files:
538 self.skipTest(f"found {len(pth_files)} .pth files in: {path}")
539
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200540 # This tests checks which modules are loaded by Python when it
541 # initially starts upon startup.
Christian Heimes179a3db2013-10-12 12:32:21 +0200542 popen = subprocess.Popen([sys.executable, '-I', '-v', '-c',
543 'import sys; print(set(sys.modules))'],
544 stdout=subprocess.PIPE,
Steve Dower313523c2016-09-17 12:22:41 -0700545 stderr=subprocess.PIPE,
546 encoding='utf-8')
Christian Heimes179a3db2013-10-12 12:32:21 +0200547 stdout, stderr = popen.communicate()
Victor Stinnerd18de462020-03-18 18:27:32 +0100548 self.assertEqual(popen.returncode, 0, (stdout, stderr))
Christian Heimes179a3db2013-10-12 12:32:21 +0200549 modules = eval(stdout)
550
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200551 self.assertIn('site', modules)
552
Christian Heimes25827622013-10-12 01:27:08 +0200553 # http://bugs.python.org/issue19205
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200554 re_mods = {'re', '_sre', 'sre_compile', 'sre_constants', 'sre_parse'}
Inada Naokic4d92c82019-05-05 18:06:30 +0900555 self.assertFalse(modules.intersection(re_mods), stderr)
556
Christian Heimes25827622013-10-12 01:27:08 +0200557 # http://bugs.python.org/issue9548
Christian Heimes179a3db2013-10-12 12:32:21 +0200558 self.assertNotIn('locale', modules, stderr)
Inada Naokic4d92c82019-05-05 18:06:30 +0900559
560 # http://bugs.python.org/issue19209
561 self.assertNotIn('copyreg', modules, stderr)
562
563 # http://bugs.python.org/issue19218
Christian Heimesf1dc3ee2013-10-13 02:04:20 +0200564 collection_mods = {'_collections', 'collections', 'functools',
565 'heapq', 'itertools', 'keyword', 'operator',
doko@ubuntu.com95743552014-04-15 20:37:54 +0200566 'reprlib', 'types', 'weakref'
567 }.difference(sys.builtin_module_names)
Ned Deilyc22bd582017-07-28 03:02:10 -0400568 self.assertFalse(modules.intersection(collection_mods), stderr)
Christian Heimes1a5fb4e2013-10-12 01:00:51 +0200569
Steve Dower6dd8eca2016-09-17 14:35:32 -0700570 def test_startup_interactivehook(self):
571 r = subprocess.Popen([sys.executable, '-c',
572 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
573 self.assertTrue(r, "'__interactivehook__' not added by site")
574
575 def test_startup_interactivehook_isolated(self):
576 # issue28192 readline is not automatically enabled in isolated mode
577 r = subprocess.Popen([sys.executable, '-I', '-c',
578 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
579 self.assertFalse(r, "'__interactivehook__' added in isolated mode")
580
581 def test_startup_interactivehook_isolated_explicit(self):
582 # issue28192 readline can be explicitly enabled in isolated mode
583 r = subprocess.Popen([sys.executable, '-I', '-c',
584 'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
585 self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()")
586
Zachary Wared48214f2017-05-14 15:49:46 -0500587
588@unittest.skipUnless(sys.platform == 'win32', "only supported on Windows")
589class _pthFileTests(unittest.TestCase):
590
Steve Dower1da055e2016-10-29 08:50:31 -0700591 def _create_underpth_exe(self, lines):
Zachary Wared48214f2017-05-14 15:49:46 -0500592 temp_dir = tempfile.mkdtemp()
593 self.addCleanup(test.support.rmtree, temp_dir)
594 exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1])
Steve Dower1da055e2016-10-29 08:50:31 -0700595 shutil.copy(sys.executable, exe_file)
Steve Dower1da055e2016-10-29 08:50:31 -0700596 _pth_file = os.path.splitext(exe_file)[0] + '._pth'
Zachary Wared48214f2017-05-14 15:49:46 -0500597 with open(_pth_file, 'w') as f:
598 for line in lines:
599 print(line, file=f)
600 return exe_file
Steve Dower1da055e2016-10-29 08:50:31 -0700601
Steve Dower5f9193a2017-02-04 15:19:29 -0800602 def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines):
603 sys_path = []
604 for line in lines:
605 if not line or line[0] == '#':
606 continue
607 abs_path = os.path.abspath(os.path.join(sys_prefix, line))
608 sys_path.append(abs_path)
609 return sys_path
610
Steve Dowerc6dd4152016-10-27 14:28:07 -0700611 def test_underpth_nosite_file(self):
Steve Dower1da055e2016-10-29 08:50:31 -0700612 libpath = os.path.dirname(os.path.dirname(encodings.__file__))
613 exe_prefix = os.path.dirname(sys.executable)
Steve Dower5f9193a2017-02-04 15:19:29 -0800614 pth_lines = [
Steve Dower1da055e2016-10-29 08:50:31 -0700615 'fake-path-name',
616 *[libpath for _ in range(200)],
Steve Dower5f9193a2017-02-04 15:19:29 -0800617 '',
Steve Dower1da055e2016-10-29 08:50:31 -0700618 '# comment',
Steve Dower5f9193a2017-02-04 15:19:29 -0800619 ]
620 exe_file = self._create_underpth_exe(pth_lines)
621 sys_path = self._calc_sys_path_for_underpth_nosite(
622 os.path.dirname(exe_file),
623 pth_lines)
Steve Dowerc6dd4152016-10-27 14:28:07 -0700624
Zachary Wared48214f2017-05-14 15:49:46 -0500625 env = os.environ.copy()
626 env['PYTHONPATH'] = 'from-env'
627 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
Steve Dower9b33bf52017-05-23 16:25:25 -0700628 output = subprocess.check_output([exe_file, '-c',
629 'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")'
630 ], env=env, encoding='ansi')
631 actual_sys_path = output.rstrip().split('\n')
Serhiy Storchaka95c32622018-02-04 18:14:47 +0200632 self.assertTrue(actual_sys_path, "sys.flags.no_site was False")
Steve Dower9b33bf52017-05-23 16:25:25 -0700633 self.assertEqual(
634 actual_sys_path,
635 sys_path,
636 "sys.path is incorrect"
637 )
Steve Dowerc6dd4152016-10-27 14:28:07 -0700638
Steve Dowerc6dd4152016-10-27 14:28:07 -0700639 def test_underpth_file(self):
Steve Dower1da055e2016-10-29 08:50:31 -0700640 libpath = os.path.dirname(os.path.dirname(encodings.__file__))
641 exe_prefix = os.path.dirname(sys.executable)
642 exe_file = self._create_underpth_exe([
643 'fake-path-name',
644 *[libpath for _ in range(200)],
Steve Dower5f9193a2017-02-04 15:19:29 -0800645 '',
Steve Dower1da055e2016-10-29 08:50:31 -0700646 '# comment',
647 'import site'
648 ])
Steve Dower5f9193a2017-02-04 15:19:29 -0800649 sys_prefix = os.path.dirname(exe_file)
Zachary Wared48214f2017-05-14 15:49:46 -0500650 env = os.environ.copy()
651 env['PYTHONPATH'] = 'from-env'
652 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
653 rc = subprocess.call([exe_file, '-c',
654 'import sys; sys.exit(not sys.flags.no_site and '
655 '%r in sys.path and %r in sys.path and %r not in sys.path and '
656 'all("\\r" not in p and "\\n" not in p for p in sys.path))' % (
657 os.path.join(sys_prefix, 'fake-path-name'),
658 libpath,
659 os.path.join(sys_prefix, 'from-env'),
660 )], env=env)
Steve Dower5f9193a2017-02-04 15:19:29 -0800661 self.assertTrue(rc, "sys.path is incorrect")
Steve Dowerc6dd4152016-10-27 14:28:07 -0700662
Steve Dower6dd8eca2016-09-17 14:35:32 -0700663
Brett Cannon0096e262004-06-05 01:12:51 +0000664if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400665 unittest.main()