【问题标题】:Python Unittest Discover return exit code 0 even if failsPython Unittest Discover即使失败也返回退出代码0
【发布时间】:2018-11-05 09:36:55
【问题描述】:

我读过几篇文章说,如果你用 unittest.main() 调用你的单元测试,如果它们失败,它们应该以失败代码退出。我用命令调用我的单元测试:python -m unittest discover -v。我正在使用 Python 3.6.6。一个示例单元测试可能如下所示:

from server import app
import unittest

class ServerTestCase(unittest.TestCase):
    """
    Unittesting for the server application.
    """


    def setUp(self):
        """
        Create a test client
        """
        self.app = app.test_client()
        self.app.testing = True 

    def tearDown(self):
        pass

    def test_root_endpoint(self):
        """
        Testing the root endpoint
        """

        result = self.app.get('/') 
        self.assertEqual(result.status_code, 200) 

    def test_health_endpoint(self):
        """
        Testing the health endpoint
        """

        result = self.app.get('/health')
        assert b'UP' in result.data

if __name__ == '__main__':
    unittest.main()

即使我的一项测试失败,我在检查退出代码时也会得到这个:

$ echo $?
0

我做错了什么?

【问题讨论】:

标签: python python-3.x unit-testing python-unittest


【解决方案1】:

您是否将单元测试文件命名为 test_*.py 之类的名称?因为这就是发现正在寻找的东西。否则无论你的测试如何,结果都是:

Ran 0 tests in 0.000s
OK

(顺便说一句,使用-m unittest discover 时您不必if __name__ ... unittest.main()

【讨论】:

  • 测试正在运行。我可以找回7/8成功,1失败,但仍然退出代码0。
  • 好吧,这很奇怪。我无法重现这种行为;对我来说,退出代码是您所期望的(0=测试成功,1=测试失败)。对不起,我完全没有想法。你能提供确切的命令行和输出吗?
最近更新 更多