def test_user_facing_error_handled_gracefully( self, m_get_parser, _m_setup_logging, capsys, logging_sandbox, caplog_text, exception, expected_exit_code, ): m_args = m_get_parser.return_value.parse_args.return_value m_args.action.side_effect = exception expected_msg = exception.msg with pytest.raises(SystemExit) as excinfo: main(["some", "args"]) exc = excinfo.value assert expected_exit_code == exc.code out, err = capsys.readouterr() assert "" == out assert "{}\n".format(expected_msg) == err error_log = caplog_text() # pytest 4.6.x started indenting trailing lines in log messages, which # meant that our matching here stopped working once we introduced # newlines into this log output in #973. (If focal moves onto pytest # 5.x before release, then we can remove this workaround.) The # upstream issue is https://github.com/pytest-dev/pytest/issues/5515 error_log = "\n".join( [line.strip() for line in error_log.splitlines()]) assert expected_msg in error_log assert "Traceback (most recent call last):" in error_log
def test_auto_attach_help(self, _m_resources, _getuid, capsys): with pytest.raises(SystemExit): with mock.patch("sys.argv", ["/usr/bin/ua", "auto-attach", "--help"]): main() out, _err = capsys.readouterr() assert HELP_OUTPUT == out
def test_refresh_help(self, _m_resources, _getuid, capsys): with pytest.raises(SystemExit): with mock.patch("sys.argv", ["/usr/bin/ua", "refresh", "--help"]): main() out, _err = capsys.readouterr() print(out) assert HELP_OUTPUT in out
def test_command_line_is_logged(self, _m_get_parser, _m_setup_logging, logging_sandbox, caplog_text): main(["some", "args"]) log = caplog_text() assert "['some', 'args']" in log
def test_url_error_handled_gracefully( self, m_get_parser, _m_setup_logging, error_url, expected_log, capsys, logging_sandbox, caplog_text, ): m_args = m_get_parser.return_value.parse_args.return_value m_args.action.side_effect = util.UrlError(socket.gaierror( -2, "Name or service not known"), url=error_url) with pytest.raises(SystemExit) as excinfo: main(["some", "args"]) exc = excinfo.value assert 1 == exc.code out, err = capsys.readouterr() assert "" == out assert "{}\n".format(status.MESSAGE_CONNECTIVITY_ERROR) == err error_log = caplog_text() assert expected_log in error_log assert "Traceback (most recent call last):" in error_log
def test_require_format_flag( self, _m_resources, _m_security_status, with_wrong_format, FakeConfig, capsys, ): cmdline_args = ["/usr/bin/ua", "security-status"] if with_wrong_format: cmdline_args.extend(["--format", "unsupported"]) with pytest.raises(SystemExit): with mock.patch("sys.argv", cmdline_args): main() _, err = capsys.readouterr() assert "usage: security-status [-h] --format {json,yaml}" in err if with_wrong_format: assert ("argument --format: invalid choice: 'unsupported'" " (choose from 'json', 'yaml')") in err else: assert "the following arguments are required: --format" in err
def test_user_facing_error_handled_gracefully( self, m_get_parser, _m_setup_logging, capsys, logging_sandbox, caplog_text, ): msg = "You need to know about this." m_args = m_get_parser.return_value.parse_args.return_value m_args.action.side_effect = UserFacingError(msg) with pytest.raises(SystemExit) as excinfo: main(["some", "args"]) exc = excinfo.value assert 1 == exc.code out, err = capsys.readouterr() assert "" == out assert "ERROR: {}\n".format(msg) == err error_log = caplog_text() assert msg in error_log assert "Traceback (most recent call last):" in error_log
def test_errors_handled_gracefully( self, m_get_parser, _m_setup_logging, capsys, logging_sandbox, caplog_text, exception, expected_error_msg, expected_log, ): m_args = m_get_parser.return_value.parse_args.return_value m_args.action.side_effect = exception with pytest.raises(SystemExit) as excinfo: with mock.patch("sys.argv", ["/usr/bin/ua", "subcmd"]): main() exc = excinfo.value assert 1 == exc.code out, err = capsys.readouterr() assert "" == out assert expected_error_msg == err error_log = caplog_text() assert "Traceback (most recent call last):" in error_log assert expected_log in error_log
def test_user_facing_error_handled_gracefully( self, m_get_parser, _m_setup_logging, capsys, logging_sandbox, caplog_text, exception, expected_exit_code, ): m_args = m_get_parser.return_value.parse_args.return_value m_args.action.side_effect = exception expected_msg = exception.msg with pytest.raises(SystemExit) as excinfo: main(["some", "args"]) exc = excinfo.value assert expected_exit_code == exc.code out, err = capsys.readouterr() assert "" == out assert "{}\n".format(expected_msg) == err error_log = caplog_text() assert expected_msg in error_log assert "Traceback (most recent call last):" in error_log
def test_collect_logs_help(self, _m_resources, _getuid, capsys): with pytest.raises(SystemExit): with mock.patch( "sys.argv", ["/usr/bin/ua", "collect-logs", "--help"] ): main() out, _err = capsys.readouterr() assert re.match(HELP_OUTPUT, out)
def test_environment_is_logged(self, _m_get_parser, _m_setup_logging, logging_sandbox, caplog_text): main(["some", "args"]) log = caplog_text() assert "UA_FEATURES_WOW=XYZ" in log assert "NOT_UA_ENV=YES" not in log
def test_enable_help( self, _m_resources, _getuid, _request_updated_contract, capsys ): with pytest.raises(SystemExit): with mock.patch("sys.argv", ["/usr/bin/ua", "enable", "--help"]): main() out, _err = capsys.readouterr() assert HELP_OUTPUT == out
def _get_help_output(): with mock.patch("sys.argv", request.param.split(" ")): main() out, _err = capsys.readouterr() if "--all" in request.param: return (out, "all") return (out, "base")
def test_security_status_help(self, _m_resources, _m_security_status, capsys): with pytest.raises(SystemExit): with mock.patch("sys.argv", ["/usr/bin/ua", "security-status", "--help"]): main() out, _err = capsys.readouterr() assert re.match(HELP_OUTPUT, out)
def test_set_error_with_help_on_invalid_key_value_pair( self, _m_resources, _logging, _getuid, kv_pair, err_msg, capsys): """Exit 1 and print help on invalid key_value_pair input param.""" with pytest.raises(SystemExit): with mock.patch("sys.argv", ["/usr/bin/ua", "config", "unset", kv_pair]): main() out, err = capsys.readouterr() assert HELP_OUTPUT == out assert err_msg in err
def test_non_root_users_are_rejected( self, _m_resources, _request_updated_contract, getuid, capsys, event, FakeConfig, ): """Check that a UID != 0 will receive a message and exit non-zero""" getuid.return_value = 1 args = mock.MagicMock() cfg = FakeConfig.for_attached_machine() with pytest.raises(exceptions.NonRootUserError): action_enable(args, cfg=cfg) with pytest.raises(SystemExit): with mock.patch( "sys.argv", [ "/usr/bin/ua", "enable", "foobar", "--assume-yes", "--format", "json", ], ): main() expected_message = messages.NONROOT_USER expected = { "_schema_version": event_logger.JSON_SCHEMA_VERSION, "result": "failure", "errors": [ { "message": expected_message.msg, "message_code": expected_message.name, "service": None, "type": "system", } ], "failed_services": [], "needs_reboot": False, "processed_services": [], "warnings": [], } assert expected == json.loads(capsys.readouterr()[0])
def test_status_help( self, _m_getuid, _m_get_contract_information, _m_get_available_resources, _m_should_reboot, _m_remove_notice, _m_contract_changed, capsys, ): with pytest.raises(SystemExit): with mock.patch("sys.argv", ["/usr/bin/ua", "status", "--help"]): main() out, _err = capsys.readouterr() assert HELP_OUTPUT == out
def test_config_show_help(self, _m_resources, _logging, logging_error, additional_params, capsys): """Show help for --help and absent positional param""" with pytest.raises(SystemExit): with mock.patch("sys.argv", ["/usr/bin/ua", "config"] + additional_params): main() out, err = capsys.readouterr() assert HELP_OUTPUT == out if additional_params == ["--help"]: assert "" == err else: # When lacking show, set or unset inform about valid values assert "\n<command> must be one of: show, set, unset\n" == err assert [mock.call("\n<command> must be one of: show, set, unset") ] == logging_error.call_args_list
def test_config_show_error_on_invalid_subcommand(self, _m_resources, _logging, _logging_error, capsys): """Exit 1 on invalid subcommands.""" with pytest.raises(SystemExit): with mock.patch("sys.argv", ["/usr/bin/ua", "config", "invalid"]): main() out, err = capsys.readouterr() assert "" == out expected_logs = [ "usage: ua config <command> [flags]", "argument : invalid choice: 'invalid' (choose from 'show', 'set'," " 'unset')", ] for log in expected_logs: assert log in err
def test_keyboard_interrupt_handled_gracefully( self, m_get_parser, _m_setup_logging, capsys, logging_sandbox, caplog_text, ): m_args = m_get_parser.return_value.parse_args.return_value m_args.action.side_effect = KeyboardInterrupt with pytest.raises(SystemExit) as excinfo: main(["some", "args"]) exc = excinfo.value assert 1 == exc.code out, err = capsys.readouterr() assert "" == out assert "Interrupt received; exiting.\n" == err error_log = caplog_text() assert "Traceback (most recent call last):" in error_log
def _get_help_output(): with mock.patch("sys.argv", ["ua", "help"]): main() out, _err = capsys.readouterr() return out