blob: ee15b1eeda03ebfe201d428c554f31b762d86da1 [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
8from test.test_support import TestSkipped, run_unittest, TESTFN
9import __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.
24
25 The setting of the encoding (set using sys.setdefaultencoding) used by
26 the Unicode implementation is not tested.
27
28 """
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
37
38 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))
58
59 def test_addpackage(self):
60 # Make sure addpackage() imports if the line starts with 'import',
61 # otherwise add a directory combined from sitedir and 'name'.
62 # Must also skip comment lines.
63 dir_path, file_name, new_dir = createpth()
64 try:
65 site.addpackage(dir_path, file_name, set())
66 self.failUnless(site.makepath(os.path.join(dir_path, new_dir))[0] in
67 sys.path)
68 finally:
69 cleanuppth(dir_path, file_name, new_dir)
70
71 def test_addsitedir(self):
72 dir_path, file_name, new_dir = createpth()
73 try:
74 site.addsitedir(dir_path, set())
75 self.failUnless(site.makepath(os.path.join(dir_path, new_dir))[0] in
76 sys.path)
77 finally:
78 cleanuppth(dir_path, file_name, new_dir)
79
80def createpth():
81 """Create a temporary .pth file at the returned location and return the
82 directory where it was created, the pth file name, and the directory
83 specified in the pth file.
84
85 Make sure to delete the file when finished.
86
87 """
88 pth_dirname = "__testdir__"
89 file_name = TESTFN + ".pth"
90 full_dirname = os.path.dirname(os.path.abspath(file_name))
91 FILE = file(os.path.join(full_dirname, file_name), 'w')
92 try:
93 print>>FILE, "#import @bad module name"
94 print>>FILE, ''
95 print>>FILE, "import os"
96 print>>FILE, pth_dirname
97 finally:
98 FILE.close()
99 os.mkdir(os.path.join(full_dirname, pth_dirname))
100 return full_dirname, file_name, pth_dirname
101
102def cleanuppth(full_dirname, file_name, pth_dirname):
103 """Clean up what createpth() made"""
104 os.remove(os.path.join(full_dirname, file_name))
105 os.rmdir(os.path.join(full_dirname, pth_dirname))
106
107class ImportSideEffectTests(unittest.TestCase):
108 """Test side-effects from importing 'site'."""
109
110 def setUp(self):
111 """Make a copy of sys.path"""
112 self.sys_path = sys.path[:]
113
114 def tearDown(self):
115 """Restore sys.path"""
116 sys.path = self.sys_path
117
118 def test_abs__file__(self):
119 # Make sure all imported modules have their __file__ attribute
120 # as an absolute path.
121 # Handled by abs__file__()
122 site.abs__file__()
123 for module in sys.modules.values():
124 try:
125 self.failUnless(os.path.isabs(module.__file__))
126 except AttributeError:
127 continue
128
129 def test_no_duplicate_paths(self):
130 # No duplicate paths should exist in sys.path
131 # Handled by removeduppaths()
132 site.removeduppaths()
133 seen_paths = set()
134 for path in sys.path:
135 self.failUnless(path not in seen_paths)
136 seen_paths.add(path)
137
138 def test_add_build_dir(self):
139 # Test that the build directory's Modules directory is used when it
140 # should be.
141 # XXX: implement
142 pass
143
144 def test_sitepackages(self):
145 # There should be a path that ends in site-packages
146 for path in sys.path:
147 if path.endswith("site-packages"):
148 break
149 else:
150 self.fail("'site-packages' directory missing'")
151
152 def test_setting_quit(self):
153 # 'quit' and 'exit' should be injected into __builtin__
154 self.failUnless(hasattr(__builtin__, "quit"))
155 self.failUnless(hasattr(__builtin__, "exit"))
156
157 def test_setting_copyright(self):
158 # 'copyright' and 'credits' should be in __builtin__
159 self.failUnless(hasattr(__builtin__, "copyright"))
160 self.failUnless(hasattr(__builtin__, "credits"))
161
162 def test_setting_help(self):
163 # 'help' should be set in __builtin__
164 self.failUnless(hasattr(__builtin__, "help"))
165
166 def test_aliasing_mbcs(self):
167 if sys.platform == "win32":
168 import locale
169 if locale.getdefaultlocale()[1].startswith('cp'):
170 for value in encodings.aliases.aliases.itervalues():
171 if value == "mbcs":
172 break
173 else:
174 self.fail("did not alias mbcs")
175
176 def test_setdefaultencoding_removed(self):
177 # Make sure sys.setdefaultencoding is gone
178 self.failUnless(not hasattr(sys, "setdefaultencoding"))
179
180 def test_sitecustomize_executed(self):
181 # If sitecustomize is available, it should have been imported.
182 if not sys.modules.has_key("sitecustomize"):
183 try:
184 import sitecustomize
185 except ImportError:
186 pass
187 else:
188 self.fail("sitecustomize not imported automatically")
189
190
191
192
193def test_main():
194 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
195
196
197
198if __name__ == "__main__":
199 test_main()