def test_log_ctrlc_and_exit(capfd, caplog): # GIVEN opslog invocation # WHEN the ops_utils.log_ctrlc_and_exit function is invoked and # the output is captured with pytest.raises(SystemExit) as e: ops_utils.log_ctrlc_and_exit() out, err = capfd.readouterr() # THEN a SystemExit exception should be raised and # the exit status should be 130 and # there should be only a single newline written to stderr and # there should be a single log message and # the log level of the message should be INFO and # the log message should match the expected text assert int(str(e.value)) == 130 assert err == "\n" assert len(caplog.records) == 1 assert caplog.records[0].levelno == logging.INFO assert caplog.records[0].message == "(130) Halted via KeyboardInterrupt."
def test_log_ctrlc_and_exit__without_logging(capfd): # GIVEN the caplog logging handler is removed and # the expected output to stderr root_logger = logging.getLogger() handler = root_logger.handlers[0] root_logger.removeHandler(handler) expected_err = ("\nCRITICAL No handlers could be found for logger \"{0}\"" "\nINFO (130) Halted via KeyboardInterrupt.\n" .format(MODULE)) # WHEN the ops_utils.log_ctrlc_and_exit function is invoked and # the output is captured with pytest.raises(SystemExit) as e: ops_utils.log_ctrlc_and_exit() out, err = capfd.readouterr() # THEN a SystemExit exception should be raised and # the exit status should be 130 and # stderr should match the expected error message assert int(str(e.value)) == 130 assert err == expected_err
cap = ops_config.OpsConfigArgParse(description=__doc__, add_args=add_args) logger = ops_logging.OpScriptsLogging(cap.prog) args = ops_config.parse_args(cap) logger.dryrun(args.dryrun) logger.set_log_level(args.verbosity) logger.remove_syslog_handler() LOG.warning("disabled logging to syslog") LOG.debug("args.program_name: {}".format(args.program_name)) return args def main(): args = setup() # noqa ops_utils.verify_root() ops_utils.request_confirmation(timeout=20) LOG.critical("test message to demonstrate use of logging module root" " logger") if __name__ == "__main__": try: main() except SystemExit as e: sys.exit(e.code) except KeyboardInterrupt: ops_utils.log_ctrlc_and_exit() except ops_utils.Fatal: ops_utils.log_fatal_and_exit() except: ops_utils.log_exception_and_exit()