test_site.py 16 KB

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