Debian Codegraph @

cpython27/Lib/test/test_site.py

raw symbols SCIP
1 """Tests for 'site'.
2
3 Tests assume the initial paths in sys.path once the interpreter has begun
4 executing have not been removed.
5
6 """
7 import unittest
8 from test.test_support import run_unittest, TESTFN, EnvironmentVarGuard
9 from test.test_support import captured_output
10 from test import support
11 import __builtin__
12 import errno
13 import os
14 import sys
15 import re
16 import encodings
17 import subprocess
18 import sysconfig
19 from copy import copy
20
21 # Need to make sure to not import 'site' if someone specified ``-S`` at the
22 # command-line. Detect this by just making sure 'site' has not been imported
23 # already.
24 if "site" in sys.modules:
25 import site
26 else:
27 raise unittest.SkipTest("importation of site.py suppressed")
28
29
30 OLD_SYS_PATH = None
31
32
33 def setUpModule():
34 global OLD_SYS_PATH
35 OLD_SYS_PATH = sys.path[:]
36
37 if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
38 # need to add user site directory for tests
39 try:
40 os.makedirs(site.USER_SITE)
41 # modify sys.path: will be restored by tearDownModule()
42 site.addsitedir(site.USER_SITE)
43 except OSError as exc:
44 if exc.errno in (errno.EACCES, errno.EPERM):
45 raise unittest.SkipTest('unable to create user site directory (%r): %s'
46 % (site.USER_SITE, exc))
47 else:
48 raise
49
50
51 def tearDownModule():
52 sys.path[:] = OLD_SYS_PATH
53
54
55 class HelperFunctionsTests(unittest.TestCase):
56 """Tests for helper functions.
57
58 The setting of the encoding (set using sys.setdefaultencoding) used by
59 the Unicode implementation is not tested.
60
61 """
62
63 def setUp(self):
64 """Save a copy of sys.path"""
65 self.sys_path = sys.path[:]
66 self.old_base = site.USER_BASE
67 self.old_site = site.USER_SITE
68 self.old_prefixes = site.PREFIXES
69 self.old_vars = copy(sysconfig._CONFIG_VARS)
70
71 def tearDown(self):
72 """Restore sys.path"""
73 sys.path[:] = self.sys_path
74 site.USER_BASE = self.old_base
75 site.USER_SITE = self.old_site
76 site.PREFIXES = self.old_prefixes
77 sysconfig._CONFIG_VARS = self.old_vars
78
79 def test_makepath(self):
80 # Test makepath() have an absolute path for its first return value
81 # and a case-normalized version of the absolute path for its
82 # second value.
83 path_parts = ("Beginning", "End")
84 original_dir = os.path.join(*path_parts)
85 abs_dir, norm_dir = site.makepath(*path_parts)
86 self.assertEqual(os.path.abspath(original_dir), abs_dir)
87 if original_dir == os.path.normcase(original_dir):
88 self.assertEqual(abs_dir, norm_dir)
89 else:
90 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
91
92 def test_init_pathinfo(self):
93 dir_set = site._init_pathinfo()
94 for entry in [site.makepath(path)[1] for path in sys.path
95 if path and os.path.isdir(path)]:
96 self.assertIn(entry, dir_set,
97 "%s from sys.path not found in set returned "
98 "by _init_pathinfo(): %s" % (entry, dir_set))
99
100 def pth_file_tests(self, pth_file):
101 """Contain common code for testing results of reading a .pth file"""
102 self.assertIn(pth_file.imported, sys.modules,
103 "%s not in sys.modules" % pth_file.imported)
104 self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
105 self.assertFalse(os.path.exists(pth_file.bad_dir_path))
106
107 def test_addpackage(self):
108 # Make sure addpackage() imports if the line starts with 'import',
109 # adds directories to sys.path for any line in the file that is not a
110 # comment or import that is a valid directory name for where the .pth
111 # file resides; invalid directories are not added
112 pth_file = PthFile()
113 pth_file.cleanup(prep=True) # to make sure that nothing is
114 # pre-existing that shouldn't be
115 try:
116 pth_file.create()
117 site.addpackage(pth_file.base_dir, pth_file.filename, set())
118 self.pth_file_tests(pth_file)
119 finally:
120 pth_file.cleanup()
121
122 def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
123 # Create a .pth file and return its (abspath, basename).
124 pth_dir = os.path.abspath(pth_dir)
125 pth_basename = pth_name + '.pth'
126 pth_fn = os.path.join(pth_dir, pth_basename)
127 pth_file = open(pth_fn, 'w')
128 self.addCleanup(lambda: os.remove(pth_fn))
129 pth_file.write(contents)
130 pth_file.close()
131 return pth_dir, pth_basename
132
133 def test_addpackage_import_bad_syntax(self):
134 # Issue 10642
135 pth_dir, pth_fn = self.make_pth("import bad)syntax\n")
136 with captured_output("stderr") as err_out:
137 site.addpackage(pth_dir, pth_fn, set())
138 self.assertRegexpMatches(err_out.getvalue(), "line 1")
139 self.assertRegexpMatches(err_out.getvalue(),
140 re.escape(os.path.join(pth_dir, pth_fn)))
141 # XXX: the previous two should be independent checks so that the
142 # order doesn't matter. The next three could be a single check
143 # but my regex foo isn't good enough to write it.
144 self.assertRegexpMatches(err_out.getvalue(), 'Traceback')
145 self.assertRegexpMatches(err_out.getvalue(), r'import bad\)syntax')
146 self.assertRegexpMatches(err_out.getvalue(), 'SyntaxError')
147
148 def test_addpackage_import_bad_exec(self):
149 # Issue 10642
150 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
151 with captured_output("stderr") as err_out:
152 site.addpackage(pth_dir, pth_fn, set())
153 self.assertRegexpMatches(err_out.getvalue(), "line 2")
154 self.assertRegexpMatches(err_out.getvalue(),
155 re.escape(os.path.join(pth_dir, pth_fn)))
156 # XXX: ditto previous XXX comment.
157 self.assertRegexpMatches(err_out.getvalue(), 'Traceback')
158 self.assertRegexpMatches(err_out.getvalue(), 'ImportError')
159
160 @unittest.skipIf(sys.platform == "win32", "Windows does not raise an "
161 "error for file paths containing null characters")
162 def test_addpackage_import_bad_pth_file(self):
163 # Issue 5258
164 pth_dir, pth_fn = self.make_pth("abc\x00def\n")
165 with captured_output("stderr") as err_out:
166 site.addpackage(pth_dir, pth_fn, set())
167 self.assertRegexpMatches(err_out.getvalue(), "line 1")
168 self.assertRegexpMatches(err_out.getvalue(),
169 re.escape(os.path.join(pth_dir, pth_fn)))
170 # XXX: ditto previous XXX comment.
171 self.assertRegexpMatches(err_out.getvalue(), 'Traceback')
172 self.assertRegexpMatches(err_out.getvalue(), 'TypeError')
173
174 def test_addsitedir(self):
175 # Same tests for test_addpackage since addsitedir() essentially just
176 # calls addpackage() for every .pth file in the directory
177 pth_file = PthFile()
178 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
179 # that is tested for
180 try:
181 pth_file.create()
182 site.addsitedir(pth_file.base_dir, set())
183 self.pth_file_tests(pth_file)
184 finally:
185 pth_file.cleanup()
186
187 @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
188 "user-site (site.ENABLE_USER_SITE)")
189 def test_s_option(self):
190 usersite = site.USER_SITE
191 self.assertIn(usersite, sys.path)
192
193 env = os.environ.copy()
194 rc = subprocess.call([sys.executable, '-c',
195 'import sys; sys.exit(%r in sys.path)' % usersite],
196 env=env)
197 self.assertEqual(rc, 1, "%r is not in sys.path (sys.exit returned %r)"
198 % (usersite, rc))
199
200 env = os.environ.copy()
201 rc = subprocess.call([sys.executable, '-s', '-c',
202 'import sys; sys.exit(%r in sys.path)' % usersite],
203 env=env)
204 self.assertEqual(rc, 0)
205
206 env = os.environ.copy()
207 env["PYTHONNOUSERSITE"] = "1"
208 rc = subprocess.call([sys.executable, '-c',
209 'import sys; sys.exit(%r in sys.path)' % usersite],
210 env=env)
211 self.assertEqual(rc, 0)
212
213 env = os.environ.copy()
214 env["PYTHONUSERBASE"] = "/tmp"
215 rc = subprocess.call([sys.executable, '-c',
216 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
217 env=env)
218 self.assertEqual(rc, 1)
219
220 def test_getuserbase(self):
221 site.USER_BASE = None
222 user_base = site.getuserbase()
223
224 # the call sets site.USER_BASE
225 self.assertEqual(site.USER_BASE, user_base)
226
227 # let's set PYTHONUSERBASE and see if it uses it
228 site.USER_BASE = None
229 import sysconfig
230 sysconfig._CONFIG_VARS = None
231
232 with EnvironmentVarGuard() as environ:
233 environ['PYTHONUSERBASE'] = 'xoxo'
234 self.assertTrue(site.getuserbase().startswith('xoxo'),
235 site.getuserbase())
236
237 def test_getusersitepackages(self):
238 site.USER_SITE = None
239 site.USER_BASE = None
240 user_site = site.getusersitepackages()
241
242 # the call sets USER_BASE *and* USER_SITE
243 self.assertEqual(site.USER_SITE, user_site)
244 self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
245 self.assertEqual(site.USER_BASE, site.getuserbase())
246
247 def test_getsitepackages(self):
248 site.PREFIXES = ['xoxo']
249 dirs = site.getsitepackages()
250
251 if sys.platform in ('os2emx', 'riscos'):
252 self.assertEqual(len(dirs), 1)
253 wanted = os.path.join('xoxo', 'Lib', 'site-packages')
254 self.assertEqual(dirs[0], wanted)
255 elif os.sep == '/':
256 # OS X, Linux, FreeBSD, etc
257 self.assertEqual(len(dirs), 2)
258 wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
259 'site-packages')
260 self.assertEqual(dirs[0], wanted)
261 wanted = os.path.join('xoxo', 'lib', 'site-python')
262 self.assertEqual(dirs[1], wanted)
263 else:
264 # other platforms
265 self.assertEqual(len(dirs), 2)
266 self.assertEqual(dirs[0], 'xoxo')
267 wanted = os.path.join('xoxo', 'lib', 'site-packages')
268 self.assertEqual(dirs[1], wanted)
269
270 def test_no_home_directory(self):
271 # bpo-10496: getuserbase() and getusersitepackages() must not fail if
272 # the current user has no home directory (if expanduser() returns the
273 # path unchanged).
274 site.USER_SITE = None
275 site.USER_BASE = None
276 sysconfig._CONFIG_VARS = None
277
278 with EnvironmentVarGuard() as environ, \
279 support.swap_attr(os.path, 'expanduser', lambda path: path):
280
281 del environ['PYTHONUSERBASE']
282 del environ['APPDATA']
283
284 user_base = site.getuserbase()
285 self.assertTrue(user_base.startswith('~' + os.sep),
286 user_base)
287
288 user_site = site.getusersitepackages()
289 self.assertTrue(user_site.startswith(user_base), user_site)
290
291 def fake_isdir(path):
292 fake_isdir.arg = path
293 return False
294 fake_isdir.arg = None
295
296 def must_not_be_called(*args):
297 raise AssertionError
298
299 with support.swap_attr(os.path, 'isdir', fake_isdir), \
300 support.swap_attr(site, 'addsitedir', must_not_be_called), \
301 support.swap_attr(site, 'ENABLE_USER_SITE', True):
302
303 # addusersitepackages() must not add user_site to sys.path
304 # if it is not an existing directory
305 known_paths = set()
306 site.addusersitepackages(known_paths)
307
308 self.assertEqual(fake_isdir.arg, user_site)
309 self.assertFalse(known_paths)
310
311
312 class PthFile(object):
313 """Helper class for handling testing of .pth files"""
314
315 def __init__(self, filename_base=TESTFN, imported="time",
316 good_dirname="__testdir__", bad_dirname="__bad"):
317 """Initialize instance variables"""
318 self.filename = filename_base + ".pth"
319 self.base_dir = os.path.abspath('')
320 self.file_path = os.path.join(self.base_dir, self.filename)
321 self.imported = imported
322 self.good_dirname = good_dirname
323 self.bad_dirname = bad_dirname
324 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
325 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
326
327 def create(self):
328 """Create a .pth file with a comment, blank lines, an ``import
329 <self.imported>``, a line with self.good_dirname, and a line with
330 self.bad_dirname.
331
332 Creation of the directory for self.good_dir_path (based off of
333 self.good_dirname) is also performed.
334
335 Make sure to call self.cleanup() to undo anything done by this method.
336
337 """
338 FILE = open(self.file_path, 'w')
339 try:
340 print>>FILE, "#import @bad module name"
341 print>>FILE, "\n"
342 print>>FILE, "import %s" % self.imported
343 print>>FILE, self.good_dirname
344 print>>FILE, self.bad_dirname
345 finally:
346 FILE.close()
347 os.mkdir(self.good_dir_path)
348
349 def cleanup(self, prep=False):
350 """Make sure that the .pth file is deleted, self.imported is not in
351 sys.modules, and that both self.good_dirname and self.bad_dirname are
352 not existing directories."""
353 if os.path.exists(self.file_path):
354 os.remove(self.file_path)
355 if prep:
356 self.imported_module = sys.modules.get(self.imported)
357 if self.imported_module:
358 del sys.modules[self.imported]
359 else:
360 if self.imported_module:
361 sys.modules[self.imported] = self.imported_module
362 if os.path.exists(self.good_dir_path):
363 os.rmdir(self.good_dir_path)
364 if os.path.exists(self.bad_dir_path):
365 os.rmdir(self.bad_dir_path)
366
367 class ImportSideEffectTests(unittest.TestCase):
368 """Test side-effects from importing 'site'."""
369
370 def setUp(self):
371 """Make a copy of sys.path"""
372 self.sys_path = sys.path[:]
373
374 def tearDown(self):
375 """Restore sys.path"""
376 sys.path[:] = self.sys_path
377
378 def test_abs__file__(self):
379 # Make sure all imported modules have their __file__ attribute
380 # as an absolute path.
381 # Handled by abs__file__()
382 site.abs__file__()
383 for module in (sys, os, __builtin__):
384 try:
385 self.assertTrue(os.path.isabs(module.__file__), repr(module))
386 except AttributeError:
387 continue
388 # We could try everything in sys.modules; however, when regrtest.py
389 # runs something like test_frozen before test_site, then we will
390 # be testing things loaded *after* test_site did path normalization
391
392 def test_no_duplicate_paths(self):
393 # No duplicate paths should exist in sys.path
394 # Handled by removeduppaths()
395 site.removeduppaths()
396 seen_paths = set()
397 for path in sys.path:
398 self.assertNotIn(path, seen_paths)
399 seen_paths.add(path)
400
401 @unittest.skip('test not implemented')
402 def test_add_build_dir(self):
403 # Test that the build directory's Modules directory is used when it
404 # should be.
405 # XXX: implement
406 pass
407
408 def test_setting_quit(self):
409 # 'quit' and 'exit' should be injected into __builtin__
410 self.assertTrue(hasattr(__builtin__, "quit"))
411 self.assertTrue(hasattr(__builtin__, "exit"))
412
413 def test_setting_copyright(self):
414 # 'copyright' and 'credits' should be in __builtin__
415 self.assertTrue(hasattr(__builtin__, "copyright"))
416 self.assertTrue(hasattr(__builtin__, "credits"))
417
418 def test_setting_help(self):
419 # 'help' should be set in __builtin__
420 self.assertTrue(hasattr(__builtin__, "help"))
421
422 def test_aliasing_mbcs(self):
423 if sys.platform == "win32":
424 import locale
425 if locale.getdefaultlocale()[1].startswith('cp'):
426 for value in encodings.aliases.aliases.itervalues():
427 if value == "mbcs":
428 break
429 else:
430 self.fail("did not alias mbcs")
431
432 def test_setdefaultencoding_removed(self):
433 # Make sure sys.setdefaultencoding is gone
434 self.assertTrue(not hasattr(sys, "setdefaultencoding"))
435
436 def test_sitecustomize_executed(self):
437 # If sitecustomize is available, it should have been imported.
438 if "sitecustomize" not in sys.modules:
439 try:
440 import sitecustomize
441 except ImportError:
442 pass
443 else:
444 self.fail("sitecustomize not imported automatically")
445
446 def test_main():
447 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
448
449 if __name__ == "__main__":
450 test_main()