Example #1
0
    def test_wanted_dirs(self):
        # _candidate_tempdir_list contains the expected directories

        # Make sure the interesting environment variables are all set.
        added = []
        try:
            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname:
                    os.environ[envname] = os.path.abspath(envname)
                    added.append(envname)

            cand = tempfile._candidate_tempdir_list()

            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname: raise ValueError
                self.assert_(dirname in cand)

            try:
                dirname = os.getcwd()
            except (AttributeError, os.error):
                dirname = os.curdir

            self.assert_(dirname in cand)

            # Not practical to try to verify the presence of OS-specific
            # paths in this list.
        finally:
            for p in added:
                del os.environ[p]
Example #2
0
    async def run_pep8ify(self, mid, code):
        """Runs PEP8ify, outputs the resulting code and logs in a tuple.."""
        name = f"{mid}{time.perf_counter() * 1000:.0f}.py"

        # noinspection PyProtectedMember
        f = os.path.join(tempfile._candidate_tempdir_list()[0], name)

        await self.run_in_thread_pool(shutil.rmtree, [f],
                                      {"ignore_errors": True})

        async with self.async_open(f, "w") as fp:
            await fp.write(code)

        args = [
            "--print-function", "--list-fixes", "-f", "all", "-f",
            "maximum_line_length", "-n", "-w", f
        ]

        p = await asyncio.create_subprocess_exec(
            "pep8ify",
            *args,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.STDOUT)
        stdout, _ = await p.communicate()

        async with self.async_open(f, "r") as fp:
            code = await fp.read()

        await self.run_in_thread_pool(shutil.rmtree, [f],
                                      {"ignore_errors": True})

        return code, stdout.decode()
Example #3
0
    async def run_yapf(self, mid, style, code):
        """Runs YAPF, outputs the resulting code and logs in a tuple.."""
        name = f"{mid}{time.perf_counter() * 1000:.0f}.py"

        # noinspection PyProtectedMember
        f = os.path.join(tempfile._candidate_tempdir_list()[0], name)

        await self.run_in_thread_pool(shutil.rmtree, [f],
                                      {"ignore_errors": True})

        async with self.async_open(f, "w") as fp:
            await fp.write(code)

        args = ["--style", style.upper(), "-i", f]

        p = await asyncio.create_subprocess_exec(
            "yapf",
            *args,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.STDOUT)
        stdout, _ = await p.communicate()

        async with self.async_open(f, "r") as fp:
            code = await fp.read()

        await self.run_in_thread_pool(shutil.rmtree, [f],
                                      {"ignore_errors": True})

        return code, stdout.decode()
Example #4
0
    def test_nonempty_list(self) -> None:
        # _candidate_tempdir_list returns a nonempty list of strings

        cand = tempfile._candidate_tempdir_list()

        self.assertFalse(len(cand) == 0)
        for c in cand:
            self.assertIsInstance(c, str)
Example #5
0
    def test_nonempty_list(self):
        # _candidate_tempdir_list returns a nonempty list of strings

        cand = tempfile._candidate_tempdir_list()

        self.assertFalse(len(cand) == 0)
        for c in cand:
            self.assertIsInstance(c, basestring)
    def test_nonempty_list(self):
        # _candidate_tempdir_list returns a nonempty list of strings

        cand = tempfile._candidate_tempdir_list()

        self.failIf(len(cand) == 0)
        for c in cand:
            self.assert_(isinstance(c, basestring), "%s is not a string" % c)
Example #7
0
    def test_nonempty_list(self):
        # _candidate_tempdir_list returns a nonempty list of strings

        cand = tempfile._candidate_tempdir_list()

        self.failIf(len(cand) == 0)
        for c in cand:
            self.assert_(isinstance(c, basestring), "%s is not a string" % c)
Example #8
0
    def test_nonempty_list(self):
        # _candidate_tempdir_list returns a nonempty list of strings

        cand = tempfile._candidate_tempdir_list()

        self.assertFalse(len(cand) == 0)
        for c in cand:
            self.assertTrue(isinstance(c, str),
                         "%s is not a string" % c)
