blob: cb7c393074d3312792964c4f7281456a420ee9b8 [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
Walter Dörwaldb525e182009-04-26 21:39:21 +00009from test.support import run_unittest, TESTFN, EnvironmentVarGuard
R. David Murrayb4ca59b2010-12-26 19:54:29 +000010from test.support import captured_stderr
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
Christian Heimes8dc226f2008-05-06 23:45:46 +000018import subprocess
Tarek Ziadéedacea32010-01-29 11:41:03 +000019import sysconfig
20from copy import copy
21
Brett Cannon0096e262004-06-05 01:12:51 +000022# Need to make sure to not import 'site' if someone specified ``-S`` at the
23# command-line. Detect this by just making sure 'site' has not been imported
24# already.
25if "site" in sys.modules:
26 import site
27else:
Benjamin Petersone549ead2009-03-28 21:42:05 +000028 raise unittest.SkipTest("importation of site.py suppressed")
Brett Cannon0096e262004-06-05 01:12:51 +000029
Ned Deily316f5732011-10-31 16:16:35 -070030if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
Christian Heimes8dc226f2008-05-06 23:45:46 +000031 # need to add user site directory for tests
32 os.makedirs(site.USER_SITE)
33 site.addsitedir(site.USER_SITE)
34
Brett Cannon0096e262004-06-05 01:12:51 +000035class HelperFunctionsTests(unittest.TestCase):
36 """Tests for helper functions.
Brett Cannon0096e262004-06-05 01:12:51 +000037 """
38
39 def setUp(self):
40 """Save a copy of sys.path"""
41 self.sys_path = sys.path[:]
Tarek Ziadé4a608c02009-08-20 21:28:05 +000042 self.old_base = site.USER_BASE
43 self.old_site = site.USER_SITE
44 self.old_prefixes = site.PREFIXES
Brett Cannon8ac95ee2012-04-04 17:31:16 -040045 self.original_vars = sysconfig._CONFIG_VARS
Tarek Ziadéedacea32010-01-29 11:41:03 +000046 self.old_vars = copy(sysconfig._CONFIG_VARS)
Brett Cannon0096e262004-06-05 01:12:51 +000047
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000048 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000049 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +000050 sys.path[:] = self.sys_path
Tarek Ziadé4a608c02009-08-20 21:28:05 +000051 site.USER_BASE = self.old_base
52 site.USER_SITE = self.old_site
53 site.PREFIXES = self.old_prefixes
Brett Cannon8ac95ee2012-04-04 17:31:16 -040054 sysconfig._CONFIG_VARS = self.original_vars
55 sysconfig._CONFIG_VARS.clear()
56 sysconfig._CONFIG_VARS.update(self.old_vars)
Raymond Hettingerebd95222004-06-27 03:02:18 +000057
Brett Cannon0096e262004-06-05 01:12:51 +000058 def test_makepath(self):
59 # Test makepath() have an absolute path for its first return value
60 # and a case-normalized version of the absolute path for its
61 # second value.
62 path_parts = ("Beginning", "End")
63 original_dir = os.path.join(*path_parts)
64 abs_dir, norm_dir = site.makepath(*path_parts)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000065 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000066 if original_dir == os.path.normcase(original_dir):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000067 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000068 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000069 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000070
71 def test_init_pathinfo(self):
72 dir_set = site._init_pathinfo()
73 for entry in [site.makepath(path)[1] for path in sys.path
74 if path and os.path.isdir(path)]:
Ezio Melottib58e0bd2010-01-23 15:40:09 +000075 self.assertIn(entry, dir_set,
76 "%s from sys.path not found in set returned "
77 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000078
Brett Cannonee86a662004-07-13 07:12:25 +000079 def pth_file_tests(self, pth_file):
80 """Contain common code for testing results of reading a .pth file"""
Ezio Melottib58e0bd2010-01-23 15:40:09 +000081 self.assertIn(pth_file.imported, sys.modules,
82 "%s not in sys.modules" % pth_file.imported)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +000083 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
84 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +000085
Brett Cannon0096e262004-06-05 01:12:51 +000086 def test_addpackage(self):
87 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000088 # adds directories to sys.path for any line in the file that is not a
89 # comment or import that is a valid directory name for where the .pth
90 # file resides; invalid directories are not added
91 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000092 pth_file.cleanup(prep=True) # to make sure that nothing is
93 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000094 try:
Brett Cannon64a84702004-07-10 02:10:45 +000095 pth_file.create()
96 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +000097 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000098 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000099 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000100
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000101 def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
102 # Create a .pth file and return its (abspath, basename).
103 pth_dir = os.path.abspath(pth_dir)
104 pth_basename = pth_name + '.pth'
105 pth_fn = os.path.join(pth_dir, pth_basename)
106 pth_file = open(pth_fn, 'w', encoding='utf-8')
107 self.addCleanup(lambda: os.remove(pth_fn))
108 pth_file.write(contents)
109 pth_file.close()
110 return pth_dir, pth_basename
111
112 def test_addpackage_import_bad_syntax(self):
113 # Issue 10642
114 pth_dir, pth_fn = self.make_pth("import bad)syntax\n")
115 with captured_stderr() as err_out:
116 site.addpackage(pth_dir, pth_fn, set())
117 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000118 self.assertRegex(err_out.getvalue(),
119 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000120 # XXX: the previous two should be independent checks so that the
121 # order doesn't matter. The next three could be a single check
122 # but my regex foo isn't good enough to write it.
123 self.assertRegex(err_out.getvalue(), 'Traceback')
124 self.assertRegex(err_out.getvalue(), r'import bad\)syntax')
125 self.assertRegex(err_out.getvalue(), 'SyntaxError')
126
127 def test_addpackage_import_bad_exec(self):
128 # Issue 10642
129 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
130 with captured_stderr() as err_out:
131 site.addpackage(pth_dir, pth_fn, set())
132 self.assertRegex(err_out.getvalue(), "line 2")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000133 self.assertRegex(err_out.getvalue(),
134 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000135 # XXX: ditto previous XXX comment.
136 self.assertRegex(err_out.getvalue(), 'Traceback')
Brett Cannon679ecb52013-07-04 17:51:50 -0400137 self.assertRegex(err_out.getvalue(), 'ImportError')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000138
R. David Murrayad4ccfd2010-12-27 04:31:48 +0000139 @unittest.skipIf(sys.platform == "win32", "Windows does not raise an "
140 "error for file paths containing null characters")
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000141 def test_addpackage_import_bad_pth_file(self):
142 # Issue 5258
143 pth_dir, pth_fn = self.make_pth("abc\x00def\n")
144 with captured_stderr() as err_out:
145 site.addpackage(pth_dir, pth_fn, set())
146 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000147 self.assertRegex(err_out.getvalue(),
148 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000149 # XXX: ditto previous XXX comment.
150 self.assertRegex(err_out.getvalue(), 'Traceback')
151 self.assertRegex(err_out.getvalue(), 'TypeError')
152
Brett Cannon0096e262004-06-05 01:12:51 +0000153 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +0000154 # Same tests for test_addpackage since addsitedir() essentially just
155 # calls addpackage() for every .pth file in the directory
156 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000157 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
158 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +0000159 try:
Brett Cannonee86a662004-07-13 07:12:25 +0000160 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +0000161 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000162 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000163 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000164 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +0000165
Ned Deily316f5732011-10-31 16:16:35 -0700166 @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
167 "user-site (site.ENABLE_USER_SITE)")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000168 def test_s_option(self):
169 usersite = site.USER_SITE
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000170 self.assertIn(usersite, sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000171
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000172 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000173 rc = subprocess.call([sys.executable, '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000174 'import sys; sys.exit(%r in sys.path)' % usersite],
175 env=env)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000176 self.assertEqual(rc, 1)
177
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000178 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000179 rc = subprocess.call([sys.executable, '-s', '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000180 'import sys; sys.exit(%r in sys.path)' % usersite],
181 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200182 if usersite == site.getsitepackages()[0]:
183 self.assertEqual(rc, 1)
184 else:
185 self.assertEqual(rc, 0)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000186
187 env = os.environ.copy()
188 env["PYTHONNOUSERSITE"] = "1"
189 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000190 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000191 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200192 if usersite == site.getsitepackages()[0]:
193 self.assertEqual(rc, 1)
194 else:
195 self.assertEqual(rc, 0)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000196
197 env = os.environ.copy()
198 env["PYTHONUSERBASE"] = "/tmp"
199 rc = subprocess.call([sys.executable, '-c',
200 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
201 env=env)
202 self.assertEqual(rc, 1)
203
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000204 def test_getuserbase(self):
205 site.USER_BASE = None
206 user_base = site.getuserbase()
207
208 # the call sets site.USER_BASE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000209 self.assertEqual(site.USER_BASE, user_base)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000210
211 # let's set PYTHONUSERBASE and see if it uses it
212 site.USER_BASE = None
Tarek Ziadéedacea32010-01-29 11:41:03 +0000213 import sysconfig
214 sysconfig._CONFIG_VARS = None
215
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000216 with EnvironmentVarGuard() as environ:
217 environ['PYTHONUSERBASE'] = 'xoxo'
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000218 self.assertTrue(site.getuserbase().startswith('xoxo'),
219 site.getuserbase())
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000220
221 def test_getusersitepackages(self):
222 site.USER_SITE = None
223 site.USER_BASE = None
224 user_site = site.getusersitepackages()
225
226 # the call sets USER_BASE *and* USER_SITE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000227 self.assertEqual(site.USER_SITE, user_site)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000228 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000229
230 def test_getsitepackages(self):
231 site.PREFIXES = ['xoxo']
232 dirs = site.getsitepackages()
233
Christian Heimesde0b9622012-11-19 00:59:39 +0100234 if (sys.platform == "darwin" and
Ned Deilyd531b292012-02-06 00:58:18 +0100235 sysconfig.get_config_var("PYTHONFRAMEWORK")):
236 # OS X framework builds
237 site.PREFIXES = ['Python.framework']
238 dirs = site.getsitepackages()
239 self.assertEqual(len(dirs), 3)
240 wanted = os.path.join('/Library',
241 sysconfig.get_config_var("PYTHONFRAMEWORK"),
242 sys.version[:3],
243 'site-packages')
244 self.assertEqual(dirs[2], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000245 elif os.sep == '/':
Ned Deilyd531b292012-02-06 00:58:18 +0100246 # OS X non-framwework builds, Linux, FreeBSD, etc
Ezio Melottifc8b2052010-08-17 08:35:41 +0000247 self.assertEqual(len(dirs), 2)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000248 wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
249 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000250 self.assertEqual(dirs[0], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000251 wanted = os.path.join('xoxo', 'lib', 'site-python')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000252 self.assertEqual(dirs[1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000253 else:
Ned Deilyd531b292012-02-06 00:58:18 +0100254 # other platforms
Ezio Melottifc8b2052010-08-17 08:35:41 +0000255 self.assertEqual(len(dirs), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000256 self.assertEqual(dirs[0], 'xoxo')
Tarek Ziadé8c0e2172009-10-27 21:24:21 +0000257 wanted = os.path.join('xoxo', 'lib', 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000258 self.assertEqual(dirs[1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000259
Brett Cannon64a84702004-07-10 02:10:45 +0000260class PthFile(object):
261 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000262
Brett Cannon64a84702004-07-10 02:10:45 +0000263 def __init__(self, filename_base=TESTFN, imported="time",
264 good_dirname="__testdir__", bad_dirname="__bad"):
265 """Initialize instance variables"""
266 self.filename = filename_base + ".pth"
267 self.base_dir = os.path.abspath('')
268 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000269 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000270 self.good_dirname = good_dirname
271 self.bad_dirname = bad_dirname
272 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
273 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000274
Brett Cannon64a84702004-07-10 02:10:45 +0000275 def create(self):
276 """Create a .pth file with a comment, blank lines, an ``import
277 <self.imported>``, a line with self.good_dirname, and a line with
278 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000279
Brett Cannon64a84702004-07-10 02:10:45 +0000280 Creation of the directory for self.good_dir_path (based off of
281 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000282
Brett Cannon64a84702004-07-10 02:10:45 +0000283 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000284
Brett Cannon64a84702004-07-10 02:10:45 +0000285 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000286 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000287 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000288 print("#import @bad module name", file=FILE)
289 print("\n", file=FILE)
290 print("import %s" % self.imported, file=FILE)
291 print(self.good_dirname, file=FILE)
292 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000293 finally:
294 FILE.close()
295 os.mkdir(self.good_dir_path)
296
Brett Cannonee86a662004-07-13 07:12:25 +0000297 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000298 """Make sure that the .pth file is deleted, self.imported is not in
299 sys.modules, and that both self.good_dirname and self.bad_dirname are
300 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000301 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000302 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000303 if prep:
304 self.imported_module = sys.modules.get(self.imported)
305 if self.imported_module:
306 del sys.modules[self.imported]
307 else:
308 if self.imported_module:
309 sys.modules[self.imported] = self.imported_module
310 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000311 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000312 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000313 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000314
315class ImportSideEffectTests(unittest.TestCase):
316 """Test side-effects from importing 'site'."""
317
318 def setUp(self):
319 """Make a copy of sys.path"""
320 self.sys_path = sys.path[:]
321
322 def tearDown(self):
323 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +0000324 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000325
Barry Warsaw28a691b2010-04-17 00:19:56 +0000326 def test_abs_paths(self):
327 # Make sure all imported modules have their __file__ and __cached__
328 # attributes as absolute paths. Arranging to put the Lib directory on
329 # PYTHONPATH would cause the os module to have a relative path for
330 # __file__ if abs_paths() does not get run. sys and builtins (the
331 # only other modules imported before site.py runs) do not have
332 # __file__ or __cached__ because they are built-in.
333 parent = os.path.relpath(os.path.dirname(os.__file__))
334 env = os.environ.copy()
335 env['PYTHONPATH'] = parent
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000336 code = ('import os, sys',
337 # use ASCII to avoid locale issues with non-ASCII directories
338 'os_file = os.__file__.encode("ascii", "backslashreplace")',
339 r'sys.stdout.buffer.write(os_file + b"\n")',
340 'os_cached = os.__cached__.encode("ascii", "backslashreplace")',
341 r'sys.stdout.buffer.write(os_cached + b"\n")')
342 command = '\n'.join(code)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000343 # First, prove that with -S (no 'import site'), the paths are
344 # relative.
345 proc = subprocess.Popen([sys.executable, '-S', '-c', command],
346 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000347 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000348 stdout, stderr = proc.communicate()
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000349
Barry Warsaw28a691b2010-04-17 00:19:56 +0000350 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000351 os__file__, os__cached__ = stdout.splitlines()[:2]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000352 self.assertFalse(os.path.isabs(os__file__))
353 self.assertFalse(os.path.isabs(os__cached__))
354 # Now, with 'import site', it works.
355 proc = subprocess.Popen([sys.executable, '-c', command],
356 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000357 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000358 stdout, stderr = proc.communicate()
359 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000360 os__file__, os__cached__ = stdout.splitlines()[:2]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000361 self.assertTrue(os.path.isabs(os__file__))
362 self.assertTrue(os.path.isabs(os__cached__))
Brett Cannon0096e262004-06-05 01:12:51 +0000363
364 def test_no_duplicate_paths(self):
365 # No duplicate paths should exist in sys.path
366 # Handled by removeduppaths()
367 site.removeduppaths()
368 seen_paths = set()
369 for path in sys.path:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000370 self.assertNotIn(path, seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000371 seen_paths.add(path)
372
373 def test_add_build_dir(self):
374 # Test that the build directory's Modules directory is used when it
375 # should be.
376 # XXX: implement
377 pass
378
Brett Cannon0096e262004-06-05 01:12:51 +0000379 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000380 # 'quit' and 'exit' should be injected into builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000381 self.assertTrue(hasattr(builtins, "quit"))
382 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000383
384 def test_setting_copyright(self):
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700385 # 'copyright', 'credits', and 'license' should be in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000386 self.assertTrue(hasattr(builtins, "copyright"))
387 self.assertTrue(hasattr(builtins, "credits"))
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700388 self.assertTrue(hasattr(builtins, "license"))
Brett Cannon0096e262004-06-05 01:12:51 +0000389
390 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000391 # 'help' should be set in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000392 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000393
394 def test_aliasing_mbcs(self):
395 if sys.platform == "win32":
396 import locale
397 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000398 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000399 if value == "mbcs":
400 break
401 else:
402 self.fail("did not alias mbcs")
403
Brett Cannon0096e262004-06-05 01:12:51 +0000404 def test_sitecustomize_executed(self):
405 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000406 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000407 try:
408 import sitecustomize
409 except ImportError:
410 pass
411 else:
412 self.fail("sitecustomize not imported automatically")
413
R David Murray1bc6ceb2013-09-14 13:28:37 -0400414 @test.support.requires_resource('network')
Georg Brandl78abc9d2013-10-27 09:41:57 +0100415 @unittest.skipUnless(sys.version_info[3] == 'final',
416 'only for released versions')
R David Murray1bc6ceb2013-09-14 13:28:37 -0400417 def test_license_exists_at_url(self):
418 # This test is a bit fragile since it depends on the format of the
419 # string displayed by license in the absence of a LICENSE file.
420 url = license._Printer__data.split()[1]
421 req = urllib.request.Request(url, method='HEAD')
422 try:
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700423 with test.support.transient_internet(url):
R David Murray1bc6ceb2013-09-14 13:28:37 -0400424 with urllib.request.urlopen(req) as data:
425 code = data.getcode()
426 except urllib.error.HTTPError as e:
427 code = e.code
428 self.assertEqual(code, 200, msg="Can't find " + url)
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700429
Brett Cannon0096e262004-06-05 01:12:51 +0000430
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200431class StartupImportTests(unittest.TestCase):
432
433 def test_startup_imports(self):
434 # This tests checks which modules are loaded by Python when it
435 # initially starts upon startup.
Christian Heimes179a3db2013-10-12 12:32:21 +0200436 popen = subprocess.Popen([sys.executable, '-I', '-v', '-c',
437 'import sys; print(set(sys.modules))'],
438 stdout=subprocess.PIPE,
439 stderr=subprocess.PIPE)
440 stdout, stderr = popen.communicate()
441 stdout = stdout.decode('utf-8')
442 stderr = stderr.decode('utf-8')
443 modules = eval(stdout)
444
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200445 self.assertIn('site', modules)
446
Christian Heimes25827622013-10-12 01:27:08 +0200447 # http://bugs.python.org/issue19205
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200448 re_mods = {'re', '_sre', 'sre_compile', 'sre_constants', 'sre_parse'}
Christian Heimesf403f502013-10-12 15:08:42 +0200449 # _osx_support uses the re module in many placs
450 if sys.platform != 'darwin':
451 self.assertFalse(modules.intersection(re_mods), stderr)
Christian Heimes25827622013-10-12 01:27:08 +0200452 # http://bugs.python.org/issue9548
Christian Heimes179a3db2013-10-12 12:32:21 +0200453 self.assertNotIn('locale', modules, stderr)
Christian Heimes86823a52013-10-17 13:40:00 +0200454 if sys.platform != 'darwin':
455 # http://bugs.python.org/issue19209
456 self.assertNotIn('copyreg', modules, stderr)
Christian Heimesf1dc3ee2013-10-13 02:04:20 +0200457 # http://bugs.python.org/issue19218>
458 collection_mods = {'_collections', 'collections', 'functools',
459 'heapq', 'itertools', 'keyword', 'operator',
460 'reprlib', 'types', 'weakref'}
Ned Deilyb795aa82013-10-17 15:21:40 -0700461 self.assertFalse(modules.intersection(collection_mods), stderr)
Christian Heimes1a5fb4e2013-10-12 01:00:51 +0200462
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200463
Brett Cannon0096e262004-06-05 01:12:51 +0000464if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400465 unittest.main()