blob: e234164b3758cca0134ed352d01584ad10dd9919 [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
Christian Heimes8dc226f2008-05-06 23:45:46 +000017import subprocess
Tarek Ziadéedacea32010-01-29 11:41:03 +000018import sysconfig
19from copy import copy
20
Zachary Ware36193e72013-12-11 16:59:44 -060021# These tests are not particularly useful if Python was invoked with -S.
22# If you add tests that are useful under -S, this skip should be moved
23# to the class level.
24if sys.flags.no_site:
25 raise unittest.SkipTest("Python was invoked with -S")
26
27import site
Brett Cannon0096e262004-06-05 01:12:51 +000028
Ned Deily316f5732011-10-31 16:16:35 -070029if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
Christian Heimes8dc226f2008-05-06 23:45:46 +000030 # need to add user site directory for tests
31 os.makedirs(site.USER_SITE)
32 site.addsitedir(site.USER_SITE)
33
Brett Cannon0096e262004-06-05 01:12:51 +000034class HelperFunctionsTests(unittest.TestCase):
35 """Tests for helper functions.
Brett Cannon0096e262004-06-05 01:12:51 +000036 """
37
38 def setUp(self):
39 """Save a copy of sys.path"""
40 self.sys_path = sys.path[:]
Tarek Ziadé4a608c02009-08-20 21:28:05 +000041 self.old_base = site.USER_BASE
42 self.old_site = site.USER_SITE
43 self.old_prefixes = site.PREFIXES
Brett Cannon8ac95ee2012-04-04 17:31:16 -040044 self.original_vars = sysconfig._CONFIG_VARS
Tarek Ziadéedacea32010-01-29 11:41:03 +000045 self.old_vars = copy(sysconfig._CONFIG_VARS)
Brett Cannon0096e262004-06-05 01:12:51 +000046
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000047 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000048 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +000049 sys.path[:] = self.sys_path
Tarek Ziadé4a608c02009-08-20 21:28:05 +000050 site.USER_BASE = self.old_base
51 site.USER_SITE = self.old_site
52 site.PREFIXES = self.old_prefixes
Brett Cannon8ac95ee2012-04-04 17:31:16 -040053 sysconfig._CONFIG_VARS = self.original_vars
54 sysconfig._CONFIG_VARS.clear()
55 sysconfig._CONFIG_VARS.update(self.old_vars)
Raymond Hettingerebd95222004-06-27 03:02:18 +000056
Brett Cannon0096e262004-06-05 01:12:51 +000057 def test_makepath(self):
58 # Test makepath() have an absolute path for its first return value
59 # and a case-normalized version of the absolute path for its
60 # second value.
61 path_parts = ("Beginning", "End")
62 original_dir = os.path.join(*path_parts)
63 abs_dir, norm_dir = site.makepath(*path_parts)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000064 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000065 if original_dir == os.path.normcase(original_dir):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000066 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000067 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000068 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000069
70 def test_init_pathinfo(self):
71 dir_set = site._init_pathinfo()
72 for entry in [site.makepath(path)[1] for path in sys.path
73 if path and os.path.isdir(path)]:
Ezio Melottib58e0bd2010-01-23 15:40:09 +000074 self.assertIn(entry, dir_set,
75 "%s from sys.path not found in set returned "
76 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000077
Brett Cannonee86a662004-07-13 07:12:25 +000078 def pth_file_tests(self, pth_file):
79 """Contain common code for testing results of reading a .pth file"""
Ezio Melottib58e0bd2010-01-23 15:40:09 +000080 self.assertIn(pth_file.imported, sys.modules,
81 "%s not in sys.modules" % pth_file.imported)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +000082 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
83 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +000084
Brett Cannon0096e262004-06-05 01:12:51 +000085 def test_addpackage(self):
86 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000087 # adds directories to sys.path for any line in the file that is not a
88 # comment or import that is a valid directory name for where the .pth
89 # file resides; invalid directories are not added
90 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000091 pth_file.cleanup(prep=True) # to make sure that nothing is
92 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000093 try:
Brett Cannon64a84702004-07-10 02:10:45 +000094 pth_file.create()
95 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +000096 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000097 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000098 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +000099
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000100 def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
101 # Create a .pth file and return its (abspath, basename).
102 pth_dir = os.path.abspath(pth_dir)
103 pth_basename = pth_name + '.pth'
104 pth_fn = os.path.join(pth_dir, pth_basename)
105 pth_file = open(pth_fn, 'w', encoding='utf-8')
106 self.addCleanup(lambda: os.remove(pth_fn))
107 pth_file.write(contents)
108 pth_file.close()
109 return pth_dir, pth_basename
110
111 def test_addpackage_import_bad_syntax(self):
112 # Issue 10642
113 pth_dir, pth_fn = self.make_pth("import bad)syntax\n")
114 with captured_stderr() as err_out:
115 site.addpackage(pth_dir, pth_fn, set())
116 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000117 self.assertRegex(err_out.getvalue(),
118 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000119 # XXX: the previous two should be independent checks so that the
120 # order doesn't matter. The next three could be a single check
121 # but my regex foo isn't good enough to write it.
122 self.assertRegex(err_out.getvalue(), 'Traceback')
123 self.assertRegex(err_out.getvalue(), r'import bad\)syntax')
124 self.assertRegex(err_out.getvalue(), 'SyntaxError')
125
126 def test_addpackage_import_bad_exec(self):
127 # Issue 10642
128 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
129 with captured_stderr() as err_out:
130 site.addpackage(pth_dir, pth_fn, set())
131 self.assertRegex(err_out.getvalue(), "line 2")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000132 self.assertRegex(err_out.getvalue(),
133 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000134 # XXX: ditto previous XXX comment.
135 self.assertRegex(err_out.getvalue(), 'Traceback')
Brett Cannon679ecb52013-07-04 17:51:50 -0400136 self.assertRegex(err_out.getvalue(), 'ImportError')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000137
R. David Murrayad4ccfd2010-12-27 04:31:48 +0000138 @unittest.skipIf(sys.platform == "win32", "Windows does not raise an "
139 "error for file paths containing null characters")
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000140 def test_addpackage_import_bad_pth_file(self):
141 # Issue 5258
142 pth_dir, pth_fn = self.make_pth("abc\x00def\n")
143 with captured_stderr() as err_out:
144 site.addpackage(pth_dir, pth_fn, set())
145 self.assertRegex(err_out.getvalue(), "line 1")
R. David Murrayab9d8d62010-12-27 00:03:13 +0000146 self.assertRegex(err_out.getvalue(),
147 re.escape(os.path.join(pth_dir, pth_fn)))
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000148 # XXX: ditto previous XXX comment.
149 self.assertRegex(err_out.getvalue(), 'Traceback')
Serhiy Storchakad8a14472014-09-06 20:07:17 +0300150 self.assertRegex(err_out.getvalue(), 'ValueError')
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000151
Brett Cannon0096e262004-06-05 01:12:51 +0000152 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +0000153 # Same tests for test_addpackage since addsitedir() essentially just
154 # calls addpackage() for every .pth file in the directory
155 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000156 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
157 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +0000158 try:
Brett Cannonee86a662004-07-13 07:12:25 +0000159 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +0000160 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000161 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000162 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000163 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +0000164
Ned Deily316f5732011-10-31 16:16:35 -0700165 @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
166 "user-site (site.ENABLE_USER_SITE)")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000167 def test_s_option(self):
168 usersite = site.USER_SITE
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000169 self.assertIn(usersite, sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000170
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000171 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000172 rc = subprocess.call([sys.executable, '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000173 'import sys; sys.exit(%r in sys.path)' % usersite],
174 env=env)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000175 self.assertEqual(rc, 1)
176
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000177 env = os.environ.copy()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000178 rc = subprocess.call([sys.executable, '-s', '-c',
Éric Araujo63ebe1c2011-01-03 17:51:11 +0000179 'import sys; sys.exit(%r in sys.path)' % usersite],
180 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200181 if usersite == site.getsitepackages()[0]:
182 self.assertEqual(rc, 1)
183 else:
184 self.assertEqual(rc, 0)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000185
186 env = os.environ.copy()
187 env["PYTHONNOUSERSITE"] = "1"
188 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000189 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000190 env=env)
Antoine Pitroua1782e12013-10-23 22:03:22 +0200191 if usersite == site.getsitepackages()[0]:
192 self.assertEqual(rc, 1)
193 else:
194 self.assertEqual(rc, 0)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000195
196 env = os.environ.copy()
197 env["PYTHONUSERBASE"] = "/tmp"
198 rc = subprocess.call([sys.executable, '-c',
199 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
200 env=env)
201 self.assertEqual(rc, 1)
202
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000203 def test_getuserbase(self):
204 site.USER_BASE = None
205 user_base = site.getuserbase()
206
207 # the call sets site.USER_BASE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000208 self.assertEqual(site.USER_BASE, user_base)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000209
210 # let's set PYTHONUSERBASE and see if it uses it
211 site.USER_BASE = None
Tarek Ziadéedacea32010-01-29 11:41:03 +0000212 import sysconfig
213 sysconfig._CONFIG_VARS = None
214
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000215 with EnvironmentVarGuard() as environ:
216 environ['PYTHONUSERBASE'] = 'xoxo'
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000217 self.assertTrue(site.getuserbase().startswith('xoxo'),
218 site.getuserbase())
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000219
220 def test_getusersitepackages(self):
221 site.USER_SITE = None
222 site.USER_BASE = None
223 user_site = site.getusersitepackages()
224
225 # the call sets USER_BASE *and* USER_SITE
Ezio Melottib3aedd42010-11-20 19:04:17 +0000226 self.assertEqual(site.USER_SITE, user_site)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000227 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000228
229 def test_getsitepackages(self):
230 site.PREFIXES = ['xoxo']
231 dirs = site.getsitepackages()
232
Christian Heimesde0b9622012-11-19 00:59:39 +0100233 if (sys.platform == "darwin" and
Ned Deilyd531b292012-02-06 00:58:18 +0100234 sysconfig.get_config_var("PYTHONFRAMEWORK")):
235 # OS X framework builds
236 site.PREFIXES = ['Python.framework']
237 dirs = site.getsitepackages()
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400238 self.assertEqual(len(dirs), 2)
Ned Deilyd531b292012-02-06 00:58:18 +0100239 wanted = os.path.join('/Library',
240 sysconfig.get_config_var("PYTHONFRAMEWORK"),
241 sys.version[:3],
242 'site-packages')
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400243 self.assertEqual(dirs[1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000244 elif os.sep == '/':
Ned Deilyd531b292012-02-06 00:58:18 +0100245 # OS X non-framwework builds, Linux, FreeBSD, etc
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400246 self.assertEqual(len(dirs), 1)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000247 wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
248 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000249 self.assertEqual(dirs[0], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000250 else:
Ned Deilyd531b292012-02-06 00:58:18 +0100251 # other platforms
Ezio Melottifc8b2052010-08-17 08:35:41 +0000252 self.assertEqual(len(dirs), 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000253 self.assertEqual(dirs[0], 'xoxo')
Tarek Ziadé8c0e2172009-10-27 21:24:21 +0000254 wanted = os.path.join('xoxo', 'lib', 'site-packages')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000255 self.assertEqual(dirs[1], wanted)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000256
Brett Cannon64a84702004-07-10 02:10:45 +0000257class PthFile(object):
258 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000259
Brett Cannon64a84702004-07-10 02:10:45 +0000260 def __init__(self, filename_base=TESTFN, imported="time",
261 good_dirname="__testdir__", bad_dirname="__bad"):
262 """Initialize instance variables"""
263 self.filename = filename_base + ".pth"
264 self.base_dir = os.path.abspath('')
265 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000266 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000267 self.good_dirname = good_dirname
268 self.bad_dirname = bad_dirname
269 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
270 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000271
Brett Cannon64a84702004-07-10 02:10:45 +0000272 def create(self):
273 """Create a .pth file with a comment, blank lines, an ``import
274 <self.imported>``, a line with self.good_dirname, and a line with
275 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000276
Brett Cannon64a84702004-07-10 02:10:45 +0000277 Creation of the directory for self.good_dir_path (based off of
278 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000279
Brett Cannon64a84702004-07-10 02:10:45 +0000280 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000281
Brett Cannon64a84702004-07-10 02:10:45 +0000282 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000283 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000284 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000285 print("#import @bad module name", file=FILE)
286 print("\n", file=FILE)
287 print("import %s" % self.imported, file=FILE)
288 print(self.good_dirname, file=FILE)
289 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000290 finally:
291 FILE.close()
292 os.mkdir(self.good_dir_path)
293
Brett Cannonee86a662004-07-13 07:12:25 +0000294 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000295 """Make sure that the .pth file is deleted, self.imported is not in
296 sys.modules, and that both self.good_dirname and self.bad_dirname are
297 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000298 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000299 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000300 if prep:
301 self.imported_module = sys.modules.get(self.imported)
302 if self.imported_module:
303 del sys.modules[self.imported]
304 else:
305 if self.imported_module:
306 sys.modules[self.imported] = self.imported_module
307 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000308 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000309 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000310 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000311
312class ImportSideEffectTests(unittest.TestCase):
313 """Test side-effects from importing 'site'."""
314
315 def setUp(self):
316 """Make a copy of sys.path"""
317 self.sys_path = sys.path[:]
318
319 def tearDown(self):
320 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +0000321 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000322
Barry Warsaw28a691b2010-04-17 00:19:56 +0000323 def test_abs_paths(self):
324 # Make sure all imported modules have their __file__ and __cached__
325 # attributes as absolute paths. Arranging to put the Lib directory on
326 # PYTHONPATH would cause the os module to have a relative path for
327 # __file__ if abs_paths() does not get run. sys and builtins (the
328 # only other modules imported before site.py runs) do not have
329 # __file__ or __cached__ because they are built-in.
330 parent = os.path.relpath(os.path.dirname(os.__file__))
331 env = os.environ.copy()
332 env['PYTHONPATH'] = parent
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000333 code = ('import os, sys',
334 # use ASCII to avoid locale issues with non-ASCII directories
335 'os_file = os.__file__.encode("ascii", "backslashreplace")',
336 r'sys.stdout.buffer.write(os_file + b"\n")',
337 'os_cached = os.__cached__.encode("ascii", "backslashreplace")',
338 r'sys.stdout.buffer.write(os_cached + b"\n")')
339 command = '\n'.join(code)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000340 # First, prove that with -S (no 'import site'), the paths are
341 # relative.
342 proc = subprocess.Popen([sys.executable, '-S', '-c', command],
343 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000344 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000345 stdout, stderr = proc.communicate()
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000346
Barry Warsaw28a691b2010-04-17 00:19:56 +0000347 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000348 os__file__, os__cached__ = stdout.splitlines()[:2]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000349 self.assertFalse(os.path.isabs(os__file__))
350 self.assertFalse(os.path.isabs(os__cached__))
351 # Now, with 'import site', it works.
352 proc = subprocess.Popen([sys.executable, '-c', command],
353 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000354 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000355 stdout, stderr = proc.communicate()
356 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000357 os__file__, os__cached__ = stdout.splitlines()[:2]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000358 self.assertTrue(os.path.isabs(os__file__))
359 self.assertTrue(os.path.isabs(os__cached__))
Brett Cannon0096e262004-06-05 01:12:51 +0000360
361 def test_no_duplicate_paths(self):
362 # No duplicate paths should exist in sys.path
363 # Handled by removeduppaths()
364 site.removeduppaths()
365 seen_paths = set()
366 for path in sys.path:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000367 self.assertNotIn(path, seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000368 seen_paths.add(path)
369
Zachary Ware9fe6d862013-12-08 00:20:35 -0600370 @unittest.skip('test not implemented')
Brett Cannon0096e262004-06-05 01:12:51 +0000371 def test_add_build_dir(self):
372 # Test that the build directory's Modules directory is used when it
373 # should be.
374 # XXX: implement
375 pass
376
Brett Cannon0096e262004-06-05 01:12:51 +0000377 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000378 # 'quit' and 'exit' should be injected into builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000379 self.assertTrue(hasattr(builtins, "quit"))
380 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000381
382 def test_setting_copyright(self):
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700383 # 'copyright', 'credits', and 'license' should be in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000384 self.assertTrue(hasattr(builtins, "copyright"))
385 self.assertTrue(hasattr(builtins, "credits"))
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700386 self.assertTrue(hasattr(builtins, "license"))
Brett Cannon0096e262004-06-05 01:12:51 +0000387
388 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000389 # 'help' should be set in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000390 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000391
392 def test_aliasing_mbcs(self):
393 if sys.platform == "win32":
394 import locale
395 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000396 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000397 if value == "mbcs":
398 break
399 else:
400 self.fail("did not alias mbcs")
401
Brett Cannon0096e262004-06-05 01:12:51 +0000402 def test_sitecustomize_executed(self):
403 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000404 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000405 try:
406 import sitecustomize
407 except ImportError:
408 pass
409 else:
410 self.fail("sitecustomize not imported automatically")
411
R David Murray1bc6ceb2013-09-14 13:28:37 -0400412 @test.support.requires_resource('network')
Benjamin Peterson337578b2015-02-01 20:16:59 -0500413 @test.support.system_must_validate_cert
Georg Brandl78abc9d2013-10-27 09:41:57 +0100414 @unittest.skipUnless(sys.version_info[3] == 'final',
415 'only for released versions')
Ned Deily5a507f02014-03-26 23:31:39 -0700416 @unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"),
417 'need SSL support to download license')
R David Murray1bc6ceb2013-09-14 13:28:37 -0400418 def test_license_exists_at_url(self):
Ned Deily944d5972014-03-26 23:43:26 -0700419 # This test is a bit fragile since it depends on the format of the
R David Murray1bc6ceb2013-09-14 13:28:37 -0400420 # string displayed by license in the absence of a LICENSE file.
421 url = license._Printer__data.split()[1]
422 req = urllib.request.Request(url, method='HEAD')
423 try:
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700424 with test.support.transient_internet(url):
R David Murray1bc6ceb2013-09-14 13:28:37 -0400425 with urllib.request.urlopen(req) as data:
426 code = data.getcode()
427 except urllib.error.HTTPError as e:
428 code = e.code
429 self.assertEqual(code, 200, msg="Can't find " + url)
Senthil Kumaran8ef519b2013-09-07 13:59:17 -0700430
Brett Cannon0096e262004-06-05 01:12:51 +0000431
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200432class StartupImportTests(unittest.TestCase):
433
434 def test_startup_imports(self):
435 # This tests checks which modules are loaded by Python when it
436 # initially starts upon startup.
Christian Heimes179a3db2013-10-12 12:32:21 +0200437 popen = subprocess.Popen([sys.executable, '-I', '-v', '-c',
438 'import sys; print(set(sys.modules))'],
439 stdout=subprocess.PIPE,
440 stderr=subprocess.PIPE)
441 stdout, stderr = popen.communicate()
442 stdout = stdout.decode('utf-8')
443 stderr = stderr.decode('utf-8')
444 modules = eval(stdout)
445
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200446 self.assertIn('site', modules)
447
Christian Heimes25827622013-10-12 01:27:08 +0200448 # http://bugs.python.org/issue19205
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200449 re_mods = {'re', '_sre', 'sre_compile', 'sre_constants', 'sre_parse'}
Christian Heimesf403f502013-10-12 15:08:42 +0200450 # _osx_support uses the re module in many placs
451 if sys.platform != 'darwin':
452 self.assertFalse(modules.intersection(re_mods), stderr)
Christian Heimes25827622013-10-12 01:27:08 +0200453 # http://bugs.python.org/issue9548
Christian Heimes179a3db2013-10-12 12:32:21 +0200454 self.assertNotIn('locale', modules, stderr)
Christian Heimes86823a52013-10-17 13:40:00 +0200455 if sys.platform != 'darwin':
456 # http://bugs.python.org/issue19209
457 self.assertNotIn('copyreg', modules, stderr)
Christian Heimesf1dc3ee2013-10-13 02:04:20 +0200458 # http://bugs.python.org/issue19218>
459 collection_mods = {'_collections', 'collections', 'functools',
460 'heapq', 'itertools', 'keyword', 'operator',
doko@ubuntu.com95743552014-04-15 20:37:54 +0200461 'reprlib', 'types', 'weakref'
462 }.difference(sys.builtin_module_names)
Ned Deilyb795aa82013-10-17 15:21:40 -0700463 self.assertFalse(modules.intersection(collection_mods), stderr)
Christian Heimes1a5fb4e2013-10-12 01:00:51 +0200464
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200465
Brett Cannon0096e262004-06-05 01:12:51 +0000466if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400467 unittest.main()