ยปCore Development>Code coverage>Lib/test/test_site.py

Python code coverage for Lib/test/test_site.py

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