blob: 85d898abade0615c2d5097e3daca51fdb70bf792 [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
Brett Cannon0096e262004-06-05 01:12:51 +000014# Need to make sure to not import 'site' if someone specified ``-S`` at the
15# command-line. Detect this by just making sure 'site' has not been imported
16# already.
17if "site" in sys.modules:
18 import site
19else:
Benjamin Petersonbec087f2009-03-26 21:10:30 +000020 raise unittest.SkipTest("importation of site.py suppressed")
Brett Cannon0096e262004-06-05 01:12:51 +000021
Christian Heimesaf748c32008-05-06 22:41:46 +000022if not os.path.isdir(site.USER_SITE):
23 # need to add user site directory for tests
24 os.makedirs(site.USER_SITE)
25 site.addsitedir(site.USER_SITE)
26
Brett Cannon0096e262004-06-05 01:12:51 +000027class HelperFunctionsTests(unittest.TestCase):
28 """Tests for helper functions.
Raymond Hettingerebd95222004-06-27 03:02:18 +000029
Brett Cannon0096e262004-06-05 01:12:51 +000030 The setting of the encoding (set using sys.setdefaultencoding) used by
31 the Unicode implementation is not tested.
Raymond Hettingerebd95222004-06-27 03:02:18 +000032
Brett Cannon0096e262004-06-05 01:12:51 +000033 """
34
35 def setUp(self):
36 """Save a copy of sys.path"""
37 self.sys_path = sys.path[:]
Tarek Ziadé764fc232009-08-20 21:23:13 +000038 self.old_base = site.USER_BASE
39 self.old_site = site.USER_SITE
40 self.old_prefixes = site.PREFIXES
Brett Cannon0096e262004-06-05 01:12:51 +000041
Neal Norwitz40388cc2008-05-14 06:47:56 +000042 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000043 """Restore sys.path"""
Nick Coghlana0e0f9e2009-10-17 16:19:51 +000044 sys.path[:] = self.sys_path
Tarek Ziadé764fc232009-08-20 21:23:13 +000045 site.USER_BASE = self.old_base
46 site.USER_SITE = self.old_site
47 site.PREFIXES = self.old_prefixes
Raymond Hettingerebd95222004-06-27 03:02:18 +000048
Brett Cannon0096e262004-06-05 01:12:51 +000049 def test_makepath(self):
50 # Test makepath() have an absolute path for its first return value
51 # and a case-normalized version of the absolute path for its
52 # second value.
53 path_parts = ("Beginning", "End")
54 original_dir = os.path.join(*path_parts)
55 abs_dir, norm_dir = site.makepath(*path_parts)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000056 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000057 if original_dir == os.path.normcase(original_dir):
Benjamin Peterson5c8da862009-06-30 22:57:08 +000058 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000059 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000060 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000061
62 def test_init_pathinfo(self):
63 dir_set = site._init_pathinfo()
64 for entry in [site.makepath(path)[1] for path in sys.path
65 if path and os.path.isdir(path)]:
Benjamin Peterson5c8da862009-06-30 22:57:08 +000066 self.assertTrue(entry in dir_set,
Brett Cannon0096e262004-06-05 01:12:51 +000067 "%s from sys.path not found in set returned "
68 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000069
Brett Cannonee86a662004-07-13 07:12:25 +000070 def pth_file_tests(self, pth_file):
71 """Contain common code for testing results of reading a .pth file"""
Benjamin Peterson5c8da862009-06-30 22:57:08 +000072 self.assertTrue(pth_file.imported in sys.modules,
Antoine Pitroud8b16ab2009-11-01 23:54:20 +000073 "%s not in sys.modules" % pth_file.imported)
74 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
75 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +000076
Brett Cannon0096e262004-06-05 01:12:51 +000077 def test_addpackage(self):
78 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000079 # adds directories to sys.path for any line in the file that is not a
80 # comment or import that is a valid directory name for where the .pth
81 # file resides; invalid directories are not added
82 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000083 pth_file.cleanup(prep=True) # to make sure that nothing is
84 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000085 try:
Brett Cannon64a84702004-07-10 02:10:45 +000086 pth_file.create()
87 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +000088 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000089 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000090 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +000091
Brett Cannon0096e262004-06-05 01:12:51 +000092 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +000093 # Same tests for test_addpackage since addsitedir() essentially just
94 # calls addpackage() for every .pth file in the directory
95 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000096 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
97 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +000098 try:
Brett Cannonee86a662004-07-13 07:12:25 +000099 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +0000100 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000101 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000102 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000103 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +0000104
Christian Heimesaf748c32008-05-06 22:41:46 +0000105 def test_s_option(self):
106 usersite = site.USER_SITE
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000107 self.assertIn(usersite, sys.path)
Christian Heimesaf748c32008-05-06 22:41:46 +0000108
109 rc = subprocess.call([sys.executable, '-c',
Antoine Pitroub03f5322009-02-22 18:20:46 +0000110 'import sys; sys.exit(%r in sys.path)' % usersite])
Brett Cannonb7019d82009-02-24 22:01:02 +0000111 self.assertEqual(rc, 1, "%r is not in sys.path (sys.exit returned %r)"
112 % (usersite, rc))
Christian Heimesaf748c32008-05-06 22:41:46 +0000113
114 rc = subprocess.call([sys.executable, '-s', '-c',
Amaury Forgeot d'Arc9b69ed92008-06-19 21:17:12 +0000115 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimesaf748c32008-05-06 22:41:46 +0000116 self.assertEqual(rc, 0)
117
118 env = os.environ.copy()
119 env["PYTHONNOUSERSITE"] = "1"
120 rc = subprocess.call([sys.executable, '-c',
Amaury Forgeot d'Arc9b69ed92008-06-19 21:17:12 +0000121 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimesaf748c32008-05-06 22:41:46 +0000122 env=env)
123 self.assertEqual(rc, 0)
124
125 env = os.environ.copy()
126 env["PYTHONUSERBASE"] = "/tmp"
127 rc = subprocess.call([sys.executable, '-c',
128 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
129 env=env)
130 self.assertEqual(rc, 1)
131
Tarek Ziadé764fc232009-08-20 21:23:13 +0000132 def test_getuserbase(self):
133 site.USER_BASE = None
134 user_base = site.getuserbase()
135
136 # the call sets site.USER_BASE
137 self.assertEquals(site.USER_BASE, user_base)
138
139 # let's set PYTHONUSERBASE and see if it uses it
140 site.USER_BASE = None
141 with EnvironmentVarGuard() as environ:
142 environ['PYTHONUSERBASE'] = 'xoxo'
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000143 self.assertTrue(site.getuserbase().startswith('xoxo'),
144 site.getuserbase())
Tarek Ziadé764fc232009-08-20 21:23:13 +0000145
146 def test_getusersitepackages(self):
147 site.USER_SITE = None
148 site.USER_BASE = None
149 user_site = site.getusersitepackages()
150
151 # the call sets USER_BASE *and* USER_SITE
152 self.assertEquals(site.USER_SITE, user_site)
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000153 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
Tarek Ziadé764fc232009-08-20 21:23:13 +0000154
155 def test_getsitepackages(self):
156 site.PREFIXES = ['xoxo']
157 dirs = site.getsitepackages()
158
159 if sys.platform in ('os2emx', 'riscos'):
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000160 self.assertEqual(len(dirs), 1)
Tarek Ziadé764fc232009-08-20 21:23:13 +0000161 wanted = os.path.join('xoxo', 'Lib', 'site-packages')
162 self.assertEquals(dirs[0], wanted)
163 elif os.sep == '/':
164 self.assertTrue(len(dirs), 2)
165 wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
166 'site-packages')
167 self.assertEquals(dirs[0], wanted)
168 wanted = os.path.join('xoxo', 'lib', 'site-python')
169 self.assertEquals(dirs[1], wanted)
170 else:
171 self.assertTrue(len(dirs), 2)
172 self.assertEquals(dirs[0], 'xoxo')
Tarek Ziadéd24cab82009-10-27 21:20:27 +0000173 wanted = os.path.join('xoxo', 'lib', 'site-packages')
Tarek Ziadé764fc232009-08-20 21:23:13 +0000174 self.assertEquals(dirs[1], wanted)
175
176 # let's try the specific Apple location
177 if sys.platform == "darwin":
178 site.PREFIXES = ['Python.framework']
179 dirs = site.getsitepackages()
Antoine Pitroud8b16ab2009-11-01 23:54:20 +0000180 self.assertEqual(len(dirs), 4)
Tarek Ziadé764fc232009-08-20 21:23:13 +0000181 wanted = os.path.join('~', 'Library', 'Python',
182 sys.version[:3], 'site-packages')
183 self.assertEquals(dirs[2], os.path.expanduser(wanted))
184 wanted = os.path.join('/Library', 'Python', sys.version[:3],
185 'site-packages')
186 self.assertEquals(dirs[3], wanted)
Christian Heimesaf748c32008-05-06 22:41:46 +0000187
Brett Cannon64a84702004-07-10 02:10:45 +0000188class PthFile(object):
189 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000190
Brett Cannon64a84702004-07-10 02:10:45 +0000191 def __init__(self, filename_base=TESTFN, imported="time",
192 good_dirname="__testdir__", bad_dirname="__bad"):
193 """Initialize instance variables"""
194 self.filename = filename_base + ".pth"
195 self.base_dir = os.path.abspath('')
196 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000197 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000198 self.good_dirname = good_dirname
199 self.bad_dirname = bad_dirname
200 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
201 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000202
Brett Cannon64a84702004-07-10 02:10:45 +0000203 def create(self):
204 """Create a .pth file with a comment, blank lines, an ``import
205 <self.imported>``, a line with self.good_dirname, and a line with
206 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000207
Brett Cannon64a84702004-07-10 02:10:45 +0000208 Creation of the directory for self.good_dir_path (based off of
209 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000210
Brett Cannon64a84702004-07-10 02:10:45 +0000211 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000212
Brett Cannon64a84702004-07-10 02:10:45 +0000213 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000214 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000215 try:
216 print>>FILE, "#import @bad module name"
217 print>>FILE, "\n"
218 print>>FILE, "import %s" % self.imported
219 print>>FILE, self.good_dirname
220 print>>FILE, self.bad_dirname
221 finally:
222 FILE.close()
223 os.mkdir(self.good_dir_path)
224
Brett Cannonee86a662004-07-13 07:12:25 +0000225 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000226 """Make sure that the .pth file is deleted, self.imported is not in
227 sys.modules, and that both self.good_dirname and self.bad_dirname are
228 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000229 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000230 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000231 if prep:
232 self.imported_module = sys.modules.get(self.imported)
233 if self.imported_module:
234 del sys.modules[self.imported]
235 else:
236 if self.imported_module:
237 sys.modules[self.imported] = self.imported_module
238 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000239 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000240 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000241 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000242
243class ImportSideEffectTests(unittest.TestCase):
244 """Test side-effects from importing 'site'."""
245
246 def setUp(self):
247 """Make a copy of sys.path"""
248 self.sys_path = sys.path[:]
249
250 def tearDown(self):
251 """Restore sys.path"""
Nick Coghlana0e0f9e2009-10-17 16:19:51 +0000252 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000253
254 def test_abs__file__(self):
255 # Make sure all imported modules have their __file__ attribute
256 # as an absolute path.
257 # Handled by abs__file__()
258 site.abs__file__()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000259 for module in (sys, os, __builtin__):
Brett Cannon0096e262004-06-05 01:12:51 +0000260 try:
Senthil Kumaran3ddc4352010-01-08 18:41:40 +0000261 self.assertTrue(os.path.isabs(module.__file__), repr(module))
Brett Cannon0096e262004-06-05 01:12:51 +0000262 except AttributeError:
263 continue
Raymond Hettingerebd95222004-06-27 03:02:18 +0000264 # We could try everything in sys.modules; however, when regrtest.py
265 # runs something like test_frozen before test_site, then we will
266 # be testing things loaded *after* test_site did path normalization
Brett Cannon0096e262004-06-05 01:12:51 +0000267
268 def test_no_duplicate_paths(self):
269 # No duplicate paths should exist in sys.path
270 # Handled by removeduppaths()
271 site.removeduppaths()
272 seen_paths = set()
273 for path in sys.path:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000274 self.assertTrue(path not in seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000275 seen_paths.add(path)
276
277 def test_add_build_dir(self):
278 # Test that the build directory's Modules directory is used when it
279 # should be.
280 # XXX: implement
281 pass
282
Brett Cannon0096e262004-06-05 01:12:51 +0000283 def test_setting_quit(self):
284 # 'quit' and 'exit' should be injected into __builtin__
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000285 self.assertTrue(hasattr(__builtin__, "quit"))
286 self.assertTrue(hasattr(__builtin__, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000287
288 def test_setting_copyright(self):
289 # 'copyright' and 'credits' should be in __builtin__
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000290 self.assertTrue(hasattr(__builtin__, "copyright"))
291 self.assertTrue(hasattr(__builtin__, "credits"))
Brett Cannon0096e262004-06-05 01:12:51 +0000292
293 def test_setting_help(self):
294 # 'help' should be set in __builtin__
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000295 self.assertTrue(hasattr(__builtin__, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000296
297 def test_aliasing_mbcs(self):
298 if sys.platform == "win32":
299 import locale
300 if locale.getdefaultlocale()[1].startswith('cp'):
301 for value in encodings.aliases.aliases.itervalues():
302 if value == "mbcs":
303 break
304 else:
305 self.fail("did not alias mbcs")
306
307 def test_setdefaultencoding_removed(self):
308 # Make sure sys.setdefaultencoding is gone
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000309 self.assertTrue(not hasattr(sys, "setdefaultencoding"))
Brett Cannon0096e262004-06-05 01:12:51 +0000310
311 def test_sitecustomize_executed(self):
312 # If sitecustomize is available, it should have been imported.
Senthil Kumaran3ddc4352010-01-08 18:41:40 +0000313 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000314 try:
315 import sitecustomize
316 except ImportError:
317 pass
318 else:
319 self.fail("sitecustomize not imported automatically")
320
Brett Cannon0096e262004-06-05 01:12:51 +0000321def test_main():
322 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
323
Brett Cannon0096e262004-06-05 01:12:51 +0000324if __name__ == "__main__":
325 test_main()