Python自动化框架UnitTest原理及应用之TestSuite

在TestCase的使用中,我们会发现两个问题

1.无法方便的控制case的执行顺序

2.无法批量执行cases

针对这两个问题,TestSuite类提供了解决方法。

我们先来看下API文档

class unittest.TestSuite(tests=())

This class represents an aggregation of individual test cases and test suites. The class presents the interface needed by the test runner to allow it to be run as any other test case. Running a TestSuite instance is the same as iterating over the suite, running each test individually.

此类是testcase的集合,提供了执行case的接口给test runner,执行TestSuite实例就是遍历suite,独立的执行每次test

If tests is given, it must be an iterable of individual test cases or other test suites that will be used to build the suite initially. Additional methods are provided to add test cases and suites to the collection later on.

TestSuite objects behave much like TestCase objects, except they do not actually implement a test. Instead, they are used to aggregate tests into groups of tests that should be run together.

如果要传参tests,入参必须得是可迭代的独立testcases或者是其他的常用于建立初始suite的testsuites。也提供了些添加testcases和suites到集合中的方法,addTests() addTest()。简单来说,TestSuite就是tests的group,可以让tests一起被执行。

class BaseTestSuite(object):
    """A simple test suite that doesn't provide class or module shared fixtures.
    """
    _cleanup = True

    def __init__(self, tests=()):
        self._tests = []
        self._removed_tests = 0
        self.addTests(tests)

    def addTest(self, test):
        # sanity checks
        if not callable(test):
            raise TypeError("{} is not callable".format(repr(test)))
        if isinstance(test, type) and issubclass(test,
                                                 (case.TestCase, TestSuite)):
            raise TypeError("TestCases and TestSuites must be instantiated "
                            "before passing them to addTest()")
        self._tests.append(test)

    def addTests(self, tests):
        if isinstance(tests, str):
            raise TypeError("tests must be an iterable of tests, not a string")
        for test in tests:
            self.addTest(test)

看下实现能够更好的理解文档的描述,传入的tests被添加到了_tests列表中,包括对tests的判断描述也能清楚理解。

再来看下TestSuite类提供的方法:

addTest(test) -- 添加testcase或testsuite到suite

addTests(tests) -- 从可迭代的testcases或testsuite添加所有的tests,然后遍历每个test单独调用addTest方法

run(result) -- 运行suite相关的tests,将结果传递到testresult对象中。注意和testcase不同,入参没有了默认值,需要传递

debug() -- debug模式

countTestCases() -- 返回对象中case的数量,包括cases和sub-suites

__iter__() -- TestSuite是可迭代的

接下来我们实例操作下:

class Testaa(unittest.TestCase):

    def setUp(self) -> None:
        print('case start...')

    def tearDown(self) -> None:
        print('case end...')

    def test_aa1(self):
        print('执行aa1...')
        self.assertEqual('aa1','aa1',msg='判断aa1')

    def test_aa2(self):
        print('执行aa2...')
        self.assertEqual('aa2','aa2',msg='判断aa2')

    def test_aa3(self):
        print('执行aa3...')
        self.assertEqual('aa3','aa3',msg='判断aa3')

class Testbb(unittest.TestCase):

    def setUp(self) -> None:
        print('case start...')

    def tearDown(self) -> None:
        print('case end...')

    def test_bb1(self):
        print('执行bb1')
        self.assertEqual('bb1','bb1',msg='判断bb1')

    def test_bb2(self):
        print('执行bb2')
        self.assertEqual('bb2','bb2',msg='判断bb2')
suite = unittest.TestSuite()
case_list = [Testaa('test_aa2'),Testaa('test_aa3'),Testaa('test_aa1')]  #将testcase先放入一个列表中,然后一块传入suite
suite.addTests(case_list)
suite.addTest(Testbb('test_bb2'))  #也可以单独添加
suite.addTest(Testbb('test_bb1'))
with open("测试报告.txt", "w", encoding="utf-8") as file:  
   runner = unittest.TextTestRunner(stream=file, descriptions=True, verbosity=2)
   runner.run(suite)  

运行结果: 

case start...
执行aa2...
case end...
case start...
执行aa3...
case end...
case start...
执行aa1...
case end...
case start...
执行bb2
case end...
case start...
执行bb1
case end...

这样就搞定了cases批量执行和执行顺序的问题

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页