blob: c9957df498d8b02aa2ff00e0e7aeaeaf945ef357 [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
Christian Heimesc5f05e42008-02-23 17:40:11 +00008from test.test_support import TestSkipped, run_unittest, TESTFN
Brett Cannon0096e262004-06-05 01:12:51 +00009import __builtin__
10import os
11import sys
12import encodings
Brett Cannon0096e262004-06-05 01:12:51 +000013# Need to make sure to not import 'site' if someone specified ``-S`` at the
14# command-line. Detect this by just making sure 'site' has not been imported
15# already.
16if "site" in sys.modules:
17 import site
18else:
19 raise TestSkipped("importation of site.py suppressed")
20
21class HelperFunctionsTests(unittest.TestCase):
22 """Tests for helper functions.
Raymond Hettingerebd95222004-06-27 03:02:18 +000023
Brett Cannon0096e262004-06-05 01:12:51 +000024 The setting of the encoding (set using sys.setdefaultencoding) used by
25 the Unicode implementation is not tested.
Raymond Hettingerebd95222004-06-27 03:02:18 +000026
Brett Cannon0096e262004-06-05 01:12:51 +000027 """
28
29 def setUp(self):
30 """Save a copy of sys.path"""
31 self.sys_path = sys.path[:]
32
33 def tearDown(self):
34 """Restore sys.path"""
35 sys.path = self.sys_path
Raymond Hettingerebd95222004-06-27 03:02:18 +000036
Brett Cannon0096e262004-06-05 01:12:51 +000037 def test_makepath(self):
38 # Test makepath() have an absolute path for its first return value
39 # and a case-normalized version of the absolute path for its
40 # second value.
41 path_parts = ("Beginning", "End")
42 original_dir = os.path.join(*path_parts)
43 abs_dir, norm_dir = site.makepath(*path_parts)
44 self.failUnlessEqual(os.path.abspath(original_dir), abs_dir)
45 if original_dir == os.path.normcase(original_dir):
46 self.failUnlessEqual(abs_dir, norm_dir)
47 else:
48 self.failUnlessEqual(os.path.normcase(abs_dir), norm_dir)
49
50 def test_init_pathinfo(self):
51 dir_set = site._init_pathinfo()
52 for entry in [site.makepath(path)[1] for path in sys.path
53 if path and os.path.isdir(path)]:
54 self.failUnless(entry in dir_set,
55 "%s from sys.path not found in set returned "
56 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000057
Brett Cannonee86a662004-07-13 07:12:25 +000058 def pth_file_tests(self, pth_file):
59 """Contain common code for testing results of reading a .pth file"""
60 self.failUnless(pth_file.imported in sys.modules,
61 "%s not in sys.path" % pth_file.imported)
62 self.failUnless(site.makepath(pth_file.good_dir_path)[0] in sys.path)
63 self.failUnless(not os.path.exists(pth_file.bad_dir_path))
64
Brett Cannon0096e262004-06-05 01:12:51 +000065 def test_addpackage(self):
66 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000067 # adds directories to sys.path for any line in the file that is not a
68 # comment or import that is a valid directory name for where the .pth
69 # file resides; invalid directories are not added
70 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000071 pth_file.cleanup(prep=True) # to make sure that nothing is
72 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000073 try:
Brett Cannon64a84702004-07-10 02:10:45 +000074 pth_file.create()
75 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +000076 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000077 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000078 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +000079
Brett Cannon0096e262004-06-05 01:12:51 +000080 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +000081 # Same tests for test_addpackage since addsitedir() essentially just
82 # calls addpackage() for every .pth file in the directory
83 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000084 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
85 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +000086 try:
Brett Cannonee86a662004-07-13 07:12:25 +000087 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +000088 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +000089 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000090 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000091 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +000092
Brett Cannon64a84702004-07-10 02:10:45 +000093class PthFile(object):
94 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +000095
Brett Cannon64a84702004-07-10 02:10:45 +000096 def __init__(self, filename_base=TESTFN, imported="time",
97 good_dirname="__testdir__", bad_dirname="__bad"):
98 """Initialize instance variables"""
99 self.filename = filename_base + ".pth"
100 self.base_dir = os.path.abspath('')
101 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000102 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000103 self.good_dirname = good_dirname
104 self.bad_dirname = bad_dirname
105 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
106 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000107
Brett Cannon64a84702004-07-10 02:10:45 +0000108 def create(self):
109 """Create a .pth file with a comment, blank lines, an ``import
110 <self.imported>``, a line with self.good_dirname, and a line with
111 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000112
Brett Cannon64a84702004-07-10 02:10:45 +0000113 Creation of the directory for self.good_dir_path (based off of
114 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000115
Brett Cannon64a84702004-07-10 02:10:45 +0000116 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000117
Brett Cannon64a84702004-07-10 02:10:45 +0000118 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000119 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000120 try:
121 print>>FILE, "#import @bad module name"
122 print>>FILE, "\n"
123 print>>FILE, "import %s" % self.imported
124 print>>FILE, self.good_dirname
125 print>>FILE, self.bad_dirname
126 finally:
127 FILE.close()
128 os.mkdir(self.good_dir_path)
129
Brett Cannonee86a662004-07-13 07:12:25 +0000130 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000131 """Make sure that the .pth file is deleted, self.imported is not in
132 sys.modules, and that both self.good_dirname and self.bad_dirname are
133 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000134 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000135 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000136 if prep:
137 self.imported_module = sys.modules.get(self.imported)
138 if self.imported_module:
139 del sys.modules[self.imported]
140 else:
141 if self.imported_module:
142 sys.modules[self.imported] = self.imported_module
143 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000144 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000145 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000146 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000147
148class ImportSideEffectTests(unittest.TestCase):
149 """Test side-effects from importing 'site'."""
150
151 def setUp(self):
152 """Make a copy of sys.path"""
153 self.sys_path = sys.path[:]
154
155 def tearDown(self):
156 """Restore sys.path"""
157 sys.path = self.sys_path
158
159 def test_abs__file__(self):
160 # Make sure all imported modules have their __file__ attribute
161 # as an absolute path.
162 # Handled by abs__file__()
163 site.abs__file__()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000164 for module in (sys, os, __builtin__):
Brett Cannon0096e262004-06-05 01:12:51 +0000165 try:
Raymond Hettingerebd95222004-06-27 03:02:18 +0000166 self.failUnless(os.path.isabs(module.__file__), `module`)
Brett Cannon0096e262004-06-05 01:12:51 +0000167 except AttributeError:
168 continue
Raymond Hettingerebd95222004-06-27 03:02:18 +0000169 # We could try everything in sys.modules; however, when regrtest.py
170 # runs something like test_frozen before test_site, then we will
171 # be testing things loaded *after* test_site did path normalization
Brett Cannon0096e262004-06-05 01:12:51 +0000172
173 def test_no_duplicate_paths(self):
174 # No duplicate paths should exist in sys.path
175 # Handled by removeduppaths()
176 site.removeduppaths()
177 seen_paths = set()
178 for path in sys.path:
179 self.failUnless(path not in seen_paths)
180 seen_paths.add(path)
181
182 def test_add_build_dir(self):
183 # Test that the build directory's Modules directory is used when it
184 # should be.
185 # XXX: implement
186 pass
187
Brett Cannon0096e262004-06-05 01:12:51 +0000188 def test_setting_quit(self):
189 # 'quit' and 'exit' should be injected into __builtin__
190 self.failUnless(hasattr(__builtin__, "quit"))
191 self.failUnless(hasattr(__builtin__, "exit"))
192
193 def test_setting_copyright(self):
194 # 'copyright' and 'credits' should be in __builtin__
195 self.failUnless(hasattr(__builtin__, "copyright"))
196 self.failUnless(hasattr(__builtin__, "credits"))
197
198 def test_setting_help(self):
199 # 'help' should be set in __builtin__
200 self.failUnless(hasattr(__builtin__, "help"))
201
202 def test_aliasing_mbcs(self):
203 if sys.platform == "win32":
204 import locale
205 if locale.getdefaultlocale()[1].startswith('cp'):
206 for value in encodings.aliases.aliases.itervalues():
207 if value == "mbcs":
208 break
209 else:
210 self.fail("did not alias mbcs")
211
212 def test_setdefaultencoding_removed(self):
213 # Make sure sys.setdefaultencoding is gone
214 self.failUnless(not hasattr(sys, "setdefaultencoding"))
215
216 def test_sitecustomize_executed(self):
217 # If sitecustomize is available, it should have been imported.
218 if not sys.modules.has_key("sitecustomize"):
219 try:
220 import sitecustomize
221 except ImportError:
222 pass
223 else:
224 self.fail("sitecustomize not imported automatically")
225
226
227
228
229def test_main():
230 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
231
232
233
234if __name__ == "__main__":
235 test_main()