blob: 11bb674a34778bf044022f276787902a9547a370 [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 Cannonee86a662004-07-13 07:12:25 +000059 def pth_file_tests(self, pth_file):
60 """Contain common code for testing results of reading a .pth file"""
61 self.failUnless(pth_file.imported in sys.modules,
62 "%s not in sys.path" % pth_file.imported)
63 self.failUnless(site.makepath(pth_file.good_dir_path)[0] in sys.path)
64 self.failUnless(not os.path.exists(pth_file.bad_dir_path))
65
Brett Cannon0096e262004-06-05 01:12:51 +000066 def test_addpackage(self):
67 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000068 # adds directories to sys.path for any line in the file that is not a
69 # comment or import that is a valid directory name for where the .pth
70 # file resides; invalid directories are not added
71 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000072 pth_file.cleanup(prep=True) # to make sure that nothing is
73 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000074 try:
Brett Cannon64a84702004-07-10 02:10:45 +000075 pth_file.create()
76 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +000077 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000078 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000079 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +000080
Brett Cannon0096e262004-06-05 01:12:51 +000081 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +000082 # Same tests for test_addpackage since addsitedir() essentially just
83 # calls addpackage() for every .pth file in the directory
84 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000085 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
86 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +000087 try:
Brett Cannonee86a662004-07-13 07:12:25 +000088 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +000089 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +000090 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000091 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000092 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +000093
Brett Cannon64a84702004-07-10 02:10:45 +000094class PthFile(object):
95 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +000096
Brett Cannon64a84702004-07-10 02:10:45 +000097 def __init__(self, filename_base=TESTFN, imported="time",
98 good_dirname="__testdir__", bad_dirname="__bad"):
99 """Initialize instance variables"""
100 self.filename = filename_base + ".pth"
101 self.base_dir = os.path.abspath('')
102 self.file_path = os.path.join(self.base_dir, self.filename)
Brett Cannonee86a662004-07-13 07:12:25 +0000103 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000104 self.good_dirname = good_dirname
105 self.bad_dirname = bad_dirname
106 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
107 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
Brett Cannon0096e262004-06-05 01:12:51 +0000108
Brett Cannon64a84702004-07-10 02:10:45 +0000109 def create(self):
110 """Create a .pth file with a comment, blank lines, an ``import
111 <self.imported>``, a line with self.good_dirname, and a line with
112 self.bad_dirname.
Tim Peters182b5ac2004-07-18 06:16:08 +0000113
Brett Cannon64a84702004-07-10 02:10:45 +0000114 Creation of the directory for self.good_dir_path (based off of
115 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000116
Brett Cannon64a84702004-07-10 02:10:45 +0000117 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000118
Brett Cannon64a84702004-07-10 02:10:45 +0000119 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000120 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000121 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000122 print("#import @bad module name", file=FILE)
123 print("\n", file=FILE)
124 print("import %s" % self.imported, file=FILE)
125 print(self.good_dirname, file=FILE)
126 print(self.bad_dirname, file=FILE)
Brett Cannon64a84702004-07-10 02:10:45 +0000127 finally:
128 FILE.close()
129 os.mkdir(self.good_dir_path)
130
Brett Cannonee86a662004-07-13 07:12:25 +0000131 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000132 """Make sure that the .pth file is deleted, self.imported is not in
133 sys.modules, and that both self.good_dirname and self.bad_dirname are
134 not existing directories."""
Brett Cannonee86a662004-07-13 07:12:25 +0000135 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000136 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000137 if prep:
138 self.imported_module = sys.modules.get(self.imported)
139 if self.imported_module:
140 del sys.modules[self.imported]
141 else:
142 if self.imported_module:
143 sys.modules[self.imported] = self.imported_module
144 if os.path.exists(self.good_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000145 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000146 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000147 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000148
149class ImportSideEffectTests(unittest.TestCase):
150 """Test side-effects from importing 'site'."""
151
152 def setUp(self):
153 """Make a copy of sys.path"""
154 self.sys_path = sys.path[:]
155
156 def tearDown(self):
157 """Restore sys.path"""
158 sys.path = self.sys_path
159
160 def test_abs__file__(self):
161 # Make sure all imported modules have their __file__ attribute
162 # as an absolute path.
163 # Handled by abs__file__()
164 site.abs__file__()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000165 for module in (sys, os, __builtin__):
Brett Cannon0096e262004-06-05 01:12:51 +0000166 try:
Brett Cannon0b70cca2006-08-25 02:59:59 +0000167 self.failUnless(os.path.isabs(module.__file__), repr(module))
Brett Cannon0096e262004-06-05 01:12:51 +0000168 except AttributeError:
169 continue
Raymond Hettingerebd95222004-06-27 03:02:18 +0000170 # We could try everything in sys.modules; however, when regrtest.py
171 # runs something like test_frozen before test_site, then we will
172 # be testing things loaded *after* test_site did path normalization
Brett Cannon0096e262004-06-05 01:12:51 +0000173
174 def test_no_duplicate_paths(self):
175 # No duplicate paths should exist in sys.path
176 # Handled by removeduppaths()
177 site.removeduppaths()
178 seen_paths = set()
179 for path in sys.path:
180 self.failUnless(path not in seen_paths)
181 seen_paths.add(path)
182
183 def test_add_build_dir(self):
184 # Test that the build directory's Modules directory is used when it
185 # should be.
186 # XXX: implement
187 pass
188
Brett Cannon0096e262004-06-05 01:12:51 +0000189 def test_setting_quit(self):
190 # 'quit' and 'exit' should be injected into __builtin__
191 self.failUnless(hasattr(__builtin__, "quit"))
192 self.failUnless(hasattr(__builtin__, "exit"))
193
194 def test_setting_copyright(self):
195 # 'copyright' and 'credits' should be in __builtin__
196 self.failUnless(hasattr(__builtin__, "copyright"))
197 self.failUnless(hasattr(__builtin__, "credits"))
198
199 def test_setting_help(self):
200 # 'help' should be set in __builtin__
201 self.failUnless(hasattr(__builtin__, "help"))
202
203 def test_aliasing_mbcs(self):
204 if sys.platform == "win32":
205 import locale
206 if locale.getdefaultlocale()[1].startswith('cp'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000207 for value in encodings.aliases.aliases.values():
Brett Cannon0096e262004-06-05 01:12:51 +0000208 if value == "mbcs":
209 break
210 else:
211 self.fail("did not alias mbcs")
212
213 def test_setdefaultencoding_removed(self):
214 # Make sure sys.setdefaultencoding is gone
215 self.failUnless(not hasattr(sys, "setdefaultencoding"))
216
217 def test_sitecustomize_executed(self):
218 # If sitecustomize is available, it should have been imported.
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000219 if "sitecustomize" not in sys.modules:
Brett Cannon0096e262004-06-05 01:12:51 +0000220 try:
221 import sitecustomize
222 except ImportError:
223 pass
224 else:
225 self.fail("sitecustomize not imported automatically")
226
227
228
229
230def test_main():
231 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
232
233
234
235if __name__ == "__main__":
236 test_main()