Exemple #1
0
 def test_security(self):
     # This test is incomplete since we are normally not run as root and
     # therefore can't test the file ownership being wrong.
     d = os_helper.TESTFN
     os.mkdir(d)
     self.addCleanup(os_helper.rmtree, d)
     fn = os.path.join(d, '.netrc')
     with open(fn, 'wt') as f:
         f.write("""\
             machine foo.domain.com login bar password pass
             default login foo password pass
             """)
     with os_helper.EnvironmentVarGuard() as environ:
         environ.set('HOME', d)
         os.chmod(fn, 0o600)
         nrc = netrc.netrc()
         self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', '', 'pass'))
         os.chmod(fn, 0o622)
         self.assertRaises(netrc.NetrcParseError, netrc.netrc)
     with open(fn, 'wt') as f:
         f.write("""\
             machine foo.domain.com login anonymous password pass
             default login foo password pass
             """)
     with os_helper.EnvironmentVarGuard() as environ:
         environ.set('HOME', d)
         os.chmod(fn, 0o600)
         nrc = netrc.netrc()
         self.assertEqual(nrc.hosts['foo.domain.com'],
                          ('anonymous', '', 'pass'))
         os.chmod(fn, 0o622)
         self.assertEqual(nrc.hosts['foo.domain.com'],
                          ('anonymous', '', 'pass'))
Exemple #2
0
 def test_expandvars(self):
     with os_helper.EnvironmentVarGuard() as env:
         env.clear()
         env["foo"] = "bar"
         env["{foo"] = "baz1"
         env["{foo}"] = "baz2"
         tester('ntpath.expandvars("foo")', "foo")
         tester('ntpath.expandvars("$foo bar")', "bar bar")
         tester('ntpath.expandvars("${foo}bar")', "barbar")
         tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar")
         tester('ntpath.expandvars("$bar bar")', "$bar bar")
         tester('ntpath.expandvars("$?bar")', "$?bar")
         tester('ntpath.expandvars("$foo}bar")', "bar}bar")
         tester('ntpath.expandvars("${foo")', "${foo")
         tester('ntpath.expandvars("${{foo}}")', "baz1}")
         tester('ntpath.expandvars("$foo$foo")', "barbar")
         tester('ntpath.expandvars("$bar$bar")', "$bar$bar")
         tester('ntpath.expandvars("%foo% bar")', "bar bar")
         tester('ntpath.expandvars("%foo%bar")', "barbar")
         tester('ntpath.expandvars("%foo%%foo%")', "barbar")
         tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar")
         tester('ntpath.expandvars("%?bar%")', "%?bar%")
         tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
         tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
         tester('ntpath.expandvars("bar\'%foo%")', "bar\'%foo%")
    def test_expandvars(self):
        expandvars = self.pathmodule.expandvars
        with os_helper.EnvironmentVarGuard() as env:
            env.clear()
            env["foo"] = "bar"
            env["{foo"] = "baz1"
            env["{foo}"] = "baz2"
            self.assertEqual(expandvars("foo"), "foo")
            self.assertEqual(expandvars("$foo bar"), "bar bar")
            self.assertEqual(expandvars("${foo}bar"), "barbar")
            self.assertEqual(expandvars("$[foo]bar"), "$[foo]bar")
            self.assertEqual(expandvars("$bar bar"), "$bar bar")
            self.assertEqual(expandvars("$?bar"), "$?bar")
            self.assertEqual(expandvars("$foo}bar"), "bar}bar")
            self.assertEqual(expandvars("${foo"), "${foo")
            self.assertEqual(expandvars("${{foo}}"), "baz1}")
            self.assertEqual(expandvars("$foo$foo"), "barbar")
            self.assertEqual(expandvars("$bar$bar"), "$bar$bar")

            self.assertEqual(expandvars(b"foo"), b"foo")
            self.assertEqual(expandvars(b"$foo bar"), b"bar bar")
            self.assertEqual(expandvars(b"${foo}bar"), b"barbar")
            self.assertEqual(expandvars(b"$[foo]bar"), b"$[foo]bar")
            self.assertEqual(expandvars(b"$bar bar"), b"$bar bar")
            self.assertEqual(expandvars(b"$?bar"), b"$?bar")
            self.assertEqual(expandvars(b"$foo}bar"), b"bar}bar")
            self.assertEqual(expandvars(b"${foo"), b"${foo")
            self.assertEqual(expandvars(b"${{foo}}"), b"baz1}")
            self.assertEqual(expandvars(b"$foo$foo"), b"barbar")
            self.assertEqual(expandvars(b"$bar$bar"), b"$bar$bar")
    def test_expandvars_nonascii(self):
        expandvars = self.pathmodule.expandvars

        def check(value, expected):
            self.assertEqual(expandvars(value), expected)

        with os_helper.EnvironmentVarGuard() as env:
            env.clear()
            nonascii = os_helper.FS_NONASCII
            env['spam'] = nonascii
            env[nonascii] = 'ham' + nonascii
            check(nonascii, nonascii)
            check('$spam bar', '%s bar' % nonascii)
            check('${spam}bar', '%sbar' % nonascii)
            check('${%s}bar' % nonascii, 'ham%sbar' % nonascii)
            check('$bar%s bar' % nonascii, '$bar%s bar' % nonascii)
            check('$spam}bar', '%s}bar' % nonascii)

            check(os.fsencode(nonascii), os.fsencode(nonascii))
            check(b'$spam bar', os.fsencode('%s bar' % nonascii))
            check(b'${spam}bar', os.fsencode('%sbar' % nonascii))
            check(os.fsencode('${%s}bar' % nonascii),
                  os.fsencode('ham%sbar' % nonascii))
            check(os.fsencode('$bar%s bar' % nonascii),
                  os.fsencode('$bar%s bar' % nonascii))
            check(b'$spam}bar', os.fsencode('%s}bar' % nonascii))
