我读过几篇文章,说如果你用 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
我究竟做错了什么?
最佳答案
您是否将单元测试文件命名为 test_*.py
?因为这就是发现正在寻找的东西。否则无论您的测试如何,结果都将是:
Ran 0 tests in 0.000s
OK
(顺便说一句,使用
if __name__ ... unittest.main()
时您不必 -m unittest discover
)
关于即使失败,Python Unittest Discover也返回退出代码0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53151704/