blob: 4029617aa1d9c16d7120e41a58a06cd5c0673a55 [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
Zachary Ware36193e72013-12-11 16:59:44 -06009from test.support import captured_stderr, TESTFN, EnvironmentVarGuard
Georg Brandl1a3284e2007-12-02 09:40:06 +000010import builtins
Brett Cannon0096e262004-06-05 01:12:51 +000011import os
12import sys
R. David Murrayab9d8d62010-12-27 00:03:13 +000013import re
Brett Cannon0096e262004-06-05 01:12:51 +000014import encodings
R David Murray1bc6ceb2013-09-14 13:28:37 -040015import urllib.request
16import urllib.error
Steve Dower1da055e2016-10-29 08:50:31 -070017import shutil
Christian Heimes8dc226f2008-05-06 23:45:46 +000018import subprocess
Tarek Ziadéedacea32010-01-29 11:41:03 +000019import sysconfig
20from copy import copy
21
Zachary Ware36193e72013-12-11 16:59:44 -060022# These tests are not particularly useful if Python was invoked with -S.
23# If you add tests that are useful under -S, this skip should be moved
24# to the class level.
25if sys.flags.no_site:
26 raise unittest.SkipTest("Python was invoked with -S")
27
28import site
Brett Cannon0096e262004-06-05 01:12:51 +000029
Victor Stinner33a5d402017-05-02 11:45:42 +020030
31OLD_SYS_PATH = None
32
33
34def setUpModule():
35 global OLD_SYS_PATH
36 OLD_SYS_PATH = sys.path[:]
37
38 if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
39 # need to add user site directory for tests
40 try:
41 os.makedirs(site.USER_SITE)
42 # modify sys.path: will be restored by tearDownModule()
43 site.addsitedir(site.USER_SITE)
44 except PermissionError as exc:
45 raise unittest.SkipTest('unable to create user site directory (%r): %s'
46 % (site.USER_SITE, exc))
47
48
49def tearDownModule():
50 sys.path[:] = OLD_SYS_PATH
Victor Stinner21d0e1b2016-03-14 17:47:03 +010051
Christian Heimes8dc226f2008-05-06 23:45:46 +000052
Brett Cannon0096e262004-06-05 01:12:51 +000053class HelperFunctionsTests(unittest.TestCase):
54 """Tests for helper functions.
Brett Cannon0096e262004-06-05 01:12:51 +000055 """
56
57 def setUp(self):
58 """Save a copy of sys.path"""
59 self.sys_path = sys.path[:]
Tarek Ziadé4a608c02009-08-20 21:28:05 +000060 self.old_base = site.USER_BASE
61 self.old_site = site.USER_SITE
62 self.old_prefixes = site.PREFIXES
Brett Cannon8ac95ee2012-04-04 17:31:16 -040063 self.original_vars = sysconfig._CONFIG_VARS
Tarek Ziadéedacea32010-01-29 11:41:03 +000064 self.old_vars = copy(sysconfig._CONFIG_VARS)
Brett Cannon0096e262004-06-05 01:12:51 +000065
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000066 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000067 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +000068 sys.path[:] = self.sys_path
Tarek Ziadé4a608c02009-08-20 21:28:05 +000069 site.USER_BASE = self.old_base
70 site.USER_SITE = self.old_site
71 site.PREFIXES = self.old_prefixes
Brett Cannon8ac95ee2012-04-04 17:31:16 -040072 sysconfig._CONFIG_VARS = self.original_vars
73 sysconfig._CONFIG_VARS.clear()
74 sysconfig._CONFIG_VARS.update(self.old_vars)
Raymond Hettingerebd95222004-06-27 03:02:18 +000075
Brett Cannon0096e262004-06-05 01:12:51 +000076 def test_makepath(self):
77 # Test makepath() have an absolute path for its first return value
78 # and a case-normalized version of the absolute path for its
79 # second value.
80 path_parts = ("Beginning", "End")
81 original_dir = os.path.join(*path_parts)
82 abs_dir, norm_dir = site.makepath(*path_parts)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000083 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000084 if original_dir == os.path.normcase(original_dir):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000085 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000086 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000087 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000088
89 def test_init_pathinfo(self):
90 dir_set = site._init_pathinfo()
91 for entry in [site.makepath(path)[1] for path in sys.path
Brett Cannon5f0507d2016-04-08 15:04:28 -070092 if path and os.path.exists(path)]:
Ezio Melottib58e0bd2010-01-23 15:40:09 +000093 self.assertIn(entry, dir_set,
94 "%s from sys.path not found in set returned "
95 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000096
Brett Cannonee86a662004-07-13 07:12:25 +000097 def pth_file_tests(self, pth_file):
98 """Contain common code for testing results of reading a .pth file"""
Ezio Melottib58e0bd2010-01-23 15:40:09 +000099 self.assertIn(pth_file.imported, sys.modules,
100 "%s not in sys.modules" % pth_file.imported)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000101 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
102 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +0000103
Brett Cannon0096e262004-06-05 01:12:51 +0000104 def test_addpackage(self):
105 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +0000106 # adds directories to sys.path for any line in the file that is not a
107 # comment or import that is a valid directory name for where the .pth
108 # file resides; invalid directories are not added
109 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000110 pth_file.cleanup(prep=True) # to make sure that nothing is
111 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +0000112 try:
Brett Cannon64a84702004-07-10 02:10:45 +0000113 pth_file.create()
114 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000115 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000116 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000117 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000118
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000119 def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
120 # Create a .pth file and return its (abspath, basename).
121 pth_dir = os.path.abspath(pth_dir)
122 pth_basename = pth_name + '.pth'
123 pth_fn = os.path.join(pth_dir, pth_basename)
124 pth_file = open(pth_fn, 'w', encoding='utf-8')
125 self.addCleanup(lambda: os.remove(pth_fn))
126 pth_file.write(contents)
127 pth_file.close()
128 return pth_dir, pth_basename
129
130 def test_addpackage_import_bad_syntax(self):
131 # Issue 10642
132 pth_dir, pth_fn = self.make_pth("import bad)syntax\n")
133 with captured_stderr() as err_out:
134 site.addpackage(pth_dir, pth_fn, set())
135 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000136 self.assertRegex(err_out.getvalue(),
137 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000138 # XXX: the previous two should be independent checks so that the
139 # order doesn't matter. The next three could be a single check
140 # but my regex foo isn't good enough to write it.
141 self.assertRegex(err_out.getvalue(), 'Traceback')
142 self.assertRegex(err_out.getvalue(), r'import bad\)syntax')
143 self.assertRegex(err_out.getvalue(), 'SyntaxError')
144
145 def test_addpackage_import_bad_exec(self):
146 # Issue 10642
147 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
148 with captured_stderr() as err_out:
149 site.addpackage(pth_dir, pth_fn, set())
150 self.assertRegex(err_out.getvalue(), "line 2")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000151 self.assertRegex(err_out.getvalue(),
152 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000153 # XXX: ditto previous XXX comment.
154 self.assertRegex(err_out.getvalue(), 'Traceback')
Eric Snow46f97b82016-09-07 16:56:15 -0700155 self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000156
157 def test_addpackage_import_bad_pth_file(self):
158 # Issue 5258
159 pth_dir, pth_fn = self.make_pth("abc\x00def\n")
160 with captured_stderr() as err_out:
161 site.addpackage(pth_dir, pth_fn, set())
162 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000163 self.assertRegex(err_out.getvalue(),
164 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000165 # XXX: ditto previous XXX comment.
166 self.assertRegex(err_out.getvalue(), 'Traceback')
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300167 self.assertRegex(err_out.getvalue(), 'ValueError')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000168
Brett Cannon0096e262004-06-05 01:12:51 +0000169 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +0000170 # Same tests for test_addpackage since addsitedir() essentially just
171 # calls addpackage() for every .pth file in the directory
172 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000173 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
174 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +0000175 try:
Brett Cannonee86a662004-07-13 07:12:25 +0000176 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +0000177 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000178 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000179 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000180 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +0000181
Ned Deily316f5732011-10-31 16:16:35 -0700182 @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
183 "user-site (site.ENABLE_USER_SITE)")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000184 def test_s_option(self):
185 usersite = site.USER_SITE
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000186 self.assertIn(usersite, sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000187
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000188 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000189 rc = subprocess.call([sys.executable, '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000190 'import sys; sys.exit(%r in sys.path)' % usersite],
191 env=env)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000192 self.assertEqual(rc, 1)
193
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000194 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000195 rc = subprocess.call([sys.executable, '-s', '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000196 'import sys; sys.exit(%r in sys.path)' % usersite],
197 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200198 if usersite == site.getsitepackages()[0]:
199 self.assertEqual(rc, 1)
200 else:
201 self.assertEqual(rc, 0)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000202
203 env = os.environ.copy()
204 env["PYTHONNOUSERSITE"] = "1"
205 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000206 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000207 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200208 if usersite == site.getsitepackages()[0]:
209 self.assertEqual(rc, 1)
210 else:
211 self.assertEqual(rc, 0)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000212
213 env = os.environ.copy()
214 env["PYTHONUSERBASE"] = "/tmp"
215 rc = subprocess.call([sys.executable, '-c',
216 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
217 env=env)
218 self.assertEqual(rc, 1)
219
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000220 def test_getuserbase(self):
221 site.USER_BASE = None
222 user_base = site.getuserbase()
223
224 # the call sets site.USER_BASE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000225 self.assertEqual(site.USER_BASE, user_base)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000226
227 # let's set PYTHONUSERBASE and see if it uses it
228 site.USER_BASE = None
Tarek Ziadéedacea32010-01-29 11:41:03 +0000229 import sysconfig
230 sysconfig._CONFIG_VARS = None
231
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000232 with EnvironmentVarGuard() as environ:
233 environ['PYTHONUSERBASE'] = 'xoxo'
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000234 self.assertTrue(site.getuserbase().startswith('xoxo'),
235 site.getuserbase())
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000236
237 def test_getusersitepackages(self):
238 site.USER_SITE = None
239 site.USER_BASE = None
240 user_site = site.getusersitepackages()
241
242 # the call sets USER_BASE *and* USER_SITE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000243 self.assertEqual(site.USER_SITE, user_site)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000244 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000245
246 def test_getsitepackages(self):
247 site.PREFIXES = ['xoxo']
248 dirs = site.getsitepackages()
249
Christian Heimesde0b9622012-11-19 00:59:39 +0100250 if (sys.platform == "darwin" and
Ned Deilyd531b292012-02-06 00:58:18 +0100251 sysconfig.get_config_var("PYTHONFRAMEWORK")):
252 # OS X framework builds
253 site.PREFIXES = ['Python.framework']
254 dirs = site.getsitepackages()
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400255 self.assertEqual(len(dirs), 2)
Ned Deilyd531b292012-02-06 00:58:18 +0100256 wanted = os.path.join('/Library',
257 sysconfig.get_config_var("PYTHONFRAMEWORK"),
Serhiy Storchaka885bdc42016-02-11 13:10:36 +0200258 '%d.%d' % sys.version_info[:2],
Ned Deilyd531b292012-02-06 00:58:18 +0100259 'site-packages')
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400260 self.assertEqual(dirs[1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000261 elif os.sep == '/':
Ned Deilyd531b292012-02-06 00:58:18 +0100262 # OS X non-framwework builds, Linux, FreeBSD, etc
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400263 self.assertEqual(len(dirs), 1)
Serhiy Storchaka885bdc42016-02-11 13:10:36 +0200264 wanted = os.path.join('xoxo', 'lib',
265 'python%d.%d' % sys.version_info[:2],
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000266 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000267 self.assertEqual(dirs[0], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000268 else:
Ned Deilyd531b292012-02-06 00:58:18 +0100269 # other platforms
Ezio Melottifc8b2052010-08-17 08:35:41 +0000270 self.assertEqual(len(dirs), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000271 self.assertEqual(dirs[0], 'xoxo')
Tarek Ziadé8c0e2172009-10-27 21:24:21 +0000272 wanted = os.path.join('xoxo', 'lib', 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000273 self.assertEqual(dirs[1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000274
Brett Cannon64a84702004-07-10 02:10:45 +0000275class PthFile(object):
276 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000277
Brett Cannon64a84702004-07-10 02:10:45 +0000278 def __init__(self, filename_base=TESTFN, imported="time",
279 good_dirname="__testdir__", bad_dirname="__bad"):
280 """Initialize instance variables"""
281 self.filename = filename_base + ".pth"
282 self.base_dir = os.path.abspath('')
283 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000284 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000285 self.good_dirname = good_dirname
286 self.bad_dirname = bad_dirname
287 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
288 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000289
Brett Cannon64a84702004-07-10 02:10:45 +0000290 def create(self):
291 """Create a .pth file with a comment, blank lines, an ``import
292 <self.imported>``, a line with self.good_dirname, and a line with
293 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000294
Brett Cannon64a84702004-07-10 02:10:45 +0000295 Creation of the directory for self.good_dir_path (based off of
296 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000297
Brett Cannon64a84702004-07-10 02:10:45 +0000298 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000299
Brett Cannon64a84702004-07-10 02:10:45 +0000300 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000301 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000302 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000303 print("#import @bad module name", file=FILE)
304 print("\n", file=FILE)
305 print("import %s" % self.imported, file=FILE)
306 print(self.good_dirname, file=FILE)
307 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000308 finally:
309 FILE.close()
310 os.mkdir(self.good_dir_path)
311
Brett Cannonee86a662004-07-13 07:12:25 +0000312 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000313 """Make sure that the .pth file is deleted, self.imported is not in
314 sys.modules, and that both self.good_dirname and self.bad_dirname are
315 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000316 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000317 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000318 if prep:
319 self.imported_module = sys.modules.get(self.imported)
320 if self.imported_module:
321 del sys.modules[self.imported]
322 else:
323 if self.imported_module:
324 sys.modules[self.imported] = self.imported_module
325 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000326 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000327 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000328 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000329
330class ImportSideEffectTests(unittest.TestCase):
331 """Test side-effects from importing 'site'."""
332
333 def setUp(self):
334 """Make a copy of sys.path"""
335 self.sys_path = sys.path[:]
336
337 def tearDown(self):
338 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +0000339 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000340
Barry Warsaw28a691b2010-04-17 00:19:56 +0000341 def test_abs_paths(self):
342 # Make sure all imported modules have their __file__ and __cached__
343 # attributes as absolute paths. Arranging to put the Lib directory on
344 # PYTHONPATH would cause the os module to have a relative path for
345 # __file__ if abs_paths() does not get run. sys and builtins (the
346 # only other modules imported before site.py runs) do not have
347 # __file__ or __cached__ because they are built-in.
348 parent = os.path.relpath(os.path.dirname(os.__file__))
349 env = os.environ.copy()
350 env['PYTHONPATH'] = parent
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000351 code = ('import os, sys',
352 # use ASCII to avoid locale issues with non-ASCII directories
353 'os_file = os.__file__.encode("ascii", "backslashreplace")',
354 r'sys.stdout.buffer.write(os_file + b"\n")',
355 'os_cached = os.__cached__.encode("ascii", "backslashreplace")',
356 r'sys.stdout.buffer.write(os_cached + b"\n")')
357 command = '\n'.join(code)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000358 # First, prove that with -S (no 'import site'), the paths are
359 # relative.
360 proc = subprocess.Popen([sys.executable, '-S', '-c', command],
361 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000362 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000363 stdout, stderr = proc.communicate()
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000364
Barry Warsaw28a691b2010-04-17 00:19:56 +0000365 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000366 os__file__, os__cached__ = stdout.splitlines()[:2]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000367 self.assertFalse(os.path.isabs(os__file__))
368 self.assertFalse(os.path.isabs(os__cached__))
369 # Now, with 'import site', it works.
370 proc = subprocess.Popen([sys.executable, '-c', command],
371 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000372 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000373 stdout, stderr = proc.communicate()
374 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000375 os__file__, os__cached__ = stdout.splitlines()[:2]
Eric Snow32439d62015-05-02 19:15:18 -0600376 self.assertTrue(os.path.isabs(os__file__),
Eric Snow00607e92015-05-04 11:48:39 -0600377 "expected absolute path, got {}"
378 .format(os__file__.decode('ascii')))
Eric Snow32439d62015-05-02 19:15:18 -0600379 self.assertTrue(os.path.isabs(os__cached__),
Eric Snow00607e92015-05-04 11:48:39 -0600380 "expected absolute path, got {}"
381 .format(os__cached__.decode('ascii')))
Brett Cannon0096e262004-06-05 01:12:51 +0000382
383 def test_no_duplicate_paths(self):
384 # No duplicate paths should exist in sys.path
385 # Handled by removeduppaths()
386 site.removeduppaths()
387 seen_paths = set()
388 for path in sys.path:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000389 self.assertNotIn(path, seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000390 seen_paths.add(path)
391
Zachary Ware9fe6d862013-12-08 00:20:35 -0600392 @unittest.skip('test not implemented')
Brett Cannon0096e262004-06-05 01:12:51 +0000393 def test_add_build_dir(self):
394 # Test that the build directory's Modules directory is used when it
395 # should be.
396 # XXX: implement
397 pass
398
Brett Cannon0096e262004-06-05 01:12:51 +0000399 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000400 # 'quit' and 'exit' should be injected into builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000401 self.assertTrue(hasattr(builtins, "quit"))
402 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000403
404 def test_setting_copyright(self):
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700405 # 'copyright', 'credits', and 'license' should be in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000406 self.assertTrue(hasattr(builtins, "copyright"))
407 self.assertTrue(hasattr(builtins, "credits"))
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700408 self.assertTrue(hasattr(builtins, "license"))
Brett Cannon0096e262004-06-05 01:12:51 +0000409
410 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000411 # 'help' should be set in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000412 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000413
414 def test_aliasing_mbcs(self):
415 if sys.platform == "win32":
416 import locale
417 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000418 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000419 if value == "mbcs":
420 break
421 else:
422 self.fail("did not alias mbcs")
423
Brett Cannon0096e262004-06-05 01:12:51 +0000424 def test_sitecustomize_executed(self):
425 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000426 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000427 try:
428 import sitecustomize
429 except ImportError:
430 pass
431 else:
432 self.fail("sitecustomize not imported automatically")
433
R David Murray1bc6ceb2013-09-14 13:28:37 -0400434 @test.support.requires_resource('network')
Benjamin Peterson337578b2015-02-01 20:16:59 -0500435 @test.support.system_must_validate_cert
Georg Brandl78abc9d2013-10-27 09:41:57 +0100436 @unittest.skipUnless(sys.version_info[3] == 'final',
437 'only for released versions')
Ned Deily5a507f02014-03-26 23:31:39 -0700438 @unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"),
439 'need SSL support to download license')
R David Murray1bc6ceb2013-09-14 13:28:37 -0400440 def test_license_exists_at_url(self):
Ned Deily944d5972014-03-26 23:43:26 -0700441 # This test is a bit fragile since it depends on the format of the
R David Murray1bc6ceb2013-09-14 13:28:37 -0400442 # string displayed by license in the absence of a LICENSE file.
443 url = license._Printer__data.split()[1]
444 req = urllib.request.Request(url, method='HEAD')
445 try:
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700446 with test.support.transient_internet(url):
R David Murray1bc6ceb2013-09-14 13:28:37 -0400447 with urllib.request.urlopen(req) as data:
448 code = data.getcode()
449 except urllib.error.HTTPError as e:
450 code = e.code
451 self.assertEqual(code, 200, msg="Can't find " + url)
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700452
Brett Cannon0096e262004-06-05 01:12:51 +0000453
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200454class StartupImportTests(unittest.TestCase):
455
456 def test_startup_imports(self):
457 # This tests checks which modules are loaded by Python when it
458 # initially starts upon startup.
Christian Heimes179a3db2013-10-12 12:32:21 +0200459 popen = subprocess.Popen([sys.executable, '-I', '-v', '-c',
460 'import sys; print(set(sys.modules))'],
461 stdout=subprocess.PIPE,
Steve Dower313523c2016-09-17 12:22:41 -0700462 stderr=subprocess.PIPE,
463 encoding='utf-8')
Christian Heimes179a3db2013-10-12 12:32:21 +0200464 stdout, stderr = popen.communicate()
Christian Heimes179a3db2013-10-12 12:32:21 +0200465 modules = eval(stdout)
466
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200467 self.assertIn('site', modules)
468
Christian Heimes25827622013-10-12 01:27:08 +0200469 # http://bugs.python.org/issue19205
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200470 re_mods = {'re', '_sre', 'sre_compile', 'sre_constants', 'sre_parse'}
Christian Heimesf403f502013-10-12 15:08:42 +0200471 # _osx_support uses the re module in many placs
472 if sys.platform != 'darwin':
473 self.assertFalse(modules.intersection(re_mods), stderr)
Christian Heimes25827622013-10-12 01:27:08 +0200474 # http://bugs.python.org/issue9548
Christian Heimes179a3db2013-10-12 12:32:21 +0200475 self.assertNotIn('locale', modules, stderr)
Christian Heimes86823a52013-10-17 13:40:00 +0200476 if sys.platform != 'darwin':
477 # http://bugs.python.org/issue19209
478 self.assertNotIn('copyreg', modules, stderr)
Christian Heimesf1dc3ee2013-10-13 02:04:20 +0200479 # http://bugs.python.org/issue19218>
480 collection_mods = {'_collections', 'collections', 'functools',
481 'heapq', 'itertools', 'keyword', 'operator',
doko@ubuntu.com95743552014-04-15 20:37:54 +0200482 'reprlib', 'types', 'weakref'
483 }.difference(sys.builtin_module_names)
Ned Deily8a2150a2016-09-12 00:26:20 -0400484 # http://bugs.python.org/issue28095
485 if sys.platform != 'darwin':
486 self.assertFalse(modules.intersection(collection_mods), stderr)
Christian Heimes1a5fb4e2013-10-12 01:00:51 +0200487
Steve Dower6dd8eca2016-09-17 14:35:32 -0700488 def test_startup_interactivehook(self):
489 r = subprocess.Popen([sys.executable, '-c',
490 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
491 self.assertTrue(r, "'__interactivehook__' not added by site")
492
493 def test_startup_interactivehook_isolated(self):
494 # issue28192 readline is not automatically enabled in isolated mode
495 r = subprocess.Popen([sys.executable, '-I', '-c',
496 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
497 self.assertFalse(r, "'__interactivehook__' added in isolated mode")
498
499 def test_startup_interactivehook_isolated_explicit(self):
500 # issue28192 readline can be explicitly enabled in isolated mode
501 r = subprocess.Popen([sys.executable, '-I', '-c',
502 'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
503 self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()")
504
Steve Dower1da055e2016-10-29 08:50:31 -0700505 @classmethod
506 def _create_underpth_exe(self, lines):
507 exe_file = os.path.join(os.getenv('TEMP'), os.path.split(sys.executable)[1])
508 shutil.copy(sys.executable, exe_file)
509
510 _pth_file = os.path.splitext(exe_file)[0] + '._pth'
511 try:
512 with open(_pth_file, 'w') as f:
513 for line in lines:
514 print(line, file=f)
515 return exe_file
516 except:
Zachary Ware7c6d6e02017-03-11 22:39:54 -0600517 test.support.unlink(_pth_file)
518 test.support.unlink(exe_file)
Steve Dower1da055e2016-10-29 08:50:31 -0700519 raise
520
521 @classmethod
522 def _cleanup_underpth_exe(self, exe_file):
523 _pth_file = os.path.splitext(exe_file)[0] + '._pth'
Zachary Ware7c6d6e02017-03-11 22:39:54 -0600524 test.support.unlink(_pth_file)
525 test.support.unlink(exe_file)
Steve Dower1da055e2016-10-29 08:50:31 -0700526
Steve Dower5f9193a2017-02-04 15:19:29 -0800527 @classmethod
528 def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines):
529 sys_path = []
530 for line in lines:
531 if not line or line[0] == '#':
532 continue
533 abs_path = os.path.abspath(os.path.join(sys_prefix, line))
534 sys_path.append(abs_path)
535 return sys_path
536
Steve Dowerc6dd4152016-10-27 14:28:07 -0700537 @unittest.skipUnless(sys.platform == 'win32', "only supported on Windows")
538 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
Steve Dower1da055e2016-10-29 08:50:31 -0700552 try:
Steve Dowerc6dd4152016-10-27 14:28:07 -0700553 env = os.environ.copy()
554 env['PYTHONPATH'] = 'from-env'
Steve Dower1da055e2016-10-29 08:50:31 -0700555 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
556 rc = subprocess.call([exe_file, '-c',
Steve Dowerc6dd4152016-10-27 14:28:07 -0700557 'import sys; sys.exit(sys.flags.no_site and '
558 'len(sys.path) > 200 and '
Steve Dower5f9193a2017-02-04 15:19:29 -0800559 'sys.path == %r)' % sys_path,
560 ], env=env)
Steve Dowerc6dd4152016-10-27 14:28:07 -0700561 finally:
Steve Dower1da055e2016-10-29 08:50:31 -0700562 self._cleanup_underpth_exe(exe_file)
Steve Dower5f9193a2017-02-04 15:19:29 -0800563 self.assertTrue(rc, "sys.path is incorrect")
Steve Dowerc6dd4152016-10-27 14:28:07 -0700564
565 @unittest.skipUnless(sys.platform == 'win32', "only supported on Windows")
566 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)
Steve Dowerc6dd4152016-10-27 14:28:07 -0700577 try:
Steve Dowerc6dd4152016-10-27 14:28:07 -0700578 env = os.environ.copy()
579 env['PYTHONPATH'] = 'from-env'
Steve Dower1da055e2016-10-29 08:50:31 -0700580 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
581 rc = subprocess.call([exe_file, '-c',
Steve Dowerc6dd4152016-10-27 14:28:07 -0700582 'import sys; sys.exit(not sys.flags.no_site and '
Steve Dower5f9193a2017-02-04 15:19:29 -0800583 '%r in sys.path and %r in sys.path and %r not in sys.path and '
584 'all("\\r" not in p and "\\n" not in p for p in sys.path))' % (
585 os.path.join(sys_prefix, 'fake-path-name'),
Steve Dowerc6dd4152016-10-27 14:28:07 -0700586 libpath,
Steve Dower5f9193a2017-02-04 15:19:29 -0800587 os.path.join(sys_prefix, 'from-env'),
Steve Dowerc6dd4152016-10-27 14:28:07 -0700588 )], env=env)
Steve Dowerc6dd4152016-10-27 14:28:07 -0700589 finally:
Steve Dower1da055e2016-10-29 08:50:31 -0700590 self._cleanup_underpth_exe(exe_file)
Steve Dower5f9193a2017-02-04 15:19:29 -0800591 self.assertTrue(rc, "sys.path is incorrect")
Steve Dowerc6dd4152016-10-27 14:28:07 -0700592
Steve Dower6dd8eca2016-09-17 14:35:32 -0700593
Brett Cannon0096e262004-06-05 01:12:51 +0000594if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400595 unittest.main()