Exemple #5
0
    def test_expanduser_pwd(self):
        pwd = import_helper.import_module('pwd')

        self.assertIsInstance(posixpath.expanduser("~/"), str)
        self.assertIsInstance(posixpath.expanduser(b"~/"), bytes)

        # if home directory == root directory, this test makes no sense
        if posixpath.expanduser("~") != '/':
            self.assertEqual(
                posixpath.expanduser("~") + "/", posixpath.expanduser("~/"))
            self.assertEqual(
                posixpath.expanduser(b"~") + b"/", posixpath.expanduser(b"~/"))
        self.assertIsInstance(posixpath.expanduser("~root/"), str)
        self.assertIsInstance(posixpath.expanduser("~foo/"), str)
        self.assertIsInstance(posixpath.expanduser(b"~root/"), bytes)
        self.assertIsInstance(posixpath.expanduser(b"~foo/"), bytes)

        with os_helper.EnvironmentVarGuard() as env:
            # expanduser should fall back to using the password database
            del env['HOME']

            home = pwd.getpwuid(os.getuid()).pw_dir
            # $HOME can end with a trailing /, so strip it (see #17809)
            home = home.rstrip("/") or '/'
            self.assertEqual(posixpath.expanduser("~"), home)

            # bpo-10496: If the HOME environment variable is not set and the
            # user (current identifier or name in the path) doesn't exist in
            # the password database (pwd.getuid() or pwd.getpwnam() fail),
            # expanduser() must return the path unchanged.
            with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError), \
                 mock.patch.object(pwd, 'getpwnam', side_effect=KeyError):
                for path in ('~', '~/.local', '~vstinner/'):
                    self.assertEqual(posixpath.expanduser(path), path)
Exemple #6
0
 def setUp(self):
     self._threads = threading_helper.threading_setup()
     os.environ = os_helper.EnvironmentVarGuard()
     self.server_started = threading.Event()
     self.thread = TestServerThread(self, self.request_handler)
     self.thread.start()
     self.server_started.wait()
