def _remove_acceptance_test_dirs():
    """Remove all acceptance tests directories.

    Designed to be called on an atexit handler.
    """
    for directory in _ACCEPTANCE_TEST_DIRS_TO_REMOVE:
        util.force_remove_tree(directory)
        def in_parent_context(self, command):
            """Get script to run command in parent context.

            The 'parent context' in this case is a shell script where the
            standard output of the container's setup script has been evaluated,
            eg, all environment variables are exported.
            """
            directory = tempfile.mkdtemp(prefix=os.path.join(os.getcwd(),
                                                             "parent_script"))

            script_path = os.path.abspath(os.path.join(directory,
                                                       "script.ps1"))
            script_path_for_shell = os.path.abspath(script_path)
            if platform.system() == "Windows":
                shell = ["powershell", "-ExecutionPolicy", "Bypass"]
                script_path_for_shell = "\"{}\"".format(script_path_for_shell)
            else:
                shell = ["bash"]

            script = ("{cls.setup_container_output.stdout}"
                      "{command}").format(cls=self.__class__, command=command)

            try:
                with util.in_dir(directory):
                    with open(script_path, "w") as script_file:
                        script_file.write(script)

                    # powershell requires that paths with spaces be
                    # quoted, even when passed as part of the command line
                    # arguments, so we use script_path here as it is formatted
                    # above
                    yield shell + [script_path_for_shell]
            finally:
                script_file.close()
                util.force_remove_tree(directory)
def in_tempdir(parent, prefix):
    """Create a temporary directory as a context manager."""
    directory = tempfile.mkdtemp(prefix, dir=parent)

    try:
        with in_dir(directory):
            yield directory
    finally:
        util.force_remove_tree(directory)
        def maybe_copy_from_existing_container(cls, target):
            """Copy from an any pre-existing container if we have one."""
            if os.environ.get("CONTAINER_DIR"):
                container_dir = os.environ["CONTAINER_DIR"]
                util.force_remove_tree(target)
                _copytree_ignore_notfound(container_dir, target)

                # Delete ciscripts in the copied container
                try:
                    util.force_remove_tree(os.path.join(target, "_scripts"))
                except (shutil.Error, OSError):  # suppress(pointless-except)
                    pass
def removable_container_dir(directory_name):
    """A contextmanager which deletes a container when the test is complete."""
    current_cwd = os.getcwd()
    printer = bootstrap.escaped_printer_with_character("\\")
    shell = bootstrap.BashParentEnvironment(printer)
    try:
        # Put a /bootstrap.py script in the container directory
        # so that we don't keep on trying to fetch it all the time
        write_bootstrap_script_into_container(directory_name)
        yield bootstrap.ContainerDir(shell,
                                     directory=directory_name,
                                     stale_check=None)
    finally:
        util.force_remove_tree(os.path.join(current_cwd, directory_name))
    def test_file_not_in_path_not_found(self):
        """Check that executables not in PATH are not found."""
        temp_dir = tempfile.mkdtemp(prefix=os.path.join(os.getcwd(),
                                                        "executable_path"))
        self.addCleanup(lambda: util.force_remove_tree(temp_dir))
        with tempfile.NamedTemporaryFile(mode="wt",
                                         dir=temp_dir) as temp_file:
            temp_file.write("#!/usr/bin/env python\nprint(\"Test\")")
            os.chmod(temp_file.name, 755)

            os.environ["PATH"] = ""

            self.assertEqual(None,
                             util.which(os.path.basename(temp_file.name)))
    def test_raise_executable_not_in_path(self):
        """Raise RuntimeError when executable is not in PATH."""
        temp_dir = tempfile.mkdtemp(prefix=os.path.join(os.getcwd(),
                                                        "executable_path"))
        self.addCleanup(lambda: util.force_remove_tree(temp_dir))
        with tempfile.NamedTemporaryFile(mode="wt",
                                         dir=temp_dir) as temp_file:
            temp_file.write("#!/usr/bin/env python\nprint(\"Test\")")
            os.chmod(temp_file.name, 755)

            with ExpectedException(RuntimeError):
                os.environ["PATH"] = "/does_not_exist"
                util.execute(Mock(),
                             util.long_running_suppressed_output(),
                             os.path.basename(temp_file.name))
    def test_execute_function_if_not_found_by_which(self):
        """Execute function with where_unavailable if executable not found."""
        temp_dir = tempfile.mkdtemp(prefix=os.path.join(os.getcwd(),
                                                        "executable_path"))
        self.addCleanup(lambda: util.force_remove_tree(temp_dir))
        with tempfile.NamedTemporaryFile(mode="wt",
                                         dir=temp_dir) as temp_file:
            temp_file.write("#!/usr/bin/env python\nprint(\"Test\")")
            os.chmod(temp_file.name, 755)

            mock = Mock()
            util.where_unavailable(os.path.basename(temp_file.name),
                                   mock,
                                   "arg")

            mock.assert_called_with("arg")
    def tearDown(self):  # suppress(N802)
        """Remove build tree."""
        build = self.__class__.container.named_cache_dir("cmake-build")
        util.force_remove_tree(build)

        super(TestConanContainerSetup, self).tearDown()
    def tearDown(self):  # suppress(N802)
        """Remove build tree."""
        build = self.__class__.container.named_cache_dir("cmake-build")
        util.force_remove_tree(build)

        super(TestPSQCPPContainerSetup, self).tearDown()