Exemple #1
0
    def __call__(self, command: str, echo: Optional[bool] = None) -> CommandResult:
        """
        Provide functionality to call application commands by calling PyscriptBridge
        ex: app('help')
        :param command: command line being run
        :param echo: if True, output will be echoed to stdout/stderr while the command runs
                     this temporarily overrides the value of self.cmd_echo
        """
        if echo is None:
            echo = self.cmd_echo

        # This will be used to capture _cmd2_app.stdout and sys.stdout
        copy_cmd_stdout = StdSim(self._cmd2_app.stdout, echo)

        # This will be used to capture sys.stderr
        copy_stderr = StdSim(sys.stderr, echo)

        self._cmd2_app._last_result = None

        try:
            self._cmd2_app.stdout = copy_cmd_stdout
            with redirect_stdout(copy_cmd_stdout):
                with redirect_stderr(copy_stderr):
                    # Include a newline in case it's a multiline command
                    self._cmd2_app.onecmd_plus_hooks(command + '\n')
        finally:
            self._cmd2_app.stdout = copy_cmd_stdout.inner_stream

        # Save the output. If stderr is empty, set it to None.
        result = CommandResult(stdout=copy_cmd_stdout.getvalue(),
                               stderr=copy_stderr.getvalue() if copy_stderr.getvalue() else None,
                               data=self._cmd2_app._last_result)
        return result
def _exec_cmd(thgcmd_app, command: str, echo: bool) -> CommandResult:
    """
    Helper to encapsulate executing a command and capturing the results
    :param thgcmd_app: thgcmd app that will run the command
    :param command: command line being run
    :param echo: if True, output will be echoed to stdout/stderr while the command runs
    :return: result of the command
    """
    copy_stdout = StdSim(sys.stdout, echo)
    copy_stderr = StdSim(sys.stderr, echo)

    copy_cmd_stdout = StdSim(thgcmd_app.stdout, echo)

    thgcmd_app._last_result = None

    try:
        thgcmd_app.stdout = copy_cmd_stdout
        with redirect_stdout(copy_stdout):
            with redirect_stderr(copy_stderr):
                # Include a newline in case it's a multiline command
                thgcmd_app.onecmd_plus_hooks(command + "\n")
    finally:
        thgcmd_app.stdout = copy_cmd_stdout.inner_stream

    # if stderr is empty, set it to None
    stderr = copy_stderr.getvalue() if copy_stderr.getvalue() else None

    outbuf = (copy_cmd_stdout.getvalue()
              if copy_cmd_stdout.getvalue() else copy_stdout.getvalue())
    result = CommandResult(stdout=outbuf,
                           stderr=stderr,
                           data=thgcmd_app._last_result)
    return result
def test__get_config__no_config_error(mocker: MockerFixture) -> None:
    """
    Test "_get_config" method must fail on no config file error.

    :param mocker: mock
    :type mocker: MockerFixture
    """

    out = StringIO()
    mocker.patch(
        "sys.argv",
        [
            "notification_jabber.py",
            "-r",
            "*****@*****.**",
            "-m",
            "TEST",
        ],
    )

    with pytest.raises(SystemExit):
        with contextlib2.redirect_stderr(out):
            NotificationJabber()

    assert (  # nosec: B101
        "ERROR: Config file /etc/nagios/notification_jabber.ini does not exist"
        in out.getvalue().strip())
def test__get_config__error(mocker: MockerFixture) -> None:
    """
    Test "_get_config" method must fail on an error.

    :param mocker: mock
    :type mocker: MockerFixture
    """

    out = StringIO()
    mocker.patch(
        "sys.argv",
        [
            "notification_jabber.py",
            "-r",
            "*****@*****.**",
            "-m",
            "TEST",
            "-c",
            "notification_jabber.ini",
        ],
    )
    mocker.patch(
        "builtins.open",
        return_value=IOError(),
    )

    with pytest.raises(SystemExit):
        with contextlib2.redirect_stderr(out):
            NotificationJabber()

    assert (  # nosec: B101
        "ERROR: Config file read notification_jabber.ini error."
        in out.getvalue().strip())
Exemple #5
0
def _exec_cmd(cmd2_app, func: Callable, echo: bool):
    """Helper to encapsulate executing a command and capturing the results"""
    copy_stdout = CopyStream(sys.stdout, echo)
    copy_stderr = CopyStream(sys.stderr, echo)

    copy_cmd_stdout = CopyStream(cmd2_app.stdout, echo)

    cmd2_app._last_result = None

    try:
        cmd2_app.stdout = copy_cmd_stdout
        with redirect_stdout(copy_stdout):
            with redirect_stderr(copy_stderr):
                func()
    finally:
        cmd2_app.stdout = copy_cmd_stdout.inner_stream

    # if stderr is empty, set it to None
    stderr = copy_stderr.buffer if copy_stderr.buffer else None

    outbuf = copy_cmd_stdout.buffer if copy_cmd_stdout.buffer else copy_stdout.buffer
    result = CommandResult(stdout=outbuf,
                           stderr=stderr,
                           data=cmd2_app._last_result)
    return result
 def getCliErrorMessages(self, args):
     """
     Run the CLI script and return any error messages.
     """
     stderr_file = six.StringIO()
     with self.assertRaises(SystemExit):
         with contextlib.redirect_stderr(stderr_file):
             mainwrapper.main(args=args)
     return stderr_file.getvalue()