Exemple #7
0
 def test_file_not_found_in_home(self):
     d = os_helper.TESTFN
     os.mkdir(d)
     self.addCleanup(os_helper.rmtree, d)
     with os_helper.EnvironmentVarGuard() as environ:
         environ.set('HOME', d)
         self.assertRaises(FileNotFoundError, netrc.netrc)
Exemple #8
0
 def fake_expanduser(s):
     called.append(s)
     with os_helper.EnvironmentVarGuard() as environ:
         environ.set('HOME', fake_home)
         environ.set('USERPROFILE', fake_home)
         result = orig_expanduser(s)
         return result
Exemple #9
0
    def test_expanduser(self):
        tester('ntpath.expanduser("test")', 'test')

        with os_helper.EnvironmentVarGuard() as env:
            env.clear()
            tester('ntpath.expanduser("~test")', '~test')

            env['HOMEPATH'] = 'eric\\idle'
            env['HOMEDRIVE'] = 'C:\\'
            tester('ntpath.expanduser("~test")', 'C:\\eric\\test')
            tester('ntpath.expanduser("~")', 'C:\\eric\\idle')

            del env['HOMEDRIVE']
            tester('ntpath.expanduser("~test")', 'eric\\test')
            tester('ntpath.expanduser("~")', 'eric\\idle')

            env.clear()
            env['USERPROFILE'] = 'C:\\eric\\idle'
            tester('ntpath.expanduser("~test")', 'C:\\eric\\test')
            tester('ntpath.expanduser("~")', 'C:\\eric\\idle')
            tester('ntpath.expanduser("~test\\foo\\bar")',
                   'C:\\eric\\test\\foo\\bar')
            tester('ntpath.expanduser("~test/foo/bar")',
                   'C:\\eric\\test/foo/bar')
            tester('ntpath.expanduser("~\\foo\\bar")',
                   'C:\\eric\\idle\\foo\\bar')
            tester('ntpath.expanduser("~/foo/bar")', 'C:\\eric\\idle/foo/bar')

            # bpo-36264: ignore `HOME` when set on windows
            env.clear()
            env['HOME'] = 'F:\\'
            env['USERPROFILE'] = 'C:\\eric\\idle'
            tester('ntpath.expanduser("~test")', 'C:\\eric\\test')
            tester('ntpath.expanduser("~")', 'C:\\eric\\idle')
 def test_mock_getcaps(self):
     # Test mailcap.getcaps() using mock mailcap file in this dir.
     # Temporarily override any existing system mailcap file by pointing the
     # MAILCAPS environment variable to our mock file.
     with os_helper.EnvironmentVarGuard() as env:
         env["MAILCAPS"] = MAILCAPFILE
         caps = mailcap.getcaps()
         self.assertDictEqual(caps, MAILCAPDICT)
 def test_sensitive(self):
     with os_helper.EnvironmentVarGuard() as env:
         env.unset('PYTHONCASEOK')
         self.caseok_env_changed(should_exist=False)
         sensitive, insensitive = self.sensitivity_test()
         self.assertIsNotNone(sensitive)
         self.assertIn(self.name, sensitive.get_filename(self.name))
         self.assertIsNone(insensitive)
Exemple #12
0
    def test_environment_preferred(self):
        webbrowser = import_helper.import_fresh_module('webbrowser')
        try:
            webbrowser.get()
            least_preferred_browser = webbrowser.get(
                webbrowser._tryorder[-1]).name
        except (webbrowser.Error, IndexError) as err:
            self.skipTest(str(err))

        with os_helper.EnvironmentVarGuard() as env:
            env["BROWSER"] = least_preferred_browser
            webbrowser = import_helper.import_fresh_module('webbrowser')
            self.assertEqual(webbrowser.get().name, least_preferred_browser)

        with os_helper.EnvironmentVarGuard() as env:
            env["BROWSER"] = sys.executable
            webbrowser = import_helper.import_fresh_module('webbrowser')
            self.assertEqual(webbrowser.get().name, sys.executable)
