python覆盖率coverage的使用

创建一个cova.py文件。用来测试代码运行的覆盖率

import os
import unittest
import coverage


#
# # 实例化覆盖类
# cov = coverage.coverage(source=['run.py'])
# # 开始分析
# cov.start()
# # suite = unittest.defaultTestLoader.discover(os.getcwd(), "run.py")
# # unittest.TextTestRunner().run(suite)
# # 结束分析
# cov.stop()
# # 结果保存
# cov.save()
# # 命令行模式展示结果
# cov.report()
# # 生成HTML覆盖率报告
# cov.html_report(directory='covhtml')


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("Test_case")]
    # 用来保存测试文件
    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("获取的测试py:",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()

 运行后会生成相关覆盖率的文件如下:

打开index.html,可查看当前运行的覆盖率

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值