move sections
[python/dscho.git] / Lib / test / test_site.py
blob192f58a664ebeb8776d6ff1f71b4765b6e8980a4
1 """Tests for 'site'.
3 Tests assume the initial paths in sys.path once the interpreter has begun
4 executing have not been removed.
6 """
7 import unittest
8 from test.test_support import run_unittest, TESTFN, EnvironmentVarGuard
9 import __builtin__
10 import os
11 import sys
12 import encodings
13 import subprocess
14 import sysconfig
15 from copy import copy
17 # 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.
20 if "site" in sys.modules:
21 import site
22 else:
23 raise unittest.SkipTest("importation of site.py suppressed")
25 if 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)
30 class HelperFunctionsTests(unittest.TestCase):
31 """Tests for helper functions.
33 The setting of the encoding (set using sys.setdefaultencoding) used by
34 the Unicode implementation is not tested.
36 """
38 def setUp(self):
39 """Save a copy of sys.path"""
40 self.sys_path = sys.path[:]
41 self.old_base = site.USER_BASE
42 self.old_site = site.USER_SITE
43 self.old_prefixes = site.PREFIXES
44 self.old_vars = copy(sysconfig._CONFIG_VARS)
46 def tearDown(self):
47 """Restore sys.path"""
48 sys.path[:] = self.sys_path
49 site.USER_BASE = self.old_base
50 site.USER_SITE = self.old_site
51 site.PREFIXES = self.old_prefixes
52 sysconfig._CONFIG_VARS = self.old_vars
54 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)
61 self.assertEqual(os.path.abspath(original_dir), abs_dir)
62 if original_dir == os.path.normcase(original_dir):
63 self.assertEqual(abs_dir, norm_dir)
64 else:
65 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
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)]:
71 self.assertIn(entry, dir_set,
72 "%s from sys.path not found in set returned "
73 "by _init_pathinfo(): %s" % (entry, dir_set))
75 def pth_file_tests(self, pth_file):
76 """Contain common code for testing results of reading a .pth file"""
77 self.assertIn(pth_file.imported, sys.modules,
78 "%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))
82 def test_addpackage(self):
83 # Make sure addpackage() imports if the line starts with 'import',
84 # 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()
88 pth_file.cleanup(prep=True) # to make sure that nothing is
89 # pre-existing that shouldn't be
90 try:
91 pth_file.create()
92 site.addpackage(pth_file.base_dir, pth_file.filename, set())
93 self.pth_file_tests(pth_file)
94 finally:
95 pth_file.cleanup()
97 def test_addsitedir(self):
98 # Same tests for test_addpackage since addsitedir() essentially just
99 # calls addpackage() for every .pth file in the directory
100 pth_file = PthFile()
101 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
102 # that is tested for
103 try:
104 pth_file.create()
105 site.addsitedir(pth_file.base_dir, set())
106 self.pth_file_tests(pth_file)
107 finally:
108 pth_file.cleanup()
110 def test_s_option(self):
111 usersite = site.USER_SITE
112 self.assertIn(usersite, sys.path)
114 rc = subprocess.call([sys.executable, '-c',
115 'import sys; sys.exit(%r in sys.path)' % usersite])
116 self.assertEqual(rc, 1, "%r is not in sys.path (sys.exit returned %r)"
117 % (usersite, rc))
119 rc = subprocess.call([sys.executable, '-s', '-c',
120 'import sys; sys.exit(%r in sys.path)' % usersite])
121 self.assertEqual(rc, 0)
123 env = os.environ.copy()
124 env["PYTHONNOUSERSITE"] = "1"
125 rc = subprocess.call([sys.executable, '-c',
126 'import sys; sys.exit(%r in sys.path)' % usersite],
127 env=env)
128 self.assertEqual(rc, 0)
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)
137 def test_getuserbase(self):
138 site.USER_BASE = None
139 user_base = site.getuserbase()
141 # the call sets site.USER_BASE
142 self.assertEquals(site.USER_BASE, user_base)
144 # let's set PYTHONUSERBASE and see if it uses it
145 site.USER_BASE = None
146 import sysconfig
147 sysconfig._CONFIG_VARS = None
149 with EnvironmentVarGuard() as environ:
150 environ['PYTHONUSERBASE'] = 'xoxo'
151 self.assertTrue(site.getuserbase().startswith('xoxo'),
152 site.getuserbase())
154 def test_getusersitepackages(self):
155 site.USER_SITE = None
156 site.USER_BASE = None
157 user_site = site.getusersitepackages()
159 # the call sets USER_BASE *and* USER_SITE
160 self.assertEquals(site.USER_SITE, user_site)
161 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
163 def test_getsitepackages(self):
164 site.PREFIXES = ['xoxo']
165 dirs = site.getsitepackages()
167 if sys.platform in ('os2emx', 'riscos'):
168 self.assertEqual(len(dirs), 1)
169 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')
181 wanted = os.path.join('xoxo', 'lib', 'site-packages')
182 self.assertEquals(dirs[1], wanted)
184 # let's try the specific Apple location
185 if (sys.platform == "darwin" and
186 sysconfig.get_config_var("PYTHONFRAMEWORK")):
187 site.PREFIXES = ['Python.framework']
188 dirs = site.getsitepackages()
189 self.assertEqual(len(dirs), 4)
190 wanted = os.path.join('~', 'Library', 'Python',
191 sys.version[:3], 'site-packages')
192 self.assertEquals(dirs[2], os.path.expanduser(wanted))
193 wanted = os.path.join('/Library', 'Python', sys.version[:3],
194 'site-packages')
195 self.assertEquals(dirs[3], wanted)
197 class PthFile(object):
198 """Helper class for handling testing of .pth files"""
200 def __init__(self, filename_base=TESTFN, imported="time",
201 good_dirname="__testdir__", bad_dirname="__bad"):
202 """Initialize instance variables"""
203 self.filename = filename_base + ".pth"
204 self.base_dir = os.path.abspath('')
205 self.file_path = os.path.join(self.base_dir, self.filename)
206 self.imported = imported
207 self.good_dirname = good_dirname
208 self.bad_dirname = bad_dirname
209 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
210 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
212 def create(self):
213 """Create a .pth file with a comment, blank lines, an ``import
214 <self.imported>``, a line with self.good_dirname, and a line with
215 self.bad_dirname.
217 Creation of the directory for self.good_dir_path (based off of
218 self.good_dirname) is also performed.
220 Make sure to call self.cleanup() to undo anything done by this method.
223 FILE = open(self.file_path, 'w')
224 try:
225 print>>FILE, "#import @bad module name"
226 print>>FILE, "\n"
227 print>>FILE, "import %s" % self.imported
228 print>>FILE, self.good_dirname
229 print>>FILE, self.bad_dirname
230 finally:
231 FILE.close()
232 os.mkdir(self.good_dir_path)
234 def cleanup(self, prep=False):
235 """Make sure that the .pth file is deleted, self.imported is not in
236 sys.modules, and that both self.good_dirname and self.bad_dirname are
237 not existing directories."""
238 if os.path.exists(self.file_path):
239 os.remove(self.file_path)
240 if prep:
241 self.imported_module = sys.modules.get(self.imported)
242 if self.imported_module:
243 del sys.modules[self.imported]
244 else:
245 if self.imported_module:
246 sys.modules[self.imported] = self.imported_module
247 if os.path.exists(self.good_dir_path):
248 os.rmdir(self.good_dir_path)
249 if os.path.exists(self.bad_dir_path):
250 os.rmdir(self.bad_dir_path)
252 class ImportSideEffectTests(unittest.TestCase):
253 """Test side-effects from importing 'site'."""
255 def setUp(self):
256 """Make a copy of sys.path"""
257 self.sys_path = sys.path[:]
259 def tearDown(self):
260 """Restore sys.path"""
261 sys.path[:] = self.sys_path
263 def test_abs__file__(self):
264 # Make sure all imported modules have their __file__ attribute
265 # as an absolute path.
266 # Handled by abs__file__()
267 site.abs__file__()
268 for module in (sys, os, __builtin__):
269 try:
270 self.assertTrue(os.path.isabs(module.__file__), repr(module))
271 except AttributeError:
272 continue
273 # We could try everything in sys.modules; however, when regrtest.py
274 # runs something like test_frozen before test_site, then we will
275 # be testing things loaded *after* test_site did path normalization
277 def test_no_duplicate_paths(self):
278 # No duplicate paths should exist in sys.path
279 # Handled by removeduppaths()
280 site.removeduppaths()
281 seen_paths = set()
282 for path in sys.path:
283 self.assertNotIn(path, seen_paths)
284 seen_paths.add(path)
286 def test_add_build_dir(self):
287 # Test that the build directory's Modules directory is used when it
288 # should be.
289 # XXX: implement
290 pass
292 def test_setting_quit(self):
293 # 'quit' and 'exit' should be injected into __builtin__
294 self.assertTrue(hasattr(__builtin__, "quit"))
295 self.assertTrue(hasattr(__builtin__, "exit"))
297 def test_setting_copyright(self):
298 # 'copyright' and 'credits' should be in __builtin__
299 self.assertTrue(hasattr(__builtin__, "copyright"))
300 self.assertTrue(hasattr(__builtin__, "credits"))
302 def test_setting_help(self):
303 # 'help' should be set in __builtin__
304 self.assertTrue(hasattr(__builtin__, "help"))
306 def test_aliasing_mbcs(self):
307 if sys.platform == "win32":
308 import locale
309 if locale.getdefaultlocale()[1].startswith('cp'):
310 for value in encodings.aliases.aliases.itervalues():
311 if value == "mbcs":
312 break
313 else:
314 self.fail("did not alias mbcs")
316 def test_setdefaultencoding_removed(self):
317 # Make sure sys.setdefaultencoding is gone
318 self.assertTrue(not hasattr(sys, "setdefaultencoding"))
320 def test_sitecustomize_executed(self):
321 # If sitecustomize is available, it should have been imported.
322 if "sitecustomize" not in sys.modules:
323 try:
324 import sitecustomize
325 except ImportError:
326 pass
327 else:
328 self.fail("sitecustomize not imported automatically")
330 def test_main():
331 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
333 if __name__ == "__main__":
334 test_main()