blob: 013bfe10940f4c3e14e09d9f8178dc4bdd4fe4da [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
Walter Dörwaldb525e182009-04-26 21:39:21 +00008from test.support import run_unittest, TESTFN, EnvironmentVarGuard
Georg Brandl1a3284e2007-12-02 09:40:06 +00009import builtins
Brett Cannon0096e262004-06-05 01:12:51 +000010import os
11import sys
12import encodings
Christian Heimes8dc226f2008-05-06 23:45:46 +000013import subprocess
Tarek Ziadéedacea32010-01-29 11:41:03 +000014import sysconfig
15from copy import copy
16
Brett Cannon0096e262004-06-05 01:12:51 +000017# Need to make sure to not import 'site' if someone specified ``-S`` at the
18# command-line. Detect this by just making sure 'site' has not been imported
19# already.
20if "site" in sys.modules:
21 import site
22else:
Benjamin Petersone549ead2009-03-28 21:42:05 +000023 raise unittest.SkipTest("importation of site.py suppressed")
Brett Cannon0096e262004-06-05 01:12:51 +000024
Christian Heimes8dc226f2008-05-06 23:45:46 +000025if not os.path.isdir(site.USER_SITE):
26 # need to add user site directory for tests
27 os.makedirs(site.USER_SITE)
28 site.addsitedir(site.USER_SITE)
29
Brett Cannon0096e262004-06-05 01:12:51 +000030class HelperFunctionsTests(unittest.TestCase):
31 """Tests for helper functions.
Raymond Hettingerebd95222004-06-27 03:02:18 +000032
Brett Cannon0096e262004-06-05 01:12:51 +000033 The setting of the encoding (set using sys.setdefaultencoding) used by
34 the Unicode implementation is not tested.
Raymond Hettingerebd95222004-06-27 03:02:18 +000035
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
Tarek Ziadéedacea32010-01-29 11:41:03 +000044 self.old_vars = copy(sysconfig._CONFIG_VARS)
Brett Cannon0096e262004-06-05 01:12:51 +000045
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000046 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000047 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +000048 sys.path[:] = self.sys_path
Tarek Ziadé4a608c02009-08-20 21:28:05 +000049 site.USER_BASE = self.old_base
50 site.USER_SITE = self.old_site
51 site.PREFIXES = self.old_prefixes
Tarek Ziadéedacea32010-01-29 11:41:03 +000052 sysconfig._CONFIG_VARS = self.old_vars
Raymond Hettingerebd95222004-06-27 03:02:18 +000053
Brett Cannon0096e262004-06-05 01:12:51 +000054 def test_makepath(self):
55 # Test makepath() have an absolute path for its first return value
56 # and a case-normalized version of the absolute path for its
57 # second value.
58 path_parts = ("Beginning", "End")
59 original_dir = os.path.join(*path_parts)
60 abs_dir, norm_dir = site.makepath(*path_parts)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000061 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000062 if original_dir == os.path.normcase(original_dir):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000063 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000064 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000065 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000066
67 def test_init_pathinfo(self):
68 dir_set = site._init_pathinfo()
69 for entry in [site.makepath(path)[1] for path in sys.path
70 if path and os.path.isdir(path)]:
Ezio Melottib58e0bd2010-01-23 15:40:09 +000071 self.assertIn(entry, dir_set,
72 "%s from sys.path not found in set returned "
73 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000074
Brett Cannonee86a662004-07-13 07:12:25 +000075 def pth_file_tests(self, pth_file):
76 """Contain common code for testing results of reading a .pth file"""
Ezio Melottib58e0bd2010-01-23 15:40:09 +000077 self.assertIn(pth_file.imported, sys.modules,
78 "%s not in sys.modules" % pth_file.imported)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +000079 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
80 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +000081
Brett Cannon0096e262004-06-05 01:12:51 +000082 def test_addpackage(self):
83 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000084 # adds directories to sys.path for any line in the file that is not a
85 # comment or import that is a valid directory name for where the .pth
86 # file resides; invalid directories are not added
87 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000088 pth_file.cleanup(prep=True) # to make sure that nothing is
89 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000090 try:
Brett Cannon64a84702004-07-10 02:10:45 +000091 pth_file.create()
92 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +000093 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000094 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000095 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +000096
Brett Cannon0096e262004-06-05 01:12:51 +000097 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +000098 # Same tests for test_addpackage since addsitedir() essentially just
99 # calls addpackage() for every .pth file in the directory
100 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000101 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
102 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +0000103 try:
Brett Cannonee86a662004-07-13 07:12:25 +0000104 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +0000105 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000106 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000107 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000108 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +0000109
Christian Heimes8dc226f2008-05-06 23:45:46 +0000110 def test_s_option(self):
111 usersite = site.USER_SITE
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000112 self.assertIn(usersite, sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000113
114 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000115 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimes8dc226f2008-05-06 23:45:46 +0000116 self.assertEqual(rc, 1)
117
118 rc = subprocess.call([sys.executable, '-s', '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000119 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimes8dc226f2008-05-06 23:45:46 +0000120 self.assertEqual(rc, 0)
121
122 env = os.environ.copy()
123 env["PYTHONNOUSERSITE"] = "1"
124 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000125 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000126 env=env)
127 self.assertEqual(rc, 0)
128
129 env = os.environ.copy()
130 env["PYTHONUSERBASE"] = "/tmp"
131 rc = subprocess.call([sys.executable, '-c',
132 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
133 env=env)
134 self.assertEqual(rc, 1)
135
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000136 def test_getuserbase(self):
137 site.USER_BASE = None
138 user_base = site.getuserbase()
139
140 # the call sets site.USER_BASE
141 self.assertEquals(site.USER_BASE, user_base)
142
143 # let's set PYTHONUSERBASE and see if it uses it
144 site.USER_BASE = None
Tarek Ziadéedacea32010-01-29 11:41:03 +0000145 import sysconfig
146 sysconfig._CONFIG_VARS = None
147
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000148 with EnvironmentVarGuard() as environ:
149 environ['PYTHONUSERBASE'] = 'xoxo'
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000150 self.assertTrue(site.getuserbase().startswith('xoxo'),
151 site.getuserbase())
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000152
153 def test_getusersitepackages(self):
154 site.USER_SITE = None
155 site.USER_BASE = None
156 user_site = site.getusersitepackages()
157
158 # the call sets USER_BASE *and* USER_SITE
159 self.assertEquals(site.USER_SITE, user_site)
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000160 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000161
162 def test_getsitepackages(self):
163 site.PREFIXES = ['xoxo']
164 dirs = site.getsitepackages()
165
166 if sys.platform in ('os2emx', 'riscos'):
Antoine Pitrou9166e6a2009-11-01 23:55:40 +0000167 self.assertEqual(len(dirs), 1)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000168 wanted = os.path.join('xoxo', 'Lib', 'site-packages')
169 self.assertEquals(dirs[0], wanted)
170 elif os.sep == '/':
Ezio Melottifc8b2052010-08-17 08:35:41 +0000171 self.assertEqual(len(dirs), 2)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000172 wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
173 'site-packages')
174 self.assertEquals(dirs[0], wanted)
175 wanted = os.path.join('xoxo', 'lib', 'site-python')
176 self.assertEquals(dirs[1], wanted)
177 else:
Ezio Melottifc8b2052010-08-17 08:35:41 +0000178 self.assertEqual(len(dirs), 2)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000179 self.assertEquals(dirs[0], 'xoxo')
Tarek Ziadé8c0e2172009-10-27 21:24:21 +0000180 wanted = os.path.join('xoxo', 'lib', 'site-packages')
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000181 self.assertEquals(dirs[1], wanted)
182
183 # let's try the specific Apple location
Brett Cannonbbb2d492010-05-14 00:04:56 +0000184 if (sys.platform == "darwin" and
185 sysconfig.get_config_var("PYTHONFRAMEWORK")):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000186 site.PREFIXES = ['Python.framework']
187 dirs = site.getsitepackages()
Ronald Oussorenbda46722010-08-01 09:02:50 +0000188 self.assertEqual(len(dirs), 3)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000189 wanted = os.path.join('/Library', 'Python', sys.version[:3],
190 'site-packages')
Ronald Oussorenbda46722010-08-01 09:02:50 +0000191 self.assertEquals(dirs[2], wanted)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000192
Brett Cannon64a84702004-07-10 02:10:45 +0000193class PthFile(object):
194 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000195
Brett Cannon64a84702004-07-10 02:10:45 +0000196 def __init__(self, filename_base=TESTFN, imported="time",
197 good_dirname="__testdir__", bad_dirname="__bad"):
198 """Initialize instance variables"""
199 self.filename = filename_base + ".pth"
200 self.base_dir = os.path.abspath('')
201 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000202 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000203 self.good_dirname = good_dirname
204 self.bad_dirname = bad_dirname
205 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
206 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000207
Brett Cannon64a84702004-07-10 02:10:45 +0000208 def create(self):
209 """Create a .pth file with a comment, blank lines, an ``import
210 <self.imported>``, a line with self.good_dirname, and a line with
211 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000212
Brett Cannon64a84702004-07-10 02:10:45 +0000213 Creation of the directory for self.good_dir_path (based off of
214 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000215
Brett Cannon64a84702004-07-10 02:10:45 +0000216 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000217
Brett Cannon64a84702004-07-10 02:10:45 +0000218 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000219 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000220 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000221 print("#import @bad module name", file=FILE)
222 print("\n", file=FILE)
223 print("import %s" % self.imported, file=FILE)
224 print(self.good_dirname, file=FILE)
225 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000226 finally:
227 FILE.close()
228 os.mkdir(self.good_dir_path)
229
Brett Cannonee86a662004-07-13 07:12:25 +0000230 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000231 """Make sure that the .pth file is deleted, self.imported is not in
232 sys.modules, and that both self.good_dirname and self.bad_dirname are
233 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000234 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000235 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000236 if prep:
237 self.imported_module = sys.modules.get(self.imported)
238 if self.imported_module:
239 del sys.modules[self.imported]
240 else:
241 if self.imported_module:
242 sys.modules[self.imported] = self.imported_module
243 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000244 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000245 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000246 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000247
248class ImportSideEffectTests(unittest.TestCase):
249 """Test side-effects from importing 'site'."""
250
251 def setUp(self):
252 """Make a copy of sys.path"""
253 self.sys_path = sys.path[:]
254
255 def tearDown(self):
256 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +0000257 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000258
Barry Warsaw28a691b2010-04-17 00:19:56 +0000259 def test_abs_paths(self):
260 # Make sure all imported modules have their __file__ and __cached__
261 # attributes as absolute paths. Arranging to put the Lib directory on
262 # PYTHONPATH would cause the os module to have a relative path for
263 # __file__ if abs_paths() does not get run. sys and builtins (the
264 # only other modules imported before site.py runs) do not have
265 # __file__ or __cached__ because they are built-in.
266 parent = os.path.relpath(os.path.dirname(os.__file__))
267 env = os.environ.copy()
268 env['PYTHONPATH'] = parent
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000269 code = ('import os, sys',
270 # use ASCII to avoid locale issues with non-ASCII directories
271 'os_file = os.__file__.encode("ascii", "backslashreplace")',
272 r'sys.stdout.buffer.write(os_file + b"\n")',
273 'os_cached = os.__cached__.encode("ascii", "backslashreplace")',
274 r'sys.stdout.buffer.write(os_cached + b"\n")')
275 command = '\n'.join(code)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000276 # First, prove that with -S (no 'import site'), the paths are
277 # relative.
278 proc = subprocess.Popen([sys.executable, '-S', '-c', command],
279 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000280 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000281 stdout, stderr = proc.communicate()
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000282
Barry Warsaw28a691b2010-04-17 00:19:56 +0000283 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000284 os__file__, os__cached__ = stdout.splitlines()[:2]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000285 self.assertFalse(os.path.isabs(os__file__))
286 self.assertFalse(os.path.isabs(os__cached__))
287 # Now, with 'import site', it works.
288 proc = subprocess.Popen([sys.executable, '-c', command],
289 env=env,
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000290 stdout=subprocess.PIPE)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000291 stdout, stderr = proc.communicate()
292 self.assertEqual(proc.returncode, 0)
Victor Stinnerf3bc2582010-04-18 07:59:53 +0000293 os__file__, os__cached__ = stdout.splitlines()[:2]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000294 self.assertTrue(os.path.isabs(os__file__))
295 self.assertTrue(os.path.isabs(os__cached__))
Brett Cannon0096e262004-06-05 01:12:51 +0000296
297 def test_no_duplicate_paths(self):
298 # No duplicate paths should exist in sys.path
299 # Handled by removeduppaths()
300 site.removeduppaths()
301 seen_paths = set()
302 for path in sys.path:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000303 self.assertNotIn(path, seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000304 seen_paths.add(path)
305
306 def test_add_build_dir(self):
307 # Test that the build directory's Modules directory is used when it
308 # should be.
309 # XXX: implement
310 pass
311
Brett Cannon0096e262004-06-05 01:12:51 +0000312 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000313 # 'quit' and 'exit' should be injected into builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000314 self.assertTrue(hasattr(builtins, "quit"))
315 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000316
317 def test_setting_copyright(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000318 # 'copyright' and 'credits' should be in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000319 self.assertTrue(hasattr(builtins, "copyright"))
320 self.assertTrue(hasattr(builtins, "credits"))
Brett Cannon0096e262004-06-05 01:12:51 +0000321
322 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000323 # 'help' should be set in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000324 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000325
326 def test_aliasing_mbcs(self):
327 if sys.platform == "win32":
328 import locale
329 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000330 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000331 if value == "mbcs":
332 break
333 else:
334 self.fail("did not alias mbcs")
335
336 def test_setdefaultencoding_removed(self):
337 # Make sure sys.setdefaultencoding is gone
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000338 self.assertTrue(not hasattr(sys, "setdefaultencoding"))
Brett Cannon0096e262004-06-05 01:12:51 +0000339
340 def test_sitecustomize_executed(self):
341 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000342 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000343 try:
344 import sitecustomize
345 except ImportError:
346 pass
347 else:
348 self.fail("sitecustomize not imported automatically")
349
Brett Cannon0096e262004-06-05 01:12:51 +0000350def test_main():
351 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
352
Brett Cannon0096e262004-06-05 01:12:51 +0000353if __name__ == "__main__":
354 test_main()