Exemple #13
0
 def test_environment(self):
     webbrowser = import_helper.import_fresh_module('webbrowser')
     try:
         browser = webbrowser.get().name
     except webbrowser.Error as err:
         self.skipTest(str(err))
     with os_helper.EnvironmentVarGuard() as env:
         env["BROWSER"] = browser
         webbrowser = import_helper.import_fresh_module('webbrowser')
         webbrowser.get()
Exemple #14
0
 def setUp(self):
     self.maxDiff = None
     self.prog_name = 'bogus_program_xxxx'
     self.temp_path_dir = os.path.abspath(os.getcwd())
     self.env = self.enterContext(os_helper.EnvironmentVarGuard())
     for cv in ('CFLAGS', 'LDFLAGS', 'CPPFLAGS', 'BASECFLAGS', 'BLDSHARED',
                'LDSHARED', 'CC', 'CXX', 'PY_CFLAGS', 'PY_LDFLAGS',
                'PY_CPPFLAGS', 'PY_CORE_CFLAGS', 'PY_CORE_LDFLAGS'):
         if cv in self.env:
             self.env.unset(cv)
Exemple #15
0
 def test_source(self):
     # XXX (ncoghlan): It would be nice to use test.import_helper.CleanImport
     # here, but that breaks because the os module registers some
     # handlers in copy_reg on import. Since CleanImport doesn't
     # revert that registration, the module is left in a broken
     # state after reversion. Reinitialising the module contents
     # and just reverting os.environ to its previous state is an OK
     # workaround
     with os_helper.EnvironmentVarGuard():
         import os
         imp.reload(os)
Exemple #16
0
    def test_expanduser_home_envvar(self):
        with os_helper.EnvironmentVarGuard() as env:
            env['HOME'] = '/home/victor'
            self.assertEqual(posixpath.expanduser("~"), "/home/victor")

            # expanduser() strips trailing slash
            env['HOME'] = '/home/victor/'
            self.assertEqual(posixpath.expanduser("~"), "/home/victor")

            for home in '/', '', '//', '///':
                with self.subTest(home=home):
                    env['HOME'] = home
                    self.assertEqual(posixpath.expanduser("~"), "/")
                    self.assertEqual(posixpath.expanduser("~/"), "/")
                    self.assertEqual(posixpath.expanduser("~/foo"), "/foo")
Exemple #17
0
 def setUp(self):
     if not os.path.isdir(LOCALEDIR):
         os.makedirs(LOCALEDIR)
     with open(MOFILE, 'wb') as fp:
         fp.write(base64.decodebytes(GNU_MO_DATA))
     with open(MOFILE_BAD_MAJOR_VERSION, 'wb') as fp:
         fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MAJOR_VERSION))
     with open(MOFILE_BAD_MINOR_VERSION, 'wb') as fp:
         fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MINOR_VERSION))
     with open(UMOFILE, 'wb') as fp:
         fp.write(base64.decodebytes(UMO_DATA))
     with open(MMOFILE, 'wb') as fp:
         fp.write(base64.decodebytes(MMO_DATA))
     self.env = os_helper.EnvironmentVarGuard()
     self.env['LANGUAGE'] = 'xx'
     gettext._translations.clear()
