blob: e3c9deebf08c02ac8f492b0e9631199f4292ff9e [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
Zachary Wared48214f2017-05-14 15:49:46 -050020import tempfile
Tarek Ziadéedacea32010-01-29 11:41:03 +000021from copy import copy
22
Zachary Ware36193e72013-12-11 16:59:44 -060023# These tests are not particularly useful if Python was invoked with -S.
24# If you add tests that are useful under -S, this skip should be moved
25# to the class level.
26if sys.flags.no_site:
27 raise unittest.SkipTest("Python was invoked with -S")
28
29import site
Brett Cannon0096e262004-06-05 01:12:51 +000030
Victor Stinnerb85c1362017-04-20 13:39:39 +020031
32OLD_SYS_PATH = None
33
34
35def setUpModule():
36 global OLD_SYS_PATH
37 OLD_SYS_PATH = sys.path[:]
38
39 if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
40 # need to add user site directory for tests
41 try:
42 os.makedirs(site.USER_SITE)
43 # modify sys.path: will be restored by tearDownModule()
44 site.addsitedir(site.USER_SITE)
45 except PermissionError as exc:
46 raise unittest.SkipTest('unable to create user site directory (%r): %s'
47 % (site.USER_SITE, exc))
48
49
50def tearDownModule():
51 sys.path[:] = OLD_SYS_PATH
Victor Stinner21d0e1b2016-03-14 17:47:03 +010052
Christian Heimes8dc226f2008-05-06 23:45:46 +000053
Brett Cannon0096e262004-06-05 01:12:51 +000054class HelperFunctionsTests(unittest.TestCase):
55 """Tests for helper functions.
Brett Cannon0096e262004-06-05 01:12:51 +000056 """
57
58 def setUp(self):
59 """Save a copy of sys.path"""
60 self.sys_path = sys.path[:]
Tarek Ziadé4a608c02009-08-20 21:28:05 +000061 self.old_base = site.USER_BASE
62 self.old_site = site.USER_SITE
63 self.old_prefixes = site.PREFIXES
Brett Cannon8ac95ee2012-04-04 17:31:16 -040064 self.original_vars = sysconfig._CONFIG_VARS
Tarek Ziadéedacea32010-01-29 11:41:03 +000065 self.old_vars = copy(sysconfig._CONFIG_VARS)
Brett Cannon0096e262004-06-05 01:12:51 +000066
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000067 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000068 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +000069 sys.path[:] = self.sys_path
Tarek Ziadé4a608c02009-08-20 21:28:05 +000070 site.USER_BASE = self.old_base
71 site.USER_SITE = self.old_site
72 site.PREFIXES = self.old_prefixes
Brett Cannon8ac95ee2012-04-04 17:31:16 -040073 sysconfig._CONFIG_VARS = self.original_vars
74 sysconfig._CONFIG_VARS.clear()
75 sysconfig._CONFIG_VARS.update(self.old_vars)
Raymond Hettingerebd95222004-06-27 03:02:18 +000076
Brett Cannon0096e262004-06-05 01:12:51 +000077 def test_makepath(self):
78 # Test makepath() have an absolute path for its first return value
79 # and a case-normalized version of the absolute path for its
80 # second value.
81 path_parts = ("Beginning", "End")
82 original_dir = os.path.join(*path_parts)
83 abs_dir, norm_dir = site.makepath(*path_parts)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000084 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000085 if original_dir == os.path.normcase(original_dir):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000086 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000087 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000088 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000089
90 def test_init_pathinfo(self):
91 dir_set = site._init_pathinfo()
92 for entry in [site.makepath(path)[1] for path in sys.path
Brett Cannon5f0507d2016-04-08 15:04:28 -070093 if path and os.path.exists(path)]:
Ezio Melottib58e0bd2010-01-23 15:40:09 +000094 self.assertIn(entry, dir_set,
95 "%s from sys.path not found in set returned "
96 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000097
Brett Cannonee86a662004-07-13 07:12:25 +000098 def pth_file_tests(self, pth_file):
99 """Contain common code for testing results of reading a .pth file"""
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000100 self.assertIn(pth_file.imported, sys.modules,
101 "%s not in sys.modules" % pth_file.imported)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000102 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
103 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +0000104
Brett Cannon0096e262004-06-05 01:12:51 +0000105 def test_addpackage(self):
106 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +0000107 # adds directories to sys.path for any line in the file that is not a
108 # comment or import that is a valid directory name for where the .pth
109 # file resides; invalid directories are not added
110 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000111 pth_file.cleanup(prep=True) # to make sure that nothing is
112 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +0000113 try:
Brett Cannon64a84702004-07-10 02:10:45 +0000114 pth_file.create()
115 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000116 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000117 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000118 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000119
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000120 def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
121 # Create a .pth file and return its (abspath, basename).
122 pth_dir = os.path.abspath(pth_dir)
123 pth_basename = pth_name + '.pth'
124 pth_fn = os.path.join(pth_dir, pth_basename)
125 pth_file = open(pth_fn, 'w', encoding='utf-8')
126 self.addCleanup(lambda: os.remove(pth_fn))
127 pth_file.write(contents)
128 pth_file.close()
129 return pth_dir, pth_basename
130
131 def test_addpackage_import_bad_syntax(self):
132 # Issue 10642
133 pth_dir, pth_fn = self.make_pth("import bad)syntax\n")
134 with captured_stderr() as err_out:
135 site.addpackage(pth_dir, pth_fn, set())
136 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000137 self.assertRegex(err_out.getvalue(),
138 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000139 # XXX: the previous two should be independent checks so that the
140 # order doesn't matter. The next three could be a single check
141 # but my regex foo isn't good enough to write it.
142 self.assertRegex(err_out.getvalue(), 'Traceback')
143 self.assertRegex(err_out.getvalue(), r'import bad\)syntax')
144 self.assertRegex(err_out.getvalue(), 'SyntaxError')
145
146 def test_addpackage_import_bad_exec(self):
147 # Issue 10642
148 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
149 with captured_stderr() as err_out:
150 site.addpackage(pth_dir, pth_fn, set())
151 self.assertRegex(err_out.getvalue(), "line 2")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000152 self.assertRegex(err_out.getvalue(),
153 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000154 # XXX: ditto previous XXX comment.
155 self.assertRegex(err_out.getvalue(), 'Traceback')
Eric Snow46f97b82016-09-07 16:56:15 -0700156 self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000157
158 def test_addpackage_import_bad_pth_file(self):
159 # Issue 5258
160 pth_dir, pth_fn = self.make_pth("abc\x00def\n")
161 with captured_stderr() as err_out:
162 site.addpackage(pth_dir, pth_fn, set())
163 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000164 self.assertRegex(err_out.getvalue(),
165 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000166 # XXX: ditto previous XXX comment.
167 self.assertRegex(err_out.getvalue(), 'Traceback')
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300168 self.assertRegex(err_out.getvalue(), 'ValueError')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000169
Brett Cannon0096e262004-06-05 01:12:51 +0000170 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +0000171 # Same tests for test_addpackage since addsitedir() essentially just
172 # calls addpackage() for every .pth file in the directory
173 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000174 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
175 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +0000176 try:
Brett Cannonee86a662004-07-13 07:12:25 +0000177 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +0000178 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000179 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000180 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000181 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +0000182
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900183 def test_getuserbase(self):
184 self.assertEqual(site._getuserbase(), sysconfig._getuserbase())
185
186 def test_get_path(self):
INADA Naokiba9ddb72017-07-28 21:28:19 +0900187 if sys.platform == 'darwin' and sys._framework:
188 scheme = 'osx_framework_user'
189 else:
190 scheme = os.name + '_user'
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900191 self.assertEqual(site._get_path(site._getuserbase()),
INADA Naokiba9ddb72017-07-28 21:28:19 +0900192 sysconfig.get_path('purelib', scheme))
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900193
Ned Deily316f5732011-10-31 16:16:35 -0700194 @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
195 "user-site (site.ENABLE_USER_SITE)")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000196 def test_s_option(self):
Eric Snow6b4be192017-05-22 21:36:03 -0700197 # (ncoghlan) Change this to use script_helper...
Christian Heimes8dc226f2008-05-06 23:45:46 +0000198 usersite = site.USER_SITE
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000199 self.assertIn(usersite, sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000200
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000201 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000202 rc = subprocess.call([sys.executable, '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000203 'import sys; sys.exit(%r in sys.path)' % usersite],
204 env=env)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000205 self.assertEqual(rc, 1)
206
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000207 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000208 rc = subprocess.call([sys.executable, '-s', '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000209 'import sys; sys.exit(%r in sys.path)' % usersite],
210 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200211 if usersite == site.getsitepackages()[0]:
212 self.assertEqual(rc, 1)
213 else:
Eric Snow6b4be192017-05-22 21:36:03 -0700214 self.assertEqual(rc, 0, "User site still added to path with -s")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000215
216 env = os.environ.copy()
217 env["PYTHONNOUSERSITE"] = "1"
218 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000219 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000220 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200221 if usersite == site.getsitepackages()[0]:
222 self.assertEqual(rc, 1)
223 else:
Eric Snow6b4be192017-05-22 21:36:03 -0700224 self.assertEqual(rc, 0,
225 "User site still added to path with PYTHONNOUSERSITE")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000226
227 env = os.environ.copy()
228 env["PYTHONUSERBASE"] = "/tmp"
229 rc = subprocess.call([sys.executable, '-c',
230 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
231 env=env)
Eric Snow6b4be192017-05-22 21:36:03 -0700232 self.assertEqual(rc, 1,
233 "User base not set by PYTHONUSERBASE")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000234
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000235 def test_getuserbase(self):
236 site.USER_BASE = None
237 user_base = site.getuserbase()
238
239 # the call sets site.USER_BASE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000240 self.assertEqual(site.USER_BASE, user_base)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000241
242 # let's set PYTHONUSERBASE and see if it uses it
243 site.USER_BASE = None
Tarek Ziadéedacea32010-01-29 11:41:03 +0000244 import sysconfig
245 sysconfig._CONFIG_VARS = None
246
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000247 with EnvironmentVarGuard() as environ:
248 environ['PYTHONUSERBASE'] = 'xoxo'
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000249 self.assertTrue(site.getuserbase().startswith('xoxo'),
250 site.getuserbase())
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000251
252 def test_getusersitepackages(self):
253 site.USER_SITE = None
254 site.USER_BASE = None
255 user_site = site.getusersitepackages()
256
257 # the call sets USER_BASE *and* USER_SITE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000258 self.assertEqual(site.USER_SITE, user_site)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000259 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000260
261 def test_getsitepackages(self):
262 site.PREFIXES = ['xoxo']
263 dirs = site.getsitepackages()
Ned Deily763f0942018-01-30 05:14:09 -0500264 if os.sep == '/':
265 # OS X, Linux, FreeBSD, etc
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400266 self.assertEqual(len(dirs), 1)
Serhiy Storchaka885bdc42016-02-11 13:10:36 +0200267 wanted = os.path.join('xoxo', 'lib',
268 'python%d.%d' % sys.version_info[:2],
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000269 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000270 self.assertEqual(dirs[0], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000271 else:
Ned Deilyd531b292012-02-06 00:58:18 +0100272 # other platforms
Ezio Melottifc8b2052010-08-17 08:35:41 +0000273 self.assertEqual(len(dirs), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000274 self.assertEqual(dirs[0], 'xoxo')
Tarek Ziadé8c0e2172009-10-27 21:24:21 +0000275 wanted = os.path.join('xoxo', 'lib', 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000276 self.assertEqual(dirs[1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000277
Brett Cannon64a84702004-07-10 02:10:45 +0000278class PthFile(object):
279 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000280
Brett Cannon64a84702004-07-10 02:10:45 +0000281 def __init__(self, filename_base=TESTFN, imported="time",
282 good_dirname="__testdir__", bad_dirname="__bad"):
283 """Initialize instance variables"""
284 self.filename = filename_base + ".pth"
285 self.base_dir = os.path.abspath('')
286 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000287 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000288 self.good_dirname = good_dirname
289 self.bad_dirname = bad_dirname
290 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
291 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000292
Brett Cannon64a84702004-07-10 02:10:45 +0000293 def create(self):
294 """Create a .pth file with a comment, blank lines, an ``import
295 <self.imported>``, a line with self.good_dirname, and a line with
296 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000297
Brett Cannon64a84702004-07-10 02:10:45 +0000298 Creation of the directory for self.good_dir_path (based off of
299 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000300
Brett Cannon64a84702004-07-10 02:10:45 +0000301 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000302
Brett Cannon64a84702004-07-10 02:10:45 +0000303 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000304 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000305 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000306 print("#import @bad module name", file=FILE)
307 print("\n", file=FILE)
308 print("import %s" % self.imported, file=FILE)
309 print(self.good_dirname, file=FILE)
310 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000311 finally:
312 FILE.close()
313 os.mkdir(self.good_dir_path)
314
Brett Cannonee86a662004-07-13 07:12:25 +0000315 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000316 """Make sure that the .pth file is deleted, self.imported is not in
317 sys.modules, and that both self.good_dirname and self.bad_dirname are
318 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000319 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000320 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000321 if prep:
322 self.imported_module = sys.modules.get(self.imported)
323 if self.imported_module:
324 del sys.modules[self.imported]
325 else:
326 if self.imported_module:
327 sys.modules[self.imported] = self.imported_module
328 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000329 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000330 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000331 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000332
333class ImportSideEffectTests(unittest.TestCase):
334 """Test side-effects from importing 'site'."""
335
336 def setUp(self):
337 """Make a copy of sys.path"""
338 self.sys_path = sys.path[:]
339
340 def tearDown(self):
341 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +0000342 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000343
Barry Warsaw28a691b2010-04-17 00:19:56 +0000344 def test_abs_paths(self):
345 # Make sure all imported modules have their __file__ and __cached__
346 # attributes as absolute paths. Arranging to put the Lib directory on
347 # PYTHONPATH would cause the os module to have a relative path for
348 # __file__ if abs_paths() does not get run. sys and builtins (the
349 # only other modules imported before site.py runs) do not have
350 # __file__ or __cached__ because they are built-in.
351 parent = os.path.relpath(os.path.dirname(os.__file__))
352 env = os.environ.copy()
353 env['PYTHONPATH'] = parent
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000354 code = ('import os, sys',
355 # use ASCII to avoid locale issues with non-ASCII directories
356 'os_file = os.__file__.encode("ascii", "backslashreplace")',
357 r'sys.stdout.buffer.write(os_file + b"\n")',
358 'os_cached = os.__cached__.encode("ascii", "backslashreplace")',
359 r'sys.stdout.buffer.write(os_cached + b"\n")')
360 command = '\n'.join(code)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000361 # First, prove that with -S (no 'import site'), the paths are
362 # relative.
363 proc = subprocess.Popen([sys.executable, '-S', '-c', command],
364 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000365 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000366 stdout, stderr = proc.communicate()
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000367
Barry Warsaw28a691b2010-04-17 00:19:56 +0000368 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000369 os__file__, os__cached__ = stdout.splitlines()[:2]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000370 self.assertFalse(os.path.isabs(os__file__))
371 self.assertFalse(os.path.isabs(os__cached__))
372 # Now, with 'import site', it works.
373 proc = subprocess.Popen([sys.executable, '-c', command],
374 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000375 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000376 stdout, stderr = proc.communicate()
377 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000378 os__file__, os__cached__ = stdout.splitlines()[:2]
Eric Snow32439d62015-05-02 19:15:18 -0600379 self.assertTrue(os.path.isabs(os__file__),
Eric Snow00607e92015-05-04 11:48:39 -0600380 "expected absolute path, got {}"
381 .format(os__file__.decode('ascii')))
Eric Snow32439d62015-05-02 19:15:18 -0600382 self.assertTrue(os.path.isabs(os__cached__),
Eric Snow00607e92015-05-04 11:48:39 -0600383 "expected absolute path, got {}"
384 .format(os__cached__.decode('ascii')))
Brett Cannon0096e262004-06-05 01:12:51 +0000385
386 def test_no_duplicate_paths(self):
387 # No duplicate paths should exist in sys.path
388 # Handled by removeduppaths()
389 site.removeduppaths()
390 seen_paths = set()
391 for path in sys.path:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000392 self.assertNotIn(path, seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000393 seen_paths.add(path)
394
Zachary Ware9fe6d862013-12-08 00:20:35 -0600395 @unittest.skip('test not implemented')
Brett Cannon0096e262004-06-05 01:12:51 +0000396 def test_add_build_dir(self):
397 # Test that the build directory's Modules directory is used when it
398 # should be.
399 # XXX: implement
400 pass
401
Brett Cannon0096e262004-06-05 01:12:51 +0000402 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000403 # 'quit' and 'exit' should be injected into builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000404 self.assertTrue(hasattr(builtins, "quit"))
405 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000406
407 def test_setting_copyright(self):
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700408 # 'copyright', 'credits', and 'license' should be in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000409 self.assertTrue(hasattr(builtins, "copyright"))
410 self.assertTrue(hasattr(builtins, "credits"))
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700411 self.assertTrue(hasattr(builtins, "license"))
Brett Cannon0096e262004-06-05 01:12:51 +0000412
413 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000414 # 'help' should be set in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000415 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000416
417 def test_aliasing_mbcs(self):
418 if sys.platform == "win32":
419 import locale
420 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000421 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000422 if value == "mbcs":
423 break
424 else:
425 self.fail("did not alias mbcs")
426
Brett Cannon0096e262004-06-05 01:12:51 +0000427 def test_sitecustomize_executed(self):
428 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000429 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000430 try:
431 import sitecustomize
432 except ImportError:
433 pass
434 else:
435 self.fail("sitecustomize not imported automatically")
436
R David Murray1bc6ceb2013-09-14 13:28:37 -0400437 @test.support.requires_resource('network')
Benjamin Peterson337578b2015-02-01 20:16:59 -0500438 @test.support.system_must_validate_cert
Georg Brandl78abc9d2013-10-27 09:41:57 +0100439 @unittest.skipUnless(sys.version_info[3] == 'final',
440 'only for released versions')
Ned Deily5a507f02014-03-26 23:31:39 -0700441 @unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"),
442 'need SSL support to download license')
R David Murray1bc6ceb2013-09-14 13:28:37 -0400443 def test_license_exists_at_url(self):
Ned Deily944d5972014-03-26 23:43:26 -0700444 # This test is a bit fragile since it depends on the format of the
R David Murray1bc6ceb2013-09-14 13:28:37 -0400445 # string displayed by license in the absence of a LICENSE file.
446 url = license._Printer__data.split()[1]
447 req = urllib.request.Request(url, method='HEAD')
448 try:
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700449 with test.support.transient_internet(url):
R David Murray1bc6ceb2013-09-14 13:28:37 -0400450 with urllib.request.urlopen(req) as data:
451 code = data.getcode()
452 except urllib.error.HTTPError as e:
453 code = e.code
454 self.assertEqual(code, 200, msg="Can't find " + url)
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700455
Brett Cannon0096e262004-06-05 01:12:51 +0000456
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200457class StartupImportTests(unittest.TestCase):
458
459 def test_startup_imports(self):
460 # This tests checks which modules are loaded by Python when it
461 # initially starts upon startup.
Christian Heimes179a3db2013-10-12 12:32:21 +0200462 popen = subprocess.Popen([sys.executable, '-I', '-v', '-c',
463 'import sys; print(set(sys.modules))'],
464 stdout=subprocess.PIPE,
Steve Dower313523c2016-09-17 12:22:41 -0700465 stderr=subprocess.PIPE,
466 encoding='utf-8')
Christian Heimes179a3db2013-10-12 12:32:21 +0200467 stdout, stderr = popen.communicate()
Christian Heimes179a3db2013-10-12 12:32:21 +0200468 modules = eval(stdout)
469
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200470 self.assertIn('site', modules)
471
Christian Heimes25827622013-10-12 01:27:08 +0200472 # http://bugs.python.org/issue19205
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200473 re_mods = {'re', '_sre', 'sre_compile', 'sre_constants', 'sre_parse'}
Christian Heimesf403f502013-10-12 15:08:42 +0200474 # _osx_support uses the re module in many placs
475 if sys.platform != 'darwin':
476 self.assertFalse(modules.intersection(re_mods), stderr)
Christian Heimes25827622013-10-12 01:27:08 +0200477 # http://bugs.python.org/issue9548
Christian Heimes179a3db2013-10-12 12:32:21 +0200478 self.assertNotIn('locale', modules, stderr)
Christian Heimes86823a52013-10-17 13:40:00 +0200479 if sys.platform != 'darwin':
480 # http://bugs.python.org/issue19209
481 self.assertNotIn('copyreg', modules, stderr)
Christian Heimesf1dc3ee2013-10-13 02:04:20 +0200482 # http://bugs.python.org/issue19218>
483 collection_mods = {'_collections', 'collections', 'functools',
484 'heapq', 'itertools', 'keyword', 'operator',
doko@ubuntu.com95743552014-04-15 20:37:54 +0200485 'reprlib', 'types', 'weakref'
486 }.difference(sys.builtin_module_names)
Ned Deilyc22bd582017-07-28 03:02:10 -0400487 self.assertFalse(modules.intersection(collection_mods), stderr)
Christian Heimes1a5fb4e2013-10-12 01:00:51 +0200488
Steve Dower6dd8eca2016-09-17 14:35:32 -0700489 def test_startup_interactivehook(self):
490 r = subprocess.Popen([sys.executable, '-c',
491 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
492 self.assertTrue(r, "'__interactivehook__' not added by site")
493
494 def test_startup_interactivehook_isolated(self):
495 # issue28192 readline is not automatically enabled in isolated mode
496 r = subprocess.Popen([sys.executable, '-I', '-c',
497 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
498 self.assertFalse(r, "'__interactivehook__' added in isolated mode")
499
500 def test_startup_interactivehook_isolated_explicit(self):
501 # issue28192 readline can be explicitly enabled in isolated mode
502 r = subprocess.Popen([sys.executable, '-I', '-c',
503 'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
504 self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()")
505
Zachary Wared48214f2017-05-14 15:49:46 -0500506
507@unittest.skipUnless(sys.platform == 'win32', "only supported on Windows")
508class _pthFileTests(unittest.TestCase):
509
Steve Dower1da055e2016-10-29 08:50:31 -0700510 def _create_underpth_exe(self, lines):
Zachary Wared48214f2017-05-14 15:49:46 -0500511 temp_dir = tempfile.mkdtemp()
512 self.addCleanup(test.support.rmtree, temp_dir)
513 exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1])
Steve Dower1da055e2016-10-29 08:50:31 -0700514 shutil.copy(sys.executable, exe_file)
Steve Dower1da055e2016-10-29 08:50:31 -0700515 _pth_file = os.path.splitext(exe_file)[0] + '._pth'
Zachary Wared48214f2017-05-14 15:49:46 -0500516 with open(_pth_file, 'w') as f:
517 for line in lines:
518 print(line, file=f)
519 return exe_file
Steve Dower1da055e2016-10-29 08:50:31 -0700520
Steve Dower5f9193a2017-02-04 15:19:29 -0800521 def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines):
522 sys_path = []
523 for line in lines:
524 if not line or line[0] == '#':
525 continue
526 abs_path = os.path.abspath(os.path.join(sys_prefix, line))
527 sys_path.append(abs_path)
528 return sys_path
529
Steve Dowerc6dd4152016-10-27 14:28:07 -0700530 def test_underpth_nosite_file(self):
Steve Dower1da055e2016-10-29 08:50:31 -0700531 libpath = os.path.dirname(os.path.dirname(encodings.__file__))
532 exe_prefix = os.path.dirname(sys.executable)
Steve Dower5f9193a2017-02-04 15:19:29 -0800533 pth_lines = [
Steve Dower1da055e2016-10-29 08:50:31 -0700534 'fake-path-name',
535 *[libpath for _ in range(200)],
Steve Dower5f9193a2017-02-04 15:19:29 -0800536 '',
Steve Dower1da055e2016-10-29 08:50:31 -0700537 '# comment',
Steve Dower5f9193a2017-02-04 15:19:29 -0800538 ]
539 exe_file = self._create_underpth_exe(pth_lines)
540 sys_path = self._calc_sys_path_for_underpth_nosite(
541 os.path.dirname(exe_file),
542 pth_lines)
Steve Dowerc6dd4152016-10-27 14:28:07 -0700543
Zachary Wared48214f2017-05-14 15:49:46 -0500544 env = os.environ.copy()
545 env['PYTHONPATH'] = 'from-env'
546 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
Steve Dower9b33bf52017-05-23 16:25:25 -0700547 output = subprocess.check_output([exe_file, '-c',
548 'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")'
549 ], env=env, encoding='ansi')
550 actual_sys_path = output.rstrip().split('\n')
Miss Islington (bot)e6499a02018-02-04 08:38:56 -0800551 self.assertTrue(actual_sys_path, "sys.flags.no_site was False")
Steve Dower9b33bf52017-05-23 16:25:25 -0700552 self.assertEqual(
553 actual_sys_path,
554 sys_path,
555 "sys.path is incorrect"
556 )
Steve Dowerc6dd4152016-10-27 14:28:07 -0700557
Steve Dowerc6dd4152016-10-27 14:28:07 -0700558 def test_underpth_file(self):
Steve Dower1da055e2016-10-29 08:50:31 -0700559 libpath = os.path.dirname(os.path.dirname(encodings.__file__))
560 exe_prefix = os.path.dirname(sys.executable)
561 exe_file = self._create_underpth_exe([
562 'fake-path-name',
563 *[libpath for _ in range(200)],
Steve Dower5f9193a2017-02-04 15:19:29 -0800564 '',
Steve Dower1da055e2016-10-29 08:50:31 -0700565 '# comment',
566 'import site'
567 ])
Steve Dower5f9193a2017-02-04 15:19:29 -0800568 sys_prefix = os.path.dirname(exe_file)
Zachary Wared48214f2017-05-14 15:49:46 -0500569 env = os.environ.copy()
570 env['PYTHONPATH'] = 'from-env'
571 env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH'))
572 rc = subprocess.call([exe_file, '-c',
573 'import sys; sys.exit(not sys.flags.no_site and '
574 '%r in sys.path and %r in sys.path and %r not in sys.path and '
575 'all("\\r" not in p and "\\n" not in p for p in sys.path))' % (
576 os.path.join(sys_prefix, 'fake-path-name'),
577 libpath,
578 os.path.join(sys_prefix, 'from-env'),
579 )], env=env)
Steve Dower5f9193a2017-02-04 15:19:29 -0800580 self.assertTrue(rc, "sys.path is incorrect")
Steve Dowerc6dd4152016-10-27 14:28:07 -0700581
Steve Dower6dd8eca2016-09-17 14:35:32 -0700582
Brett Cannon0096e262004-06-05 01:12:51 +0000583if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400584 unittest.main()