blob: ac516ed94ac959c4fb8a426e3b0d000da539f06a [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
Brett Cannon64a84702004-07-10 02:10:45 +00008from test.test_support import TestSkipped, TestFailed, run_unittest, TESTFN
Brett Cannon0096e262004-06-05 01:12:51 +00009import __builtin__
10import os
11import sys
12import encodings
13import tempfile
14# 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:
20 raise TestSkipped("importation of site.py suppressed")
21
22class HelperFunctionsTests(unittest.TestCase):
23 """Tests for helper functions.
Raymond Hettingerebd95222004-06-27 03:02:18 +000024
Brett Cannon0096e262004-06-05 01:12:51 +000025 The setting of the encoding (set using sys.setdefaultencoding) used by
26 the Unicode implementation is not tested.
Raymond Hettingerebd95222004-06-27 03:02:18 +000027
Brett Cannon0096e262004-06-05 01:12:51 +000028 """
29
30 def setUp(self):
31 """Save a copy of sys.path"""
32 self.sys_path = sys.path[:]
33
34 def tearDown(self):
35 """Restore sys.path"""
36 sys.path = self.sys_path
Raymond Hettingerebd95222004-06-27 03:02:18 +000037
Brett Cannon0096e262004-06-05 01:12:51 +000038 def test_makepath(self):
39 # Test makepath() have an absolute path for its first return value
40 # and a case-normalized version of the absolute path for its
41 # second value.
42 path_parts = ("Beginning", "End")
43 original_dir = os.path.join(*path_parts)
44 abs_dir, norm_dir = site.makepath(*path_parts)
45 self.failUnlessEqual(os.path.abspath(original_dir), abs_dir)
46 if original_dir == os.path.normcase(original_dir):
47 self.failUnlessEqual(abs_dir, norm_dir)
48 else:
49 self.failUnlessEqual(os.path.normcase(abs_dir), norm_dir)
50
51 def test_init_pathinfo(self):
52 dir_set = site._init_pathinfo()
53 for entry in [site.makepath(path)[1] for path in sys.path
54 if path and os.path.isdir(path)]:
55 self.failUnless(entry in dir_set,
56 "%s from sys.path not found in set returned "
57 "by _init_pathinfo(): %s" % (entry, dir_set))
Raymond Hettingerebd95222004-06-27 03:02:18 +000058
Brett Cannon0096e262004-06-05 01:12:51 +000059 def test_addpackage(self):
60 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000061 # adds directories to sys.path for any line in the file that is not a
62 # comment or import that is a valid directory name for where the .pth
63 # file resides; invalid directories are not added
64 pth_file = PthFile()
65 pth_file.cleanup() # to make sure that nothing is pre-existing that
66 # shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000067 try:
Brett Cannon64a84702004-07-10 02:10:45 +000068 pth_file.create()
69 site.addpackage(pth_file.base_dir, pth_file.filename, set())
70 unittest.FunctionTestCase(pth_file.test)
Brett Cannon0096e262004-06-05 01:12:51 +000071 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000072 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +000073
Brett Cannon0096e262004-06-05 01:12:51 +000074 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +000075 # Same tests for test_addpackage since addsitedir() essentially just
76 # calls addpackage() for every .pth file in the directory
77 pth_file = PthFile()
78 pth_file.cleanup() # Make sure that nothing is pre-existing that is
79 # tested for
Brett Cannon0096e262004-06-05 01:12:51 +000080 try:
Brett Cannon64a84702004-07-10 02:10:45 +000081 site.addsitedir(pth_file.base_dir, set())
82 unittest.FunctionTestCase(pth_file.test)
Brett Cannon0096e262004-06-05 01:12:51 +000083 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000084 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +000085
Brett Cannon64a84702004-07-10 02:10:45 +000086class PthFile(object):
87 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +000088
Brett Cannon64a84702004-07-10 02:10:45 +000089 def __init__(self, filename_base=TESTFN, imported="time",
90 good_dirname="__testdir__", bad_dirname="__bad"):
91 """Initialize instance variables"""
92 self.filename = filename_base + ".pth"
93 self.base_dir = os.path.abspath('')
94 self.file_path = os.path.join(self.base_dir, self.filename)
95 self.imported = "time"
96 self.good_dirname = good_dirname
97 self.bad_dirname = bad_dirname
98 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
99 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000100
Brett Cannon64a84702004-07-10 02:10:45 +0000101 def create(self):
102 """Create a .pth file with a comment, blank lines, an ``import
103 <self.imported>``, a line with self.good_dirname, and a line with
104 self.bad_dirname.
105
106 Creation of the directory for self.good_dir_path (based off of
107 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000108
Brett Cannon64a84702004-07-10 02:10:45 +0000109 Make sure to call self.cleanup() to undo anything done by this method.
110
111 """
112 FILE = open(self.file_path, 'wU')
113 try:
114 print>>FILE, "#import @bad module name"
115 print>>FILE, "\n"
116 print>>FILE, "import %s" % self.imported
117 print>>FILE, self.good_dirname
118 print>>FILE, self.bad_dirname
119 finally:
120 FILE.close()
121 os.mkdir(self.good_dir_path)
122
123 def cleanup(self):
124 """Make sure that the .pth file is deleted, self.imported is not in
125 sys.modules, and that both self.good_dirname and self.bad_dirname are
126 not existing directories."""
127 try:
128 os.remove(self.file_path)
129 except OSError:
130 pass
131 try:
132 del sys.modules[self.imported]
133 except KeyError:
134 pass
135 try:
136 os.rmdir(self.good_dir_path)
137 except OSError:
138 pass
139 try:
140 os.rmdir(self.bad_dir_path)
141 except OSError:
142 pass
143
144 def test(self):
145 """Test to make sure that was and was not supposed to be created by
146 using the .pth file occurred"""
147 assert site.makepath(self.good_dir_path)[0] in sys.path
148 assert self.imported in sys.modules
149 assert not os.path.exists(self.bad_dir_path)
150
Brett Cannon0096e262004-06-05 01:12:51 +0000151
152class ImportSideEffectTests(unittest.TestCase):
153 """Test side-effects from importing 'site'."""
154
155 def setUp(self):
156 """Make a copy of sys.path"""
157 self.sys_path = sys.path[:]
158
159 def tearDown(self):
160 """Restore sys.path"""
161 sys.path = self.sys_path
162
163 def test_abs__file__(self):
164 # Make sure all imported modules have their __file__ attribute
165 # as an absolute path.
166 # Handled by abs__file__()
167 site.abs__file__()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000168 for module in (sys, os, __builtin__):
Brett Cannon0096e262004-06-05 01:12:51 +0000169 try:
Raymond Hettingerebd95222004-06-27 03:02:18 +0000170 self.failUnless(os.path.isabs(module.__file__), `module`)
Brett Cannon0096e262004-06-05 01:12:51 +0000171 except AttributeError:
172 continue
Raymond Hettingerebd95222004-06-27 03:02:18 +0000173 # We could try everything in sys.modules; however, when regrtest.py
174 # runs something like test_frozen before test_site, then we will
175 # be testing things loaded *after* test_site did path normalization
Brett Cannon0096e262004-06-05 01:12:51 +0000176
177 def test_no_duplicate_paths(self):
178 # No duplicate paths should exist in sys.path
179 # Handled by removeduppaths()
180 site.removeduppaths()
181 seen_paths = set()
182 for path in sys.path:
183 self.failUnless(path not in seen_paths)
184 seen_paths.add(path)
185
186 def test_add_build_dir(self):
187 # Test that the build directory's Modules directory is used when it
188 # should be.
189 # XXX: implement
190 pass
191
Brett Cannon0096e262004-06-05 01:12:51 +0000192 def test_setting_quit(self):
193 # 'quit' and 'exit' should be injected into __builtin__
194 self.failUnless(hasattr(__builtin__, "quit"))
195 self.failUnless(hasattr(__builtin__, "exit"))
196
197 def test_setting_copyright(self):
198 # 'copyright' and 'credits' should be in __builtin__
199 self.failUnless(hasattr(__builtin__, "copyright"))
200 self.failUnless(hasattr(__builtin__, "credits"))
201
202 def test_setting_help(self):
203 # 'help' should be set in __builtin__
204 self.failUnless(hasattr(__builtin__, "help"))
205
206 def test_aliasing_mbcs(self):
207 if sys.platform == "win32":
208 import locale
209 if locale.getdefaultlocale()[1].startswith('cp'):
210 for value in encodings.aliases.aliases.itervalues():
211 if value == "mbcs":
212 break
213 else:
214 self.fail("did not alias mbcs")
215
216 def test_setdefaultencoding_removed(self):
217 # Make sure sys.setdefaultencoding is gone
218 self.failUnless(not hasattr(sys, "setdefaultencoding"))
219
220 def test_sitecustomize_executed(self):
221 # If sitecustomize is available, it should have been imported.
222 if not sys.modules.has_key("sitecustomize"):
223 try:
224 import sitecustomize
225 except ImportError:
226 pass
227 else:
228 self.fail("sitecustomize not imported automatically")
229
230
231
232
233def test_main():
234 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
235
236
237
238if __name__ == "__main__":
239 test_main()