Exemple #18
0
    def test_expanduser(self):
        tester('ntpath.expanduser("test")', 'test')

        with os_helper.EnvironmentVarGuard() as env:
            env.clear()
            tester('ntpath.expanduser("~test")', '~test')

            env['HOMEDRIVE'] = 'C:\\'
            env['HOMEPATH'] = 'Users\\eric'
            env['USERNAME'] = '******'
            tester('ntpath.expanduser("~test")', 'C:\\Users\\test')
            tester('ntpath.expanduser("~")', 'C:\\Users\\eric')

            del env['HOMEDRIVE']
            tester('ntpath.expanduser("~test")', 'Users\\test')
            tester('ntpath.expanduser("~")', 'Users\\eric')

            env.clear()
            env['USERPROFILE'] = 'C:\\Users\\eric'
            env['USERNAME'] = '******'
            tester('ntpath.expanduser("~test")', 'C:\\Users\\test')
            tester('ntpath.expanduser("~")', 'C:\\Users\\eric')
            tester('ntpath.expanduser("~test\\foo\\bar")',
                   'C:\\Users\\test\\foo\\bar')
            tester('ntpath.expanduser("~test/foo/bar")',
                   'C:\\Users\\test/foo/bar')
            tester('ntpath.expanduser("~\\foo\\bar")',
                   'C:\\Users\\eric\\foo\\bar')
            tester('ntpath.expanduser("~/foo/bar")',
                   'C:\\Users\\eric/foo/bar')

            # bpo-36264: ignore `HOME` when set on windows
            env.clear()
            env['HOME'] = 'F:\\'
            env['USERPROFILE'] = 'C:\\Users\\eric'
            env['USERNAME'] = '******'
            tester('ntpath.expanduser("~test")', 'C:\\Users\\test')
            tester('ntpath.expanduser("~")', 'C:\\Users\\eric')

            # bpo-39899: don't guess another user's home directory if
            # `%USERNAME% != basename(%USERPROFILE%)`
            env.clear()
            env['USERPROFILE'] = 'C:\\Users\\eric'
            env['USERNAME'] = '******'
            tester('ntpath.expanduser("~test")', '~test')
            tester('ntpath.expanduser("~")', 'C:\\Users\\eric')
Exemple #19
0
 def test_load_from_source(self):
     # Verify that the imp module can correctly load and find .py files
     # XXX (ncoghlan): It would be nice to use import_helper.CleanImport
     # here, but that breaks because the os module registers some
     # handlers in copy_reg on import. Since CleanImport doesn't
     # revert that registration, the module is left in a broken
     # state after reversion. Reinitialising the module contents
     # and just reverting os.environ to its previous state is an OK
     # workaround
     orig_path = os.path
     orig_getenv = os.getenv
     with os_helper.EnvironmentVarGuard():
         x = imp.find_module("os")
         self.addCleanup(x[0].close)
         new_os = imp.load_module("os", *x)
         self.assertIs(os, new_os)
         self.assertIs(orig_path, new_os.path)
         self.assertIsNot(orig_getenv, new_os.getenv)
 def test_listmailcapfiles(self):
     # The return value for listmailcapfiles() will vary by system.
     # So verify that listmailcapfiles() returns a list of strings that is of
     # non-zero length.
     mcfiles = mailcap.listmailcapfiles()
     self.assertIsInstance(mcfiles, list)
     for m in mcfiles:
         self.assertIsInstance(m, str)
     with os_helper.EnvironmentVarGuard() as env:
         # According to RFC 1524, if MAILCAPS env variable exists, use that
         # and only that.
         if "MAILCAPS" in env:
             env_mailcaps = env["MAILCAPS"].split(os.pathsep)
         else:
             env_mailcaps = ["/testdir1/.mailcap", "/testdir2/mailcap"]
             env["MAILCAPS"] = os.pathsep.join(env_mailcaps)
             mcfiles = mailcap.listmailcapfiles()
     self.assertEqual(env_mailcaps, mcfiles)
Exemple #21
0
 def test_expandvars_nonascii(self):
     def check(value, expected):
         tester('ntpath.expandvars(%r)' % value, expected)
     with os_helper.EnvironmentVarGuard() as env:
         env.clear()
         nonascii = os_helper.FS_NONASCII
         env['spam'] = nonascii
         env[nonascii] = 'ham' + nonascii
         check('$spam bar', '%s bar' % nonascii)
         check('$%s bar' % nonascii, '$%s bar' % nonascii)
         check('${spam}bar', '%sbar' % nonascii)
         check('${%s}bar' % nonascii, 'ham%sbar' % nonascii)
         check('$spam}bar', '%s}bar' % nonascii)
         check('$%s}bar' % nonascii, '$%s}bar' % nonascii)
         check('%spam% bar', '%s bar' % nonascii)
         check('%{}% bar'.format(nonascii), 'ham%s bar' % nonascii)
         check('%spam%bar', '%sbar' % nonascii)
         check('%{}%bar'.format(nonascii), 'ham%sbar' % nonascii)
