blob: 4af83b3a160d341bbff77865cd19c14e68565193 [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örwald4b965f62009-04-26 20:51:44 +00008from test.test_support import run_unittest, TESTFN, EnvironmentVarGuard
Brett Cannon0096e262004-06-05 01:12:51 +00009import __builtin__
10import os
11import sys
12import encodings
Christian Heimesaf748c32008-05-06 22:41:46 +000013import subprocess
Tarek Ziadé5633a802010-01-23 09:23:15 +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 Petersonbec087f2009-03-26 21:10:30 +000023 raise unittest.SkipTest("importation of site.py suppressed")
Brett Cannon0096e262004-06-05 01:12:51 +000024
Christian Heimesaf748c32008-05-06 22:41: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é764fc232009-08-20 21:23:13 +000041 self.old_base = site.USER_BASE
42 self.old_site = site.USER_SITE
43 self.old_prefixes = site.PREFIXES
Tarek Ziadé5633a802010-01-23 09:23:15 +000044 self.old_vars = copy(sysconfig._CONFIG_VARS)
Brett Cannon0096e262004-06-05 01:12:51 +000045
Neal Norwitz40388cc2008-05-14 06:47:56 +000046 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000047 """Restore sys.path"""
Nick Coghlana0e0f9e2009-10-17 16:19:51 +000048 sys.path[:] = self.sys_path
Tarek Ziadé764fc232009-08-20 21:23:13 +000049 site.USER_BASE = self.old_base
50 site.USER_SITE = self.old_site
51 site.PREFIXES = self.old_prefixes
Tarek Ziadé5633a802010-01-23 09:23:15 +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 Peterson5c8da862009-06-30 22:57:08 +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 Peterson5c8da862009-06-30 22:57:08 +000063 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000064 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +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)]:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000071 self.assertTrue(entry in dir_set,
Brett Cannon0096e262004-06-05 01:12:51 +000072 "%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"""
Benjamin Peterson5c8da862009-06-30 22:57:08 +000077 self.assertTrue(pth_file.imported in sys.modules,
Antoine Pitroud8b16ab2009-11-01 23:54:20 +000078 "%s not in sys.modules" % pth_file.imported)
79 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 Heimesaf748c32008-05-06 22:41:46 +0000110 def test_s_option(self):
111 usersite = site.USER_SITE
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000112 self.assertIn(usersite, sys.path)
Christian Heimesaf748c32008-05-06 22:41:46 +0000113
114 rc = subprocess.call([sys.executable, '-c',
Antoine Pitroub03f5322009-02-22 18:20:46 +0000115 'import sys; sys.exit(%r in sys.path)' % usersite])
Brett Cannonb7019d82009-02-24 22:01:02 +0000116 self.assertEqual(rc, 1, "%r is not in sys.path (sys.exit returned %r)"
117 % (usersite, rc))
Christian Heimesaf748c32008-05-06 22:41:46 +0000118
119 rc = subprocess.call([sys.executable, '-s', '-c',
Amaury Forgeot d'Arc9b69ed92008-06-19 21:17:12 +0000120 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimesaf748c32008-05-06 22:41:46 +0000121 self.assertEqual(rc, 0)
122
123 env = os.environ.copy()
124 env["PYTHONNOUSERSITE"] = "1"
125 rc = subprocess.call([sys.executable, '-c',
Amaury Forgeot d'Arc9b69ed92008-06-19 21:17:12 +0000126 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimesaf748c32008-05-06 22:41:46 +0000127 env=env)
128 self.assertEqual(rc, 0)
129
130 env = os.environ.copy()
131 env["PYTHONUSERBASE"] = "/tmp"
132 rc = subprocess.call([sys.executable, '-c',
133 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
134 env=env)
135 self.assertEqual(rc, 1)
136
Tarek Ziadé764fc232009-08-20 21:23:13 +0000137 def test_getuserbase(self):
138 site.USER_BASE = None
139 user_base = site.getuserbase()
140
141 # the call sets site.USER_BASE
142 self.assertEquals(site.USER_BASE, user_base)
143
144 # let's set PYTHONUSERBASE and see if it uses it
145 site.USER_BASE = None
Tarek Ziadé5633a802010-01-23 09:23:15 +0000146 import sysconfig
147 sysconfig._CONFIG_VARS = None
148
Tarek Ziadé764fc232009-08-20 21:23:13 +0000149 with EnvironmentVarGuard() as environ:
150 environ['PYTHONUSERBASE'] = 'xoxo'
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000151 self.assertTrue(site.getuserbase().startswith('xoxo'),
152 site.getuserbase())
Tarek Ziadé764fc232009-08-20 21:23:13 +0000153
154 def test_getusersitepackages(self):
155 site.USER_SITE = None
156 site.USER_BASE = None
157 user_site = site.getusersitepackages()
158
159 # the call sets USER_BASE *and* USER_SITE
160 self.assertEquals(site.USER_SITE, user_site)
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000161 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
Tarek Ziadé764fc232009-08-20 21:23:13 +0000162
163 def test_getsitepackages(self):
164 site.PREFIXES = ['xoxo']
165 dirs = site.getsitepackages()
166
167 if sys.platform in ('os2emx', 'riscos'):
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000168 self.assertEqual(len(dirs), 1)
Tarek Ziadé764fc232009-08-20 21:23:13 +0000169 wanted = os.path.join('xoxo', 'Lib', 'site-packages')
170 self.assertEquals(dirs[0], wanted)
171 elif os.sep == '/':
172 self.assertTrue(len(dirs), 2)
173 wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
174 'site-packages')
175 self.assertEquals(dirs[0], wanted)
176 wanted = os.path.join('xoxo', 'lib', 'site-python')
177 self.assertEquals(dirs[1], wanted)
178 else:
179 self.assertTrue(len(dirs), 2)
180 self.assertEquals(dirs[0], 'xoxo')
Tarek Ziadéd24cab82009-10-27 21:20:27 +0000181 wanted = os.path.join('xoxo', 'lib', 'site-packages')
Tarek Ziadé764fc232009-08-20 21:23:13 +0000182 self.assertEquals(dirs[1], wanted)
183
184 # let's try the specific Apple location
185 if sys.platform == "darwin":
186 site.PREFIXES = ['Python.framework']
187 dirs = site.getsitepackages()
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000188 self.assertEqual(len(dirs), 4)
Tarek Ziadé764fc232009-08-20 21:23:13 +0000189 wanted = os.path.join('~', 'Library', 'Python',
190 sys.version[:3], 'site-packages')
191 self.assertEquals(dirs[2], os.path.expanduser(wanted))
192 wanted = os.path.join('/Library', 'Python', sys.version[:3],
193 'site-packages')
194 self.assertEquals(dirs[3], wanted)
Christian Heimesaf748c32008-05-06 22:41:46 +0000195
Brett Cannon64a84702004-07-10 02:10:45 +0000196class PthFile(object):
197 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000198
Brett Cannon64a84702004-07-10 02:10:45 +0000199 def __init__(self, filename_base=TESTFN, imported="time",
200 good_dirname="__testdir__", bad_dirname="__bad"):
201 """Initialize instance variables"""
202 self.filename = filename_base + ".pth"
203 self.base_dir = os.path.abspath('')
204 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000205 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000206 self.good_dirname = good_dirname
207 self.bad_dirname = bad_dirname
208 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
209 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000210
Brett Cannon64a84702004-07-10 02:10:45 +0000211 def create(self):
212 """Create a .pth file with a comment, blank lines, an ``import
213 <self.imported>``, a line with self.good_dirname, and a line with
214 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000215
Brett Cannon64a84702004-07-10 02:10:45 +0000216 Creation of the directory for self.good_dir_path (based off of
217 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000218
Brett Cannon64a84702004-07-10 02:10:45 +0000219 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000220
Brett Cannon64a84702004-07-10 02:10:45 +0000221 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000222 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000223 try:
224 print>>FILE, "#import @bad module name"
225 print>>FILE, "\n"
226 print>>FILE, "import %s" % self.imported
227 print>>FILE, self.good_dirname
228 print>>FILE, self.bad_dirname
229 finally:
230 FILE.close()
231 os.mkdir(self.good_dir_path)
232
Brett Cannonee86a662004-07-13 07:12:25 +0000233 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000234 """Make sure that the .pth file is deleted, self.imported is not in
235 sys.modules, and that both self.good_dirname and self.bad_dirname are
236 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000237 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000238 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000239 if prep:
240 self.imported_module = sys.modules.get(self.imported)
241 if self.imported_module:
242 del sys.modules[self.imported]
243 else:
244 if self.imported_module:
245 sys.modules[self.imported] = self.imported_module
246 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000247 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000248 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000249 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000250
251class ImportSideEffectTests(unittest.TestCase):
252 """Test side-effects from importing 'site'."""
253
254 def setUp(self):
255 """Make a copy of sys.path"""
256 self.sys_path = sys.path[:]
257
258 def tearDown(self):
259 """Restore sys.path"""
Nick Coghlana0e0f9e2009-10-17 16:19:51 +0000260 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000261
262 def test_abs__file__(self):
263 # Make sure all imported modules have their __file__ attribute
264 # as an absolute path.
265 # Handled by abs__file__()
266 site.abs__file__()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000267 for module in (sys, os, __builtin__):
Brett Cannon0096e262004-06-05 01:12:51 +0000268 try:
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000269 self.assertTrue(os.path.isabs(module.__file__), `module`)
Brett Cannon0096e262004-06-05 01:12:51 +0000270 except AttributeError:
271 continue
Raymond Hettingerebd95222004-06-27 03:02:18 +0000272 # We could try everything in sys.modules; however, when regrtest.py
273 # runs something like test_frozen before test_site, then we will
274 # be testing things loaded *after* test_site did path normalization
Brett Cannon0096e262004-06-05 01:12:51 +0000275
276 def test_no_duplicate_paths(self):
277 # No duplicate paths should exist in sys.path
278 # Handled by removeduppaths()
279 site.removeduppaths()
280 seen_paths = set()
281 for path in sys.path:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000282 self.assertTrue(path not in seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000283 seen_paths.add(path)
284
285 def test_add_build_dir(self):
286 # Test that the build directory's Modules directory is used when it
287 # should be.
288 # XXX: implement
289 pass
290
Brett Cannon0096e262004-06-05 01:12:51 +0000291 def test_setting_quit(self):
292 # 'quit' and 'exit' should be injected into __builtin__
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000293 self.assertTrue(hasattr(__builtin__, "quit"))
294 self.assertTrue(hasattr(__builtin__, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000295
296 def test_setting_copyright(self):
297 # 'copyright' and 'credits' should be in __builtin__
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000298 self.assertTrue(hasattr(__builtin__, "copyright"))
299 self.assertTrue(hasattr(__builtin__, "credits"))
Brett Cannon0096e262004-06-05 01:12:51 +0000300
301 def test_setting_help(self):
302 # 'help' should be set in __builtin__
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000303 self.assertTrue(hasattr(__builtin__, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000304
305 def test_aliasing_mbcs(self):
306 if sys.platform == "win32":
307 import locale
308 if locale.getdefaultlocale()[1].startswith('cp'):
309 for value in encodings.aliases.aliases.itervalues():
310 if value == "mbcs":
311 break
312 else:
313 self.fail("did not alias mbcs")
314
315 def test_setdefaultencoding_removed(self):
316 # Make sure sys.setdefaultencoding is gone
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000317 self.assertTrue(not hasattr(sys, "setdefaultencoding"))
Brett Cannon0096e262004-06-05 01:12:51 +0000318
319 def test_sitecustomize_executed(self):
320 # If sitecustomize is available, it should have been imported.
Senthil Kumarance8e33a2010-01-08 19:04:16 +0000321 if not sys.modules.has_key("sitecustomize"):
Brett Cannon0096e262004-06-05 01:12:51 +0000322 try:
323 import sitecustomize
324 except ImportError:
325 pass
326 else:
327 self.fail("sitecustomize not imported automatically")
328
Brett Cannon0096e262004-06-05 01:12:51 +0000329def test_main():
330 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
331
Brett Cannon0096e262004-06-05 01:12:51 +0000332if __name__ == "__main__":
333 test_main()