Issue #7051: Clarify behaviour of 'g' and 'G'-style formatting.
[python.git] / Lib / test / test_site.py
blobdf264220b703cf0a67429d6f7ffdee850dae6a73
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[:]
38 self.old_base = site.USER_BASE
39 self.old_site = site.USER_SITE
40 self.old_prefixes = site.PREFIXES
42 def tearDown(self):
43 """Restore sys.path"""
44 sys.path = self.sys_path
45 site.USER_BASE = self.old_base
46 site.USER_SITE = self.old_site
47 site.PREFIXES = self.old_prefixes
49 def test_makepath(self):
50 # Test makepath() have an absolute path for its first return value
51 # and a case-normalized version of the absolute path for its
52 # second value.
53 path_parts = ("Beginning", "End")
54 original_dir = os.path.join(*path_parts)
55 abs_dir, norm_dir = site.makepath(*path_parts)
56 self.assertEqual(os.path.abspath(original_dir), abs_dir)
57 if original_dir == os.path.normcase(original_dir):
58 self.assertEqual(abs_dir, norm_dir)
59 else:
60 self.assertEqual(os.path.normcase(abs_dir), norm_dir)
62 def test_init_pathinfo(self):
63 dir_set = site._init_pathinfo()
64 for entry in [site.makepath(path)[1] for path in sys.path
65 if path and os.path.isdir(path)]:
66 self.assertTrue(entry in dir_set,
67 "%s from sys.path not found in set returned "
68 "by _init_pathinfo(): %s" % (entry, dir_set))
70 def pth_file_tests(self, pth_file):
71 """Contain common code for testing results of reading a .pth file"""
72 self.assertTrue(pth_file.imported in sys.modules,
73 "%s not in sys.path" % pth_file.imported)
74 self.assertTrue(site.makepath(pth_file.good_dir_path)[0] in sys.path)
75 self.assertTrue(not os.path.exists(pth_file.bad_dir_path))
77 def test_addpackage(self):
78 # Make sure addpackage() imports if the line starts with 'import',
79 # adds directories to sys.path for any line in the file that is not a
80 # comment or import that is a valid directory name for where the .pth
81 # file resides; invalid directories are not added
82 pth_file = PthFile()
83 pth_file.cleanup(prep=True) # to make sure that nothing is
84 # pre-existing that shouldn't be
85 try:
86 pth_file.create()
87 site.addpackage(pth_file.base_dir, pth_file.filename, set())
88 self.pth_file_tests(pth_file)
89 finally:
90 pth_file.cleanup()
92 def test_addsitedir(self):
93 # Same tests for test_addpackage since addsitedir() essentially just
94 # calls addpackage() for every .pth file in the directory
95 pth_file = PthFile()
96 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
97 # that is tested for
98 try:
99 pth_file.create()
100 site.addsitedir(pth_file.base_dir, set())
101 self.pth_file_tests(pth_file)
102 finally:
103 pth_file.cleanup()
105 def test_s_option(self):
106 usersite = site.USER_SITE
107 self.assertTrue(usersite in sys.path)
109 rc = subprocess.call([sys.executable, '-c',
110 'import sys; sys.exit(%r in sys.path)' % usersite])
111 self.assertEqual(rc, 1, "%r is not in sys.path (sys.exit returned %r)"
112 % (usersite, rc))
114 rc = subprocess.call([sys.executable, '-s', '-c',
115 'import sys; sys.exit(%r in sys.path)' % usersite])
116 self.assertEqual(rc, 0)
118 env = os.environ.copy()
119 env["PYTHONNOUSERSITE"] = "1"
120 rc = subprocess.call([sys.executable, '-c',
121 'import sys; sys.exit(%r in sys.path)' % usersite],
122 env=env)
123 self.assertEqual(rc, 0)
125 env = os.environ.copy()
126 env["PYTHONUSERBASE"] = "/tmp"
127 rc = subprocess.call([sys.executable, '-c',
128 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
129 env=env)
130 self.assertEqual(rc, 1)
132 def test_getuserbase(self):
133 site.USER_BASE = None
134 user_base = site.getuserbase()
136 # the call sets site.USER_BASE
137 self.assertEquals(site.USER_BASE, user_base)
139 # let's set PYTHONUSERBASE and see if it uses it
140 site.USER_BASE = None
141 with EnvironmentVarGuard() as environ:
142 environ['PYTHONUSERBASE'] = 'xoxo'
143 self.assertTrue(site.getuserbase().startswith('xoxo'))
145 def test_getusersitepackages(self):
146 site.USER_SITE = None
147 site.USER_BASE = None
148 user_site = site.getusersitepackages()
150 # the call sets USER_BASE *and* USER_SITE
151 self.assertEquals(site.USER_SITE, user_site)
152 self.assertTrue(user_site.startswith(site.USER_BASE))
154 def test_getsitepackages(self):
155 site.PREFIXES = ['xoxo']
156 dirs = site.getsitepackages()
158 if sys.platform in ('os2emx', 'riscos'):
159 self.assertTrue(len(dirs), 1)
160 wanted = os.path.join('xoxo', 'Lib', 'site-packages')
161 self.assertEquals(dirs[0], wanted)
162 elif os.sep == '/':
163 self.assertTrue(len(dirs), 2)
164 wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
165 'site-packages')
166 self.assertEquals(dirs[0], wanted)
167 wanted = os.path.join('xoxo', 'lib', 'site-python')
168 self.assertEquals(dirs[1], wanted)
169 else:
170 self.assertTrue(len(dirs), 2)
171 self.assertEquals(dirs[0], 'xoxo')
172 wanted = os.path.join('xoxo', 'Lib', 'site-packages')
173 self.assertEquals(dirs[1], wanted)
175 # let's try the specific Apple location
176 if sys.platform == "darwin":
177 site.PREFIXES = ['Python.framework']
178 dirs = site.getsitepackages()
179 self.assertTrue(len(dirs), 4)
180 wanted = os.path.join('~', 'Library', 'Python',
181 sys.version[:3], 'site-packages')
182 self.assertEquals(dirs[2], os.path.expanduser(wanted))
183 wanted = os.path.join('/Library', 'Python', sys.version[:3],
184 'site-packages')
185 self.assertEquals(dirs[3], wanted)
187 class PthFile(object):
188 """Helper class for handling testing of .pth files"""
190 def __init__(self, filename_base=TESTFN, imported="time",
191 good_dirname="__testdir__", bad_dirname="__bad"):
192 """Initialize instance variables"""
193 self.filename = filename_base + ".pth"
194 self.base_dir = os.path.abspath('')
195 self.file_path = os.path.join(self.base_dir, self.filename)
196 self.imported = imported
197 self.good_dirname = good_dirname
198 self.bad_dirname = bad_dirname
199 self.good_dir_path = os.path.join(self.base_dir, self.good_dirname)
200 self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname)
202 def create(self):
203 """Create a .pth file with a comment, blank lines, an ``import
204 <self.imported>``, a line with self.good_dirname, and a line with
205 self.bad_dirname.
207 Creation of the directory for self.good_dir_path (based off of
208 self.good_dirname) is also performed.
210 Make sure to call self.cleanup() to undo anything done by this method.
213 FILE = open(self.file_path, 'w')
214 try:
215 print>>FILE, "#import @bad module name"
216 print>>FILE, "\n"
217 print>>FILE, "import %s" % self.imported
218 print>>FILE, self.good_dirname
219 print>>FILE, self.bad_dirname
220 finally:
221 FILE.close()
222 os.mkdir(self.good_dir_path)
224 def cleanup(self, prep=False):
225 """Make sure that the .pth file is deleted, self.imported is not in
226 sys.modules, and that both self.good_dirname and self.bad_dirname are
227 not existing directories."""
228 if os.path.exists(self.file_path):
229 os.remove(self.file_path)
230 if prep:
231 self.imported_module = sys.modules.get(self.imported)
232 if self.imported_module:
233 del sys.modules[self.imported]
234 else:
235 if self.imported_module:
236 sys.modules[self.imported] = self.imported_module
237 if os.path.exists(self.good_dir_path):
238 os.rmdir(self.good_dir_path)
239 if os.path.exists(self.bad_dir_path):
240 os.rmdir(self.bad_dir_path)
242 class ImportSideEffectTests(unittest.TestCase):
243 """Test side-effects from importing 'site'."""
245 def setUp(self):
246 """Make a copy of sys.path"""
247 self.sys_path = sys.path[:]
249 def tearDown(self):
250 """Restore sys.path"""
251 sys.path = self.sys_path
253 def test_abs__file__(self):
254 # Make sure all imported modules have their __file__ attribute
255 # as an absolute path.
256 # Handled by abs__file__()
257 site.abs__file__()
258 for module in (sys, os, __builtin__):
259 try:
260 self.assertTrue(os.path.isabs(module.__file__), `module`)
261 except AttributeError:
262 continue
263 # We could try everything in sys.modules; however, when regrtest.py
264 # runs something like test_frozen before test_site, then we will
265 # be testing things loaded *after* test_site did path normalization
267 def test_no_duplicate_paths(self):
268 # No duplicate paths should exist in sys.path
269 # Handled by removeduppaths()
270 site.removeduppaths()
271 seen_paths = set()
272 for path in sys.path:
273 self.assertTrue(path not in seen_paths)
274 seen_paths.add(path)
276 def test_add_build_dir(self):
277 # Test that the build directory's Modules directory is used when it
278 # should be.
279 # XXX: implement
280 pass
282 def test_setting_quit(self):
283 # 'quit' and 'exit' should be injected into __builtin__
284 self.assertTrue(hasattr(__builtin__, "quit"))
285 self.assertTrue(hasattr(__builtin__, "exit"))
287 def test_setting_copyright(self):
288 # 'copyright' and 'credits' should be in __builtin__
289 self.assertTrue(hasattr(__builtin__, "copyright"))
290 self.assertTrue(hasattr(__builtin__, "credits"))
292 def test_setting_help(self):
293 # 'help' should be set in __builtin__
294 self.assertTrue(hasattr(__builtin__, "help"))
296 def test_aliasing_mbcs(self):
297 if sys.platform == "win32":
298 import locale
299 if locale.getdefaultlocale()[1].startswith('cp'):
300 for value in encodings.aliases.aliases.itervalues():
301 if value == "mbcs":
302 break
303 else:
304 self.fail("did not alias mbcs")
306 def test_setdefaultencoding_removed(self):
307 # Make sure sys.setdefaultencoding is gone
308 self.assertTrue(not hasattr(sys, "setdefaultencoding"))
310 def test_sitecustomize_executed(self):
311 # If sitecustomize is available, it should have been imported.
312 if not sys.modules.has_key("sitecustomize"):
313 try:
314 import sitecustomize
315 except ImportError:
316 pass
317 else:
318 self.fail("sitecustomize not imported automatically")
320 def test_main():
321 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
323 if __name__ == "__main__":
324 test_main()