Exemple #7
0
def _get_console_out(to_eval, namespace):
    fake_out, fake_err = StringIO(), StringIO()
    console = code.InteractiveConsole(locals=namespace)
    with redirect_stdout(fake_out), redirect_stderr(fake_err):
        for function in namespace.get("functions", []):
            for statement in function.split("\\n"):
                console.push(statement)
        for statement in to_eval.split("\n"):
            if statement:
                console.push(statement)
            else:
                console.push('\n')
    return fake_out.getvalue(), fake_err.getvalue()
def test__get_options__missing_server_option(mocker):
    """
    Test "_get_options" method must exit with server option missing error.
    """

    out = StringIO()
    mocker.patch("sys.argv", ["check_hddtemp.py"])

    with pytest.raises(SystemExit):
        with contextlib2.redirect_stderr(out):
            CheckHDDTemp()

    assert (  # nosec: B101
        "Required server address option missing" in out.getvalue().strip())
def test__get_options__missing_recipient_option(mocker: MockerFixture) -> None:
    """
    Test "_get_options" method must exit with recipient option missing error.

    :param mocker: mock
    :type mocker: MockerFixture
    """

    out = StringIO()
    mocker.patch("sys.argv", ["notification_jabber.py"])

    with pytest.raises(SystemExit):
        with contextlib2.redirect_stderr(out):
            NotificationJabber()

    assert "Required recipient option missing" in out.getvalue().strip(
    )  # nosec: B101
Exemple #10
0
def test__get_options__missing_server_option(mocker):
    """
    Test "_get_options" method must exit with server option missing error.

    :param mocker: mock
    :type mocker: MockerFixture
    """

    out = StringIO()
    mocker.patch("sys.argv", ["check_supervisord.py"])

    with pytest.raises(SystemExit):
        with contextlib2.redirect_stderr(out):
            CheckSupervisord()

    assert (  # nosec: B101
        "Required server address option missing" in out.getvalue().strip())
def test__get_options__warning_gte_critical(mocker):
    """
    Test "_get_options" method must exit with warning option
    greater or equal than critical error.
    """

    out = StringIO()
    mocker.patch(
        "sys.argv",
        ["check_hddtemp.py", "-s"
         "127.0.0.1", "-w", "65", "-c", "40"])

    with pytest.raises(SystemExit):
        with contextlib2.redirect_stderr(out):
            CheckHDDTemp()

    assert (  # nosec: B101
        "Warning temperature option value must be less than critical option value"
        in out.getvalue().strip())
Exemple #12
0
def run_cmd(app, cmd):
    """ Clear out and err StdSim buffers, run the command, and return out and err """
    saved_sysout = sys.stdout
    sys.stdout = app.stdout

    # This will be used to capture app.stdout and sys.stdout
    copy_cmd_stdout = StdSim(app.stdout)

    # This will be used to capture sys.stderr
    copy_stderr = StdSim(sys.stderr)

    try:
        app.stdout = copy_cmd_stdout
        with redirect_stdout(copy_cmd_stdout):
            with redirect_stderr(copy_stderr):
                app.onecmd_plus_hooks(cmd)
    finally:
        app.stdout = copy_cmd_stdout.inner_stream
        sys.stdout = saved_sysout

    out = copy_cmd_stdout.getvalue()
    err = copy_stderr.getvalue()
    return normalize(out), normalize(err)
def test__get_config__no_section_option_error(mocker: MockerFixture) -> None:
    """
    Test "_get_config" method must fail on no section/option error.

    :param mocker: mock
    :type mocker: MockerFixture
    """

    out = StringIO()
    data = """
    [JABBER]
    password = secret
    """
    mocker.patch(
        "sys.argv",
        [
            "notification_jabber.py",
            "-r",
            "*****@*****.**",
            "-m",
            "TEST",
            "-c",
            "notification_jabber.ini",
        ],
    )
    mocker.patch(
        "builtins.open",
        mock_open(read_data=data),
    )
    with pytest.raises(SystemExit):
        with contextlib2.redirect_stderr(out):
            NotificationJabber()

    assert (  # nosec: B101
        "ERROR: Config file missing section/option error."
        in out.getvalue().strip())