Exemple #22
0
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            raise unittest.SkipTest('Absolute path should have drive part')
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'], fullname[0],
                                     fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest('Cannot connect to UNC Path')

        with os_helper.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            stdout = subprocess.check_output(
                [unc_name, '-c', 'import tkinter; print(tkinter)'])

        self.assertIn(b'tkinter', stdout)
Exemple #23
0
 def test_uname_win32_ARCHITEW6432(self):
     # Issue 7860: make sure we get architecture from the correct variable
     # on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
     # using it, per
     # http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
     try:
         with os_helper.EnvironmentVarGuard() as environ:
             if 'PROCESSOR_ARCHITEW6432' in environ:
                 del environ['PROCESSOR_ARCHITEW6432']
             environ['PROCESSOR_ARCHITECTURE'] = 'foo'
             platform._uname_cache = None
             system, node, release, version, machine, processor = platform.uname()
             self.assertEqual(machine, 'foo')
             environ['PROCESSOR_ARCHITEW6432'] = 'bar'
             platform._uname_cache = None
             system, node, release, version, machine, processor = platform.uname()
             self.assertEqual(machine, 'bar')
     finally:
         platform._uname_cache = None
Exemple #24
0
    def test_find_on_libpath(self):
        import subprocess
        import tempfile

        try:
            p = subprocess.Popen(['gcc', '--version'],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.DEVNULL)
            out, _ = p.communicate()
        except OSError:
            raise unittest.SkipTest('gcc, needed for test, not available')
        with tempfile.TemporaryDirectory() as d:
            # create an empty temporary file
            srcname = os.path.join(d, 'dummy.c')
            libname = 'py_ctypes_test_dummy'
            dstname = os.path.join(d, 'lib%s.so' % libname)
            with open(srcname, 'w') as f:
                pass
            self.assertTrue(os.path.exists(srcname))
            # compile the file to a shared library
            cmd = [
                'gcc', '-o', dstname, '--shared',
                '-Wl,-soname,lib%s.so' % libname, srcname
            ]
            out = subprocess.check_output(cmd)
            self.assertTrue(os.path.exists(dstname))
            # now check that the .so can't be found (since not in
            # LD_LIBRARY_PATH)
            self.assertIsNone(find_library(libname))
            # now add the location to LD_LIBRARY_PATH
            with os_helper.EnvironmentVarGuard() as env:
                KEY = 'LD_LIBRARY_PATH'
                if KEY not in env:
                    v = d
                else:
                    v = '%s:%s' % (env[KEY], d)
                env.set(KEY, v)
                # now check that the .so can be found (since in
                # LD_LIBRARY_PATH)
                self.assertEqual(find_library(libname), 'lib%s.so' % libname)
Exemple #25
0
    def testLoadTkFailure(self):
        old_display = None
        if sys.platform.startswith(('win', 'darwin', 'cygwin')):
            # no failure possible on windows?

            # XXX Maybe on tk older than 8.4.13 it would be possible,
            # see tkinter.h.
            return
        with os_helper.EnvironmentVarGuard() as env:
            if 'DISPLAY' in os.environ:
                del env['DISPLAY']
                # on some platforms, deleting environment variables
                # doesn't actually carry through to the process level
                # because they don't support unsetenv
                # If that's the case, abort.
                with os.popen('echo $DISPLAY') as pipe:
                    display = pipe.read().strip()
                if display:
                    return

            tcl = Tcl()
            self.assertRaises(TclError, tcl.winfo_geometry)
            self.assertRaises(TclError, tcl.loadtk)
