blob: 6cea58d934fbac5f0e51541e06b95cce07b09e86 [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
Steve Dowera73e7902018-09-20 14:39:21 -07009from test.support import (captured_stderr, TESTFN, EnvironmentVarGuard,
10 change_cwd)
Georg Brandl1a3284e2007-12-02 09:40:06 +000011import builtins
Brett Cannon0096e262004-06-05 01:12:51 +000012import os
13import sys
R. David Murrayab9d8d62010-12-27 00:03:13 +000014import re
Brett Cannon0096e262004-06-05 01:12:51 +000015import encodings
R David Murray1bc6ceb2013-09-14 13:28:37 -040016import urllib.request
17import urllib.error
Steve Dower1da055e2016-10-29 08:50:31 -070018import shutil
Christian Heimes8dc226f2008-05-06 23:45:46 +000019import subprocess
Tarek Ziadéedacea32010-01-29 11:41:03 +000020import sysconfig
Zachary Wared48214f2017-05-14 15:49:46 -050021import tempfile
Tarek Ziadéedacea32010-01-29 11:41:03 +000022from copy import copy
23
Zachary Ware36193e72013-12-11 16:59:44 -060024# These tests are not particularly useful if Python was invoked with -S.
25# If you add tests that are useful under -S, this skip should be moved
26# to the class level.
27if sys.flags.no_site:
28 raise unittest.SkipTest("Python was invoked with -S")
29
30import site
Brett Cannon0096e262004-06-05 01:12:51 +000031
Victor Stinnerb85c1362017-04-20 13:39:39 +020032
33OLD_SYS_PATH = None
34
35
36def setUpModule():
37 global OLD_SYS_PATH
38 OLD_SYS_PATH = sys.path[:]
39
40 if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
41 # need to add user site directory for tests
42 try:
43 os.makedirs(site.USER_SITE)
44 # modify sys.path: will be restored by tearDownModule()
45 site.addsitedir(site.USER_SITE)
46 except PermissionError as exc:
47 raise unittest.SkipTest('unable to create user site directory (%r): %s'
48 % (site.USER_SITE, exc))
49
50
51def tearDownModule():
52 sys.path[:] = OLD_SYS_PATH
Victor Stinner21d0e1b2016-03-14 17:47:03 +010053
Christian Heimes8dc226f2008-05-06 23:45:46 +000054
Brett Cannon0096e262004-06-05 01:12:51 +000055class HelperFunctionsTests(unittest.TestCase):
56 """Tests for helper functions.
Brett Cannon0096e262004-06-05 01:12:51 +000057 """
58
59 def setUp(self):
60 """Save a copy of sys.path"""
61 self.sys_path = sys.path[:]
Tarek Ziadé4a608c02009-08-20 21:28:05 +000062 self.old_base = site.USER_BASE
63 self.old_site = site.USER_SITE
64 self.old_prefixes = site.PREFIXES
Brett Cannon8ac95ee2012-04-04 17:31:16 -040065 self.original_vars = sysconfig._CONFIG_VARS
Tarek Ziadéedacea32010-01-29 11:41:03 +000066 self.old_vars = copy(sysconfig._CONFIG_VARS)
Brett Cannon0096e262004-06-05 01:12:51 +000067
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000068 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000069 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +000070 sys.path[:] = self.sys_path
Tarek Ziadé4a608c02009-08-20 21:28:05 +000071 site.USER_BASE = self.old_base
72 site.USER_SITE = self.old_site
73 site.PREFIXES = self.old_prefixes
Brett Cannon8ac95ee2012-04-04 17:31:16 -040074 sysconfig._CONFIG_VARS = self.original_vars
75 sysconfig._CONFIG_VARS.clear()
76 sysconfig._CONFIG_VARS.update(self.old_vars)
Raymond Hettingerebd95222004-06-27 03:02:18 +000077
Brett Cannon0096e262004-06-05 01:12:51 +000078 def test_makepath(self):
79 # Test makepath() have an absolute path for its first return value
80 # and a case-normalized version of the absolute path for its
81 # second value.
82 path_parts = ("Beginning", "End")
83 original_dir = os.path.join(*path_parts)
84 abs_dir, norm_dir = site.makepath(*path_parts)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000085 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000086 if original_dir == os.path.normcase(original_dir):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000087 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000088 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000089 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000090
91 def test_init_pathinfo(self):
92 dir_set = site._init_pathinfo()
93 for entry in [site.makepath(path)[1] for path in sys.path
Brett Cannon5f0507d2016-04-08 15:04:28 -070094 if path and os.path.exists(path)]:
Ezio Melottib58e0bd2010-01-23 15:40:09 +000095 self.assertIn(entry, dir_set,
96 "%s from sys.path not found in set returned "
97 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000098
Brett Cannonee86a662004-07-13 07:12:25 +000099 def pth_file_tests(self, pth_file):
100 """Contain common code for testing results of reading a .pth file"""
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000101 self.assertIn(pth_file.imported, sys.modules,
102 "%s not in sys.modules" % pth_file.imported)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000103 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
104 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +0000105
Brett Cannon0096e262004-06-05 01:12:51 +0000106 def test_addpackage(self):
107 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +0000108 # adds directories to sys.path for any line in the file that is not a
109 # comment or import that is a valid directory name for where the .pth
110 # file resides; invalid directories are not added
111 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000112 pth_file.cleanup(prep=True) # to make sure that nothing is
113 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +0000114 try:
Brett Cannon64a84702004-07-10 02:10:45 +0000115 pth_file.create()
116 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000117 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000118 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000119 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000120
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000121 def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
122 # Create a .pth file and return its (abspath, basename).
123 pth_dir = os.path.abspath(pth_dir)
124 pth_basename = pth_name + '.pth'
125 pth_fn = os.path.join(pth_dir, pth_basename)
126 pth_file = open(pth_fn, 'w', encoding='utf-8')
127 self.addCleanup(lambda: os.remove(pth_fn))
128 pth_file.write(contents)
129 pth_file.close()
130 return pth_dir, pth_basename
131
132 def test_addpackage_import_bad_syntax(self):
133 # Issue 10642
134 pth_dir, pth_fn = self.make_pth("import bad)syntax\n")
135 with captured_stderr() as err_out:
136 site.addpackage(pth_dir, pth_fn, set())
137 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000138 self.assertRegex(err_out.getvalue(),
139 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000140 # XXX: the previous two should be independent checks so that the
141 # order doesn't matter. The next three could be a single check
142 # but my regex foo isn't good enough to write it.
143 self.assertRegex(err_out.getvalue(), 'Traceback')
144 self.assertRegex(err_out.getvalue(), r'import bad\)syntax')
145 self.assertRegex(err_out.getvalue(), 'SyntaxError')
146
147 def test_addpackage_import_bad_exec(self):
148 # Issue 10642
149 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
150 with captured_stderr() as err_out:
151 site.addpackage(pth_dir, pth_fn, set())
152 self.assertRegex(err_out.getvalue(), "line 2")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000153 self.assertRegex(err_out.getvalue(),
154 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000155 # XXX: ditto previous XXX comment.
156 self.assertRegex(err_out.getvalue(), 'Traceback')
Eric Snow46f97b82016-09-07 16:56:15 -0700157 self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000158
159 def test_addpackage_import_bad_pth_file(self):
160 # Issue 5258
161 pth_dir, pth_fn = self.make_pth("abc\x00def\n")
162 with captured_stderr() as err_out:
163 site.addpackage(pth_dir, pth_fn, set())
164 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000165 self.assertRegex(err_out.getvalue(),
166 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000167 # XXX: ditto previous XXX comment.
168 self.assertRegex(err_out.getvalue(), 'Traceback')
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300169 self.assertRegex(err_out.getvalue(), 'ValueError')
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
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900184 def test_getuserbase(self):
185 self.assertEqual(site._getuserbase(), sysconfig._getuserbase())
186
187 def test_get_path(self):
INADA Naokiba9ddb72017-07-28 21:28:19 +0900188 if sys.platform == 'darwin' and sys._framework:
189 scheme = 'osx_framework_user'
190 else:
191 scheme = os.name + '_user'
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900192 self.assertEqual(site._get_path(site._getuserbase()),
INADA Naokiba9ddb72017-07-28 21:28:19 +0900193 sysconfig.get_path('purelib', scheme))
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900194
Ned Deily316f5732011-10-31 16:16:35 -0700195 @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
196 "user-site (site.ENABLE_USER_SITE)")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000197 def test_s_option(self):
Eric Snow6b4be192017-05-22 21:36:03 -0700198 # (ncoghlan) Change this to use script_helper...
Christian Heimes8dc226f2008-05-06 23:45:46 +0000199 usersite = site.USER_SITE
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000200 self.assertIn(usersite, sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000201
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000202 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000203 rc = subprocess.call([sys.executable, '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000204 'import sys; sys.exit(%r in sys.path)' % usersite],
205 env=env)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000206 self.assertEqual(rc, 1)
207
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000208 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000209 rc = subprocess.call([sys.executable, '-s', '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000210 'import sys; sys.exit(%r in sys.path)' % usersite],
211 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200212 if usersite == site.getsitepackages()[0]:
213 self.assertEqual(rc, 1)
214 else:
Eric Snow6b4be192017-05-22 21:36:03 -0700215 self.assertEqual(rc, 0, "User site still added to path with -s")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000216
217 env = os.environ.copy()
218 env["PYTHONNOUSERSITE"] = "1"
219 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000220 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000221 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200222 if usersite == site.getsitepackages()[0]:
223 self.assertEqual(rc, 1)
224 else:
Eric Snow6b4be192017-05-22 21:36:03 -0700225 self.assertEqual(rc, 0,
226 "User site still added to path with PYTHONNOUSERSITE")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000227
228 env = os.environ.copy()
229 env["PYTHONUSERBASE"] = "/tmp"
230 rc = subprocess.call([sys.executable, '-c',
231 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
232 env=env)
Eric Snow6b4be192017-05-22 21:36:03 -0700233 self.assertEqual(rc, 1,
234 "User base not set by PYTHONUSERBASE")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000235
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000236 def test_getuserbase(self):
237 site.USER_BASE = None
238 user_base = site.getuserbase()
239
240 # the call sets site.USER_BASE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000241 self.assertEqual(site.USER_BASE, user_base)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000242
243 # let's set PYTHONUSERBASE and see if it uses it
244 site.USER_BASE = None
Tarek Ziadéedacea32010-01-29 11:41:03 +0000245 import sysconfig
246 sysconfig._CONFIG_VARS = None
247
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000248 with EnvironmentVarGuard() as environ:
249 environ['PYTHONUSERBASE'] = 'xoxo'
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000250 self.assertTrue(site.getuserbase().startswith('xoxo'),
251 site.getuserbase())
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000252
253 def test_getusersitepackages(self):
254 site.USER_SITE = None
255 site.USER_BASE = None
256 user_site = site.getusersitepackages()
257
258 # the call sets USER_BASE *and* USER_SITE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000259 self.assertEqual(site.USER_SITE, user_site)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000260 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000261
262 def test_getsitepackages(self):
263 site.PREFIXES = ['xoxo']
264 dirs = site.getsitepackages()
Ned Deily763f0942018-01-30 05:14:09 -0500265 if os.sep == '/':
266 # OS X, Linux, FreeBSD, etc
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400267 self.assertEqual(len(dirs), 1)
Serhiy Storchaka885bdc42016-02-11 13:10:36 +0200268 wanted = os.path.join('xoxo', 'lib',
269 'python%d.%d' % sys.version_info[:2],
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000270 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000271 self.assertEqual(dirs[0], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000272 else:
Ned Deilyd531b292012-02-06 00:58:18 +0100273 # other platforms
Ezio Melottifc8b2052010-08-17 08:35:41 +0000274 self.assertEqual(len(dirs), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000275 self.assertEqual(dirs[0], 'xoxo')
Tarek Ziadé8c0e2172009-10-27 21:24:21 +0000276 wanted = os.path.join('xoxo', 'lib', 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000277 self.assertEqual(dirs[1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000278
Brett Cannon64a84702004-07-10 02:10:45 +0000279class PthFile(object):
280 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000281
Brett Cannon64a84702004-07-10 02:10:45 +0000282 def __init__(self, filename_base=TESTFN, imported="time",
283 good_dirname="__testdir__", bad_dirname="__bad"):
284 """Initialize instance variables"""
285 self.filename = filename_base + ".pth"
286 self.base_dir = os.path.abspath('')
287 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000288 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000289 self.good_dirname = good_dirname
290 self.bad_dirname = bad_dirname
291 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
292 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000293
Brett Cannon64a84702004-07-10 02:10:45 +0000294 def create(self):
295 """Create a .pth file with a comment, blank lines, an ``import
296 <self.imported>``, a line with self.good_dirname, and a line with
297 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000298
Brett Cannon64a84702004-07-10 02:10:45 +0000299 Creation of the directory for self.good_dir_path (based off of
300 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000301
Brett Cannon64a84702004-07-10 02:10:45 +0000302 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000303
Brett Cannon64a84702004-07-10 02:10:45 +0000304 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000305 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000306 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000307 print("#import @bad module name", file=FILE)
308 print("\n", file=FILE)
309 print("import %s" % self.imported, file=FILE)
310 print(self.good_dirname, file=FILE)
311 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000312 finally:
313 FILE.close()
314 os.mkdir(self.good_dir_path)
315
Brett Cannonee86a662004-07-13 07:12:25 +0000316 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000317 """Make sure that the .pth file is deleted, self.imported is not in
318 sys.modules, and that both self.good_dirname and self.bad_dirname are
319 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000320 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000321 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000322 if prep:
323 self.imported_module = sys.modules.get(self.imported)
324 if self.imported_module:
325 del sys.modules[self.imported]
326 else:
327 if self.imported_module:
328 sys.modules[self.imported] = self.imported_module
329 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000330 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000331 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000332 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000333
334class ImportSideEffectTests(unittest.TestCase):
335 """Test side-effects from importing 'site'."""
336
337 def setUp(self):
338 """Make a copy of sys.path"""
339 self.sys_path = sys.path[:]
340
341 def tearDown(self):
342 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +0000343 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000344
Barry Warsaw28a691b2010-04-17 00:19:56 +0000345 def test_abs_paths(self):
346 # Make sure all imported modules have their __file__ and __cached__
347 # attributes as absolute paths. Arranging to put the Lib directory on
348 # PYTHONPATH would cause the os module to have a relative path for
349 # __file__ if abs_paths() does not get run. sys and builtins (the
350 # only other modules imported before site.py runs) do not have
351 # __file__ or __cached__ because they are built-in.
Steve Dowera73e7902018-09-20 14:39:21 -0700352 try:
353 parent = os.path.relpath(os.path.dirname(os.__file__))
354 cwd = os.getcwd()
355 except ValueError:
356 # Failure to get relpath probably means we need to chdir
357 # to the same drive.
358 cwd, parent = os.path.split(os.path.dirname(os.__file__))
359 with change_cwd(cwd):
360 env = os.environ.copy()
361 env['PYTHONPATH'] = parent
362 code = ('import os, sys',
363 # use ASCII to avoid locale issues with non-ASCII directories
364 'os_file = os.__file__.encode("ascii", "backslashreplace")',
365 r'sys.stdout.buffer.write(os_file + b"\n")',
366 'os_cached = os.__cached__.encode("ascii", "backslashreplace")',
367 r'sys.stdout.buffer.write(os_cached + b"\n")')
368 command = '\n'.join(code)
369 # First, prove that with -S (no 'import site'), the paths are
370 # relative.
371 proc = subprocess.Popen([sys.executable, '-S', '-c', command],
372 env=env,
373 stdout=subprocess.PIPE)
374 stdout, stderr = proc.communicate()
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000375
Steve Dowera73e7902018-09-20 14:39:21 -0700376 self.assertEqual(proc.returncode, 0)
377 os__file__, os__cached__ = stdout.splitlines()[:2]
378 self.assertFalse(os.path.isabs(os__file__))
379 self.assertFalse(os.path.isabs(os__cached__))
380 # Now, with 'import site', it works.
381 proc = subprocess.Popen([sys.executable, '-c', command],
382 env=env,
383 stdout=subprocess.PIPE)
384 stdout, stderr = proc.communicate()
385 self.assertEqual(proc.returncode, 0)
386 os__file__, os__cached__ = stdout.splitlines()[:2]
387 self.assertTrue(os.path.isabs(os__file__),
388 "expected absolute path, got {}"
389 .format(os__file__.decode('ascii')))
390 self.assertTrue(os.path.isabs(os__cached__),
391 "expected absolute path, got {}"
392 .format(os__cached__.decode('ascii')))
Brett Cannon0096e262004-06-05 01:12:51 +0000393
394 def test_no_duplicate_paths(self):
395 # No duplicate paths should exist in sys.path
396 # Handled by removeduppaths()
397 site.removeduppaths()
398 seen_paths = set()
399 for path in sys.path:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000400 self.assertNotIn(path, seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000401 seen_paths.add(path)
402
Zachary Ware9fe6d862013-12-08 00:20:35 -0600403 @unittest.skip('test not implemented')
Brett Cannon0096e262004-06-05 01:12:51 +0000404 def test_add_build_dir(self):
405 # Test that the build directory's Modules directory is used when it
406 # should be.
407 # XXX: implement
408 pass
409
Brett Cannon0096e262004-06-05 01:12:51 +0000410 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000411 # 'quit' and 'exit' should be injected into builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000412 self.assertTrue(hasattr(builtins, "quit"))
413 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000414
415 def test_setting_copyright(self):
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700416 # 'copyright', 'credits', and 'license' should be in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000417 self.assertTrue(hasattr(builtins, "copyright"))
418 self.assertTrue(hasattr(builtins, "credits"))
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700419 self.assertTrue(hasattr(builtins, "license"))
Brett Cannon0096e262004-06-05 01:12:51 +0000420
421 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000422 # 'help' should be set in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000423 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000424
425 def test_aliasing_mbcs(self):
426 if sys.platform == "win32":
427 import locale
428 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000429 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000430 if value == "mbcs":
431 break
432 else:
433 self.fail("did not alias mbcs")
434
Brett Cannon0096e262004-06-05 01:12:51 +0000435 def test_sitecustomize_executed(self):
436 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000437 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000438 try:
439 import sitecustomize
440 except ImportError:
441 pass
442 else:
443 self.fail("sitecustomize not imported automatically")
444
R David Murray1bc6ceb2013-09-14 13:28:37 -0400445 @test.support.requires_resource('network')
Benjamin Peterson337578b2015-02-01 20:16:59 -0500446 @test.support.system_must_validate_cert
Georg Brandl78abc9d2013-10-27 09:41:57 +0100447 @unittest.skipUnless(sys.version_info[3] == 'final',
448 'only for released versions')
Ned Deily5a507f02014-03-26 23:31:39 -0700449 @unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"),
450 'need SSL support to download license')
R David Murray1bc6ceb2013-09-14 13:28:37 -0400451 def test_license_exists_at_url(self):
Ned Deily944d5972014-03-26 23:43:26 -0700452 # This test is a bit fragile since it depends on the format of the
R David Murray1bc6ceb2013-09-14 13:28:37 -0400453 # string displayed by license in the absence of a LICENSE file.
454 url = license._Printer__data.split()[1]
455 req = urllib.request.Request(url, method='HEAD')
456 try:
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700457 with test.support.transient_internet(url):
R David Murray1bc6ceb2013-09-14 13:28:37 -0400458 with urllib.request.urlopen(req) as data:
459 code = data.getcode()
460 except urllib.error.HTTPError as e:
461 code = e.code
462 self.assertEqual(code, 200, msg="Can't find " + url)
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700463
Brett Cannon0096e262004-06-05 01:12:51 +0000464
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200465class StartupImportTests(unittest.TestCase):
466
467 def test_startup_imports(self):
468 # This tests checks which modules are loaded by Python when it
469 # initially starts upon startup.
Christian Heimes179a3db2013-10-12 12:32:21 +0200470 popen = subprocess.Popen([sys.executable, '-I', '-v', '-c',
471 'import sys; print(set(sys.modules))'],
472 stdout=subprocess.PIPE,
Steve Dower313523c2016-09-17 12:22:41 -0700473 stderr=subprocess.PIPE,
474 encoding='utf-8')
Christian Heimes179a3db2013-10-12 12:32:21 +0200475 stdout, stderr = popen.communicate()
Christian Heimes179a3db2013-10-12 12:32:21 +0200476 modules = eval(stdout)
477
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200478 self.assertIn('site', modules)
479
Christian Heimes25827622013-10-12 01:27:08 +0200480 # http://bugs.python.org/issue19205
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200481 re_mods = {'re', '_sre', 'sre_compile', 'sre_constants', 'sre_parse'}
Christian Heimesf403f502013-10-12 15:08:42 +0200482 # _osx_support uses the re module in many placs
483 if sys.platform != 'darwin':
484 self.assertFalse(modules.intersection(re_mods), stderr)
Christian Heimes25827622013-10-12 01:27:08 +0200485 # http://bugs.python.org/issue9548
Christian Heimes179a3db2013-10-12 12:32:21 +0200486 self.assertNotIn('locale', modules, stderr)
Christian Heimes86823a52013-10-17 13:40:00 +0200487 if sys.platform != 'darwin':
488 # http://bugs.python.org/issue19209
489 self.assertNotIn('copyreg', modules, stderr)
Christian Heimesf1dc3ee2013-10-13 02:04:20 +0200490 # http://bugs.python.org/issue19218>
491 collection_mods = {'_collections', 'collections', 'functools',
492 'heapq', 'itertools', 'keyword', 'operator',
doko@ubuntu.com95743552014-04-15 20:37:54 +0200493 'reprlib', 'types', 'weakref'
494 }.difference(sys.builtin_module_names)
Ned Deilyc22bd582017-07-28 03:02:10 -0400495 self.assertFalse(modules.intersection(collection_mods), stderr)
Christian Heimes1a5fb4e2013-10-12 01:00:51 +0200496
Steve Dower6dd8eca2016-09-17 14:35:32 -0700497 def test_startup_interactivehook(self):
498 r = subprocess.Popen([sys.executable, '-c',
499 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
500 self.assertTrue(r, "'__interactivehook__' not added by site")
501
502 def test_startup_interactivehook_isolated(self):
503 # issue28192 readline is not automatically enabled in isolated mode
504 r = subprocess.Popen([sys.executable, '-I', '-c',
505 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
506 self.assertFalse(r, "'__interactivehook__' added in isolated mode")
507
508 def test_startup_interactivehook_isolated_explicit(self):
509 # issue28192 readline can be explicitly enabled in isolated mode
510 r = subprocess.Popen([sys.executable, '-I', '-c',
511 'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
512 self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()")
513
Zachary Wared48214f2017-05-14 15:49:46 -0500514
515@unittest.skipUnless(sys.platform == 'win32', "only supported on Windows")
516class _pthFileTests(unittest.TestCase):
517
Steve Dower1da055e2016-10-29 08:50:31 -0700518 def _create_underpth_exe(self, lines):
Zachary Wared48214f2017-05-14 15:49:46 -0500519 temp_dir = tempfile.mkdtemp()
520 self.addCleanup(test.support.rmtree, temp_dir)
521 exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1])
Steve Dower1da055e2016-10-29 08:50:31 -0700522 shutil.copy(sys.executable, exe_file)
Steve Dower1da055e2016-10-29 08:50:31 -0700523 _pth_file = os.path.splitext(exe_file)[0] + '._pth'
Zachary Wared48214f2017-05-14 15:49:46 -0500524 with open(_pth_file, 'w') as f:
525 for line in lines:
526 print(line, file=f)
527 return exe_file
Steve Dower1da055e2016-10-29 08:50:31 -0700528
Steve Dower5f9193a2017-02-04 15:19:29 -0800529 def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines):
530 sys_path = []
531 for line in lines:
532 if not line or line[0] == '#':
533 continue
534 abs_path = os.path.abspath(os.path.join(sys_prefix, line))
535 sys_path.append(abs_path)
536 return sys_path
537
Steve Dowerc6dd4152016-10-27 14:28:07 -0700538 def test_underpth_nosite_file(self):
Steve Dower1da055e2016-10-29 08:50:31 -0700539 libpath = os.path.dirname(os.path.dirname(encodings.__file__))
540 exe_prefix = os.path.dirname(sys.executable)
Steve Dower5f9193a2017-02-04 15:19:29 -0800541 pth_lines = [
Steve Dower1da055e2016-10-29 08:50:31 -0700542 'fake-path-name',
543 *[libpath for _ in range(200)],
Steve Dower5f9193a2017-02-04 15:19:29 -0800544 '',
Steve Dower1da055e2016-10-29 08:50:31 -0700545 '# comment',
Steve Dower5f9193a2017-02-04 15:19:29 -0800546 ]
547 exe_file = self._create_underpth_exe(pth_lines)
548 sys_path = self._calc_sys_path_for_underpth_nosite(
549 os.path.dirname(exe_file),
550 pth_lines)
Steve Dowerc6dd4152016-10-27 14:28:07 -0700551
Zachary Wared48214f2017-05-14 15:49:46 -0500552 env = os.environ.copy()
553 env['PYTHONPATH'] = 'from-env'
554 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
Steve Dower9b33bf52017-05-23 16:25:25 -0700555 output = subprocess.check_output([exe_file, '-c',
556 'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")'
557 ], env=env, encoding='ansi')
558 actual_sys_path = output.rstrip().split('\n')
Miss Islington (bot)e6499a02018-02-04 08:38:56 -0800559 self.assertTrue(actual_sys_path, "sys.flags.no_site was False")
Steve Dower9b33bf52017-05-23 16:25:25 -0700560 self.assertEqual(
561 actual_sys_path,
562 sys_path,
563 "sys.path is incorrect"
564 )
Steve Dowerc6dd4152016-10-27 14:28:07 -0700565
Steve Dowerc6dd4152016-10-27 14:28:07 -0700566 def test_underpth_file(self):
Steve Dower1da055e2016-10-29 08:50:31 -0700567 libpath = os.path.dirname(os.path.dirname(encodings.__file__))
568 exe_prefix = os.path.dirname(sys.executable)
569 exe_file = self._create_underpth_exe([
570 'fake-path-name',
571 *[libpath for _ in range(200)],
Steve Dower5f9193a2017-02-04 15:19:29 -0800572 '',
Steve Dower1da055e2016-10-29 08:50:31 -0700573 '# comment',
574 'import site'
575 ])
Steve Dower5f9193a2017-02-04 15:19:29 -0800576 sys_prefix = os.path.dirname(exe_file)
Zachary Wared48214f2017-05-14 15:49:46 -0500577 env = os.environ.copy()
578 env['PYTHONPATH'] = 'from-env'
579 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
580 rc = subprocess.call([exe_file, '-c',
581 'import sys; sys.exit(not sys.flags.no_site and '
582 '%r in sys.path and %r in sys.path and %r not in sys.path and '
583 'all("\\r" not in p and "\\n" not in p for p in sys.path))' % (
584 os.path.join(sys_prefix, 'fake-path-name'),
585 libpath,
586 os.path.join(sys_prefix, 'from-env'),
587 )], env=env)
Steve Dower5f9193a2017-02-04 15:19:29 -0800588 self.assertTrue(rc, "sys.path is incorrect")
Steve Dowerc6dd4152016-10-27 14:28:07 -0700589
Steve Dower6dd8eca2016-09-17 14:35:32 -0700590
Brett Cannon0096e262004-06-05 01:12:51 +0000591if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400592 unittest.main()