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

yipeiwu_com4年前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实现分段线性插值

本文实例为大家分享了Python实现分段线性插值的具体代码,供大家参考,具体内容如下 函数: 算法 这个算法不算难。甚至可以说是非常简陋。但是在代码实现上却比之前的稍微麻烦点。主要体现...

使用批处理脚本自动生成并上传NuGet包(操作方法)

使用批处理脚本自动生成并上传NuGet包(操作方法)

  Hello 大家好,我是TANZAME,我们又见面了。   NuGet是什么这里就不再重复啰嗦,园子里一搜一大把。今天要跟大家分享的是,在日常开发过程中如何统一管理我们的包,如何通过...

python 常见字符串与函数的用法详解

strip去除空格 s = ' abcd efg ' print(s.strip()) #去除所有空格 print(s.lstrip()) #去除左边空格 print(s.rs...

分享Pycharm中一些不为人知的技巧

分享Pycharm中一些不为人知的技巧

工欲善其事必先利其器,Pycharm 是最受欢迎的Python开发工具,它提供的功能非常强大,是构建大型项目的理想工具之一,如果能挖掘出里面实用技巧,能带来事半功倍的效果。 以下操作都是...

基于python监控程序是否关闭

这篇文章主要介绍了基于python监控程序是否关闭,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 监控一个服务系exe在他关闭后打印,...