创建一个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,可查看当前运行的覆盖率