blob: 7ed0ee24d489f199a1c2766ebfca60d062dd80e8 [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[:]
38
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +000039 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000040 """Restore sys.path"""
41 sys.path = self.sys_path
Raymond Hettingerebd95222004-06-27 03:02:18 +000042
Brett Cannon0096e262004-06-05 01:12:51 +000043 def test_makepath(self):
44 # Test makepath() have an absolute path for its first return value
45 # and a case-normalized version of the absolute path for its
46 # second value.
47 path_parts = ("Beginning", "End")
48 original_dir = os.path.join(*path_parts)
49 abs_dir, norm_dir = site.makepath(*path_parts)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000050 self.assertEqual(os.path.abspath(original_dir), abs_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000051 if original_dir == os.path.normcase(original_dir):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000052 self.assertEqual(abs_dir, norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000053 else:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000054 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
Brett Cannon0096e262004-06-05 01:12:51 +000055
56 def test_init_pathinfo(self):
57 dir_set = site._init_pathinfo()
58 for entry in [site.makepath(path)[1] for path in sys.path
59 if path and os.path.isdir(path)]:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000060 self.assertTrue(entry in dir_set,
Brett Cannon0096e262004-06-05 01:12:51 +000061 "%s from sys.path not found in set returned "
62 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000063
Brett Cannonee86a662004-07-13 07:12:25 +000064 def pth_file_tests(self, pth_file):
65 """Contain common code for testing results of reading a .pth file"""
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000066 self.assertTrue(pth_file.imported in sys.modules,
Brett Cannonee86a662004-07-13 07:12:25 +000067 "%s not in sys.path" % pth_file.imported)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000068 self.assertTrue(site.makepath(pth_file.good_dir_path)[0] in sys.path)
69 self.assertTrue(not os.path.exists(pth_file.bad_dir_path))
Brett Cannonee86a662004-07-13 07:12:25 +000070
Brett Cannon0096e262004-06-05 01:12:51 +000071 def test_addpackage(self):
72 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000073 # adds directories to sys.path for any line in the file that is not a
74 # comment or import that is a valid directory name for where the .pth
75 # file resides; invalid directories are not added
76 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000077 pth_file.cleanup(prep=True) # to make sure that nothing is
78 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000079 try:
Brett Cannon64a84702004-07-10 02:10:45 +000080 pth_file.create()
81 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +000082 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000083 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000084 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +000085
Brett Cannon0096e262004-06-05 01:12:51 +000086 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +000087 # Same tests for test_addpackage since addsitedir() essentially just
88 # calls addpackage() for every .pth file in the directory
89 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000090 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
91 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +000092 try:
Brett Cannonee86a662004-07-13 07:12:25 +000093 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +000094 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +000095 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000096 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000097 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +000098
Christian Heimes8dc226f2008-05-06 23:45:46 +000099 def test_s_option(self):
100 usersite = site.USER_SITE
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000101 self.assertTrue(usersite in sys.path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000102
103 rc = subprocess.call([sys.executable, '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000104 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimes8dc226f2008-05-06 23:45:46 +0000105 self.assertEqual(rc, 1)
106
107 rc = subprocess.call([sys.executable, '-s', '-c',
Benjamin Petersonfea6a942008-07-02 16:11:42 +0000108 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimes8dc226f2008-05-06 23:45:46 +0000109 self.assertEqual(rc, 0)
110
111 env = os.environ.copy()
112 env["PYTHONNOUSERSITE"] = "1"
113 rc = subprocess.call([sys.executable, '-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 env=env)
116 self.assertEqual(rc, 0)
117
118 env = os.environ.copy()
119 env["PYTHONUSERBASE"] = "/tmp"
120 rc = subprocess.call([sys.executable, '-c',
121 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
122 env=env)
123 self.assertEqual(rc, 1)
124
125
Brett Cannon64a84702004-07-10 02:10:45 +0000126class PthFile(object):
127 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000128
Brett Cannon64a84702004-07-10 02:10:45 +0000129 def __init__(self, filename_base=TESTFN, imported="time",
130 good_dirname="__testdir__", bad_dirname="__bad"):
131 """Initialize instance variables"""
132 self.filename = filename_base + ".pth"
133 self.base_dir = os.path.abspath('')
134 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000135 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000136 self.good_dirname = good_dirname
137 self.bad_dirname = bad_dirname
138 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
139 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000140
Brett Cannon64a84702004-07-10 02:10:45 +0000141 def create(self):
142 """Create a .pth file with a comment, blank lines, an ``import
143 <self.imported>``, a line with self.good_dirname, and a line with
144 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000145
Brett Cannon64a84702004-07-10 02:10:45 +0000146 Creation of the directory for self.good_dir_path (based off of
147 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000148
Brett Cannon64a84702004-07-10 02:10:45 +0000149 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000150
Brett Cannon64a84702004-07-10 02:10:45 +0000151 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000152 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000153 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000154 print("#import @bad module name", file=FILE)
155 print("\n", file=FILE)
156 print("import %s" % self.imported, file=FILE)
157 print(self.good_dirname, file=FILE)
158 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000159 finally:
160 FILE.close()
161 os.mkdir(self.good_dir_path)
162
Brett Cannonee86a662004-07-13 07:12:25 +0000163 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000164 """Make sure that the .pth file is deleted, self.imported is not in
165 sys.modules, and that both self.good_dirname and self.bad_dirname are
166 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000167 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000168 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000169 if prep:
170 self.imported_module = sys.modules.get(self.imported)
171 if self.imported_module:
172 del sys.modules[self.imported]
173 else:
174 if self.imported_module:
175 sys.modules[self.imported] = self.imported_module
176 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000177 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000178 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000179 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000180
181class ImportSideEffectTests(unittest.TestCase):
182 """Test side-effects from importing 'site'."""
183
184 def setUp(self):
185 """Make a copy of sys.path"""
186 self.sys_path = sys.path[:]
187
188 def tearDown(self):
189 """Restore sys.path"""
190 sys.path = self.sys_path
191
192 def test_abs__file__(self):
193 # Make sure all imported modules have their __file__ attribute
194 # as an absolute path.
195 # Handled by abs__file__()
196 site.abs__file__()
Georg Brandl1a3284e2007-12-02 09:40:06 +0000197 for module in (sys, os, builtins):
Brett Cannon0096e262004-06-05 01:12:51 +0000198 try:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000199 self.assertTrue(os.path.isabs(module.__file__), repr(module))
Brett Cannon0096e262004-06-05 01:12:51 +0000200 except AttributeError:
201 continue
Raymond Hettingerebd95222004-06-27 03:02:18 +0000202 # We could try everything in sys.modules; however, when regrtest.py
203 # runs something like test_frozen before test_site, then we will
204 # be testing things loaded *after* test_site did path normalization
Brett Cannon0096e262004-06-05 01:12:51 +0000205
206 def test_no_duplicate_paths(self):
207 # No duplicate paths should exist in sys.path
208 # Handled by removeduppaths()
209 site.removeduppaths()
210 seen_paths = set()
211 for path in sys.path:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000212 self.assertTrue(path not in seen_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000213 seen_paths.add(path)
214
215 def test_add_build_dir(self):
216 # Test that the build directory's Modules directory is used when it
217 # should be.
218 # XXX: implement
219 pass
220
Brett Cannon0096e262004-06-05 01:12:51 +0000221 def test_setting_quit(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000222 # 'quit' and 'exit' should be injected into builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000223 self.assertTrue(hasattr(builtins, "quit"))
224 self.assertTrue(hasattr(builtins, "exit"))
Brett Cannon0096e262004-06-05 01:12:51 +0000225
226 def test_setting_copyright(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000227 # 'copyright' and 'credits' should be in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000228 self.assertTrue(hasattr(builtins, "copyright"))
229 self.assertTrue(hasattr(builtins, "credits"))
Brett Cannon0096e262004-06-05 01:12:51 +0000230
231 def test_setting_help(self):
Georg Brandl1a3284e2007-12-02 09:40:06 +0000232 # 'help' should be set in builtins
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000233 self.assertTrue(hasattr(builtins, "help"))
Brett Cannon0096e262004-06-05 01:12:51 +0000234
235 def test_aliasing_mbcs(self):
236 if sys.platform == "win32":
237 import locale
238 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000239 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000240 if value == "mbcs":
241 break
242 else:
243 self.fail("did not alias mbcs")
244
245 def test_setdefaultencoding_removed(self):
246 # Make sure sys.setdefaultencoding is gone
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000247 self.assertTrue(not hasattr(sys, "setdefaultencoding"))
Brett Cannon0096e262004-06-05 01:12:51 +0000248
249 def test_sitecustomize_executed(self):
250 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000251 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000252 try:
253 import sitecustomize
254 except ImportError:
255 pass
256 else:
257 self.fail("sitecustomize not imported automatically")
258
Brett Cannon0096e262004-06-05 01:12:51 +0000259def test_main():
260 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
261
Brett Cannon0096e262004-06-05 01:12:51 +0000262if __name__ == "__main__":
263 test_main()