首页 > 解决方案 > python unittest的返回状态

问题描述

我正在尝试从另一个 python 文件调用单元测试,并评估退出代码。我能够使用unittest.TestLoader().loadTestsFromModuleunittest.TextTestRunner.run从另一个 python 文件调用 unittest,但这会将整个结果返回到 cmd。我想简单地设置一个等于状态代码的变量,以便我可以评估它。我能够找到一个方法 unittest.TestResult.wasSuccessful,但我在实现它时遇到了麻烦。当我将它添加到用例中时,我得到以下 AttributeError:AttributeError: 'ConnectionTest' object has no attribute 'failures'

我在下面包含了一些代码示例和所需结果的模型,以说明我想要实现的目标。先感谢您。

""" Tests/ConnectionTest.py """

import unittest
from Connection import Connection


class ConnectionTest(unittest.TestCase):

    def test_connection(self):
        #my tests

    def test_pass(self):
        return unittest.TestResult.wasSuccessful(self)


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


""" StatusTest.py """

import unittest
import Tests.ConnectionTest as test
#import Tests.Test2 as test2
#import Tests.Test3 as test3
#import other unit tests ...

suite = unittest.TestLoader().loadTestsFromModule(test)
unittest.TextTestRunner(verbosity=2).run(suite)


""" Return True if unit test passed
"""
def test_passed(test):
    if test.test_pass() == 0:
        return True
    else:
        return False

""" Run unittest for each module before using it in code
"""
def main():
    tests = "test test2 test3".split()
    for test in tests:
        if test_passed(test):
            # do something
        else:
            # log failure
            pass

更新

更简单地说,我需要将下面突出显示的变量设置为突出显示的值。

目标

标签: windowspython-3.xpython-unittest

解决方案


您提到您尝试实施result.wasSuccessful,但需要以下工作:

result = unittest.TextTestRunner(verbosity=2).run(suite)
test_exit_code = int(not result.wasSuccessful())

当测试套件成功运行时,的值test_exit_code将是 0,否则为 1。

如果要禁用输出,TextTestRunner可以指定自己的流,例如:

from io import StringIO

result = unittest.TextTestRunner(stream=StringIO(), verbosity=2).run(suite)

推荐阅读