Exemple #26
0
 def wrapper(*args, **kwargs):
     with os_helper.EnvironmentVarGuard() as env:
         env['SOURCE_DATE_EPOCH'] = '123456789'
         return fxn(*args, **kwargs)
Exemple #27
0
 def wrapper(*args, **kwargs):
     with os_helper.EnvironmentVarGuard() as env:
         env.unset('SOURCE_DATE_EPOCH')
         return fxn(*args, **kwargs)
Exemple #28
0
    def test_find_executable(self):
        with os_helper.temp_dir() as tmp_dir:
            # use TESTFN to get a pseudo-unique filename
            program_noeext = os_helper.TESTFN
            # Give the temporary program an ".exe" suffix for all.
            # It's needed on Windows and not harmful on other platforms.
            program = program_noeext + ".exe"

            filename = os.path.join(tmp_dir, program)
            with open(filename, "wb"):
                pass
            os.chmod(filename, stat.S_IXUSR)

            # test path parameter
            rv = find_executable(program, path=tmp_dir)
            self.assertEqual(rv, filename)

            if sys.platform == 'win32':
                # test without ".exe" extension
                rv = find_executable(program_noeext, path=tmp_dir)
                self.assertEqual(rv, filename)

            # test find in the current directory
            with os_helper.change_cwd(tmp_dir):
                rv = find_executable(program)
                self.assertEqual(rv, program)

            # test non-existent program
            dont_exist_program = "dontexist_" + program
            rv = find_executable(dont_exist_program, path=tmp_dir)
            self.assertIsNone(rv)

            # PATH='': no match, except in the current directory
            with os_helper.EnvironmentVarGuard() as env:
                env['PATH'] = ''
                with unittest.mock.patch('distutils.spawn.os.confstr',
                                         return_value=tmp_dir, create=True), \
                     unittest.mock.patch('distutils.spawn.os.defpath',
                                         tmp_dir):
                    rv = find_executable(program)
                    self.assertIsNone(rv)

                    # look in current directory
                    with os_helper.change_cwd(tmp_dir):
                        rv = find_executable(program)
                        self.assertEqual(rv, program)

            # PATH=':': explicitly looks in the current directory
            with os_helper.EnvironmentVarGuard() as env:
                env['PATH'] = os.pathsep
                with unittest.mock.patch('distutils.spawn.os.confstr',
                                         return_value='', create=True), \
                     unittest.mock.patch('distutils.spawn.os.defpath', ''):
                    rv = find_executable(program)
                    self.assertIsNone(rv)

                    # look in current directory
                    with os_helper.change_cwd(tmp_dir):
                        rv = find_executable(program)
                        self.assertEqual(rv, program)

            # missing PATH: test os.confstr("CS_PATH") and os.defpath
            with os_helper.EnvironmentVarGuard() as env:
                env.pop('PATH', None)

                # without confstr
                with unittest.mock.patch('distutils.spawn.os.confstr',
                                         side_effect=ValueError,
                                         create=True), \
                     unittest.mock.patch('distutils.spawn.os.defpath',
                                         tmp_dir):
                    rv = find_executable(program)
                    self.assertEqual(rv, filename)

                # with confstr
                with unittest.mock.patch('distutils.spawn.os.confstr',
                                         return_value=tmp_dir, create=True), \
                     unittest.mock.patch('distutils.spawn.os.defpath', ''):
                    rv = find_executable(program)
                    self.assertEqual(rv, filename)
Exemple #29
0
 def test_case_insensitivity(self):
     with os_helper.EnvironmentVarGuard() as env:
         env.set('PYTHONCASEOK', '1')
         self.caseok_env_changed(should_exist=True)
         loader = self.find_module()
         self.assertTrue(hasattr(loader, 'load_module'))
Exemple #30
0
 def test_case_sensitive(self):
     with os_helper.EnvironmentVarGuard() as env:
         env.unset('PYTHONCASEOK')
         self.caseok_env_changed(should_exist=False)
         loader = self.find_module()
         self.assertIsNone(loader)