blob: 2dfddcd900221a6c3eb12111796035b30a5403e5 [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
Christian Heimesc5f05e42008-02-23 17:40:11 +00008from test.test_support import TestSkipped, run_unittest, TESTFN
Brett Cannon0096e262004-06-05 01:12:51 +00009import __builtin__
10import os
11import sys
12import encodings
Christian Heimesaf748c32008-05-06 22:41:46 +000013import subprocess
Brett Cannon0096e262004-06-05 01:12:51 +000014# 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
Christian Heimesaf748c32008-05-06 22:41:46 +000022if 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)
26
Brett Cannon0096e262004-06-05 01:12:51 +000027class HelperFunctionsTests(unittest.TestCase):
28 """Tests for helper functions.
Raymond Hettingerebd95222004-06-27 03:02:18 +000029
Brett Cannon0096e262004-06-05 01:12:51 +000030 The setting of the encoding (set using sys.setdefaultencoding) used by
31 the Unicode implementation is not tested.
Raymond Hettingerebd95222004-06-27 03:02:18 +000032
Brett Cannon0096e262004-06-05 01:12:51 +000033 """
34
35 def setUp(self):
36 """Save a copy of sys.path"""
37 self.sys_path = sys.path[:]
38
Neal Norwitz40388cc2008-05-14 06:47:56 +000039 def tearDown(self):
Brett Cannon0096e262004-06-05 01:12:51 +000040 """Restore sys.path"""
41 sys.path = self.sys_path
Raymond Hettingerebd95222004-06-27 03:02:18 +000042
Brett Cannon0096e262004-06-05 01:12:51 +000043 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)
55
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))
Raymond Hettingerebd95222004-06-27 03:02:18 +000063
Brett Cannonee86a662004-07-13 07:12:25 +000064 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))
70
Brett Cannon0096e262004-06-05 01:12:51 +000071 def test_addpackage(self):
72 # Make sure addpackage() imports if the line starts with 'import',
Brett Cannon64a84702004-07-10 02:10:45 +000073 # 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()
Brett Cannonee86a662004-07-13 07:12:25 +000077 pth_file.cleanup(prep=True) # to make sure that nothing is
78 # pre-existing that shouldn't be
Brett Cannon0096e262004-06-05 01:12:51 +000079 try:
Brett Cannon64a84702004-07-10 02:10:45 +000080 pth_file.create()
81 site.addpackage(pth_file.base_dir, pth_file.filename, set())
Brett Cannonee86a662004-07-13 07:12:25 +000082 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000083 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000084 pth_file.cleanup()
Raymond Hettingerebd95222004-06-27 03:02:18 +000085
Brett Cannon0096e262004-06-05 01:12:51 +000086 def test_addsitedir(self):
Brett Cannon64a84702004-07-10 02:10:45 +000087 # Same tests for test_addpackage since addsitedir() essentially just
88 # calls addpackage() for every .pth file in the directory
89 pth_file = PthFile()
Brett Cannonee86a662004-07-13 07:12:25 +000090 pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing
91 # that is tested for
Brett Cannon0096e262004-06-05 01:12:51 +000092 try:
Brett Cannonee86a662004-07-13 07:12:25 +000093 pth_file.create()
Brett Cannon64a84702004-07-10 02:10:45 +000094 site.addsitedir(pth_file.base_dir, set())
Brett Cannonee86a662004-07-13 07:12:25 +000095 self.pth_file_tests(pth_file)
Brett Cannon0096e262004-06-05 01:12:51 +000096 finally:
Brett Cannon64a84702004-07-10 02:10:45 +000097 pth_file.cleanup()
Brett Cannon0096e262004-06-05 01:12:51 +000098
Christian Heimesaf748c32008-05-06 22:41:46 +000099 def test_s_option(self):
100 usersite = site.USER_SITE
101 self.assert_(usersite in sys.path)
102
103 rc = subprocess.call([sys.executable, '-c',
Antoine Pitroub03f5322009-02-22 18:20:46 +0000104 'import sys; sys.exit(%r in sys.path)' % usersite])
Brett Cannonb7019d82009-02-24 22:01:02 +0000105 self.assertEqual(rc, 1, "%r is not in sys.path (sys.exit returned %r)"
106 % (usersite, rc))
Christian Heimesaf748c32008-05-06 22:41:46 +0000107
108 rc = subprocess.call([sys.executable, '-s', '-c',
Amaury Forgeot d'Arc9b69ed92008-06-19 21:17:12 +0000109 'import sys; sys.exit(%r in sys.path)' % usersite])
Christian Heimesaf748c32008-05-06 22:41:46 +0000110 self.assertEqual(rc, 0)
111
112 env = os.environ.copy()
113 env["PYTHONNOUSERSITE"] = "1"
114 rc = subprocess.call([sys.executable, '-c',
Amaury Forgeot d'Arc9b69ed92008-06-19 21:17:12 +0000115 'import sys; sys.exit(%r in sys.path)' % usersite],
Christian Heimesaf748c32008-05-06 22:41:46 +0000116 env=env)
117 self.assertEqual(rc, 0)
118
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)
125
126
Brett Cannon64a84702004-07-10 02:10:45 +0000127class PthFile(object):
128 """Helper class for handling testing of .pth files"""
Brett Cannon0096e262004-06-05 01:12:51 +0000129
Brett Cannon64a84702004-07-10 02:10:45 +0000130 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)
Brett Cannonee86a662004-07-13 07:12:25 +0000136 self.imported = imported
Brett Cannon64a84702004-07-10 02:10:45 +0000137 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)
Brett Cannon0096e262004-06-05 01:12:51 +0000141
Brett Cannon64a84702004-07-10 02:10:45 +0000142 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.
Tim Peters182b5ac2004-07-18 06:16:08 +0000146
Brett Cannon64a84702004-07-10 02:10:45 +0000147 Creation of the directory for self.good_dir_path (based off of
148 self.good_dirname) is also performed.
Brett Cannon0096e262004-06-05 01:12:51 +0000149
Brett Cannon64a84702004-07-10 02:10:45 +0000150 Make sure to call self.cleanup() to undo anything done by this method.
Tim Peters182b5ac2004-07-18 06:16:08 +0000151
Brett Cannon64a84702004-07-10 02:10:45 +0000152 """
Michael W. Hudsonff522862005-05-27 14:58:06 +0000153 FILE = open(self.file_path, 'w')
Brett Cannon64a84702004-07-10 02:10:45 +0000154 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)
163
Brett Cannonee86a662004-07-13 07:12:25 +0000164 def cleanup(self, prep=False):
Brett Cannon64a84702004-07-10 02:10:45 +0000165 """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."""
Brett Cannonee86a662004-07-13 07:12:25 +0000168 if os.path.exists(self.file_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000169 os.remove(self.file_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000170 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):
Brett Cannon64a84702004-07-10 02:10:45 +0000178 os.rmdir(self.good_dir_path)
Brett Cannonee86a662004-07-13 07:12:25 +0000179 if os.path.exists(self.bad_dir_path):
Brett Cannon64a84702004-07-10 02:10:45 +0000180 os.rmdir(self.bad_dir_path)
Brett Cannon0096e262004-06-05 01:12:51 +0000181
182class ImportSideEffectTests(unittest.TestCase):
183 """Test side-effects from importing 'site'."""
184
185 def setUp(self):
186 """Make a copy of sys.path"""
187 self.sys_path = sys.path[:]
188
189 def tearDown(self):
190 """Restore sys.path"""
191 sys.path = self.sys_path
192
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__()
Raymond Hettingerebd95222004-06-27 03:02:18 +0000198 for module in (sys, os, __builtin__):
Brett Cannon0096e262004-06-05 01:12:51 +0000199 try:
Raymond Hettingerebd95222004-06-27 03:02:18 +0000200 self.failUnless(os.path.isabs(module.__file__), `module`)
Brett Cannon0096e262004-06-05 01:12:51 +0000201 except AttributeError:
202 continue
Raymond Hettingerebd95222004-06-27 03:02:18 +0000203 # 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
Brett Cannon0096e262004-06-05 01:12:51 +0000206
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)
215
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
221
Brett Cannon0096e262004-06-05 01:12:51 +0000222 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"))
226
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"))
231
232 def test_setting_help(self):
233 # 'help' should be set in __builtin__
234 self.failUnless(hasattr(__builtin__, "help"))
235
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")
245
246 def test_setdefaultencoding_removed(self):
247 # Make sure sys.setdefaultencoding is gone
248 self.failUnless(not hasattr(sys, "setdefaultencoding"))
249
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")
259
Brett Cannon0096e262004-06-05 01:12:51 +0000260def test_main():
261 run_unittest(HelperFunctionsTests, ImportSideEffectTests)
262
Brett Cannon0096e262004-06-05 01:12:51 +0000263if __name__ == "__main__":
264 test_main()