【问题标题】:How to use python coverage inside the code如何在代码中使用 python 覆盖率
【发布时间】:2019-03-30 01:22:36
【问题描述】:

我想从代码内部捕获覆盖率。我尝试了以下一项,但出现错误。参考下面的覆盖 API 链接。 https://coverage.readthedocs.io/en/v4.5.x/api.html#api

import os
import pandas as pd
import sys
import requests
import xml.etree.ElementTree as ET
from xml.dom import minidom
import coverage

cov = coverage.Coverage()
cov.start()

#actual code

cov.stop()
cov.save()

cov.html_report(directory='covhtml')

遇到错误

CoverageException                         Traceback (most recent call last)
<ipython-input-15-2047badbbd57> in <module>()
     48 cov.save()
     49 
---> 50 cov.html_report(directory='covhtml')

C:\Users\\Anaconda2\lib\site-packages\coverage\control.pyc in html_report(self, morfs, directory, ignore_errors, omit, include, extra_css, title, skip_covered)
   1093             )
   1094         reporter = HtmlReporter(self, self.config)
-> 1095         return reporter.report(morfs)
   1096 
   1097     def xml_report(

C:\Users\\Anaconda2\lib\site-packages\coverage\html.pyc in report(self, morfs)
    137 
    138         # Process all the files.
--> 139         self.report_files(self.html_file, morfs, self.config.html_dir)
    140 
    141         if not self.all_files_nums:

C:\Users\\Anaconda2\lib\site-packages\coverage\report.pyc in report_files(self, report_fn, morfs, directory)
     81 
     82         if not file_reporters:
---> 83             raise CoverageException("No data to report.")
     84 
     85         self.directory = directory

CoverageException: No data to report.

【问题讨论】:

  • 你能说一下你为什么要使用coverage API吗?为什么不在命令行上运行覆盖?
  • 我有一个调用不同 python 脚本的 shell 脚本。因此,我觉得对于每个 python 脚本,我都可以插入覆盖代码并将输出重定向到每个 python 脚本的单独目录。这看起来比命令行选项更干净。
  • 我不知道为什么这对你来说似乎更干净。覆盖率测量应该是一个可以应用于现有代码的可选过程。您可以在 shell 脚本中更改一行来实现它。

标签: python code-coverage


【解决方案1】:

如果您将 #actual code 的所有内容包装在一个函数中,那么它将起作用。这是一个(最小的)示例:

import coverage

def test_it(x):
    return x + 1

cov = coverage.Coverage()
cov.start()

test_it(123)

cov.stop()
cov.save()

cov.html_report(directory='covhtml')

但是,如果您只是通过执行一些内联​​语句(如 x = 123; x += 1; print(x))来替换 test_it(123),那么覆盖模块将会失败。

它隐藏得很好,但文档确实解释了这种行为:

开始()

开始测量代码覆盖率。

覆盖率测量只发生在 start() 之后调用的函数中 调用。与 start() 范围相同的语句将不会被测量。

一旦你调用 start(),你最终也必须调用 stop(),或者你的 进程可能无法完全关闭。

强调我自己的,这是链接:https://coverage.readthedocs.io/en/v4.5.x/api_coverage.html#coverage.Coverage.start

【讨论】:

  • Matt - 我试过你的代码,但它也失败了,同样的错误。
  • @RishiBansal 你确定吗?您将它完全原样复制/粘贴到一个新文件中,并通过您的python解释器运行该文件?它对我有用(只需通过快速复制/粘贴仔细检查),我使用的是 Python 3.6,MacOS。
  • 是的,我又试了一次,但失败了。我正在使用 Python 2.7 Anaconda/Jupiter,Windows 10。
  • @RishiBansal 你有什么版本的报道?我刚刚尝试使用 conda env 中的 Python 2.7,它仍然有效。我的版本是 4.5.1。要获取版本,请执行import coverage; coverage.__version__
  • @RishiBansal 为了安全起见,我认为如果您要覆盖的代码也在不同的模块中,它也最有效。这也可能解决问题。
猜你喜欢
  • 2013-07-31
  • 2011-02-15
  • 1970-01-01
  • 2011-03-18
  • 2023-02-02
  • 2012-06-30
  • 1970-01-01
  • 2019-01-23
  • 2018-01-11
相关资源
最近更新 更多