blob: 6935798a3fe49b93bcc424fcd7e3f6b3918db967 [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
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 Petersone549ead2009-03-28 21:42:05 +000020 raise unittest.SkipTest("importation of site.py suppressed")
Brett Cannon0096e262004-06-05 01:12:51 +000021
Christian Heimes8dc226f2008-05-06 23:45: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é4a608c02009-08-20 21:28:05 +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
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000042 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000043 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +000044 sys.path[:] = self.sys_path
Tarek Ziadé4a608c02009-08-20 21:28:05 +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 Petersonc9c0f202009-06-30 23:06:06 +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 Petersonc9c0f202009-06-30 23:06:06 +000058 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000059 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +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 Petersonc9c0f202009-06-30 23:06:06 +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 Petersonc9c0f202009-06-30 23:06:06 +000072 self.assertTrue(pth_file.imported in sys.modules,
Brett Cannonee86a662004-07-13 07:12:25 +000073 "%s not in sys.path" % pth_file.imported)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000074 self.assertTrue(site.makepath(pth_file.good_dir_path)[0] in sys.path)
75 self.assertTrue(not 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 Heimes8dc226f2008-05-06 23:45:46 +0000105 def test_s_option(self):
106 usersite = site.USER_SITE
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000107 self.assertTrue(usersite in sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000108
109 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000110 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimes8dc226f2008-05-06 23:45:46 +0000111 self.assertEqual(rc, 1)
112
113 rc = subprocess.call([sys.executable, '-s', '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000114 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimes8dc226f2008-05-06 23:45:46 +0000115 self.assertEqual(rc, 0)
116
117 env = os.environ.copy()
118 env["PYTHONNOUSERSITE"] = "1"
119 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000120 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000121 env=env)
122 self.assertEqual(rc, 0)
123
124 env = os.environ.copy()
125 env["PYTHONUSERBASE"] = "/tmp"
126 rc = subprocess.call([sys.executable, '-c',
127 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
128 env=env)
129 self.assertEqual(rc, 1)
130
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000131 def test_getuserbase(self):
132 site.USER_BASE = None
133 user_base = site.getuserbase()
134
135 # the call sets site.USER_BASE
136 self.assertEquals(site.USER_BASE, user_base)
137
138 # let's set PYTHONUSERBASE and see if it uses it
139 site.USER_BASE = None
140 with EnvironmentVarGuard() as environ:
141 environ['PYTHONUSERBASE'] = 'xoxo'
142 self.assertTrue(site.getuserbase().startswith('xoxo'))
143
144 def test_getusersitepackages(self):
145 site.USER_SITE = None
146 site.USER_BASE = None
147 user_site = site.getusersitepackages()
148
149 # the call sets USER_BASE *and* USER_SITE
150 self.assertEquals(site.USER_SITE, user_site)
151 self.assertTrue(user_site.startswith(site.USER_BASE))
152
153 def test_getsitepackages(self):
154 site.PREFIXES = ['xoxo']
155 dirs = site.getsitepackages()
156
157 if sys.platform in ('os2emx', 'riscos'):
158 self.assertTrue(len(dirs), 1)
159 wanted = os.path.join('xoxo', 'Lib', 'site-packages')
160 self.assertEquals(dirs[0], wanted)
161 elif os.sep == '/':
162 self.assertTrue(len(dirs), 2)
163 wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
164 'site-packages')
165 self.assertEquals(dirs[0], wanted)
166 wanted = os.path.join('xoxo', 'lib', 'site-python')
167 self.assertEquals(dirs[1], wanted)
168 else:
169 self.assertTrue(len(dirs), 2)
170 self.assertEquals(dirs[0], 'xoxo')
171 wanted = os.path.join('xoxo', 'Lib', 'site-packages')
172 self.assertEquals(dirs[1], wanted)
173
174 # let's try the specific Apple location
175 if sys.platform == "darwin":
176 site.PREFIXES = ['Python.framework']
177 dirs = site.getsitepackages()
178 self.assertTrue(len(dirs), 4)
179 wanted = os.path.join('~', 'Library', 'Python',
180 sys.version[:3], 'site-packages')
181 self.assertEquals(dirs[2], os.path.expanduser(wanted))
182 wanted = os.path.join('/Library', 'Python', sys.version[:3],
183 'site-packages')
184 self.assertEquals(dirs[3], wanted)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000185
Brett Cannon64a84702004-07-10 02:10:45 +0000186class PthFile(object):
187 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000188
Brett Cannon64a84702004-07-10 02:10:45 +0000189 def __init__(self, filename_base=TESTFN, imported="time",
190 good_dirname="__testdir__", bad_dirname="__bad"):
191 """Initialize instance variables"""
192 self.filename = filename_base + ".pth"
193 self.base_dir = os.path.abspath('')
194 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000195 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000196 self.good_dirname = good_dirname
197 self.bad_dirname = bad_dirname
198 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
199 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000200
Brett Cannon64a84702004-07-10 02:10:45 +0000201 def create(self):
202 """Create a .pth file with a comment, blank lines, an ``import
203 <self.imported>``, a line with self.good_dirname, and a line with
204 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000205
Brett Cannon64a84702004-07-10 02:10:45 +0000206 Creation of the directory for self.good_dir_path (based off of
207 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000208
Brett Cannon64a84702004-07-10 02:10:45 +0000209 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000210
Brett Cannon64a84702004-07-10 02:10:45 +0000211 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000212 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000213 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000214 print("#import @bad module name", file=FILE)
215 print("\n", file=FILE)
216 print("import %s" % self.imported, file=FILE)
217 print(self.good_dirname, file=FILE)
218 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000219 finally:
220 FILE.close()
221 os.mkdir(self.good_dir_path)
222
Brett Cannonee86a662004-07-13 07:12:25 +0000223 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000224 """Make sure that the .pth file is deleted, self.imported is not in
225 sys.modules, and that both self.good_dirname and self.bad_dirname are
226 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000227 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000228 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000229 if prep:
230 self.imported_module = sys.modules.get(self.imported)
231 if self.imported_module:
232 del sys.modules[self.imported]
233 else:
234 if self.imported_module:
235 sys.modules[self.imported] = self.imported_module
236 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000237 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000238 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000239 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000240
241class ImportSideEffectTests(unittest.TestCase):
242 """Test side-effects from importing 'site'."""
243
244 def setUp(self):
245 """Make a copy of sys.path"""
246 self.sys_path = sys.path[:]
247
248 def tearDown(self):
249 """Restore sys.path"""
Nick Coghlan6ead5522009-10-18 13:19:33 +0000250 sys.path[:] = self.sys_path
Brett Cannon0096e262004-06-05 01:12:51 +0000251
252 def test_abs__file__(self):
253 # Make sure all imported modules have their __file__ attribute
254 # as an absolute path.
255 # Handled by abs__file__()
256 site.abs__file__()
Georg Brandl1a3284e2007-12-02 09:40:06 +0000257 for module in (sys, os, builtins):
Brett Cannon0096e262004-06-05 01:12:51 +0000258 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000259 self.assertTrue(os.path.isabs(module.__file__), repr(module))
Brett Cannon0096e262004-06-05 01:12:51 +0000260 except AttributeError:
261 continue
Raymond Hettingerebd95222004-06-27 03:02:18 +0000262 # We could try everything in sys.modules; however, when regrtest.py
263 # runs something like test_frozen before test_site, then we will
264 # be testing things loaded *after* test_site did path normalization
Brett Cannon0096e262004-06-05 01:12:51 +0000265
266 def test_no_duplicate_paths(self):
267 # No duplicate paths should exist in sys.path
268 # Handled by removeduppaths()
269 site.removeduppaths()
270 seen_paths = set()
271 for path in sys.path:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000272 self.assertTrue(path not in seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000273 seen_paths.add(path)
274
275 def test_add_build_dir(self):
276 # Test that the build directory's Modules directory is used when it
277 # should be.
278 # XXX: implement
279 pass
280
Brett Cannon0096e262004-06-05 01:12:51 +0000281 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000282 # 'quit' and 'exit' should be injected into builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000283 self.assertTrue(hasattr(builtins, "quit"))
284 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000285
286 def test_setting_copyright(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000287 # 'copyright' and 'credits' should be in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000288 self.assertTrue(hasattr(builtins, "copyright"))
289 self.assertTrue(hasattr(builtins, "credits"))
Brett Cannon0096e262004-06-05 01:12:51 +0000290
291 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000292 # 'help' should be set in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000293 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000294
295 def test_aliasing_mbcs(self):
296 if sys.platform == "win32":
297 import locale
298 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000299 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000300 if value == "mbcs":
301 break
302 else:
303 self.fail("did not alias mbcs")
304
305 def test_setdefaultencoding_removed(self):
306 # Make sure sys.setdefaultencoding is gone
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000307 self.assertTrue(not hasattr(sys, "setdefaultencoding"))
Brett Cannon0096e262004-06-05 01:12:51 +0000308
309 def test_sitecustomize_executed(self):
310 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000311 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000312 try:
313 import sitecustomize
314 except ImportError:
315 pass
316 else:
317 self.fail("sitecustomize not imported automatically")
318
Brett Cannon0096e262004-06-05 01:12:51 +0000319def test_main():
320 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
321
Brett Cannon0096e262004-06-05 01:12:51 +0000322if __name__ == "__main__":
323 test_main()