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设计】。

相关文章

Centos7 下安装最新的python3.8

Python 3.8是Python语言的最新版本,它适合用于编写脚本、自动化以及机器学习和Web开发等各种任务。现在Python 3.8已经进入官方的beta阶段,这个版本带来了许多语法...

详解基于python-django框架的支付宝支付案例

详解基于python-django框架的支付宝支付案例

一. 开发前的准备 1. 必须了解的知识 SDK:软件开发工具包,可以为开发者提供快速开发的工具 沙箱环境:也就是测试环境 支付宝支付金额的精度:小数点后两位(面试)...

python控制台实现tab补全和清屏的例子

在shell(bash)下有2个很基本的功能,那就是tab补全,和clear清屏,对于我这种时不时不自觉的就手残要clear清屏一下的人来说,python控制台不能清屏很不爽,经过goo...

Python中将字典转换为XML以及相关的命名空间解析

尽管 xml.etree.ElementTree 库通常用来做解析工作,其实它也可以创建XML文档。 例如,考虑如下这个函数: from xml.etree.ElementTree...

Sublime开发python程序的示例代码

本文介绍了Sublime开发python程序的示例代码,分享给大家,具体如下: 下载、安装Python程序 https://www.python.org/downloads/ 下载、安...