1 | n/a | """Tests for 'site'. |
---|
2 | n/a | |
---|
3 | n/a | Tests assume the initial paths in sys.path once the interpreter has begun |
---|
4 | n/a | executing have not been removed. |
---|
5 | n/a | |
---|
6 | n/a | """ |
---|
7 | n/a | import unittest |
---|
8 | n/a | import test.support |
---|
9 | n/a | from test.support import captured_stderr, TESTFN, EnvironmentVarGuard |
---|
10 | n/a | import builtins |
---|
11 | n/a | import os |
---|
12 | n/a | import sys |
---|
13 | n/a | import re |
---|
14 | n/a | import encodings |
---|
15 | n/a | import urllib.request |
---|
16 | n/a | import urllib.error |
---|
17 | n/a | import shutil |
---|
18 | n/a | import subprocess |
---|
19 | n/a | import sysconfig |
---|
20 | n/a | from copy import copy |
---|
21 | n/a | |
---|
22 | n/a | # These tests are not particularly useful if Python was invoked with -S. |
---|
23 | n/a | # If you add tests that are useful under -S, this skip should be moved |
---|
24 | n/a | # to the class level. |
---|
25 | n/a | if sys.flags.no_site: |
---|
26 | n/a | raise unittest.SkipTest("Python was invoked with -S") |
---|
27 | n/a | |
---|
28 | n/a | import site |
---|
29 | n/a | |
---|
30 | n/a | if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE): |
---|
31 | n/a | # need to add user site directory for tests |
---|
32 | n/a | try: |
---|
33 | n/a | os.makedirs(site.USER_SITE) |
---|
34 | n/a | site.addsitedir(site.USER_SITE) |
---|
35 | n/a | except PermissionError as exc: |
---|
36 | n/a | raise unittest.SkipTest('unable to create user site directory (%r): %s' |
---|
37 | n/a | % (site.USER_SITE, exc)) |
---|
38 | n/a | |
---|
39 | n/a | |
---|
40 | n/a | class HelperFunctionsTests(unittest.TestCase): |
---|
41 | n/a | """Tests for helper functions. |
---|
42 | n/a | """ |
---|
43 | n/a | |
---|
44 | n/a | def setUp(self): |
---|
45 | n/a | """Save a copy of sys.path""" |
---|
46 | n/a | self.sys_path = sys.path[:] |
---|
47 | n/a | self.old_base = site.USER_BASE |
---|
48 | n/a | self.old_site = site.USER_SITE |
---|
49 | n/a | self.old_prefixes = site.PREFIXES |
---|
50 | n/a | self.original_vars = sysconfig._CONFIG_VARS |
---|
51 | n/a | self.old_vars = copy(sysconfig._CONFIG_VARS) |
---|
52 | n/a | |
---|
53 | n/a | def tearDown(self): |
---|
54 | n/a | """Restore sys.path""" |
---|
55 | n/a | sys.path[:] = self.sys_path |
---|
56 | n/a | site.USER_BASE = self.old_base |
---|
57 | n/a | site.USER_SITE = self.old_site |
---|
58 | n/a | site.PREFIXES = self.old_prefixes |
---|
59 | n/a | sysconfig._CONFIG_VARS = self.original_vars |
---|
60 | n/a | sysconfig._CONFIG_VARS.clear() |
---|
61 | n/a | sysconfig._CONFIG_VARS.update(self.old_vars) |
---|
62 | n/a | |
---|
63 | n/a | def test_makepath(self): |
---|
64 | n/a | # Test makepath() have an absolute path for its first return value |
---|
65 | n/a | # and a case-normalized version of the absolute path for its |
---|
66 | n/a | # second value. |
---|
67 | n/a | path_parts = ("Beginning", "End") |
---|
68 | n/a | original_dir = os.path.join(*path_parts) |
---|
69 | n/a | abs_dir, norm_dir = site.makepath(*path_parts) |
---|
70 | n/a | self.assertEqual(os.path.abspath(original_dir), abs_dir) |
---|
71 | n/a | if original_dir == os.path.normcase(original_dir): |
---|
72 | n/a | self.assertEqual(abs_dir, norm_dir) |
---|
73 | n/a | else: |
---|
74 | n/a | self.assertEqual(os.path.normcase(abs_dir), norm_dir) |
---|
75 | n/a | |
---|
76 | n/a | def test_init_pathinfo(self): |
---|
77 | n/a | dir_set = site._init_pathinfo() |
---|
78 | n/a | for entry in [site.makepath(path)[1] for path in sys.path |
---|
79 | n/a | if path and os.path.exists(path)]: |
---|
80 | n/a | self.assertIn(entry, dir_set, |
---|
81 | n/a | "%s from sys.path not found in set returned " |
---|
82 | n/a | "by _init_pathinfo(): %s" % (entry, dir_set)) |
---|
83 | n/a | |
---|
84 | n/a | def pth_file_tests(self, pth_file): |
---|
85 | n/a | """Contain common code for testing results of reading a .pth file""" |
---|
86 | n/a | self.assertIn(pth_file.imported, sys.modules, |
---|
87 | n/a | "%s not in sys.modules" % pth_file.imported) |
---|
88 | n/a | self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path) |
---|
89 | n/a | self.assertFalse(os.path.exists(pth_file.bad_dir_path)) |
---|
90 | n/a | |
---|
91 | n/a | def test_addpackage(self): |
---|
92 | n/a | # Make sure addpackage() imports if the line starts with 'import', |
---|
93 | n/a | # adds directories to sys.path for any line in the file that is not a |
---|
94 | n/a | # comment or import that is a valid directory name for where the .pth |
---|
95 | n/a | # file resides; invalid directories are not added |
---|
96 | n/a | pth_file = PthFile() |
---|
97 | n/a | pth_file.cleanup(prep=True) # to make sure that nothing is |
---|
98 | n/a | # pre-existing that shouldn't be |
---|
99 | n/a | try: |
---|
100 | n/a | pth_file.create() |
---|
101 | n/a | site.addpackage(pth_file.base_dir, pth_file.filename, set()) |
---|
102 | n/a | self.pth_file_tests(pth_file) |
---|
103 | n/a | finally: |
---|
104 | n/a | pth_file.cleanup() |
---|
105 | n/a | |
---|
106 | n/a | def make_pth(self, contents, pth_dir='.', pth_name=TESTFN): |
---|
107 | n/a | # Create a .pth file and return its (abspath, basename). |
---|
108 | n/a | pth_dir = os.path.abspath(pth_dir) |
---|
109 | n/a | pth_basename = pth_name + '.pth' |
---|
110 | n/a | pth_fn = os.path.join(pth_dir, pth_basename) |
---|
111 | n/a | pth_file = open(pth_fn, 'w', encoding='utf-8') |
---|
112 | n/a | self.addCleanup(lambda: os.remove(pth_fn)) |
---|
113 | n/a | pth_file.write(contents) |
---|
114 | n/a | pth_file.close() |
---|
115 | n/a | return pth_dir, pth_basename |
---|
116 | n/a | |
---|
117 | n/a | def test_addpackage_import_bad_syntax(self): |
---|
118 | n/a | # Issue 10642 |
---|
119 | n/a | pth_dir, pth_fn = self.make_pth("import bad)syntax\n") |
---|
120 | n/a | with captured_stderr() as err_out: |
---|
121 | n/a | site.addpackage(pth_dir, pth_fn, set()) |
---|
122 | n/a | self.assertRegex(err_out.getvalue(), "line 1") |
---|
123 | n/a | self.assertRegex(err_out.getvalue(), |
---|
124 | n/a | re.escape(os.path.join(pth_dir, pth_fn))) |
---|
125 | n/a | # XXX: the previous two should be independent checks so that the |
---|
126 | n/a | # order doesn't matter. The next three could be a single check |
---|
127 | n/a | # but my regex foo isn't good enough to write it. |
---|
128 | n/a | self.assertRegex(err_out.getvalue(), 'Traceback') |
---|
129 | n/a | self.assertRegex(err_out.getvalue(), r'import bad\)syntax') |
---|
130 | n/a | self.assertRegex(err_out.getvalue(), 'SyntaxError') |
---|
131 | n/a | |
---|
132 | n/a | def test_addpackage_import_bad_exec(self): |
---|
133 | n/a | # Issue 10642 |
---|
134 | n/a | pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n") |
---|
135 | n/a | with captured_stderr() as err_out: |
---|
136 | n/a | site.addpackage(pth_dir, pth_fn, set()) |
---|
137 | n/a | self.assertRegex(err_out.getvalue(), "line 2") |
---|
138 | n/a | self.assertRegex(err_out.getvalue(), |
---|
139 | n/a | re.escape(os.path.join(pth_dir, pth_fn))) |
---|
140 | n/a | # XXX: ditto previous XXX comment. |
---|
141 | n/a | self.assertRegex(err_out.getvalue(), 'Traceback') |
---|
142 | n/a | self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError') |
---|
143 | n/a | |
---|
144 | n/a | def test_addpackage_import_bad_pth_file(self): |
---|
145 | n/a | # Issue 5258 |
---|
146 | n/a | pth_dir, pth_fn = self.make_pth("abc\x00def\n") |
---|
147 | n/a | with captured_stderr() as err_out: |
---|
148 | n/a | site.addpackage(pth_dir, pth_fn, set()) |
---|
149 | n/a | self.assertRegex(err_out.getvalue(), "line 1") |
---|
150 | n/a | self.assertRegex(err_out.getvalue(), |
---|
151 | n/a | re.escape(os.path.join(pth_dir, pth_fn))) |
---|
152 | n/a | # XXX: ditto previous XXX comment. |
---|
153 | n/a | self.assertRegex(err_out.getvalue(), 'Traceback') |
---|
154 | n/a | self.assertRegex(err_out.getvalue(), 'ValueError') |
---|
155 | n/a | |
---|
156 | n/a | def test_addsitedir(self): |
---|
157 | n/a | # Same tests for test_addpackage since addsitedir() essentially just |
---|
158 | n/a | # calls addpackage() for every .pth file in the directory |
---|
159 | n/a | pth_file = PthFile() |
---|
160 | n/a | pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing |
---|
161 | n/a | # that is tested for |
---|
162 | n/a | try: |
---|
163 | n/a | pth_file.create() |
---|
164 | n/a | site.addsitedir(pth_file.base_dir, set()) |
---|
165 | n/a | self.pth_file_tests(pth_file) |
---|
166 | n/a | finally: |
---|
167 | n/a | pth_file.cleanup() |
---|
168 | n/a | |
---|
169 | n/a | @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 " |
---|
170 | n/a | "user-site (site.ENABLE_USER_SITE)") |
---|
171 | n/a | def test_s_option(self): |
---|
172 | n/a | usersite = site.USER_SITE |
---|
173 | n/a | self.assertIn(usersite, sys.path) |
---|
174 | n/a | |
---|
175 | n/a | env = os.environ.copy() |
---|
176 | n/a | rc = subprocess.call([sys.executable, '-c', |
---|
177 | n/a | 'import sys; sys.exit(%r in sys.path)' % usersite], |
---|
178 | n/a | env=env) |
---|
179 | n/a | self.assertEqual(rc, 1) |
---|
180 | n/a | |
---|
181 | n/a | env = os.environ.copy() |
---|
182 | n/a | rc = subprocess.call([sys.executable, '-s', '-c', |
---|
183 | n/a | 'import sys; sys.exit(%r in sys.path)' % usersite], |
---|
184 | n/a | env=env) |
---|
185 | n/a | if usersite == site.getsitepackages()[0]: |
---|
186 | n/a | self.assertEqual(rc, 1) |
---|
187 | n/a | else: |
---|
188 | n/a | self.assertEqual(rc, 0) |
---|
189 | n/a | |
---|
190 | n/a | env = os.environ.copy() |
---|
191 | n/a | env["PYTHONNOUSERSITE"] = "1" |
---|
192 | n/a | rc = subprocess.call([sys.executable, '-c', |
---|
193 | n/a | 'import sys; sys.exit(%r in sys.path)' % usersite], |
---|
194 | n/a | env=env) |
---|
195 | n/a | if usersite == site.getsitepackages()[0]: |
---|
196 | n/a | self.assertEqual(rc, 1) |
---|
197 | n/a | else: |
---|
198 | n/a | self.assertEqual(rc, 0) |
---|
199 | n/a | |
---|
200 | n/a | env = os.environ.copy() |
---|
201 | n/a | env["PYTHONUSERBASE"] = "/tmp" |
---|
202 | n/a | rc = subprocess.call([sys.executable, '-c', |
---|
203 | n/a | 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'], |
---|
204 | n/a | env=env) |
---|
205 | n/a | self.assertEqual(rc, 1) |
---|
206 | n/a | |
---|
207 | n/a | def test_getuserbase(self): |
---|
208 | n/a | site.USER_BASE = None |
---|
209 | n/a | user_base = site.getuserbase() |
---|
210 | n/a | |
---|
211 | n/a | # the call sets site.USER_BASE |
---|
212 | n/a | self.assertEqual(site.USER_BASE, user_base) |
---|
213 | n/a | |
---|
214 | n/a | # let's set PYTHONUSERBASE and see if it uses it |
---|
215 | n/a | site.USER_BASE = None |
---|
216 | n/a | import sysconfig |
---|
217 | n/a | sysconfig._CONFIG_VARS = None |
---|
218 | n/a | |
---|
219 | n/a | with EnvironmentVarGuard() as environ: |
---|
220 | n/a | environ['PYTHONUSERBASE'] = 'xoxo' |
---|
221 | n/a | self.assertTrue(site.getuserbase().startswith('xoxo'), |
---|
222 | n/a | site.getuserbase()) |
---|
223 | n/a | |
---|
224 | n/a | def test_getusersitepackages(self): |
---|
225 | n/a | site.USER_SITE = None |
---|
226 | n/a | site.USER_BASE = None |
---|
227 | n/a | user_site = site.getusersitepackages() |
---|
228 | n/a | |
---|
229 | n/a | # the call sets USER_BASE *and* USER_SITE |
---|
230 | n/a | self.assertEqual(site.USER_SITE, user_site) |
---|
231 | n/a | self.assertTrue(user_site.startswith(site.USER_BASE), user_site) |
---|
232 | n/a | |
---|
233 | n/a | def test_getsitepackages(self): |
---|
234 | n/a | site.PREFIXES = ['xoxo'] |
---|
235 | n/a | dirs = site.getsitepackages() |
---|
236 | n/a | |
---|
237 | n/a | if (sys.platform == "darwin" and |
---|
238 | n/a | sysconfig.get_config_var("PYTHONFRAMEWORK")): |
---|
239 | n/a | # OS X framework builds |
---|
240 | n/a | site.PREFIXES = ['Python.framework'] |
---|
241 | n/a | dirs = site.getsitepackages() |
---|
242 | n/a | self.assertEqual(len(dirs), 2) |
---|
243 | n/a | wanted = os.path.join('/Library', |
---|
244 | n/a | sysconfig.get_config_var("PYTHONFRAMEWORK"), |
---|
245 | n/a | '%d.%d' % sys.version_info[:2], |
---|
246 | n/a | 'site-packages') |
---|
247 | n/a | self.assertEqual(dirs[1], wanted) |
---|
248 | n/a | elif os.sep == '/': |
---|
249 | n/a | # OS X non-framwework builds, Linux, FreeBSD, etc |
---|
250 | n/a | self.assertEqual(len(dirs), 1) |
---|
251 | n/a | wanted = os.path.join('xoxo', 'lib', |
---|
252 | n/a | 'python%d.%d' % sys.version_info[:2], |
---|
253 | n/a | 'site-packages') |
---|
254 | n/a | self.assertEqual(dirs[0], wanted) |
---|
255 | n/a | else: |
---|
256 | n/a | # other platforms |
---|
257 | n/a | self.assertEqual(len(dirs), 2) |
---|
258 | n/a | self.assertEqual(dirs[0], 'xoxo') |
---|
259 | n/a | wanted = os.path.join('xoxo', 'lib', 'site-packages') |
---|
260 | n/a | self.assertEqual(dirs[1], wanted) |
---|
261 | n/a | |
---|
262 | n/a | class PthFile(object): |
---|
263 | n/a | """Helper class for handling testing of .pth files""" |
---|
264 | n/a | |
---|
265 | n/a | def __init__(self, filename_base=TESTFN, imported="time", |
---|
266 | n/a | good_dirname="__testdir__", bad_dirname="__bad"): |
---|
267 | n/a | """Initialize instance variables""" |
---|
268 | n/a | self.filename = filename_base + ".pth" |
---|
269 | n/a | self.base_dir = os.path.abspath('') |
---|
270 | n/a | self.file_path = os.path.join(self.base_dir, self.filename) |
---|
271 | n/a | self.imported = imported |
---|
272 | n/a | self.good_dirname = good_dirname |
---|
273 | n/a | self.bad_dirname = bad_dirname |
---|
274 | n/a | self.good_dir_path = os.path.join(self.base_dir, self.good_dirname) |
---|
275 | n/a | self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname) |
---|
276 | n/a | |
---|
277 | n/a | def create(self): |
---|
278 | n/a | """Create a .pth file with a comment, blank lines, an ``import |
---|
279 | n/a | <self.imported>``, a line with self.good_dirname, and a line with |
---|
280 | n/a | self.bad_dirname. |
---|
281 | n/a | |
---|
282 | n/a | Creation of the directory for self.good_dir_path (based off of |
---|
283 | n/a | self.good_dirname) is also performed. |
---|
284 | n/a | |
---|
285 | n/a | Make sure to call self.cleanup() to undo anything done by this method. |
---|
286 | n/a | |
---|
287 | n/a | """ |
---|
288 | n/a | FILE = open(self.file_path, 'w') |
---|
289 | n/a | try: |
---|
290 | n/a | print("#import @bad module name", file=FILE) |
---|
291 | n/a | print("\n", file=FILE) |
---|
292 | n/a | print("import %s" % self.imported, file=FILE) |
---|
293 | n/a | print(self.good_dirname, file=FILE) |
---|
294 | n/a | print(self.bad_dirname, file=FILE) |
---|
295 | n/a | finally: |
---|
296 | n/a | FILE.close() |
---|
297 | n/a | os.mkdir(self.good_dir_path) |
---|
298 | n/a | |
---|
299 | n/a | def cleanup(self, prep=False): |
---|
300 | n/a | """Make sure that the .pth file is deleted, self.imported is not in |
---|
301 | n/a | sys.modules, and that both self.good_dirname and self.bad_dirname are |
---|
302 | n/a | not existing directories.""" |
---|
303 | n/a | if os.path.exists(self.file_path): |
---|
304 | n/a | os.remove(self.file_path) |
---|
305 | n/a | if prep: |
---|
306 | n/a | self.imported_module = sys.modules.get(self.imported) |
---|
307 | n/a | if self.imported_module: |
---|
308 | n/a | del sys.modules[self.imported] |
---|
309 | n/a | else: |
---|
310 | n/a | if self.imported_module: |
---|
311 | n/a | sys.modules[self.imported] = self.imported_module |
---|
312 | n/a | if os.path.exists(self.good_dir_path): |
---|
313 | n/a | os.rmdir(self.good_dir_path) |
---|
314 | n/a | if os.path.exists(self.bad_dir_path): |
---|
315 | n/a | os.rmdir(self.bad_dir_path) |
---|
316 | n/a | |
---|
317 | n/a | class ImportSideEffectTests(unittest.TestCase): |
---|
318 | n/a | """Test side-effects from importing 'site'.""" |
---|
319 | n/a | |
---|
320 | n/a | def setUp(self): |
---|
321 | n/a | """Make a copy of sys.path""" |
---|
322 | n/a | self.sys_path = sys.path[:] |
---|
323 | n/a | |
---|
324 | n/a | def tearDown(self): |
---|
325 | n/a | """Restore sys.path""" |
---|
326 | n/a | sys.path[:] = self.sys_path |
---|
327 | n/a | |
---|
328 | n/a | def test_abs_paths(self): |
---|
329 | n/a | # Make sure all imported modules have their __file__ and __cached__ |
---|
330 | n/a | # attributes as absolute paths. Arranging to put the Lib directory on |
---|
331 | n/a | # PYTHONPATH would cause the os module to have a relative path for |
---|
332 | n/a | # __file__ if abs_paths() does not get run. sys and builtins (the |
---|
333 | n/a | # only other modules imported before site.py runs) do not have |
---|
334 | n/a | # __file__ or __cached__ because they are built-in. |
---|
335 | n/a | parent = os.path.relpath(os.path.dirname(os.__file__)) |
---|
336 | n/a | env = os.environ.copy() |
---|
337 | n/a | env['PYTHONPATH'] = parent |
---|
338 | n/a | code = ('import os, sys', |
---|
339 | n/a | # use ASCII to avoid locale issues with non-ASCII directories |
---|
340 | n/a | 'os_file = os.__file__.encode("ascii", "backslashreplace")', |
---|
341 | n/a | r'sys.stdout.buffer.write(os_file + b"\n")', |
---|
342 | n/a | 'os_cached = os.__cached__.encode("ascii", "backslashreplace")', |
---|
343 | n/a | r'sys.stdout.buffer.write(os_cached + b"\n")') |
---|
344 | n/a | command = '\n'.join(code) |
---|
345 | n/a | # First, prove that with -S (no 'import site'), the paths are |
---|
346 | n/a | # relative. |
---|
347 | n/a | proc = subprocess.Popen([sys.executable, '-S', '-c', command], |
---|
348 | n/a | env=env, |
---|
349 | n/a | stdout=subprocess.PIPE) |
---|
350 | n/a | stdout, stderr = proc.communicate() |
---|
351 | n/a | |
---|
352 | n/a | self.assertEqual(proc.returncode, 0) |
---|
353 | n/a | os__file__, os__cached__ = stdout.splitlines()[:2] |
---|
354 | n/a | self.assertFalse(os.path.isabs(os__file__)) |
---|
355 | n/a | self.assertFalse(os.path.isabs(os__cached__)) |
---|
356 | n/a | # Now, with 'import site', it works. |
---|
357 | n/a | proc = subprocess.Popen([sys.executable, '-c', command], |
---|
358 | n/a | env=env, |
---|
359 | n/a | stdout=subprocess.PIPE) |
---|
360 | n/a | stdout, stderr = proc.communicate() |
---|
361 | n/a | self.assertEqual(proc.returncode, 0) |
---|
362 | n/a | os__file__, os__cached__ = stdout.splitlines()[:2] |
---|
363 | n/a | self.assertTrue(os.path.isabs(os__file__), |
---|
364 | n/a | "expected absolute path, got {}" |
---|
365 | n/a | .format(os__file__.decode('ascii'))) |
---|
366 | n/a | self.assertTrue(os.path.isabs(os__cached__), |
---|
367 | n/a | "expected absolute path, got {}" |
---|
368 | n/a | .format(os__cached__.decode('ascii'))) |
---|
369 | n/a | |
---|
370 | n/a | def test_no_duplicate_paths(self): |
---|
371 | n/a | # No duplicate paths should exist in sys.path |
---|
372 | n/a | # Handled by removeduppaths() |
---|
373 | n/a | site.removeduppaths() |
---|
374 | n/a | seen_paths = set() |
---|
375 | n/a | for path in sys.path: |
---|
376 | n/a | self.assertNotIn(path, seen_paths) |
---|
377 | n/a | seen_paths.add(path) |
---|
378 | n/a | |
---|
379 | n/a | @unittest.skip('test not implemented') |
---|
380 | n/a | def test_add_build_dir(self): |
---|
381 | n/a | # Test that the build directory's Modules directory is used when it |
---|
382 | n/a | # should be. |
---|
383 | n/a | # XXX: implement |
---|
384 | n/a | pass |
---|
385 | n/a | |
---|
386 | n/a | def test_setting_quit(self): |
---|
387 | n/a | # 'quit' and 'exit' should be injected into builtins |
---|
388 | n/a | self.assertTrue(hasattr(builtins, "quit")) |
---|
389 | n/a | self.assertTrue(hasattr(builtins, "exit")) |
---|
390 | n/a | |
---|
391 | n/a | def test_setting_copyright(self): |
---|
392 | n/a | # 'copyright', 'credits', and 'license' should be in builtins |
---|
393 | n/a | self.assertTrue(hasattr(builtins, "copyright")) |
---|
394 | n/a | self.assertTrue(hasattr(builtins, "credits")) |
---|
395 | n/a | self.assertTrue(hasattr(builtins, "license")) |
---|
396 | n/a | |
---|
397 | n/a | def test_setting_help(self): |
---|
398 | n/a | # 'help' should be set in builtins |
---|
399 | n/a | self.assertTrue(hasattr(builtins, "help")) |
---|
400 | n/a | |
---|
401 | n/a | def test_aliasing_mbcs(self): |
---|
402 | n/a | if sys.platform == "win32": |
---|
403 | n/a | import locale |
---|
404 | n/a | if locale.getdefaultlocale()[1].startswith('cp'): |
---|
405 | n/a | for value in encodings.aliases.aliases.values(): |
---|
406 | n/a | if value == "mbcs": |
---|
407 | n/a | break |
---|
408 | n/a | else: |
---|
409 | n/a | self.fail("did not alias mbcs") |
---|
410 | n/a | |
---|
411 | n/a | def test_sitecustomize_executed(self): |
---|
412 | n/a | # If sitecustomize is available, it should have been imported. |
---|
413 | n/a | if "sitecustomize" not in sys.modules: |
---|
414 | n/a | try: |
---|
415 | n/a | import sitecustomize |
---|
416 | n/a | except ImportError: |
---|
417 | n/a | pass |
---|
418 | n/a | else: |
---|
419 | n/a | self.fail("sitecustomize not imported automatically") |
---|
420 | n/a | |
---|
421 | n/a | @test.support.requires_resource('network') |
---|
422 | n/a | @test.support.system_must_validate_cert |
---|
423 | n/a | @unittest.skipUnless(sys.version_info[3] == 'final', |
---|
424 | n/a | 'only for released versions') |
---|
425 | n/a | @unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"), |
---|
426 | n/a | 'need SSL support to download license') |
---|
427 | n/a | def test_license_exists_at_url(self): |
---|
428 | n/a | # This test is a bit fragile since it depends on the format of the |
---|
429 | n/a | # string displayed by license in the absence of a LICENSE file. |
---|
430 | n/a | url = license._Printer__data.split()[1] |
---|
431 | n/a | req = urllib.request.Request(url, method='HEAD') |
---|
432 | n/a | try: |
---|
433 | n/a | with test.support.transient_internet(url): |
---|
434 | n/a | with urllib.request.urlopen(req) as data: |
---|
435 | n/a | code = data.getcode() |
---|
436 | n/a | except urllib.error.HTTPError as e: |
---|
437 | n/a | code = e.code |
---|
438 | n/a | self.assertEqual(code, 200, msg="Can't find " + url) |
---|
439 | n/a | |
---|
440 | n/a | |
---|
441 | n/a | class StartupImportTests(unittest.TestCase): |
---|
442 | n/a | |
---|
443 | n/a | def test_startup_imports(self): |
---|
444 | n/a | # This tests checks which modules are loaded by Python when it |
---|
445 | n/a | # initially starts upon startup. |
---|
446 | n/a | popen = subprocess.Popen([sys.executable, '-I', '-v', '-c', |
---|
447 | n/a | 'import sys; print(set(sys.modules))'], |
---|
448 | n/a | stdout=subprocess.PIPE, |
---|
449 | n/a | stderr=subprocess.PIPE, |
---|
450 | n/a | encoding='utf-8') |
---|
451 | n/a | stdout, stderr = popen.communicate() |
---|
452 | n/a | modules = eval(stdout) |
---|
453 | n/a | |
---|
454 | n/a | self.assertIn('site', modules) |
---|
455 | n/a | |
---|
456 | n/a | # http://bugs.python.org/issue19205 |
---|
457 | n/a | re_mods = {'re', '_sre', 'sre_compile', 'sre_constants', 'sre_parse'} |
---|
458 | n/a | # _osx_support uses the re module in many placs |
---|
459 | n/a | if sys.platform != 'darwin': |
---|
460 | n/a | self.assertFalse(modules.intersection(re_mods), stderr) |
---|
461 | n/a | # http://bugs.python.org/issue9548 |
---|
462 | n/a | self.assertNotIn('locale', modules, stderr) |
---|
463 | n/a | if sys.platform != 'darwin': |
---|
464 | n/a | # http://bugs.python.org/issue19209 |
---|
465 | n/a | self.assertNotIn('copyreg', modules, stderr) |
---|
466 | n/a | # http://bugs.python.org/issue19218> |
---|
467 | n/a | collection_mods = {'_collections', 'collections', 'functools', |
---|
468 | n/a | 'heapq', 'itertools', 'keyword', 'operator', |
---|
469 | n/a | 'reprlib', 'types', 'weakref' |
---|
470 | n/a | }.difference(sys.builtin_module_names) |
---|
471 | n/a | # http://bugs.python.org/issue28095 |
---|
472 | n/a | if sys.platform != 'darwin': |
---|
473 | n/a | self.assertFalse(modules.intersection(collection_mods), stderr) |
---|
474 | n/a | |
---|
475 | n/a | def test_startup_interactivehook(self): |
---|
476 | n/a | r = subprocess.Popen([sys.executable, '-c', |
---|
477 | n/a | 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait() |
---|
478 | n/a | self.assertTrue(r, "'__interactivehook__' not added by site") |
---|
479 | n/a | |
---|
480 | n/a | def test_startup_interactivehook_isolated(self): |
---|
481 | n/a | # issue28192 readline is not automatically enabled in isolated mode |
---|
482 | n/a | r = subprocess.Popen([sys.executable, '-I', '-c', |
---|
483 | n/a | 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait() |
---|
484 | n/a | self.assertFalse(r, "'__interactivehook__' added in isolated mode") |
---|
485 | n/a | |
---|
486 | n/a | def test_startup_interactivehook_isolated_explicit(self): |
---|
487 | n/a | # issue28192 readline can be explicitly enabled in isolated mode |
---|
488 | n/a | r = subprocess.Popen([sys.executable, '-I', '-c', |
---|
489 | n/a | 'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait() |
---|
490 | n/a | self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()") |
---|
491 | n/a | |
---|
492 | n/a | @classmethod |
---|
493 | n/a | def _create_underpth_exe(self, lines): |
---|
494 | n/a | exe_file = os.path.join(os.getenv('TEMP'), os.path.split(sys.executable)[1]) |
---|
495 | n/a | shutil.copy(sys.executable, exe_file) |
---|
496 | n/a | |
---|
497 | n/a | _pth_file = os.path.splitext(exe_file)[0] + '._pth' |
---|
498 | n/a | try: |
---|
499 | n/a | with open(_pth_file, 'w') as f: |
---|
500 | n/a | for line in lines: |
---|
501 | n/a | print(line, file=f) |
---|
502 | n/a | return exe_file |
---|
503 | n/a | except: |
---|
504 | n/a | os.unlink(_pth_file) |
---|
505 | n/a | os.unlink(exe_file) |
---|
506 | n/a | raise |
---|
507 | n/a | |
---|
508 | n/a | @classmethod |
---|
509 | n/a | def _cleanup_underpth_exe(self, exe_file): |
---|
510 | n/a | _pth_file = os.path.splitext(exe_file)[0] + '._pth' |
---|
511 | n/a | os.unlink(_pth_file) |
---|
512 | n/a | os.unlink(exe_file) |
---|
513 | n/a | |
---|
514 | n/a | @classmethod |
---|
515 | n/a | def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines): |
---|
516 | n/a | sys_path = [] |
---|
517 | n/a | for line in lines: |
---|
518 | n/a | if not line or line[0] == '#': |
---|
519 | n/a | continue |
---|
520 | n/a | abs_path = os.path.abspath(os.path.join(sys_prefix, line)) |
---|
521 | n/a | sys_path.append(abs_path) |
---|
522 | n/a | return sys_path |
---|
523 | n/a | |
---|
524 | n/a | @unittest.skipUnless(sys.platform == 'win32', "only supported on Windows") |
---|
525 | n/a | def test_underpth_nosite_file(self): |
---|
526 | n/a | libpath = os.path.dirname(os.path.dirname(encodings.__file__)) |
---|
527 | n/a | exe_prefix = os.path.dirname(sys.executable) |
---|
528 | n/a | pth_lines = [ |
---|
529 | n/a | 'fake-path-name', |
---|
530 | n/a | *[libpath for _ in range(200)], |
---|
531 | n/a | '', |
---|
532 | n/a | '# comment', |
---|
533 | n/a | ] |
---|
534 | n/a | exe_file = self._create_underpth_exe(pth_lines) |
---|
535 | n/a | sys_path = self._calc_sys_path_for_underpth_nosite( |
---|
536 | n/a | os.path.dirname(exe_file), |
---|
537 | n/a | pth_lines) |
---|
538 | n/a | |
---|
539 | n/a | try: |
---|
540 | n/a | env = os.environ.copy() |
---|
541 | n/a | env['PYTHONPATH'] = 'from-env' |
---|
542 | n/a | env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH')) |
---|
543 | n/a | rc = subprocess.call([exe_file, '-c', |
---|
544 | n/a | 'import sys; sys.exit(sys.flags.no_site and ' |
---|
545 | n/a | 'len(sys.path) > 200 and ' |
---|
546 | n/a | 'sys.path == %r)' % sys_path, |
---|
547 | n/a | ], env=env) |
---|
548 | n/a | finally: |
---|
549 | n/a | self._cleanup_underpth_exe(exe_file) |
---|
550 | n/a | self.assertTrue(rc, "sys.path is incorrect") |
---|
551 | n/a | |
---|
552 | n/a | @unittest.skipUnless(sys.platform == 'win32', "only supported on Windows") |
---|
553 | n/a | def test_underpth_file(self): |
---|
554 | n/a | libpath = os.path.dirname(os.path.dirname(encodings.__file__)) |
---|
555 | n/a | exe_prefix = os.path.dirname(sys.executable) |
---|
556 | n/a | exe_file = self._create_underpth_exe([ |
---|
557 | n/a | 'fake-path-name', |
---|
558 | n/a | *[libpath for _ in range(200)], |
---|
559 | n/a | '', |
---|
560 | n/a | '# comment', |
---|
561 | n/a | 'import site' |
---|
562 | n/a | ]) |
---|
563 | n/a | sys_prefix = os.path.dirname(exe_file) |
---|
564 | n/a | try: |
---|
565 | n/a | env = os.environ.copy() |
---|
566 | n/a | env['PYTHONPATH'] = 'from-env' |
---|
567 | n/a | env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH')) |
---|
568 | n/a | rc = subprocess.call([exe_file, '-c', |
---|
569 | n/a | 'import sys; sys.exit(not sys.flags.no_site and ' |
---|
570 | n/a | '%r in sys.path and %r in sys.path and %r not in sys.path and ' |
---|
571 | n/a | 'all("\\r" not in p and "\\n" not in p for p in sys.path))' % ( |
---|
572 | n/a | os.path.join(sys_prefix, 'fake-path-name'), |
---|
573 | n/a | libpath, |
---|
574 | n/a | os.path.join(sys_prefix, 'from-env'), |
---|
575 | n/a | )], env=env) |
---|
576 | n/a | finally: |
---|
577 | n/a | self._cleanup_underpth_exe(exe_file) |
---|
578 | n/a | self.assertTrue(rc, "sys.path is incorrect") |
---|
579 | n/a | |
---|
580 | n/a | |
---|
581 | n/a | if __name__ == "__main__": |
---|
582 | n/a | unittest.main() |
---|