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