Example #9
0
def find_good_temp_dir():
    """
    Given a list of candidate temp directories extracted from ``ansible.cfg``
    and stored in _candidate_temp_dirs, combine it with the Python-builtin list
    of candidate directories used by :mod:`tempfile`, then iteratively try each
    in turn until one is found that is both writeable and executable.
    """
    paths = [
        os.path.expandvars(os.path.expanduser(p)) for p in _candidate_temp_dirs
    ]
    paths.extend(tempfile._candidate_tempdir_list())

    for path in paths:
        try:
            tmp = tempfile.NamedTemporaryFile(
                prefix='ansible_mitogen_find_good_temp_dir',
                dir=path,
            )
        except (OSError, IOError) as e:
            LOG.debug('temp dir %r unusable: %s', path, e)
            continue

        try:
            try:
                os.chmod(tmp.name, int('0700', 8))
            except OSError as e:
                LOG.debug('temp dir %r unusable: %s: chmod failed: %s', path,
                          e)
                continue

            try:
                # access(.., X_OK) is sufficient to detect noexec.
                if not os.access(tmp.name, os.X_OK):
                    raise OSError('filesystem appears to be mounted noexec')
            except OSError as e:
                LOG.debug('temp dir %r unusable: %s: %s', path, e)
                continue

            LOG.debug('Selected temp directory: %r (from %r)', path, paths)
            return path
        finally:
            tmp.close()

    raise IOError(MAKE_TEMP_FAILED_MSG % {
        'paths': '\n    '.join(paths),
    })
 def test_wanted_dirs(self):
     with support.EnvironmentVarGuard() as env:
         for envname in ('TMPDIR', 'TEMP', 'TMP'):
             dirname = os.getenv(envname)
             if not dirname:
                 env[envname] = os.path.abspath(envname)
         cand = tempfile._candidate_tempdir_list()
         for envname in ('TMPDIR', 'TEMP', 'TMP'):
             dirname = os.getenv(envname)
             if not dirname:
                 raise ValueError
             self.assertIn(dirname, cand)
         try:
             dirname = os.getcwd()
         except (AttributeError, OSError):
             dirname = os.curdir
         self.assertIn(dirname, cand)
Example #11
0
def find_good_temp_dir():
    """
    Given a list of candidate temp directories extracted from ``ansible.cfg``
    and stored in _candidate_temp_dirs, combine it with the Python-builtin list
    of candidate directories used by :mod:`tempfile`, then iteratively try each
    in turn until one is found that is both writeable and executable.
    """
    paths = [os.path.expandvars(os.path.expanduser(p))
             for p in _candidate_temp_dirs]
    paths.extend(tempfile._candidate_tempdir_list())

    for path in paths:
        try:
            tmp = tempfile.NamedTemporaryFile(
                prefix='ansible_mitogen_find_good_temp_dir',
                dir=path,
            )
        except (OSError, IOError) as e:
            LOG.debug('temp dir %r unusable: %s', path, e)
            continue

        try:
            try:
                os.chmod(tmp.name, int('0700', 8))
            except OSError as e:
                LOG.debug('temp dir %r unusable: %s: chmod failed: %s',
                          path, e)
                continue

            try:
                # access(.., X_OK) is sufficient to detect noexec.
                if not os.access(tmp.name, os.X_OK):
                    raise OSError('filesystem appears to be mounted noexec')
            except OSError as e:
                LOG.debug('temp dir %r unusable: %s: %s', path, e)
                continue

            LOG.debug('Selected temp directory: %r (from %r)', path, paths)
            return path
        finally:
            tmp.close()

    raise IOError(MAKE_TEMP_FAILED_MSG % {
        'paths': '\n    '.join(paths),
    })
Example #12
0
    def test_wanted_dirs(self) -> None:
        # _candidate_tempdir_list contains the expected directories

        # Make sure the interesting environment variables are all set.
        with support.EnvironmentVarGuard() as env:
            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname:
                    env[envname] = os.path.abspath(envname)

            cand = tempfile._candidate_tempdir_list()

            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname: raise ValueError
                self.assertIn(dirname, cand)

            try:
                dirname = os.getcwd()
            except (AttributeError, os.error):
                dirname = os.curdir

            self.assertIn(dirname, cand)
Example #13
0
    def test_wanted_dirs(self):
        # _candidate_tempdir_list contains the expected directories

        # Make sure the interesting environment variables are all set.
        with support.EnvironmentVarGuard() as env:
            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname:
                    env[envname] = os.path.abspath(envname)

            cand = tempfile._candidate_tempdir_list()

            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname: raise ValueError
                self.assertIn(dirname, cand)

            try:
                dirname = os.getcwd()
            except (AttributeError, os.error):
                dirname = os.curdir

            self.assertIn(dirname, cand)
Example #14
0
def find_good_temp_dir(candidate_temp_dirs):
    """
    Given a list of candidate temp directories extracted from ``ansible.cfg``,
    combine it with the Python-builtin list of candidate directories used by
    :mod:`tempfile`, then iteratively try each until one is found that is both
    writeable and executable.

    :param list candidate_temp_dirs:
        List of candidate $variable-expanded and tilde-expanded directory paths
        that may be usable as a temporary directory.
    """
    paths = [os.path.expandvars(os.path.expanduser(p))
             for p in candidate_temp_dirs]
    paths.extend(tempfile._candidate_tempdir_list())

    for path in paths:
        if is_good_temp_dir(path):
            LOG.debug('Selected temp directory: %r (from %r)', path, paths)
            return path

    raise IOError(MAKE_TEMP_FAILED_MSG % {
        'paths': '\n    '.join(paths),
    })
Example #15
0
 def update_event(self, inp=-1):
     self.set_output_val(0, tempfile._candidate_tempdir_list())
 def test_nonempty_list(self):
     cand = tempfile._candidate_tempdir_list()
     self.assertFalse(len(cand) == 0)
     for c in cand:
         self.assertIsInstance(c, str)