基于上一篇文章,这篇文章是关于使用coverage来实现代码覆盖的操作实例,源代码在上一篇已经给出相应链接。
本篇文章字用来实现代码覆盖的源代码,整个项目的测试框架如下:
就是在源代码的基础上加了一个codecover.py文件,执行该文件会在目录coveragereport生成相应的覆盖报告。如下是codecover.py的源码:
#coding=utf8 import os import time def findtestwithpath(): current_dir=os.getcwd() foldername=os.listdir(current_dir) #print foldername #获取到测试文件所在目录 testsuit=[suite for suite in foldername if not suite.find(testsuit)] #用来保存测试文件 testfile=[] withpathfile=[] for suite in testsuit: #获取测试目录下的所有测试文件 testfile=testfile+os.listdir(.\\+suite) for withpath in testfile: withpath=current_dir+\\+suite+\\+withpath withpathfile.append(withpath) del testfile #把testfile中的py文件挑选出来 withpathfile=[name for name in withpathfile if not pyc in name] #print testfile print withpathfile return withpathfile def codecoverage(): now = time.strftime(%y%m%d%h%m) htmlreport=os.getcwd()+\\+coveragereport htmlcmd=coverage html -d + htmlreport +\\+now for pyfile in findtestwithpath(): runpycmd=coverage run + pyfile if os.path.exists(htmlreport) : os.system(runpycmd) os.system(htmlcmd) else: os.mkdir(htmlreport) os.system(runpycmd) os.system(htmlcmd) if name==main: codecoverage()
运行结果图:
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
python使用unittest测试接口步奏详解
python字典的清单如何使用
以上就是unittest+coverage怎么进行单元测试覆盖的详细内容。
