深入解读Python的unittest并拓展HTMLTestRunner
unnitest
就是unnitest=TestCase+TestResult
,到其实最终执行的是 TestCase
中的run
方法,并把结果给 TestResult
(或它的子类)。
import unittest
class Mydemo(unittest.TestCase):
def setUp(self):
self.a=1
def test1(self):
print "i am test1 the value of a is {}".format(self.a)
def test2(self):
print "i am test2 the value of a is {}".format(self.a)
def test3(self):
print "i am test3 the value of a is {}".format(self.a)
if __name__ == '__main__':
unittest.main()
i am test1 the value of a is 1
...
i am test2 the value of a is 1
i am test3 the value of a is 1
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
这个是没有问题的,那么我们可能要想这个unnitest.main()
是什么东西,还有其他的写法来执行吗,能只执行test1
,test2
,不执行test3
吗(暂时不用skip)?那么我们从unittest.main()
看起来。debug进入其实最终执行的是TestProgram这类,贴出构造函数部分代码:
if argv is None:
argv = sys.argv#得到当前模块的绝对路径
self.exit = exit
self.failfast = failfast
self.catchbreak = catchbreak
self.verbosity = verbosity
self.buffer = buffer
self.defaultTest = defaultTest
self.testRunner = testRunner
self.testLoader = testLoader
self.progName = os.path.basename(argv[0])
self.parseArgs(argv)#查找当前module的Testsuite
self.runTests()#执行测试
从上面我们可以看出来其实也就2个主要的步骤就是第一:找出要测试的testcase,并加入到Testsuite,第二:运行Testsuite并把结果给TestResult。
首先,第一:了解什么是TestCase?什么是TestSuite?第二:如果找出这些Testcase,或者TestSuite?
什么是TestCase?
有人说TesetCase
就是以test开头的就叫一个testcase
,准确的说:是实例了一个TesetCase
类的叫一个TestCase
,比如这样:
import unittest
class Mydemo(unittest.TestCase):
def setUp(self):
self.a=1
def Mytest1(self):
print "i am Mytest1 the value of a is {}".format(self.a)
def Mytest2(self):
print "i am Mytest2 the value of a is {}".format(self.a)
def Mytest3(self):
print