【问题标题】:Use `unittest` to verify that the `exit` function was called使用 `unittest` 验证是否调用了 `exit` 函数
【发布时间】:2013-04-05 14:37:31
【问题描述】:

我定义了一个非常简单的配置管理器(解析配置文件并验证其中是否存在某些键),现在我正在为它编写一些测试。

在许多配置文件无效的情况下,我希望配置处理程序调用exit()。有什么方法可以编写测试以确保调用 exit 并且仍然继续测试?我是否可以仅针对测试环境“模拟”exit 函数?

我正在使用 Python 2.7 和 unittest

【问题讨论】:

    标签: python unit-testing python-2.7 exit


    【解决方案1】:

    sys.exit() 引发 SystemExit 异常,应该由 unittest 框架捕获。因此,您可以检查这些测试用例是否引发了 SystemExit

    例如,exit_test.py:

    import sys
    import unittest
    
    
    def func():
        sys.exit()
    
    
    class MyTest(unittest.TestCase):
    
        def test_func(self):
            self.assertRaises(SystemExit, func)
    
    
    if __name__ == "__main__":
        unittest.main()
    

    运行:

    $ python exit_test.py 
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    
    OK
    

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      相关资源
      最近更新 更多