Remove unnecessary use of context for long getters.
[python.git] / Lib / test / test_site.py
blob03f6d80155123918a7885b91e3680366bc1163ff
1 """Tests for 'site'.
3 Tests assume the initial paths in sys.path once the interpreter has begun
4 executing have not been removed.
6 """
7 import unittest
8 from test.test_support import run_unittest, TESTFN, EnvironmentVarGuard
9 import __builtin__
10 import os
11 import sys
12 import encodings
13 import subprocess
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.
17 if "site" in sys.modules:
18 import site
19 else:
20 raise unittest.SkipTest("importation of site.py suppressed")
22 if 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)
27 class HelperFunctionsTests(unittest.TestCase):
28 """Tests for helper functions.
30 The setting of the encoding (set using sys.setdefaultencoding) used by
31 the Unicode implementation is not tested.
33 """
35 def setUp(self):
36 """Save a copy of sys.path"""
37 self.sys_path = sys.path[:]
39 def tearDown(self):
40 """Restore sys.path"""
41 sys.path = self.sys_path
43 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)
50 self.failUnlessEqual(os.path.abspath(original_dir), abs_dir)
51 if original_dir == os.path.normcase(original_dir):
52 self.failUnlessEqual(abs_dir, norm_dir)
53 else:
54 self.failUnlessEqual(os.path.normcase(abs_dir), norm_dir)
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)]:
60 self.failUnless(entry in dir_set,
61 "%s from sys.path not found in set returned "
62 "by _init_pathinfo(): %s" % (entry, dir_set))
64 def pth_file_tests(self, pth_file):
65 """Contain common code for testing results of reading a .pth file"""
66 self.failUnless(pth_file.imported in sys.modules,
67 "%s not in sys.path" % pth_file.imported)
68 self.failUnless(site.makepath(pth_file.good_dir_path)[0] in sys.path)
69 self.failUnless(not os.path.exists(pth_file.bad_dir_path))
71 def test_addpackage(self):
72 # Make sure addpackage() imports if the line starts with 'import',
73 # 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()
77 pth_file.cleanup(prep=True) # to make sure that nothing is
78 # pre-existing that shouldn't be
79 try:
80 pth_file.create()
81 site.addpackage(pth_file.base_dir, pth_file.filename, set())
82 self.pth_file_tests(pth_file)
83 finally:
84 pth_file.cleanup()
86 def test_addsitedir(self):
87 # Same tests for test_addpackage since addsitedir() essentially just
88 # calls addpackage() for every .pth file in the directory
89 pth_file = PthFile()
90 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
91 # that is tested for
92 try:
93 pth_file.create()
94 site.addsitedir(pth_file.base_dir, set())
95 self.pth_file_tests(pth_file)
96 finally:
97 pth_file.cleanup()
99 def test_s_option(self):
100 usersite = site.USER_SITE
101 self.assert_(usersite in sys.path)
103 rc = subprocess.call([sys.executable, '-c',
104 'import sys; sys.exit(%r in sys.path)' % usersite])
105 self.assertEqual(rc, 1, "%r is not in sys.path (sys.exit returned %r)"
106 % (usersite, rc))
108 rc = subprocess.call([sys.executable, '-s', '-c',
109 'import sys; sys.exit(%r in sys.path)' % usersite])
110 self.assertEqual(rc, 0)
112 env = os.environ.copy()
113 env["PYTHONNOUSERSITE"] = "1"
114 rc = subprocess.call([sys.executable, '-c',
115 'import sys; sys.exit(%r in sys.path)' % usersite],
116 env=env)
117 self.assertEqual(rc, 0)
119 env = os.environ.copy()
120 env["PYTHONUSERBASE"] = "/tmp"
121 rc = subprocess.call([sys.executable, '-c',
122 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
123 env=env)
124 self.assertEqual(rc, 1)
127 class PthFile(object):
128 """Helper class for handling testing of .pth files"""
130 def __init__(self, filename_base=TESTFN, imported="time",
131 good_dirname="__testdir__", bad_dirname="__bad"):
132 """Initialize instance variables"""
133 self.filename = filename_base + ".pth"
134 self.base_dir = os.path.abspath('')
135 self.file_path = os.path.join(self.base_dir, self.filename)
136 self.imported = imported
137 self.good_dirname = good_dirname
138 self.bad_dirname = bad_dirname
139 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
140 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
142 def create(self):
143 """Create a .pth file with a comment, blank lines, an ``import
144 <self.imported>``, a line with self.good_dirname, and a line with
145 self.bad_dirname.
147 Creation of the directory for self.good_dir_path (based off of
148 self.good_dirname) is also performed.
150 Make sure to call self.cleanup() to undo anything done by this method.
153 FILE = open(self.file_path, 'w')
154 try:
155 print>>FILE, "#import @bad module name"
156 print>>FILE, "\n"
157 print>>FILE, "import %s" % self.imported
158 print>>FILE, self.good_dirname
159 print>>FILE, self.bad_dirname
160 finally:
161 FILE.close()
162 os.mkdir(self.good_dir_path)
164 def cleanup(self, prep=False):
165 """Make sure that the .pth file is deleted, self.imported is not in
166 sys.modules, and that both self.good_dirname and self.bad_dirname are
167 not existing directories."""
168 if os.path.exists(self.file_path):
169 os.remove(self.file_path)
170 if prep:
171 self.imported_module = sys.modules.get(self.imported)
172 if self.imported_module:
173 del sys.modules[self.imported]
174 else:
175 if self.imported_module:
176 sys.modules[self.imported] = self.imported_module
177 if os.path.exists(self.good_dir_path):
178 os.rmdir(self.good_dir_path)
179 if os.path.exists(self.bad_dir_path):
180 os.rmdir(self.bad_dir_path)
182 class ImportSideEffectTests(unittest.TestCase):
183 """Test side-effects from importing 'site'."""
185 def setUp(self):
186 """Make a copy of sys.path"""
187 self.sys_path = sys.path[:]
189 def tearDown(self):
190 """Restore sys.path"""
191 sys.path = self.sys_path
193 def test_abs__file__(self):
194 # Make sure all imported modules have their __file__ attribute
195 # as an absolute path.
196 # Handled by abs__file__()
197 site.abs__file__()
198 for module in (sys, os, __builtin__):
199 try:
200 self.failUnless(os.path.isabs(module.__file__), `module`)
201 except AttributeError:
202 continue
203 # We could try everything in sys.modules; however, when regrtest.py
204 # runs something like test_frozen before test_site, then we will
205 # be testing things loaded *after* test_site did path normalization
207 def test_no_duplicate_paths(self):
208 # No duplicate paths should exist in sys.path
209 # Handled by removeduppaths()
210 site.removeduppaths()
211 seen_paths = set()
212 for path in sys.path:
213 self.failUnless(path not in seen_paths)
214 seen_paths.add(path)
216 def test_add_build_dir(self):
217 # Test that the build directory's Modules directory is used when it
218 # should be.
219 # XXX: implement
220 pass
222 def test_setting_quit(self):
223 # 'quit' and 'exit' should be injected into __builtin__
224 self.failUnless(hasattr(__builtin__, "quit"))
225 self.failUnless(hasattr(__builtin__, "exit"))
227 def test_setting_copyright(self):
228 # 'copyright' and 'credits' should be in __builtin__
229 self.failUnless(hasattr(__builtin__, "copyright"))
230 self.failUnless(hasattr(__builtin__, "credits"))
232 def test_setting_help(self):
233 # 'help' should be set in __builtin__
234 self.failUnless(hasattr(__builtin__, "help"))
236 def test_aliasing_mbcs(self):
237 if sys.platform == "win32":
238 import locale
239 if locale.getdefaultlocale()[1].startswith('cp'):
240 for value in encodings.aliases.aliases.itervalues():
241 if value == "mbcs":
242 break
243 else:
244 self.fail("did not alias mbcs")
246 def test_setdefaultencoding_removed(self):
247 # Make sure sys.setdefaultencoding is gone
248 self.failUnless(not hasattr(sys, "setdefaultencoding"))
250 def test_sitecustomize_executed(self):
251 # If sitecustomize is available, it should have been imported.
252 if not sys.modules.has_key("sitecustomize"):
253 try:
254 import sitecustomize
255 except ImportError:
256 pass
257 else:
258 self.fail("sitecustomize not imported automatically")
260 def test_main():
261 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
263 if __name__ == "__main__":
264 test_main()