unnitest是#wiki/1514.html” target=”_blank”>python的一个重要的单元测试框架,对于用python进行开发的同事们可能不需要对他有过深入的了解会用就行,但是,对于自动化测试人员我觉得是要熟知unnitest的执行原理以及相关模块的作用。我这边提几个简单的需求如下:
1.如何利用unnitest执行流程测试而非单元测试。比如我们可能利用selenium+unnitest来跑一段流程,比如test1里面我们实现登陆,test2在test1成功登陆的基础上,实现一个查询的测试,test3我们查询一些数据后,页面选择性提交数据。这个你总不能在test1里面登陆完然后关闭浏览器;在test2里面再登陆再执行查询后关闭浏览器;test3再登陆执行提交数据。你或者可以这样想把这几个步骤写在一个test里面。但是,如果流程过长怎么办?自己难道感觉不到剪不断理还乱的纠结吗….
2.如何控制unnitest的执行顺序。unnitest里面tests数组里面存放的testcase默认是以首字母排序的,这对于test1,test2….test9这样的执行顺序是没用问题的,但是对于多个test比如test1,test2………test18,这样unnitest可不是按照这个顺序,我说了是按照首字母排序来的,他会这样执行test1,test10,….test18,test2,……….test9,当然我说的这些对于单元测试是影响不大的(除非各个test之间有数据依赖关系,后面提到),对于流程可能是颠覆性的。
3.流程测试中如何动态的控制是否跳过某个test的执行。对于流程来说,这也是常见的一种想法,比如test1我连登陆都没有成功,还有意义执行后面的test吗,之后报出来的都是一些nosuchelement的错误,这些错误没有任何意义,而且纯粹浪费时间….出来的报告也是不”人性的”。那么我们现在一个好的想法是:如果test1没有执行成功,后面的test能动态全部跳过,其实不止是test1没成功,后面test跳过,准确的说是,test1,test2……..testn中如果任意某个test没有通过,后面的能动态的全部跳过。当然,如果后面的test和前面test没什么关系,也可能选择不管前面是否成功均不跳过;也可以是只和test1登录有关,只要登录成功了我就不跳过,如果登录不成功我就跳过…还有很多…..更重要的是,报告中有所展现,不能说skip了某个用例,你报告就不显示了,这样老板认为你偷懒,用例写这么少? 你还要瑟瑟发抖的去解释,是因为前面的用例没通过所以,没显示了…我们高大上的是这样的,test1执行失败了,test2…….testn,报告中都体现,标注是skip的case,而且点开还有原因解释:”test1没有执行成功,所以跳过此case”。这就是我拓展htmltestrunner的原因,后面逐行解释如果拓展它。
…….还有很多
补充一下,为什么往流程上扯呢,因为公司的模块太多,而且复杂,单元测试机会不太会用,只要保证各个业务的主流程没问题即可,但是不影响我们解析unnitest。
我们的想法很多,但是如何来实现呢?那就让我们来深入探讨下python的unnitest吧!
关于unnitest看似复杂我给出来就是unnitest=testcase+testresult,只要熟知这2个模块,你就能”为所欲为”!!可能有人说不对不是有什么testsuite吗还有texttestrunner等等吗,不错确实我们平时用到的大多是这些模块,但是,到其实最终执行的是testcase中的run方法,并把结果给testresult(或它的子类)。我们先来看一个简单的unnitest例子,并以此来拓展!例子如下:
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 “i am mytest3 the value of a is {}”.format(self.a)
if __name__ == ‘__main__’:
test_runner=unittest.texttestrunner()
test_suit=unittest.testsuite()
test_suit.addtests(map(mydemo,[“mytest1″,”mytest2″,”mytest3”]))
test_runner.run(test_suit)
运行结果如下:
…
i am mytest1 the value of a is 1
———————————————————————-
i am mytest2 the value of a is 1
ran 3 tests in 0.000s
i am mytest3 the value of a is 1
ok
上面3个testcase可并没有以test开头…那么为什么大家都要默认以test开头来写呢,我们打开c:\python27\lib\unittest\loader.py这个模块在296行有写defaulttestloader = testloader(),我们来看看testloader这个类第一行就看见testmethodprefix = ‘test’,也就是说如果你使用到defaulttestloader,那么默认是以test开头的方法为一个用例,具体可以在testloader类中的gettestcasenames得到实现,红字注释部分为什么testcaseclass要有call方法,我们后面提到。(不知道call这个魔法属性的用法自行百度)
def gettestcasenames(self, testcaseclass):
“””return a sorted sequence of method names found within testcaseclass
“””
def istestmethod(attrname, testcase__call__’)#返回一个testcaseclass有__call__方法且attrname以prefix开头的为一个testcase
testfnnames = filter(istestmethod, dir(testcaseclass))
if self.sorttestmethodsusing:
testfnnames.sort(key=_cmptokey(self.sorttestmethodsusing))
return testfnnames
原来是这样啊,我们上文提到的unittest.main()其实用的就是defaulttestloader,当然你把if name == ‘main’下面的代码换成unittest.main()肯定不成功,除非你把上文提到的testmethodprefix 换成”mytest”。有了对testcase的看法,我们具体来看看这个类。
这个类里面包含了我们所能用的方法。我列出来一些主要的吧。
setup()在每个test执行前都要执行的方法。
teardown()在每个test执行后都要执行的方法。(不管是否执行成功)
setupclass()在一个测试类中在所有test开始之前,执行一次且必须使用到testsuite(只有在testsuite的run方法里面才对其调用)
teardownclass()在一个测试类中在所有test结束之后,执行一次且必须使用到testsuite(只有在testsuite的run方法里面才对其调用)
run()这是unnitest的核心,逻辑也相对复杂,但是很好理解,具体自己看源码。所有最终case的执行都会归结到该run方法。
还有一个重要的_resultfordocleanups私有变量,存储testresult的执行结果,这个在构建后面的skip用到。
我们要明确testcase类中所有的测试用例是独立的,我上面说过了,其实每个testcase就是一个个testcase类的实例对象,所以不要企图在某个test存储或改变一个变量,下个test中能用到,除非利用到setupclass。我们看个例子:
import unittest
class mydemo(unittest.testcase):
def test1(self):
self.a=1
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)
if __name__ == ‘__main__’:
unittest.main()
结果:
c:\python27\python.exe d:/moudle/module_1/test4.py
i am test1 the value of a is 1
.e
======================================================================
error: test2 (__main__.mydemo)
———————————————————————-
traceback (most recent call last):
file “d:/moudle/module_1/test4.py”, line 7, in test2
print “i am test2 the value of a is {}”.format(self.a)
attributeerror: ‘mydemo’ object has no attribute ‘a’
———————————————————————-
ran 2 tests in 0.001s
failed (errors=1)
上面就是说明testcase类中所有的测试用例是独立的,每个testcase就是由testcase实例化的一个独立的实例。那是不是就是每个testcase不能共享数据呢?答案是否定的,不能共享的原因是我们上面用到的是self(实例对象属性),能共享我们就必须使用类属性,比如下个例子:
import unittest
class mydemo(unittest.testcase):
def test1(self): mydemo.a=1
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(mydemo.a)
if name == ‘main’:
unittest.main()
运行结果如下:
i am test1 the value of a is 1
..
i am test2 the value of a is 1
———————————————————————-
ran 2 tests in 0.000s
ok
这些东西其实是python类的一些动态行为,但是既然和unnitest关联,就随便提下。我们运行test1的时候,给mydemo加了一个新的属性a(值为1),当我们运行test2时,我们就能拿到mydemo类的属性了。说了tasecase我们不得不说下testsuite。testsuite是有一个个testcase组成的,当然testsuite里面可以再嵌套testsuite。我们打开c:\python27\lib\unittest\suite.py找到testsuite,它继承于basetestsuite,其实主要的一些属性就那么几个:
1.self._tests这个私有变量里面方的是所有的testcase或者testsuite。
2.run()方法,方法如下:
def run(self, result, debug=false):
toplevel = false
if getattr(result, ‘_testrunentered’, false) is false:
result._testrunentered = toplevel = true
for test in self:#这个循环会一直遍历_tests中的变量
if result.shouldstop:
break
if _isnotsuite(test):
self._teardownpreviousclass(test, result)
self._handlemodulefixture(test, result)
self._handleclasssetup(test, result)#这一句提到了调用setupclass的规则
result._previoustestclass = test.__class__
if (getattr(test.__class__, ‘_classsetupfailed’, false) or
getattr(result, ‘_modulesetupfailed’, false)):
continue
if not debug:
test(result)#如果是testsuit继续调用该方法,如果是testcase则调用testcase中的run方法
else:
test.debug()
if toplevel:
self._teardownpreviousclass(none, result)
self._handlemoduleteardown(result)
result._testrunentered = false
return result
注释1:self是个迭代对象,一直遍历上文提到的self._tests变量
注释2:我们看看_handleclasssetup中的方法,发现在在用例的执行过程中,每个testcase类只会调用一次setupclass方法,同理teardownclass。对用这一点我们举个例子:
import unittest
class mydemo(unittest.testcase):
@classmethod
def setupclass(cls):
print “i am setupclass”
def test1(self):
print “i am test1 ”
def test2(self):
print “i am test2”
@classmethod
def teardownclass(cls):
print “i am teardownclass”
if __name__ == ‘__main__’:
unittest.main()
运行结果是:
c:\python27\python.exe d:/moudle/module_1/test4.py
i am setupclass
..
i am test1
———————————————————————-
i am test2
ran 2 tests in 0.001s
i am teardownclass
ok
说明类方法setupclass与teardownclass只执行了一遍了,这就回答了我们第一个问题了:在setupclass中启动浏览器,执行完所有流程后关闭浏览器,举一个简单的demo就是:
#coding=utf-
import unittest
from selenium import webdriver
class mydemo(unittest.testcase):
@classmethod
def setupclass(cls):
cls.browser=webdriver.firefox()
def test1(self):
”’登录”’
browser=self.browser
#do someting about login
def test2(self):
”’查询”’
browser = self.browser
# do someting about search
def test3(self):
”’提交数据”’
browser = self.browser
# do someting about submmit
@classmethod
def teardownclass(cls):
browser=self.browser
browser.close()
if name == ‘main’:
unittest.main()
上面就会在所有的case执行之前启动firefox,因为每个test中拿到的都是mydemo类中同一个webdriver对象,所以能保证操作的都是同一个浏览器句柄。关于这个setupclass如果想要动态的改变某个值一定要使用python的可变的对象比如list,dict等…这些其实都是一些python类的一些知识,算我啰嗦吧我还是想举个例子,嫌烦的同学,绕过这一部分吧。
#coding=utf-8
import unittest
from selenium import webdriver
class mydemo(unittest.testcase):
@classmethod
def setupclass(cls):
cls.a=1
def test1(self):
print “before update the a in test1 is:{}”.format(self.a)
self.a=self.a+1
print “after update the a in test1 is:{}”.format(self.a)
def test2(self):
print “the value in test2 is:{}”.format(self.a)
@classmethod
def teardownclass(cls):
print “i am teardownclass”
if name == ‘main’:
unittest.main()
运行结果:
c:\python27\python.exe d:/moudle/module_1/test4.py
before update the a in test1 is:1
..
after update the a in test1 is:2
———————————————————————-
the value in test2 is:1
i am teardownclass
ran 2 tests in 0.001s
ok
我们想在test1中改变a的值,但是test2中的结果说明a没有被改变,这其实也很好理解。如果我们想要改变怎么办,看看下面的例子:
#coding=utf-8
import unittest
from selenium import webdriver
class mydemo(unittest.testcase):
@classmethod
def setupclass(cls):
cls.a=[0]
def test1(self):
print “before update the a in test1 is:{}”.format(self.a[0])
self.a[0]=self.a[0]+1
print “after update the a in test1 is:{}”.format(self.a[0])
def test2(self):
print “the value in test2 is:{}”.format(self.a[0])
@classmethod
def teardownclass(cls):
print “i am teardownclass”
if name == ‘main’:
unittest.main()
运行结果:
c:\python27\python.exe d:/moudle/module_1/test4.py
..
before update the a in test1 is:0
———————————————————————-
after update the a in test1 is:1
ran 2 tests in 0.000s
the value in test2 is:1
i am teardownclass
ok
我们把a变成一个list,发现a的值在test2中改变了。好了这一部分就这样了。
注释三:这个其实也是python类的一些知识可能有的人没有关注就是call这个魔法属性,我们看到在这个循环中test如果是testsuite对象,那么会调用中testsuite类中的call方法(在其父类basetestsuite中),该方法中会再次调用run方法。一直到test是个testcase对象,那么就会调用我们上文提到的testcase中的call(这就是我们上面提到为什么找有call属性类实例的方法),一样该call中的方法也是调用testcase中的run。所以最终所有的执行其实都是执行testcase中的run方法。
上面大致讲了一些testcase与testsuit的知识,可能穿插的比较多。
如何创建这些testcase或者testsuite?
1.自己手动实例化testcase
这个上面已经有例子,与普通类无异,这中在自动化领域用处不大,我们不能一个个的实例化吧…
2.利用c:\python27\lib\unittest\loader.py模块的testloader,该类提供了多种不同情境find testcase。
1.loadtestsfromtestcase利用给出的testcase类名称返回找到所有的suite。
2.loadtestsfrommoudle利用给出的moudle返回找到所有的suite。
3.loadtestsfromname利用给出的moudle名称返回找到所有的suite。
4.discover返回给定目录下符合pattern类型(默认test*.py)所有的suite。
其实这些方法最终都要归结到loadtestsfromtestcase,可能官方不提供我们也能写,既然有了就直接用吧。
经过上面的说明,我觉得大家对一testcase,testsuite应该有一个比较清楚的认识了,也解决了我自己的提问。问题一:我们可以用类方法setupclass实现。对于问题二:我们可以利用testloader类中的方法返回suite,然后对这些suite按照自己的想法进行一些排序,然后再调用run方法。说完了testcase我们再说下testresult。
什么是testresult?
顾名思义,testresult就是存储测试结果的,不过通过何种方式调用run函数,最终到testcase中的run方法时必须传一个result(如果为none则自己实例化一个testresult对象)。这个result就是testresult对象或者是其子类的对象,我们每次执行的结果都会调用其addfailure,addsuccess,addskip….等方法将执行结果保存到testresult实例属性中。我们还是来看看testcase的run方法:
def run(self, result=none):
orig_result = result
if result is none:#如果没有传入result对象自己实例化一个testresult对象
result = self.defaulttestresult()
starttestrun = getattr(result, ‘starttestrun’, none)
if starttestrun is not none:
starttestrun()
self._resultfordocleanups = result
result.starttest(self)
testmethod = getattr(self, self._testmethodname)
if (getattr(self.__class__, “__unittest_skip__”, false) or
getattr(testmethod, “__unittest_skip__”, false)):
# if the class or method was skipped.
try:
skip_why = (getattr(self.__class__, ‘__unittest_skip_why__’, ”)
or getattr(testmethod, ‘__unittest_skip_why__’, ”))
self._addskip(result, skip_why)#调用addskip
finally:
result.stoptest(self)
return
try:
success = false
try:
self.setup()
except skiptest as e:
self._addskip(result, str(e))
except keyboardinterrupt:
raise
except:
result.adderror(self, sys.exc_info())#调用adderror
else:
try:
testmethod()
except keyboardinterrupt:
raise
except self.failureexception:
result.addfailure(self, sys.exc_info())#调用addfailure
except _expectedfailure as e:
addexpectedfailure = getattr(result, ‘addexpectedfailure’, none)
if addexpectedfailure is not none:
addexpectedfailure(self, e.exc_info)#调用addexpectedfailure
else:
warnings.warn(“testresult has no addexpectedfailure method, reporting as passes”,
runtimewarning)
result.addsuccess(self)#调用addsuccess
except _unexpectedsuccess:
addunexpectedsuccess = getattr(result, ‘addunexpectedsuccess’, none)
if addunexpectedsuccess is not none:
addunexpectedsuccess(self)
else:
warnings.warn(“testresult has no addunexpectedsuccess method, reporting as failures”,
runtimewarning)
result.addfailure(self, sys.exc_info())
except skiptest as e:
self._addskip(result, str(e))
except:
result.adderror(self, sys.exc_info())
else:
success = true
try:
self.teardown()
except keyboardinterrupt:
raise
except:
result.adderror(self, sys.exc_info())
success = false
cleanupsuccess = self.docleanups()
success = success and cleanupsuccess
if success:
result.addsuccess(self)
finally:
result.stoptest(self)
if orig_result is none:
stoptestrun = getattr(result, ‘stoptestrun’, none)
if stoptestrun is not none:
stoptestrun()
通过注释部分我们可以看出,每次执行用例时,都会把执行结果保存到testresult中。我们再看看texttestrunner这个类,在开始就使用了类texttestresult,而这个类也是继承testresult,而后在执行的过程中最终把texttestresult实例对象传递给testcase的run方法。所以我上文说了,不过你是用什么方式执行unnitest,到最后都是testcase的run方法与testresult的游戏。而我们的htmltestrunner模块也是在继承在testresult类的基础上的。
说完了testcase我们来看看第三个问题吧,也是比较有实际意义的话题,开始我是这样跳过某些test的,代码是这样的:
#coding=utf-8
import unittest
a=[false]
class mydemo(unittest.testcase):
def test1(self):
try:
print “i am test1″
#test 1 do some thing
except exception,e:
a[0] = true
raise e
@unittest.skipif(a[0],”test1 fail skip test2”)
def test2(self):
try:
print “i am test2”
raise assertionerror(“error”)
# test2 do some thing
except exception,e:
a[0] = true
raise e
@unittest.skipif(a[0], “test1 fail skip test2”)
def test3(self):
try:
print “i am test3”
# test2 do some thing
except exception, e:
a[0] =true
raise e
if __name__ == ‘__main__’:
unittest.main()
想法很简单:就是利用一个全局的数组,如果某个test执行出错我就更改这个数组元素,到下一个case执行的时候就会判断是否要跳过。上面因为test2出错了,原本我们想跳过test3,但是很遗憾并没有跳过test3!结果如下:
c:\python27\python.exe d:/moudle/module_1/test4.py
i am test1
.f.
i am test2
======================================================================
i am test3
fail: test2 (__main__.mydemo)
———————————————————————-
traceback (most recent call last):
file “d:/moudle/module_1/test4.py”, line 20, in test2
raise e
assertionerror: error
———————————————————————-
ran 3 tests in 0.000s
failed (failures=1)
原因很简单:python在创建mydemo这个类的时候,由于实例方法都使用了装饰器unittest.skipif,所以每个方法都向unittest.skipif这个装饰传递传递参数a[0],但是这个a[0]是没用执行过任何case之前的a[0],也就是我们刚开始定义的a[0]=flase,所以不可能跳过的。退一万步讲,即使这样可行,也太不美观了吧。我们想的是当执行当前的test时能判断前面是否有出错的case,有的话就跳过了。可行吗?我觉得可行。主要就是用到我上面提到的testcase中的_resultfordocleanups的变量,这个其实就是testresult一个引用。那么我们可以这样写:
#coding=utf-8
import unittest
class mydemo(unittest.testcase):
def test1(self):
print “excute test1”
def test2(self):
if self._resultfordocleanups.failures or self._resultfordocleanups.errors:
raise unittest.skiptest(“{} do not excute because {} is failed”.format(self._testmethodname,self._resultfordocleanups.failures[0][0]._testmethodname))
print “excute test2”
raise assertionerror(“test2 fail”)
def test3(self):
if self._resultfordocleanups.failures or self._resultfordocleanups.errors:
raise unittest.skiptest(“{} do not excute because {} is failed”.format(self._testmethodname,self._resultfordocleanups.failures[0][0]._testmethodname))
print “excute test3”
if name == ‘main’:
unittest.main()
运行结果如下:
.fs
======================================================================
fail: test2 (main.mydemo)
———————————————————————-
traceback (most recent call last):
file “d:/moudle/module_1/test4.py”, line 10, in test2
raise assertionerror(“test2 fail”)
assertionerror: test2 fail
———————————————————————-
ran 3 tests in 0.001s
failed (failures=1, skipped=1)
excute test1
excute test2
可以了,我们看出,test2失败了,test3跳过;当然test2如果正确,test3会执行。目的是达到了,可是每个case都这样写不太好,我们想到了装饰器(不会自行百度),在c:\python27\lib\unittest\case.py中新增如下代码:
def myskip(func):
def rebacktest(self):
if self._resultfordocleanups.failures or self._resultfordocleanups.errors:
raise unittest.skiptest(“{} do not excute because {} is failed”.format(func.name,self._resultfordocleanups.failures[0][0]._testmethodname))
func(self)
return rebacktest
然后c:\python27\lib\unittest\init.py中新增:
all = [‘testresult’, ‘testcase’, ‘testsuite’,
‘texttestrunner’, ‘testloader’, ‘functiontestcase’, ‘main’,
‘defaulttestloader’, ‘skiptest’, ‘skip’, ‘skipif’, ‘skipunless’,
‘expectedfailure’, ‘texttestresult’, ‘installhandler’,
‘registerresult’, ‘removeresult’, ‘removehandler’,’myskip’]
……
from .case import (testcase, functiontestcase, skiptest, skip, skipif,myskip,
skipunless, expectedfailure)
最终我们这样写:
#coding=utf-8
import unittest
class mydemo(unittest.testcase):
def test1(self):
print “excute test1”
@unittest.myskip
def test2(self):
print “excute test2”
raise assertionerror(“test2 fail”)
@unittest.myskip
def test3(self):
print “excute test3”
if name == ‘main’:
unittest.main()
好了,看上去还不错….关于其他的unnitest相关知识,不想再扯了,最后拓展htmltestrunner报告,这可能是大家关心的!写这个htmltestrunner的大神是在好久之前的了,基本能满足大家需求。但是,目前对于web自动化,我觉得至少要新增2个东西。第一个新增skip列:因为我可能会skip某些case;第二新增截图列,如果有错误我可能要截图。打了这么久字不想再多说了….我给出全部代码,然后代码中我改变的地方我给出标记并加注释吧,完整代码如下:(可能有点长,但是要有点耐心)
#coding=utf-8
“””
a testrunner for use with the python unit testing framework. it
generates a html report to show the result at a glance.
the simplest way to use this is to invoke its main method. e.g.
import unittest
import htmltestrunner
… define your tests …
if name == ‘main’:
htmltestrunner.main()
for more customization options, instantiates a htmltestrunner object.
htmltestrunner is a counterpart to unittest’s texttestrunner. e.g.
# output to a file
fp = file(‘my_report.html’, ‘wb’)
runner = htmltestrunner.htmltestrunner(
stream=fp,
title=’my unit test’,
description=’this demonstrates the report output by htmltestrunner.’
)
# use an external stylesheet.
# see the template_mixin class for more customizable options
runner.stylesheet_tmpl = ”
# run the test
runner.run(my_test_suite)
————————————————————————
copyright (c) 2004-2007, wai yip tung
all rights reserved.
redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* neither the name wai yip tung nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
this software is provided by the copyright holders and contributors “as
is” and any express or implied warranties, including, but not limited
to, the implied warranties of merchantability and fitness for a
particular purpose are disclaimed. in no event shall the copyright owner
or contributors be liable for any direct, indirect, incidental, special,
exemplary, or consequential damages (including, but not limited to,
procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including
negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
“””
# url: http://tungwaiyip.info/software/htmltestrunner.html
author = “wai yip tung”
version = “0.8.2”
“””
change history
version 0.8.2
* show output inline instead of popup window (viorel lupu).
version in 0.8.1
* validated xhtml (wolfgang borgert).
* added description of test classes and test cases.
version in 0.8.0
* define template_mixin class for customization.
* workaround a ie 6 bug that it does not treat 《script》 block as cdata.
version in 0.7.1
* back port to python 2.3 (frank horowitz).
* fix missing scroll bars in detail log (podi).
“””
# todo: color stderr
# todo: simplify javascript using ,ore than 1 class in the class attribute?
#coding=utf-8
import datetime
import io
import sys
reload(sys)
sys.setdefaultencoding(‘utf8’)
import time
import unittest
import re
from xml.sax import saxutils
# ————————————————————————
# the redirectors below are used to capture output during testing. output
# sent to sys.stdout and sys.stderr are automatically captured. however
# in some cases sys.stdout is already cached before htmltestrunner is
# invoked (e.g. calling logging.basicconfig). in order to capture those
# output, use the redirectors for the cached stream.
#
# e.g.
# >>> logging.basicconfig(stream=htmltestrunner.stdout_redirector)
# >>>
class outputredirector(object):
“”” wrapper to redirect stdout or stderr “””
def init(self, fp):
self.fp = fp
def write(self, s):
self.fp.write(s)
def writelines(self, lines):
self.fp.writelines(lines)
def flush(self):
self.fp.flush()
stdout_redirector = outputredirector(sys.stdout)
stderr_redirector = outputredirector(sys.stderr)
# ———————————————————————-
# template
class template_mixin(object):
“””
define a html template for report customerization and generation.
overall structure of an html report
html
+————————+
| |
| |
| |
| stylesheet |
| +—————-+ |
| | | |
| +—————-+ |
| |
| |
| |
| |
| |
| heading |
| +—————-+ |
| | | |
| +—————-+ |
| |
| report |
| +—————-+ |
| | | |
| +—————-+ |
| |
| ending |
| +—————-+ |
| | | |
| +—————-+ |
| |
| |
| |
+————————+
“””
status = {
0: ‘pass’,
1: ‘fail’,
2: ‘error’,
}
default_title = ‘unit test report’
default_description = ”
# ————————————————————————
# html template
html_tmpl = r”””
%(title)s
%(stylesheet)s
《script》
%(heading)s
%(report)s
%(ending)s
“””
# variables: (title, generator, stylesheet, heading, report, ending)
# ————————————————————————
# stylesheet
#
# alternatively use a for external style sheet, e.g.
#
stylesheet_tmpl = “””
“””
# ————————————————————————
# heading
#
heading_tmpl = “””
%(title)s
%(parameters)s
%(description)s
“”” # variables: (title, parameters, description)
heading_attribute_tmpl = “””
%(name)s: %(value)s
“”” # variables: (name, value)
# ————————————————————————
# report
#
report_tmpl = “””
show
summary
failed
all
test group/test case
count
pass
fail
error
view
%(test_list)s
total
%(count)s
%(pass)s
%(fail)s
%(error)s
“”” # variables: (test_list, count, pass, fail, error)
report_class_tmpl = r”””
%(desc)s
%(count)s
%(pass)s
%(fail)s
%(error)s
detail
“”” # variables: (style, desc, count, pass, fail,skip, error, cid) “”” # variables: (tid, class, style, desc, status) “”” # variables: (tid, class, style, desc, status)
report_test_output_tmpl = r”””
%(id)s: %(output)s
“””
# variables: (id, output)
# ————————————————————————
# ending
#
ending_tmpl = “””
“””
# ——————– the end of the template class ——————-
testresult = unittest.testresult
class _testresult(testresult):
# note: _testresult is a pure representation of results.
# it lacks the output and reporting ability compares to unittest._texttestresult.
def init(self, verbosity=1):
testresult.init(self)
self.stdout0 = none
self.stderr0 = none
self.success_count = 0
self.failure_count = 0
self.error_count = 0
self.verbosity = verbosity
# result is a list of result in 4 tuple
# (
# result code (0: success; 1: fail; 2: error),
# testcase object,
# test output (byte string),
# stack trace,
# )
self.result = []
def starttest(self, test):
testresult.starttest(self, test)
# just one buffer for both stdout and stderr
self.outputbuffer = io.bytesio()
stdout_redirector.fp = self.outputbuffer
stderr_redirector.fp = self.outputbuffer
self.stdout0 = sys.stdout
self.stderr0 = sys.stderr
sys.stdout = stdout_redirector
sys.stderr = stderr_redirector
def complete_output(self):
“””
disconnect output redirection and return buffer.
safe to call multiple times.
“””
if self.stdout0:
sys.stdout = self.stdout0
sys.stderr = self.stderr0
self.stdout0 = none
self.stderr0 = none
return self.outputbuffer.getvalue()
def stoptest(self, test):
# usually one of addsuccess, adderror or addfailure would have been called.
# but there are some path in unittest that would bypass this.
# we must disconnect stdout in stoptest(), which is guaranteed to be called.
self.complete_output()
def addsuccess(self, test):
self.success_count += 1
testresult.addsuccess(self, test)
output = self.complete_output()
self.result.append((0, test, output, ”))
if self.verbosity > 1:
sys.stderr.write(‘ok ‘)
sys.stderr.write(str(test))
sys.stderr.write(‘\n’)
else:
sys.stderr.write(‘.’)
def adderror(self, test, err):
self.error_count += 1
testresult.adderror(self, test, err)
_, _exc_str = self.errors[-1]
output = self.complete_output()
self.result.append((2, test, output, _exc_str))
if self.verbosity > 1:
sys.stderr.write(‘e ‘)
sys.stderr.write(str(test))
sys.stderr.write(‘\n’)
else:
sys.stderr.write(‘e’)
def addfailure(self, test, err):
self.failure_count += 1
testresult.addfailure(self, test, err)
_, _exc_str = self.failures[-1]
output = self.complete_output()
self.result.append((1, test, output, _exc_str))
if self.verbosity > 1:
sys.stderr.write(‘f ‘)
sys.stderr.write(str(test))
sys.stderr.write(‘\n’)
else:
sys.stderr.write(‘f’)
class htmltestrunner(template_mixin):
“””
“””
def init(self, stream=sys.stdout, verbosity=1, title=none, description=none,name=none):
self.stream = stream
self.verbosity = verbosity
if title is none:
self.title = self.default_title
else:
self.title = title
if name is none:
self.name =”
else:
self.name = name
if description is none:
self.description = self.default_description
else:
self.description = description
self.starttime = datetime.datetime.now()
def run(self, test):
“run the given test case or test suite.”
result = _testresult(self.verbosity)
test(result)
self.stoptime = datetime.datetime.now()
self.generatereport(test, result)
# print (sys.stderr, ‘\ntime elapsed: %s’ % (self.stoptime-self.starttime))
return result
def sortresult(self, result_list):
# unittest does not seems to run in any particular order.
# here at least we want to group them together by class.
rmap = {}
classes = []
for n,t,o,e in result_list:
cls = t.class
if not cls in rmap:
rmap[cls] = []
classes.append(cls)
rmap[cls].append((n,t,o,e))
r = [(cls, rmap[cls]) for cls in classes]
return r
def getreportattributes(self, result):
“””
return report attributes as a list of (name, value).
override this to add custom attributes.
“””
starttime = str(self.starttime)[:19]
duration = str(self.stoptime – self.starttime)
status = []
if result.success_count: status.append(‘pass %s’ % result.success_count)
if result.failure_count: status.append(‘failure %s’ % result.failure_count)
if result.error_count: status.append(‘error %s’ % result.error_count )
if status:
status = ‘ ‘.join(status)
else:
status = ‘none’
return [
(‘start time’, starttime),
(‘duration’, duration),
(‘status’, status),
]
def generatereport(self, test, result):
report_attrs = self.getreportattributes(result)#报告的头部
generator = ‘htmltestrunner %s’ % version
stylesheet = self._generate_stylesheet()#拿到css文件
heading = self._generate_heading(report_attrs)
report = self._generate_report(result)
ending = self._generate_ending()
output = self.html_tmpl % dict(
title = saxutils.escape(self.title),
generator = generator,
stylesheet = stylesheet,
heading = heading,
report = report,
ending = ending,
)
self.stream.write(output.encode(‘utf8’))
def _generate_stylesheet(self):
return self.stylesheet_tmpl
def _generate_heading(self, report_attrs):
a_lines = []
for name, value in report_attrs:
line = self.heading_attribute_tmpl % dict(
name = saxutils.escape(name),
value = saxutils.escape(value),
)
a_lines.append(line)
heading = self.heading_tmpl % dict(
title = saxutils.escape(self.title),
parameters = ”.join(a_lines),
description = saxutils.escape(self.description),
)
return heading
#根据result收集报告
def _generate_report(self, result):
rows = []
sortedresult = self.sortresult(result.result)
i = 0
for cid, (cls, cls_results) in enumerate(sortedresult):
# subtotal for a class
for n,t,o,e in cls_results:
if n == 0: np += 1
elif n == 1: nf += 1
else: ne += 1
# format class description
# if cls.module == “main”:
# name = cls.name
# else:
# name = “%s.%s” % (cls.module, cls.name)
name = cls.name
try:
core_name=self.name[i]
except exception,e:
core_name =”
# doc = (cls.doc)+core_name and (cls.doc+core_name).split(“\n”)[0] or “”
doc = (cls.doc) and cls.doc .split(“\n”)[0] or “”
desc = doc and ‘%s: %s’ % (name, doc) or name
i=i+1
#生成每个testcase类的汇总数据,对于报告中的
row = self.report_class_tmpl % dict(
style = ne > 0 and ‘errorclass’ or nf > 0 and ‘failclass’ or ‘passclass’,
desc = desc, ,
pass = np,
fail = nf,
error = ne,
cid = ‘c%s’ % (cid+1),
)
rows.append(row)
#生成每个testcase类中所有方法的测试结果
for tid, (n,t,o,e) in enumerate(cls_results):
self._generate_report_test(rows, cid, tid, n, t, o, e)
report = self.report_tmpl % dict(
test_list = ”.join(rows),
count = str(result.success_count+result.failure_count+result.error_count+result.skipped_count),
pass = str(result.success_count),
fail = str(result.failure_count),
error = str(result.error_count),
)
return report
def _generate_report_test(self, rows, cid, tid, n, t, o, e):
# e.g. ‘pt1.1’, ‘ft1.1’, etc
has_output = bool(o or e)
name = t.id().split(‘.’)[-1]
doc = t.shortdescription() or “”
desc = doc and (‘%s: %s’ % (name, doc)) or name
tmpl = has_output and self.report_test_with_output_tmpl or self.report_test_no_output_tmpl
uo1=””
# o and e should be byte string because they are collected from stdout and stderr?
if isinstance(o,str):
uo = str(o)
else:
uo = e
if isinstance(e,str):
# todo: some problem with ‘string_escape’: it escape \n and mess up formating
# ue = unicode(e.encode(‘string_escape’))
ue = e
else:
ue = o
script = self.report_test_output_tmpl % dict(
id = tid,
output = saxutils.escape(str(uo) + str(ue))
)
row = tmpl % dict(
tid = tid,
class = (n == 0 and ‘hiddenrow’ or ‘none’),
desc = desc,
script = script,
hidde=hidde_status,
image=image_url,
status = self.status[n],
)
rows.append(row)
if not has_output:
return
def _generate_ending(self):
return self.ending_tmpl
##############################################################################
# facilities for running tests from the command line
##############################################################################
# note: reuse unittest.testprogram to launch test. in the future we may
# build our own launcher to support more specific command line
# parameters like test title, css, etc.
# class testprogram(unittest.testprogram):
# “””
# a variation of the unittest.testprogram. please refer to the base
# class for command line parameters.
# “””
# def runtests(self):
# # pick htmltestrunner as the default test runner.
# # base class’s testrunner parameter is not useful because it means
# # we have to instantiate htmltestrunner before we know self.verbosity.
# if self.testrunner is none:
# self.testrunner = htmltestrunner(verbosity=self.verbosity)
# unittest.testprogram.runtests(self)
#
# main = testprogram
##############################################################################
# executing this module from the command line
##############################################################################
if name == “main”:
main(module=none)
把上面代码复制覆盖原来的htmltestrunner就好,截图那块我是把错误的图像放在apache服务器的某个路径下的,如果有错误就显示图片超链接,没有就隐藏这超链接。
关于上面的改动其实很简单,熟悉一定的前端语言(html.javascript)即可。htmltestrunner原理就是我们上文提到的利用_testresult继承unnitest中的testresult类,并重写了addsuccess,addskip,adderror等方法,把测试结果放在一个self.result里面,最后遍历这个result利用前端的一些知识生成一个html报告。这边贴图贴一下生成的样式吧,执行testcase的代码:
#coding=utf-8
import unittest
import htmltestrunner
import sys,os
class mydemo(unittest.testcase):
def test1(self):
print “excute test1”
@unittest.myskip
def test2(self):
print “excute test2”
raise assertionerror(“test2 fail”)
@unittest.myskip
def test3(self):
print “excute test3”
@unittest.myskip
def test4(self):
print “excute test4”
if name == ‘main’:
module_name=os.path.basename(sys.argv[0]).split(“.”)[0]
module=import(module_name)
fp=file(“./new.html”,”wb”)
runner=htmltestrunner.htmltestrunner(fp)
all_suite=unittest.defaulttestloader.loadtestsfrommodule(module)
runner.run(all_suite)
最后生成的报告如下:
以上就是python的unittest并拓展htmltestrunner详细说明的详细内容,更多请关注 第一php社区 其它相关文章!