代码之家  ›  专栏  ›  技术社区  ›  danielo

Python Unittest Discover即使失败也返回退出代码0

  •  2
  • danielo  · 技术社区  · 6 年前

    我读过几篇文章说,如果用unittest.main()调用unittests,如果失败,它们将以失败代码退出。我用命令调用unittests: python -m unittest discover -v . 我正在使用Python3.6.6。unittest示例如下:

    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
    

    我做错什么了?

    2 回复  |  直到 6 年前
        1
  •  0
  •   digitalarbeiter    6 年前

    你把unittest文件命名为 test_*.py ? 因为这正是探索的目标。否则,无论您的测试结果是:

    Ran 0 tests in 0.000s
    OK
    

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