blob: 343f8ef64be9c4475c9b7988911ac56fc9a2028f [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
R. David Murray6cb252f2010-12-26 22:24:54 +00009from test.support import captured_output
Georg Brandl1a3284e2007-12-02 09:40:06 +000010import builtins
Brett Cannon0096e262004-06-05 01:12:51 +000011import os
12import sys
13import encodings
Christian Heimes8dc226f2008-05-06 23:45:46 +000014import subprocess
Brett Cannon0096e262004-06-05 01:12:51 +000015# Need to make sure to not import 'site' if someone specified ``-S`` at the
16# command-line. Detect this by just making sure 'site' has not been imported
17# already.
18if "site" in sys.modules:
19 import site
20else:
Benjamin Petersone549ead2009-03-28 21:42:05 +000021 raise unittest.SkipTest("importation of site.py suppressed")
Brett Cannon0096e262004-06-05 01:12:51 +000022
Christian Heimes8dc226f2008-05-06 23:45:46 +000023if not os.path.isdir(site.USER_SITE):
24 # need to add user site directory for tests
25 os.makedirs(site.USER_SITE)
26 site.addsitedir(site.USER_SITE)
27
Brett Cannon0096e262004-06-05 01:12:51 +000028class HelperFunctionsTests(unittest.TestCase):
29 """Tests for helper functions.
Raymond Hettingerebd95222004-06-27 03:02:18 +000030
Brett Cannon0096e262004-06-05 01:12:51 +000031 The setting of the encoding (set using sys.setdefaultencoding) used by
32 the Unicode implementation is not tested.
Raymond Hettingerebd95222004-06-27 03:02:18 +000033
Brett Cannon0096e262004-06-05 01:12:51 +000034 """
35
36 def setUp(self):
37 """Save a copy of sys.path"""
38 self.sys_path = sys.path[:]
39
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000040 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000041 """Restore sys.path"""
42 sys.path = self.sys_path
Raymond Hettingerebd95222004-06-27 03:02:18 +000043
Brett Cannon0096e262004-06-05 01:12:51 +000044 def test_makepath(self):
45 # Test makepath() have an absolute path for its first return value
46 # and a case-normalized version of the absolute path for its
47 # second value.
48 path_parts = ("Beginning", "End")
49 original_dir = os.path.join(*path_parts)
50 abs_dir, norm_dir = site.makepath(*path_parts)
Georg Brandlab91fde2009-08-13 08:51:18 +000051 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000052 if original_dir == os.path.normcase(original_dir):
Georg Brandlab91fde2009-08-13 08:51:18 +000053 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000054 else:
Georg Brandlab91fde2009-08-13 08:51:18 +000055 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000056
57 def test_init_pathinfo(self):
58 dir_set = site._init_pathinfo()
59 for entry in [site.makepath(path)[1] for path in sys.path
60 if path and os.path.isdir(path)]:
Georg Brandlab91fde2009-08-13 08:51:18 +000061 self.assertTrue(entry in dir_set,
Brett Cannon0096e262004-06-05 01:12:51 +000062 "%s from sys.path not found in set returned "
63 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000064
Brett Cannonee86a662004-07-13 07:12:25 +000065 def pth_file_tests(self, pth_file):
66 """Contain common code for testing results of reading a .pth file"""
Georg Brandlab91fde2009-08-13 08:51:18 +000067 self.assertTrue(pth_file.imported in sys.modules,
Brett Cannonee86a662004-07-13 07:12:25 +000068 "%s not in sys.path" % pth_file.imported)
Georg Brandlab91fde2009-08-13 08:51:18 +000069 self.assertTrue(site.makepath(pth_file.good_dir_path)[0] in sys.path)
70 self.assertTrue(not os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +000071
Brett Cannon0096e262004-06-05 01:12:51 +000072 def test_addpackage(self):
73 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000074 # adds directories to sys.path for any line in the file that is not a
75 # comment or import that is a valid directory name for where the .pth
76 # file resides; invalid directories are not added
77 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000078 pth_file.cleanup(prep=True) # to make sure that nothing is
79 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000080 try:
Brett Cannon64a84702004-07-10 02:10:45 +000081 pth_file.create()
82 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +000083 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000084 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000085 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +000086
R. David Murray6cb252f2010-12-26 22:24:54 +000087 def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
88 # Create a .pth file and return its (abspath, basename).
89 pth_dir = os.path.abspath(pth_dir)
90 pth_basename = pth_name + '.pth'
91 pth_fn = os.path.join(pth_dir, pth_basename)
92 pth_file = open(pth_fn, 'w', encoding='utf-8')
93 self.addCleanup(lambda: os.remove(pth_fn))
94 pth_file.write(contents)
95 pth_file.close()
96 return pth_dir, pth_basename
97
98 def test_addpackage_import_bad_syntax(self):
99 # Issue 10642
100 pth_dir, pth_fn = self.make_pth("import bad)syntax\n")
101 with captured_output("stderr") as err_out:
102 site.addpackage(pth_dir, pth_fn, set())
103 self.assertRegexpMatches(err_out.getvalue(), "line 1")
104 self.assertRegexpMatches(err_out.getvalue(), os.path.join(pth_dir, pth_fn))
105 # XXX: the previous two should be independent checks so that the
106 # order doesn't matter. The next three could be a single check
107 # but my regex foo isn't good enough to write it.
108 self.assertRegexpMatches(err_out.getvalue(), 'Traceback')
109 self.assertRegexpMatches(err_out.getvalue(), r'import bad\)syntax')
110 self.assertRegexpMatches(err_out.getvalue(), 'SyntaxError')
111
112 def test_addpackage_import_bad_exec(self):
113 # Issue 10642
114 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
115 with captured_output("stderr") as err_out:
116 site.addpackage(pth_dir, pth_fn, set())
117 self.assertRegexpMatches(err_out.getvalue(), "line 2")
118 self.assertRegexpMatches(err_out.getvalue(), os.path.join(pth_dir, pth_fn))
119 # XXX: ditto previous XXX comment.
120 self.assertRegexpMatches(err_out.getvalue(), 'Traceback')
121 self.assertRegexpMatches(err_out.getvalue(), 'ImportError')
122
123 def test_addpackage_import_bad_pth_file(self):
124 # Issue 5258
125 pth_dir, pth_fn = self.make_pth("abc\x00def\n")
126 with captured_output("stderr") as err_out:
127 site.addpackage(pth_dir, pth_fn, set())
128 self.assertRegexpMatches(err_out.getvalue(), "line 1")
129 self.assertRegexpMatches(err_out.getvalue(), os.path.join(pth_dir, pth_fn))
130 # XXX: ditto previous XXX comment.
131 self.assertRegexpMatches(err_out.getvalue(), 'Traceback')
132 self.assertRegexpMatches(err_out.getvalue(), 'TypeError')
133
Brett Cannon0096e262004-06-05 01:12:51 +0000134 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +0000135 # Same tests for test_addpackage since addsitedir() essentially just
136 # calls addpackage() for every .pth file in the directory
137 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +0000138 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
139 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +0000140 try:
Brett Cannonee86a662004-07-13 07:12:25 +0000141 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +0000142 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +0000143 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +0000144 finally:
Brett Cannon64a84702004-07-10 02:10:45 +0000145 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +0000146
Christian Heimes8dc226f2008-05-06 23:45:46 +0000147 def test_s_option(self):
148 usersite = site.USER_SITE
Georg Brandlab91fde2009-08-13 08:51:18 +0000149 self.assertTrue(usersite in sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000150
151 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000152 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimes8dc226f2008-05-06 23:45:46 +0000153 self.assertEqual(rc, 1)
154
155 rc = subprocess.call([sys.executable, '-s', '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000156 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimes8dc226f2008-05-06 23:45:46 +0000157 self.assertEqual(rc, 0)
158
159 env = os.environ.copy()
160 env["PYTHONNOUSERSITE"] = "1"
161 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000162 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000163 env=env)
164 self.assertEqual(rc, 0)
165
166 env = os.environ.copy()
167 env["PYTHONUSERBASE"] = "/tmp"
168 rc = subprocess.call([sys.executable, '-c',
169 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
170 env=env)
171 self.assertEqual(rc, 1)
172
173
Brett Cannon64a84702004-07-10 02:10:45 +0000174class PthFile(object):
175 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000176
Brett Cannon64a84702004-07-10 02:10:45 +0000177 def __init__(self, filename_base=TESTFN, imported="time",
178 good_dirname="__testdir__", bad_dirname="__bad"):
179 """Initialize instance variables"""
180 self.filename = filename_base + ".pth"
181 self.base_dir = os.path.abspath('')
182 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000183 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000184 self.good_dirname = good_dirname
185 self.bad_dirname = bad_dirname
186 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
187 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000188
Brett Cannon64a84702004-07-10 02:10:45 +0000189 def create(self):
190 """Create a .pth file with a comment, blank lines, an ``import
191 <self.imported>``, a line with self.good_dirname, and a line with
192 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000193
Brett Cannon64a84702004-07-10 02:10:45 +0000194 Creation of the directory for self.good_dir_path (based off of
195 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000196
Brett Cannon64a84702004-07-10 02:10:45 +0000197 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000198
Brett Cannon64a84702004-07-10 02:10:45 +0000199 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000200 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000201 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000202 print("#import @bad module name", file=FILE)
203 print("\n", file=FILE)
204 print("import %s" % self.imported, file=FILE)
205 print(self.good_dirname, file=FILE)
206 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000207 finally:
208 FILE.close()
209 os.mkdir(self.good_dir_path)
210
Brett Cannonee86a662004-07-13 07:12:25 +0000211 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000212 """Make sure that the .pth file is deleted, self.imported is not in
213 sys.modules, and that both self.good_dirname and self.bad_dirname are
214 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000215 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000216 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000217 if prep:
218 self.imported_module = sys.modules.get(self.imported)
219 if self.imported_module:
220 del sys.modules[self.imported]
221 else:
222 if self.imported_module:
223 sys.modules[self.imported] = self.imported_module
224 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000225 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000226 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000227 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000228
229class ImportSideEffectTests(unittest.TestCase):
230 """Test side-effects from importing 'site'."""
231
232 def setUp(self):
233 """Make a copy of sys.path"""
234 self.sys_path = sys.path[:]
235
236 def tearDown(self):
237 """Restore sys.path"""
238 sys.path = self.sys_path
239
240 def test_abs__file__(self):
241 # Make sure all imported modules have their __file__ attribute
242 # as an absolute path.
243 # Handled by abs__file__()
244 site.abs__file__()
Georg Brandl1a3284e2007-12-02 09:40:06 +0000245 for module in (sys, os, builtins):
Brett Cannon0096e262004-06-05 01:12:51 +0000246 try:
Georg Brandlab91fde2009-08-13 08:51:18 +0000247 self.assertTrue(os.path.isabs(module.__file__), repr(module))
Brett Cannon0096e262004-06-05 01:12:51 +0000248 except AttributeError:
249 continue
Raymond Hettingerebd95222004-06-27 03:02:18 +0000250 # We could try everything in sys.modules; however, when regrtest.py
251 # runs something like test_frozen before test_site, then we will
252 # be testing things loaded *after* test_site did path normalization
Brett Cannon0096e262004-06-05 01:12:51 +0000253
254 def test_no_duplicate_paths(self):
255 # No duplicate paths should exist in sys.path
256 # Handled by removeduppaths()
257 site.removeduppaths()
258 seen_paths = set()
259 for path in sys.path:
Georg Brandlab91fde2009-08-13 08:51:18 +0000260 self.assertTrue(path not in seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000261 seen_paths.add(path)
262
263 def test_add_build_dir(self):
264 # Test that the build directory's Modules directory is used when it
265 # should be.
266 # XXX: implement
267 pass
268
Brett Cannon0096e262004-06-05 01:12:51 +0000269 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000270 # 'quit' and 'exit' should be injected into builtins
Georg Brandlab91fde2009-08-13 08:51:18 +0000271 self.assertTrue(hasattr(builtins, "quit"))
272 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000273
274 def test_setting_copyright(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000275 # 'copyright' and 'credits' should be in builtins
Georg Brandlab91fde2009-08-13 08:51:18 +0000276 self.assertTrue(hasattr(builtins, "copyright"))
277 self.assertTrue(hasattr(builtins, "credits"))
Brett Cannon0096e262004-06-05 01:12:51 +0000278
279 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000280 # 'help' should be set in builtins
Georg Brandlab91fde2009-08-13 08:51:18 +0000281 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000282
283 def test_aliasing_mbcs(self):
284 if sys.platform == "win32":
285 import locale
286 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000287 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000288 if value == "mbcs":
289 break
290 else:
291 self.fail("did not alias mbcs")
292
293 def test_setdefaultencoding_removed(self):
294 # Make sure sys.setdefaultencoding is gone
Georg Brandlab91fde2009-08-13 08:51:18 +0000295 self.assertTrue(not hasattr(sys, "setdefaultencoding"))
Brett Cannon0096e262004-06-05 01:12:51 +0000296
297 def test_sitecustomize_executed(self):
298 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000299 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000300 try:
301 import sitecustomize
302 except ImportError:
303 pass
304 else:
305 self.fail("sitecustomize not imported automatically")
306
Brett Cannon0096e262004-06-05 01:12:51 +0000307def test_main():
308 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
309
Brett Cannon0096e262004-06-05 01:12:51 +0000310if __name__ == "__main__":
311 test_main()