unittest+coverage单元测试代码覆盖操作实例详解

yipeiwu_com5年前Python基础

基于上一篇文章,这篇文章是关于使用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设计】。

相关文章

python发送邮件实例分享

python发送邮件实例分享

为了更好的理解邮件发送功能的实现,要先了解邮件发送系统的大致流程。首先  电子邮件之间的相互发送接受就像  邮局邮件发送一样,从一个站点(邮件发送服务器)到目的地站点...

pycharm 使用心得(七)一些实用功能介绍

pycharm 使用心得(七)一些实用功能介绍

实时比较 PyCharm 对一个文件里你做的改动保持实时的跟踪,通过在编辑器的左侧栏显示一个蓝色的标记。这一点非常方便,我之前一直是在Eclipse里面用命令“Compare again...

Python Pillow.Image 图像保存和参数选择方式

保存时代码如下: figure_corp = figure.crop( (32*rate/2, 32*rate/2, 32-32*rate/2, 32-32*rate/2)) fig...

python模块之time模块(实例讲解)

python模块之time模块(实例讲解)

time 表示时间的三种形式 时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time()...

python实现生成Word、docx文件的方法分析

本文实例讲述了python实现生成Word、docx文件的方法。分享给大家供大家参考,具体如下: http://python-docx.readthedocs.io/en/latest/...