def test_instant_failure_calls_through_to_container(self):
        """Execute a command with failure."""
        container = Mock()
        with testutil.CapturedOutput():
            util.execute(container, util.output_on_fail, "false")

        self.assertThat(container.note_failure.call_args_list,
                        Not(Equals(list())))
    def test_execute_with_success_running_output(self):
        """Execute a command with success, but show output."""
        captured_output = testutil.CapturedOutput()
        with captured_output:
            util.execute(Mock(), util.running_output, "python", "--version")

        self.assertThat(captured_output.stderr,
                        DocTestMatches("\nPython ...",
                                       doctest.ELLIPSIS |
                                       doctest.NORMALIZE_WHITESPACE))
    def test_running_output_no_double_leading_slash_n(self):
        """Using running_output does not allow double-leading slash-n."""
        captured_output = testutil.CapturedOutput()
        with captured_output:
            util.execute(Mock(),
                         util.running_output,
                         "python",
                         "-c",
                         "print(\"\")")

        self.assertThat(captured_output.stderr,
                        DocTestMatches("\n",
                                       doctest.ELLIPSIS |
                                       doctest.NORMALIZE_WHITESPACE))
    def test_execute_with_failure_output(self):
        """Execute a command with failure, showing output."""
        if "POLYSQUARE_ALWAYS_PRINT_PROCESS_OUTPUT" in os.environ:
            del os.environ["POLYSQUARE_ALWAYS_PRINT_PROCESS_OUTPUT"]

        captured_output = testutil.CapturedOutput()
        with captured_output:
            util.execute(Mock(),
                         util.output_on_fail,
                         "python",
                         "/does-not-exist")

        self.assertThat(captured_output.stderr.strip(),
                        Contains("/does-not-exist"))
    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_running_stderr_at_end(self):
        """Execute a command with success, but display stderr at end."""
        captured_output = testutil.CapturedOutput()
        with captured_output:
            util.execute(Mock(),
                         util.running_output,
                         "python",
                         "-c",
                         "import sys; "
                         "sys.stdout.write('a\\nb'); "
                         "sys.stderr.write('c'); "
                         "sys.stdout.write('d')")

        self.assertEqual(captured_output.stderr.replace("\r\n", "\n"),
                         "\na\nbd\nc\n")
    def test_execute_passes_environment_variables(self):
        """Pass specified environment variables to subprocess."""
        captured_output = testutil.CapturedOutput()
        with captured_output:
            util.execute(Mock(),
                         util.running_output,
                         "python",
                         "-c",
                         "import os; print(os.environ['KEY'])",
                         env={"KEY": "VALUE"})

        self.assertThat(captured_output.stderr,
                        DocTestMatches("...VALUE...",
                                       doctest.ELLIPSIS |
                                       doctest.NORMALIZE_WHITESPACE))
 def test_execute_with_failure(self):
     """Execute a command with failure."""
     with testutil.CapturedOutput():
         self.assertEqual(1,
                          util.execute(Mock(),
                                       util.output_on_fail,
                                       "false"))
    def test_override_suppressed_output(self):
        """Override suppressed output with environment variable."""
        os.environ["POLYSQUARE_ALWAYS_PRINT_PROCESS_OUTPUT"] = "1"

        captured_output = testutil.CapturedOutput()
        with captured_output:
            util.execute(Mock(),
                         util.output_on_fail,
                         "python",
                         "-c",
                         "print('Hello')")

        self.assertThat(captured_output.stderr,
                        DocTestMatches("...Hello...",
                                       doctest.ELLIPSIS |
                                       doctest.NORMALIZE_WHITESPACE |
                                       doctest.REPORT_NDIFF))
    def test_execute_show_dots_for_long_running_processes(self):
        """Show dots for long running processes."""
        if "POLYSQUARE_ALWAYS_PRINT_PROCESS_OUTPUT" in os.environ:
            del os.environ["POLYSQUARE_ALWAYS_PRINT_PROCESS_OUTPUT"]

        captured_output = testutil.CapturedOutput()
        with captured_output:
            util.execute(Mock(),
                         util.long_running_suppressed_output(dot_timeout=1),
                         "sleep", "3")

        # There will be fewer dots as the watcher thread start a little
        # later than the subprocess does. However, there can be some cases
        # where there's a little bit of lag between terminating threads, so
        # there might be three dots. Match both cases.
        self.assertThat(captured_output.stderr.strip(),
                        MatchesAny(Equals(".."),  # suppress(PYC90)
                                   Equals("...")))  # suppress(PYC90)
    def test_output_on_fail_handles_utf8(self):
        """Handle utf-8 strings correctly when showing failure output."""
        if "POLYSQUARE_ALWAYS_PRINT_PROCESS_OUTPUT" in os.environ:
            del os.environ["POLYSQUARE_ALWAYS_PRINT_PROCESS_OUTPUT"]

        if (platform.python_implementation() != "CPython" or
                platform.system() == "Windows" or
                sys.version_info.major != 3):
            expected = "  ..."
        else:
            expected = u"\N{check mark} ..."

        captured_output = testutil.CapturedOutput()
        with captured_output:
            util.execute(Mock(),
                         util.running_output,
                         "python",
                         _utf8_print_cmd())

        self.assertThat(captured_output.stderr[1:],
                        DocTestMatches(expected,
                                       doctest.ELLIPSIS |
                                       doctest.NORMALIZE_WHITESPACE))
 def test_execute_with_success(self):
     """Execute a command with success."""
     self.assertEqual(0, util.execute(Mock(), util.output_on_fail, "true"))