如何在代码内使用python coverage [英] How to use python coverage inside the code
问题描述
我想从代码内部捕获内容。我尝试了一个以下但出现错误。请参阅以下链接以获取Coverage API。
https://coverage.readthedocs.io/ zh_cn / v4.5.x / api.html#api
I want to capture the coverage from inside the code. I tried below one but getting error. Referred to below link for coverage 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.
推荐答案
如果将 #actual代码
的内容包装在函数中,则它将起作用。这是一个(最小的)示例:
If you wrap whatever you have for #actual code
in a function, then it will work. Here's a (minimalish) example:
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')
但是,如果您要替换 test_it(123)
内联语句(例如 x = 123; x + = 1; print(x)
),那么coverage模块将失败。
However, if you would replace test_it(123)
by just doing some inline statement (like x = 123; x += 1; print(x)
), then the coverage module will fail.
它已经很好地隐藏了,但是文档确实解释了此行为:
It's well hidden, but the docs do explain this behavior:
start()
start()
开始测量代码覆盖率。
覆盖率测量仅在调用start()
之后调用的函数中进行。
一旦您调用start(),最终您还必须调用stop(),否则您的
进程可能无法完全关闭。
Once you invoke start(), you must also call stop() eventually, or your process might not shut down cleanly.
强调一下我自己的内容,这里是链接: https://coverage.readthedocs.io/zh-CN/v4.5。 x / api_coverage.html#coverage.Coverage.start
Emphasis my own, here's the link: https://coverage.readthedocs.io/en/v4.5.x/api_coverage.html#coverage.Coverage.start
这篇关于如何在代码内使用python coverage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!