且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单元测试 - Python unittest如何收集测试结果

更新时间:2023-02-20 20:34:20

使用unittest模块本身的方法即可:

import unittest


class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'F0O')
        self.assertEqual('foo'.upper(), 'F0O')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)


def main():
    suite = unittest.TestLoader().loadTestsFromTestCase(TestStringMethods)
    test_result = unittest.TextTestRunner(verbosity=2).run(suite)
    print('All case number')
    print(test_result.testsRun)
    print('Failed case number')
    print(len(test_result.failures))
    print('Failed case and reason')
    print(test_result.failures)
    for case, reason in test_result.failures:
        print case.id()
        print reason


if __name__ == '__main__':
    main()