如何从打印消息并关闭程序的函数创建unittest?

2024-04-23 21:04:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下功能,可以打印错误消息并关闭程序:

def show_error_message(error_message):
    print(error_message)
    sys.exit()  # Close Program

现在我正在创建unittest,并找到了关于测试sys.exit()this topic,但它不起作用。我想是因为它在关闭邮件之前打印出来的。你知道吗

我如何测试这个?Python标准库中有什么东西可以在我的项目中随时使用来完成与此函数相同的任务吗?你知道吗

我想测试的是这样的:

    def test_function_runs(self):
        """Basic smoke test: does the function run."""
        with self.assertRaises(SystemExit) as cm:
            show_error_message('message')
        self.assertEqual(cm.exception.code, 1)

我得到的错误是:

Traceback (most recent call last):
File ".test_dynamic_message.py", line 14, in test_function_runs
self.assertEqual(cm.exception.code, 1)
AssertionError: None != 1

我还是python新手,希望有人能帮我。
谢谢


Tags: testselfmessagedefshow错误sysexit
3条回答

异常的属性可以是代码、消息、参数等等。你知道吗

class TestExit(unittest.TestCase):

    def test_sys_exit_exception(self):
        with self.assertRaises(SystemExit) as e:
            sys.exit('exit_with_err')
        self.assertTrue(isinstance(e.exception, SystemExit))
        self.assertEqual(e.exception.code, 'exit_with_err')
        self.assertEqual(e.exception.message, 'exit_with_err')
        self.assertEqual(e.exception.args, ('exit_with_err',))


    def test_show_error_msg_exception(self):
        # Test the exception type
        with self.assertRaises(SystemExit) as e:
            show_error_message('test but not mock exit')
        self.assertTrue(isinstance(e.exception, SystemExit))

在这种情况下,是代码错了。您的测试是正确的,无需更改。你知道吗

已成功退出的内容(返回代码0):

def show_error_message(error_message):
    print(error_message)
    sys.exit()  # Close Program

要将错误消息打印到stderr并以失败(返回代码1)退出,您需要:

def show_error_message_and_quit(error_message):
    sys.exit(error_message)

the python docs

If the value is an integer, it specifies the system exit status (passed to C’s exit() function); if it is None, the exit status is zero; if it has another type (such as a string), the object’s value is printed and the exit status is one.

您正在测试的函数以默认退出代码0退出。
您的测试假设异常中的退出代码为1,而根据文档您应该期望它为None。你知道吗

相关问题 更多 >