问题
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')
getting below errors
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.
回答1:
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')
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 measuring code coverage.
Coverage measurement only occurs in functions called after start() is invoked. Statements in the same scope as start() won’t be measured.
Once you invoke start(), you must also call stop() eventually, or your process might not shut down cleanly.
Emphasis my own, here's the link: https://coverage.readthedocs.io/en/v4.5.x/api_coverage.html#coverage.Coverage.start
来源:https://stackoverflow.com/questions/52989127/how-to-use-python-coverage-inside-the-code