当前位置: 首页 > 工具软件 > PyUnit > 使用案例 >

Pyunit源码笔记之十一 pyunit运行方式之二:testsuit方式

漆雕修德
2023-12-01

这种方法,先要组建testsuit,实例化testsuit,加入testcase,或者包含其他的testsuit

针对下面的用例:

class MyTest(unittest.TestCase):
    def setUp(self):
        print("Set up...")
        self.myclassa = MyClassA.MyClassA()
    
    def testsum(self, a = 4, b = 5): 
        self.assertEqual(self.myclassa.addMy(a, b), a * b)
    
    def testmul(self, a = 4, b = 5): 
        self.assertEqual(self.myclassa.mulMy(a, b), a * b)
        
    def tearDown(self):
        print("Tear down...")
        pass

先看testsuit的初始化和加入test:

    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)

可以实例化后,再加testcase,最后run:

ts = unittest.TestSuite()
ts.addTest(MyTest("testsum"))
ts.addTest(MyTest("testmul"))

其他相似的组建testsuit方式:

def suite():
    suite = unittest.TestSuite()
    suite.addTest(MyTest("testsum"))
    suite.addTest(MyTest("testmul"))
    return suite
def suite():
    tests = ['testsum', 'testmul']
    return unittest.TestSuite(map(MyTest, tests))

利用unittest的TestLoader生成默认的testsuit

ts = unittest.TestLoader().loadTestsFromTestCase(MyTest)
多个testsuit组成更大的testsuit:

ts1 = unittest.TestSuite([MyTest("testsum"),])
ts2 = unittest.TestSuite([MyTest("testmul"),])
ts = unittest.TestSuite([ts1, ts2])

最后run:

runner = unittest.TextTestRunner()
runner.run(ts)


 类似资料: