diff options
Diffstat (limited to 'coverage')
-rw-r--r-- | coverage/annotate.py | 10 | ||||
-rw-r--r-- | coverage/bytecode.py | 16 | ||||
-rw-r--r-- | coverage/codeunit.py | 38 | ||||
-rw-r--r-- | coverage/collector.py | 8 | ||||
-rw-r--r-- | coverage/control.py | 61 | ||||
-rw-r--r-- | coverage/html.py | 20 | ||||
-rw-r--r-- | coverage/htmlfiles/index.html | 90 | ||||
-rw-r--r-- | coverage/htmlfiles/pyfile.html | 88 | ||||
-rw-r--r-- | coverage/phystokens.py | 5 | ||||
-rw-r--r-- | coverage/python.py | 41 | ||||
-rw-r--r-- | coverage/report.py | 44 | ||||
-rw-r--r-- | coverage/results.py | 6 | ||||
-rw-r--r-- | coverage/summary.py | 14 | ||||
-rw-r--r-- | coverage/templite.py | 2 | ||||
-rw-r--r-- | coverage/tracer.c | 315 | ||||
-rw-r--r-- | coverage/version.py | 4 | ||||
-rw-r--r-- | coverage/xmlreport.py | 11 |
17 files changed, 457 insertions, 316 deletions
diff --git a/coverage/annotate.py b/coverage/annotate.py index 3487feb6..b77df4ec 100644 --- a/coverage/annotate.py +++ b/coverage/annotate.py @@ -41,10 +41,10 @@ class AnnotateReporter(Reporter): """ self.report_files(self.annotate_file, morfs, directory) - def annotate_file(self, cu, analysis): + def annotate_file(self, fr, analysis): """Annotate a single file. - `cu` is the CodeUnit for the file to annotate. + `fr` is the FileReporter for the file to annotate. """ statements = sorted(analysis.statements) @@ -52,18 +52,18 @@ class AnnotateReporter(Reporter): excluded = sorted(analysis.excluded) if self.directory: - dest_file = os.path.join(self.directory, cu.flat_rootname()) + dest_file = os.path.join(self.directory, fr.flat_rootname()) if dest_file.endswith("_py"): dest_file = dest_file[:-3] + ".py" dest_file += ",cover" else: - dest_file = cu.filename + ",cover" + dest_file = fr.filename + ",cover" with open(dest_file, 'w') as dest: i = 0 j = 0 covered = True - source = cu.source() + source = fr.source() for lineno, line in enumerate(source.splitlines(True), start=1): while i < len(statements) and statements[i] < lineno: i += 1 diff --git a/coverage/bytecode.py b/coverage/bytecode.py index 3f62dfaf..d7304936 100644 --- a/coverage/bytecode.py +++ b/coverage/bytecode.py @@ -1,9 +1,11 @@ """Bytecode manipulation for coverage.py""" -import opcode, types +import opcode +import types from coverage.backward import byte_to_int + class ByteCode(object): """A single bytecode.""" def __init__(self): @@ -26,6 +28,9 @@ class ByteCode(object): class ByteCodes(object): """Iterator over byte codes in `code`. + This handles the logic of EXTENDED_ARG byte codes internally. Those byte + codes are not returned by this iterator. + Returns `ByteCode` objects. """ @@ -37,6 +42,7 @@ class ByteCodes(object): def __iter__(self): offset = 0 + ext_arg = 0 while offset < len(self.code): bc = ByteCode() bc.op = self[offset] @@ -44,7 +50,7 @@ class ByteCodes(object): next_offset = offset+1 if bc.op >= opcode.HAVE_ARGUMENT: - bc.arg = self[offset+1] + 256*self[offset+2] + bc.arg = ext_arg + self[offset+1] + 256*self[offset+2] next_offset += 2 label = -1 @@ -55,7 +61,11 @@ class ByteCodes(object): bc.jump_to = label bc.next_offset = offset = next_offset - yield bc + if bc.op == opcode.EXTENDED_ARG: + ext_arg = bc.arg * 256*256 + else: + ext_arg = 0 + yield bc class CodeObjects(object): diff --git a/coverage/codeunit.py b/coverage/codeunit.py deleted file mode 100644 index ef7e8485..00000000 --- a/coverage/codeunit.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Code unit (module) handling for Coverage.""" - -import os - -from coverage.files import FileLocator -from coverage.plugin import FileReporter - - -class CodeUnit(FileReporter): - """Code unit: a filename or module. - - Instance attributes: - - `name` is a human-readable name for this code unit. - `filename` is the os path from which we can read the source. - - """ - - def __init__(self, morf, file_locator=None): - self.file_locator = file_locator or FileLocator() - - if hasattr(morf, '__file__'): - filename = morf.__file__ - else: - filename = morf - filename = self._adjust_filename(filename) - self.filename = self.file_locator.canonical_filename(filename) - - if hasattr(morf, '__name__'): - name = morf.__name__ - name = name.replace(".", os.sep) + ".py" - else: - name = self.file_locator.relative_filename(filename) - self.name = name - - def _adjust_filename(self, f): - # TODO: This shouldn't be in the base class, right? - return f diff --git a/coverage/collector.py b/coverage/collector.py index c1560902..948cbbb0 100644 --- a/coverage/collector.py +++ b/coverage/collector.py @@ -291,10 +291,14 @@ class Collector(object): """ if self.branch: # If we were measuring branches, then we have to re-build the dict - # to show line data. + # to show line data. We'll use the first lines of all the arcs, + # if they are actual lines. We don't need the second lines, because + # the second lines will also be first lines, sometimes to exits. line_data = {} for f, arcs in self.data.items(): - line_data[f] = dict((l1, None) for l1, _ in arcs.keys() if l1) + line_data[f] = dict( + (l1, None) for l1, _ in arcs.keys() if l1 > 0 + ) return line_data else: return self.data diff --git a/coverage/control.py b/coverage/control.py index 0bbe301c..563925ef 100644 --- a/coverage/control.py +++ b/coverage/control.py @@ -18,13 +18,13 @@ from coverage.data import CoverageData from coverage.debug import DebugControl from coverage.files import FileLocator, TreeMatcher, FnmatchMatcher from coverage.files import PathAliases, find_python_files, prep_patterns -from coverage.files import ModuleMatcher +from coverage.files import ModuleMatcher, abs_file from coverage.html import HtmlReporter from coverage.misc import CoverageException, bool_or_none, join_regex from coverage.misc import file_be_gone, overrides from coverage.monkey import patch_multiprocessing from coverage.plugin import CoveragePlugin, FileReporter -from coverage.python import PythonCodeUnit +from coverage.python import PythonFileReporter from coverage.results import Analysis, Numbers from coverage.summary import SummaryReporter from coverage.xmlreport import XmlReporter @@ -168,7 +168,7 @@ class Coverage(object): self.omit = self.include = self.source = None self.source_pkgs = self.file_locator = None self.data = self.collector = None - self.plugins = self.file_tracers = None + self.plugins = self.file_tracing_plugins = None self.pylib_dirs = self.cover_dir = None self.data_suffix = self.run_suffix = None self._exclude_re = None @@ -203,10 +203,10 @@ class Coverage(object): # Load plugins self.plugins = Plugins.load_plugins(self.config.plugins, self.config) - self.file_tracers = [] + self.file_tracing_plugins = [] for plugin in self.plugins: if overrides(plugin, "file_tracer", CoveragePlugin): - self.file_tracers.append(plugin) + self.file_tracing_plugins.append(plugin) # _exclude_re is a dict that maps exclusion list names to compiled # regexes. @@ -242,15 +242,18 @@ class Coverage(object): ) # Early warning if we aren't going to be able to support plugins. - if self.file_tracers and not self.collector.supports_plugins: - raise CoverageException( + if self.file_tracing_plugins and not self.collector.supports_plugins: + self._warn( "Plugin file tracers (%s) aren't supported with %s" % ( ", ".join( - ft._coverage_plugin_name for ft in self.file_tracers + plugin._coverage_plugin_name + for plugin in self.file_tracing_plugins ), self.collector.tracer_name(), ) ) + for plugin in self.file_tracing_plugins: + plugin._coverage_enabled = False # Suffixes are a bit tricky. We want to use the data suffix only when # collecting data, not when combining data. So we save it as @@ -341,7 +344,7 @@ class Coverage(object): def _canonical_dir(self, morf): """Return the canonical directory of the module or file `morf`.""" - morf_filename = PythonCodeUnit(morf, self).filename + morf_filename = PythonFileReporter(morf, self).filename return os.path.split(morf_filename)[0] def _source_for_file(self, filename): @@ -462,15 +465,14 @@ class Coverage(object): # Try the plugins, see if they have an opinion about the file. plugin = None - for plugin in self.file_tracers: + for plugin in self.file_tracing_plugins: if not plugin._coverage_enabled: continue try: file_tracer = plugin.file_tracer(canonical) if file_tracer is not None: - file_tracer._coverage_plugin_name = \ - plugin._coverage_plugin_name + file_tracer._coverage_plugin = plugin disp.trace = True disp.file_tracer = file_tracer if file_tracer.has_dynamic_source_filename(): @@ -481,7 +483,7 @@ class Coverage(object): file_tracer.source_filename() ) break - except Exception as e: + except Exception: self._warn( "Disabling plugin %r due to an exception:" % ( plugin._coverage_plugin_name @@ -835,12 +837,13 @@ class Coverage(object): plugin = None if isinstance(morf, string_class): - plugin_name = self.data.plugin_data().get(morf) + abs_morf = abs_file(morf) + plugin_name = self.data.plugin_data().get(abs_morf) if plugin_name: plugin = self.plugins.get(plugin_name) if plugin: - file_reporter = plugin.file_reporter(morf) + file_reporter = plugin.file_reporter(abs_morf) if file_reporter is None: raise CoverageException( "Plugin %r did not provide a file reporter for %r." % ( @@ -848,7 +851,14 @@ class Coverage(object): ) ) else: - file_reporter = PythonCodeUnit(morf, self) + file_reporter = PythonFileReporter(morf, self) + + # The FileReporter can have a name attribute, but if it doesn't, we'll + # supply it as the relative path to self.filename. + if not hasattr(file_reporter, "name"): + file_reporter.name = self.file_locator.relative_filename( + file_reporter.filename + ) return file_reporter @@ -887,9 +897,9 @@ class Coverage(object): Each module in `morfs` is listed, with counts of statements, executed statements, missing statements, and a list of lines missed. - `include` is a list of filename patterns. Modules whose filenames - match those patterns will be included in the report. Modules matching - `omit` will not be included in the report. + `include` is a list of filename patterns. Files that match will be + included in the report. Files matching `omit` will not be included in + the report. Returns a float, the total percentage covered. @@ -987,7 +997,7 @@ class Coverage(object): outfile = open(self.config.xml_output, "w") file_to_close = outfile try: - reporter = XmlReporter(self, self.config) + reporter = XmlReporter(self, self.config, self.file_locator) return reporter.report(morfs, outfile=outfile) except CoverageException: delete_file = True @@ -1009,15 +1019,20 @@ class Coverage(object): except AttributeError: implementation = "unknown" + ft_plugins = [] + for ft in self.file_tracing_plugins: + ft_name = ft._coverage_plugin_name + if not ft._coverage_enabled: + ft_name += " (disabled)" + ft_plugins.append(ft_name) + info = [ ('version', covmod.__version__), ('coverage', covmod.__file__), ('cover_dir', self.cover_dir), ('pylib_dirs', self.pylib_dirs), ('tracer', self.collector.tracer_name()), - ('file_tracers', [ - ft._coverage_plugin_name for ft in self.file_tracers - ]), + ('file_tracing_plugins', ft_plugins), ('config_files', self.config.attempted_config_files), ('configs_read', self.config.config_files), ('data_path', self.data.filename), diff --git a/coverage/html.py b/coverage/html.py index 2a9e0d11..8ed085ba 100644 --- a/coverage/html.py +++ b/coverage/html.py @@ -150,20 +150,20 @@ class HtmlReporter(Reporter): with open(fname, "wb") as fout: fout.write(html.encode('ascii', 'xmlcharrefreplace')) - def file_hash(self, source, cu): + def file_hash(self, source, fr): """Compute a hash that changes if the file needs to be re-reported.""" m = Hasher() m.update(source) - self.coverage.data.add_to_hash(cu.filename, m) + self.coverage.data.add_to_hash(fr.filename, m) return m.hexdigest() - def html_file(self, cu, analysis): + def html_file(self, fr, analysis): """Generate an HTML file for one source file.""" - source = cu.source() + source = fr.source() # Find out if the file on disk is already correct. - flat_rootname = cu.flat_rootname() - this_hash = self.file_hash(source.encode('utf-8'), cu) + flat_rootname = fr.flat_rootname() + this_hash = self.file_hash(source.encode('utf-8'), fr) that_hash = self.status.file_hash(flat_rootname) if this_hash == that_hash: # Nothing has changed to require the file to be reported again. @@ -186,7 +186,7 @@ class HtmlReporter(Reporter): lines = [] - for lineno, line in enumerate(cu.source_token_lines(), start=1): + for lineno, line in enumerate(fr.source_token_lines(), start=1): # Figure out how to mark this line. line_class = [] annotate_html = "" @@ -221,7 +221,7 @@ class HtmlReporter(Reporter): else: tok_html = escape(tok_text) or ' ' html.append( - "<span class='%s'>%s</span>" % (tok_type, tok_html) + '<span class="%s">%s</span>' % (tok_type, tok_html) ) lines.append({ @@ -236,7 +236,7 @@ class HtmlReporter(Reporter): template_values = { 'c_exc': c_exc, 'c_mis': c_mis, 'c_par': c_par, 'c_run': c_run, 'arcs': self.arcs, 'extra_css': self.extra_css, - 'cu': cu, 'nums': nums, 'lines': lines, + 'fr': fr, 'nums': nums, 'lines': lines, } html = spaceless(self.source_tmpl.render(template_values)) @@ -248,7 +248,7 @@ class HtmlReporter(Reporter): index_info = { 'nums': nums, 'html_filename': html_filename, - 'name': cu.name, + 'name': fr.name, } self.files.append(index_info) self.status.set_index_info(flat_rootname, index_info) diff --git a/coverage/htmlfiles/index.html b/coverage/htmlfiles/index.html index 90802c81..5242d329 100644 --- a/coverage/htmlfiles/index.html +++ b/coverage/htmlfiles/index.html @@ -1,30 +1,30 @@ <!DOCTYPE html> <html> <head> - <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>{{ title|escape }}</title> - <link rel='stylesheet' href='style.css' type='text/css'> + <link rel="stylesheet" href="style.css" type="text/css"> {% if extra_css %} - <link rel='stylesheet' href='{{ extra_css }}' type='text/css'> + <link rel="stylesheet" href="{{ extra_css }}" type="text/css"> {% endif %} - <script type='text/javascript' src='jquery.min.js'></script> - <script type='text/javascript' src='jquery.debounce.min.js'></script> - <script type='text/javascript' src='jquery.tablesorter.min.js'></script> - <script type='text/javascript' src='jquery.hotkeys.js'></script> - <script type='text/javascript' src='coverage_html.js'></script> - <script type='text/javascript'> + <script type="text/javascript" src="jquery.min.js"></script> + <script type="text/javascript" src="jquery.debounce.min.js"></script> + <script type="text/javascript" src="jquery.tablesorter.min.js"></script> + <script type="text/javascript" src="jquery.hotkeys.js"></script> + <script type="text/javascript" src="coverage_html.js"></script> + <script type="text/javascript"> jQuery(document).ready(coverage.index_ready); </script> </head> -<body class='indexfile'> +<body class="indexfile"> -<div id='header'> - <div class='content'> +<div id="header"> + <div class="content"> <h1>{{ title|escape }}: - <span class='pc_cov'>{{totals.pc_covered_str}}%</span> + <span class="pc_cov">{{totals.pc_covered_str}}%</span> </h1> - <img id='keyboard_icon' src='keybd_closed.png' alt='Show keyboard shortcuts' /> + <img id="keyboard_icon" src="keybd_closed.png" alt="Show keyboard shortcuts" /> <form id="filter_container"> <input id="filter" type="text" value="" placeholder="filter..." /> @@ -32,44 +32,44 @@ </div> </div> -<div class='help_panel'> - <img id='panel_icon' src='keybd_open.png' alt='Hide keyboard shortcuts' /> - <p class='legend'>Hot-keys on this page</p> +<div class="help_panel"> + <img id="panel_icon" src="keybd_open.png" alt="Hide keyboard shortcuts" /> + <p class="legend">Hot-keys on this page</p> <div> - <p class='keyhelp'> - <span class='key'>n</span> - <span class='key'>s</span> - <span class='key'>m</span> - <span class='key'>x</span> + <p class="keyhelp"> + <span class="key">n</span> + <span class="key">s</span> + <span class="key">m</span> + <span class="key">x</span> {% if arcs %} - <span class='key'>b</span> - <span class='key'>p</span> + <span class="key">b</span> + <span class="key">p</span> {% endif %} - <span class='key'>c</span> change column sorting + <span class="key">c</span> change column sorting </p> </div> </div> -<div id='index'> - <table class='index'> +<div id="index"> + <table class="index"> <thead> - {# The title='' attr doesn't work in Safari. #} - <tr class='tablehead' title='Click to sort'> - <th class='name left headerSortDown shortkey_n'>Module</th> - <th class='shortkey_s'>statements</th> - <th class='shortkey_m'>missing</th> - <th class='shortkey_x'>excluded</th> + {# The title="" attr doesn"t work in Safari. #} + <tr class="tablehead" title="Click to sort"> + <th class="name left headerSortDown shortkey_n">Module</th> + <th class="shortkey_s">statements</th> + <th class="shortkey_m">missing</th> + <th class="shortkey_x">excluded</th> {% if arcs %} - <th class='shortkey_b'>branches</th> - <th class='shortkey_p'>partial</th> + <th class="shortkey_b">branches</th> + <th class="shortkey_p">partial</th> {% endif %} - <th class='right shortkey_c'>coverage</th> + <th class="right shortkey_c">coverage</th> </tr> </thead> {# HTML syntax requires thead, tfoot, tbody #} <tfoot> - <tr class='total'> - <td class='name left'>Total</td> + <tr class="total"> + <td class="name left">Total</td> <td>{{totals.n_statements}}</td> <td>{{totals.n_missing}}</td> <td>{{totals.n_excluded}}</td> @@ -77,13 +77,13 @@ <td>{{totals.n_branches}}</td> <td>{{totals.n_partial_branches}}</td> {% endif %} - <td class='right' data-ratio='{{totals.ratio_covered|pair}}'>{{totals.pc_covered_str}}%</td> + <td class="right" data-ratio="{{totals.ratio_covered|pair}}">{{totals.pc_covered_str}}%</td> </tr> </tfoot> <tbody> {% for file in files %} - <tr class='file'> - <td class='name left'><a href='{{file.html_filename}}'>{{file.name}}</a></td> + <tr class="file"> + <td class="name left"><a href="{{file.html_filename}}">{{file.name}}</a></td> <td>{{file.nums.n_statements}}</td> <td>{{file.nums.n_missing}}</td> <td>{{file.nums.n_excluded}}</td> @@ -91,7 +91,7 @@ <td>{{file.nums.n_branches}}</td> <td>{{file.nums.n_partial_branches}}</td> {% endif %} - <td class='right' data-ratio='{{file.nums.ratio_covered|pair}}'>{{file.nums.pc_covered_str}}%</td> + <td class="right" data-ratio="{{file.nums.ratio_covered|pair}}">{{file.nums.pc_covered_str}}%</td> </tr> {% endfor %} </tbody> @@ -102,10 +102,10 @@ </p> </div> -<div id='footer'> - <div class='content'> +<div id="footer"> + <div class="content"> <p> - <a class='nav' href='{{__url__}}'>coverage.py v{{__version__}}</a> + <a class="nav" href="{{__url__}}">coverage.py v{{__version__}}</a> </p> </div> </div> diff --git a/coverage/htmlfiles/pyfile.html b/coverage/htmlfiles/pyfile.html index 38dfb47b..72b69288 100644 --- a/coverage/htmlfiles/pyfile.html +++ b/coverage/htmlfiles/pyfile.html @@ -1,90 +1,90 @@ <!DOCTYPE html> <html> <head> - <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> {# IE8 rounds line-height incorrectly, and adding this emulateIE7 line makes it right! #} {# http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/7684445e-f080-4d8f-8529-132763348e21 #} - <meta http-equiv='X-UA-Compatible' content='IE=emulateIE7' /> - <title>Coverage for {{cu.name|escape}}: {{nums.pc_covered_str}}%</title> - <link rel='stylesheet' href='style.css' type='text/css'> + <meta http-equiv="X-UA-Compatible" content="IE=emulateIE7" /> + <title>Coverage for {{fr.name|escape}}: {{nums.pc_covered_str}}%</title> + <link rel="stylesheet" href="style.css" type="text/css"> {% if extra_css %} - <link rel='stylesheet' href='{{ extra_css }}' type='text/css'> + <link rel="stylesheet" href="{{ extra_css }}" type="text/css"> {% endif %} - <script type='text/javascript' src='jquery.min.js'></script> - <script type='text/javascript' src='jquery.hotkeys.js'></script> - <script type='text/javascript' src='jquery.isonscreen.js'></script> - <script type='text/javascript' src='coverage_html.js'></script> - <script type='text/javascript'> + <script type="text/javascript" src="jquery.min.js"></script> + <script type="text/javascript" src="jquery.hotkeys.js"></script> + <script type="text/javascript" src="jquery.isonscreen.js"></script> + <script type="text/javascript" src="coverage_html.js"></script> + <script type="text/javascript"> jQuery(document).ready(coverage.pyfile_ready); </script> </head> -<body class='pyfile'> +<body class="pyfile"> -<div id='header'> - <div class='content'> - <h1>Coverage for <b>{{cu.name|escape}}</b> : - <span class='pc_cov'>{{nums.pc_covered_str}}%</span> +<div id="header"> + <div class="content"> + <h1>Coverage for <b>{{fr.name|escape}}</b> : + <span class="pc_cov">{{nums.pc_covered_str}}%</span> </h1> - <img id='keyboard_icon' src='keybd_closed.png' alt='Show keyboard shortcuts' /> + <img id="keyboard_icon" src="keybd_closed.png" alt="Show keyboard shortcuts" /> - <h2 class='stats'> + <h2 class="stats"> {{nums.n_statements}} statements - <span class='{{c_run}} shortkey_r button_toggle_run'>{{nums.n_executed}} run</span> - <span class='{{c_mis}} shortkey_m button_toggle_mis'>{{nums.n_missing}} missing</span> - <span class='{{c_exc}} shortkey_x button_toggle_exc'>{{nums.n_excluded}} excluded</span> + <span class="{{c_run}} shortkey_r button_toggle_run">{{nums.n_executed}} run</span> + <span class="{{c_mis}} shortkey_m button_toggle_mis">{{nums.n_missing}} missing</span> + <span class="{{c_exc}} shortkey_x button_toggle_exc">{{nums.n_excluded}} excluded</span> {% if arcs %} - <span class='{{c_par}} shortkey_p button_toggle_par'>{{nums.n_partial_branches}} partial</span> + <span class="{{c_par}} shortkey_p button_toggle_par">{{nums.n_partial_branches}} partial</span> {% endif %} </h2> </div> </div> -<div class='help_panel'> - <img id='panel_icon' src='keybd_open.png' alt='Hide keyboard shortcuts' /> - <p class='legend'>Hot-keys on this page</p> +<div class="help_panel"> + <img id="panel_icon" src="keybd_open.png" alt="Hide keyboard shortcuts" /> + <p class="legend">Hot-keys on this page</p> <div> - <p class='keyhelp'> - <span class='key'>r</span> - <span class='key'>m</span> - <span class='key'>x</span> - <span class='key'>p</span> toggle line displays + <p class="keyhelp"> + <span class="key">r</span> + <span class="key">m</span> + <span class="key">x</span> + <span class="key">p</span> toggle line displays </p> - <p class='keyhelp'> - <span class='key'>j</span> - <span class='key'>k</span> next/prev highlighted chunk + <p class="keyhelp"> + <span class="key">j</span> + <span class="key">k</span> next/prev highlighted chunk </p> - <p class='keyhelp'> - <span class='key'>0</span> (zero) top of page + <p class="keyhelp"> + <span class="key">0</span> (zero) top of page </p> - <p class='keyhelp'> - <span class='key'>1</span> (one) first highlighted chunk + <p class="keyhelp"> + <span class="key">1</span> (one) first highlighted chunk </p> </div> </div> -<div id='source'> +<div id="source"> <table> <tr> - <td class='linenos'> + <td class="linenos"> {% for line in lines %} - <p id='n{{line.number}}' class='{{line.class}}'><a href='#n{{line.number}}'>{{line.number}}</a></p> + <p id="n{{line.number}}" class="{{line.class}}"><a href="#n{{line.number}}">{{line.number}}</a></p> {% endfor %} </td> - <td class='text'> + <td class="text"> {% for line in lines %} - <p id='t{{line.number}}' class='{{line.class}}'>{% if line.annotate %}<span class='annotate' title='{{line.annotate_title}}'>{{line.annotate}}</span>{% endif %}{{line.html}}<span class='strut'> </span></p> + <p id="t{{line.number}}" class="{{line.class}}">{% if line.annotate %}<span class="annotate" title="{{line.annotate_title}}">{{line.annotate}}</span>{% endif %}{{line.html}}<span class="strut"> </span></p> {% endfor %} </td> </tr> </table> </div> -<div id='footer'> - <div class='content'> +<div id="footer"> + <div class="content"> <p> - <a class='nav' href='index.html'>« index</a> <a class='nav' href='{{__url__}}'>coverage.py v{{__version__}}</a> + <a class="nav" href="index.html">« index</a> <a class="nav" href="{{__url__}}">coverage.py v{{__version__}}</a> </p> </div> </div> diff --git a/coverage/phystokens.py b/coverage/phystokens.py index b3b08704..ed6bd238 100644 --- a/coverage/phystokens.py +++ b/coverage/phystokens.py @@ -85,8 +85,11 @@ def source_token_lines(source): ws_tokens = set([token.INDENT, token.DEDENT, token.NEWLINE, tokenize.NL]) line = [] col = 0 - source = source.expandtabs(8).replace('\r\n', '\n') + + # The \f is because of http://bugs.python.org/issue19035 + source = source.expandtabs(8).replace('\r\n', '\n').replace('\f', ' ') tokgen = generate_tokens(source) + for ttype, ttext, (_, scol), (_, ecol), _ in phys_tokens(tokgen): mark_start = True for part in re.split('(\n)', ttext): diff --git a/coverage/python.py b/coverage/python.py index 53da5615..19212a5b 100644 --- a/coverage/python.py +++ b/coverage/python.py @@ -7,10 +7,11 @@ import zipimport from coverage import env from coverage.backward import unicode_class -from coverage.codeunit import CodeUnit +from coverage.files import FileLocator from coverage.misc import NoSource, join_regex from coverage.parser import PythonParser from coverage.phystokens import source_token_lines, source_encoding +from coverage.plugin import FileReporter def read_python_source(filename): @@ -86,13 +87,35 @@ def get_zip_bytes(filename): return None -class PythonCodeUnit(CodeUnit): - """Represents a Python file.""" +class PythonFileReporter(FileReporter): + """Report support for a Python file.""" def __init__(self, morf, coverage=None): self.coverage = coverage - file_locator = coverage.file_locator if coverage else None - super(PythonCodeUnit, self).__init__(morf, file_locator) + file_locator = coverage.file_locator if coverage else FileLocator() + + if hasattr(morf, '__file__'): + filename = morf.__file__ + else: + filename = morf + + # .pyc files should always refer to a .py instead. + if filename.endswith(('.pyc', '.pyo')): + filename = filename[:-1] + elif filename.endswith('$py.class'): # Jython + filename = filename[:-9] + ".py" + + super(PythonFileReporter, self).__init__( + file_locator.canonical_filename(filename) + ) + + if hasattr(morf, '__name__'): + name = morf.__name__ + name = name.replace(".", os.sep) + ".py" + else: + name = file_locator.relative_filename(filename) + self.name = name + self._source = None self._parser = None self._statements = None @@ -138,14 +161,6 @@ class PythonCodeUnit(CodeUnit): def exit_counts(self): return self.parser.exit_counts() - def _adjust_filename(self, fname): - # .pyc files should always refer to a .py instead. - if fname.endswith(('.pyc', '.pyo')): - fname = fname[:-1] - elif fname.endswith('$py.class'): # Jython - fname = fname[:-9] + ".py" - return fname - def source(self): if self._source is None: self._source = get_python_source(self.filename) diff --git a/coverage/report.py b/coverage/report.py index 93b6c928..33a46070 100644 --- a/coverage/report.py +++ b/coverage/report.py @@ -19,40 +19,40 @@ class Reporter(object): self.coverage = coverage self.config = config - # The code units to report on. Set by find_code_units. - self.code_units = [] + # The FileReporters to report on. Set by find_file_reporters. + self.file_reporters = [] # The directory into which to place the report, used by some derived # classes. self.directory = None - def find_code_units(self, morfs): - """Find the code units we'll report on. + def find_file_reporters(self, morfs): + """Find the FileReporters we'll report on. `morfs` is a list of modules or filenames. """ - self.code_units = self.coverage._get_file_reporters(morfs) + self.file_reporters = self.coverage._get_file_reporters(morfs) if self.config.include: patterns = prep_patterns(self.config.include) matcher = FnmatchMatcher(patterns) filtered = [] - for cu in self.code_units: - if matcher.match(cu.filename): - filtered.append(cu) - self.code_units = filtered + for fr in self.file_reporters: + if matcher.match(fr.filename): + filtered.append(fr) + self.file_reporters = filtered if self.config.omit: patterns = prep_patterns(self.config.omit) matcher = FnmatchMatcher(patterns) filtered = [] - for cu in self.code_units: - if not matcher.match(cu.filename): - filtered.append(cu) - self.code_units = filtered + for fr in self.file_reporters: + if not matcher.match(fr.filename): + filtered.append(fr) + self.file_reporters = filtered - self.code_units.sort() + self.file_reporters.sort() def report_files(self, report_fn, morfs, directory=None): """Run a reporting function on a number of morfs. @@ -60,29 +60,29 @@ class Reporter(object): `report_fn` is called for each relative morf in `morfs`. It is called as:: - report_fn(code_unit, analysis) + report_fn(file_reporter, analysis) - where `code_unit` is the `CodeUnit` for the morf, and `analysis` is - the `Analysis` for the morf. + where `file_reporter` is the `FileReporter` for the morf, and + `analysis` is the `Analysis` for the morf. """ - self.find_code_units(morfs) + self.find_file_reporters(morfs) - if not self.code_units: + if not self.file_reporters: raise CoverageException("No data to report.") self.directory = directory if self.directory and not os.path.exists(self.directory): os.makedirs(self.directory) - for cu in self.code_units: + for fr in self.file_reporters: try: - report_fn(cu, self.coverage._analyze(cu)) + report_fn(fr, self.coverage._analyze(fr)) except NoSource: if not self.config.ignore_errors: raise except NotPython: # Only report errors for .py files, and only if we didn't # explicitly suppress those errors. - if cu.should_be_python() and not self.config.ignore_errors: + if fr.should_be_python() and not self.config.ignore_errors: raise diff --git a/coverage/results.py b/coverage/results.py index def3a075..7b621c18 100644 --- a/coverage/results.py +++ b/coverage/results.py @@ -7,11 +7,11 @@ from coverage.misc import format_lines class Analysis(object): - """The results of analyzing a code unit.""" + """The results of analyzing a FileReporter.""" - def __init__(self, cov, code_unit): + def __init__(self, cov, file_reporters): self.coverage = cov - self.file_reporter = code_unit + self.file_reporter = file_reporters self.filename = self.file_reporter.filename self.statements = self.file_reporter.statements() self.excluded = self.file_reporter.excluded_statements() diff --git a/coverage/summary.py b/coverage/summary.py index 10ac7e2c..5b8c903f 100644 --- a/coverage/summary.py +++ b/coverage/summary.py @@ -20,10 +20,10 @@ class SummaryReporter(Reporter): `outfile` is a file object to write the summary to. """ - self.find_code_units(morfs) + self.find_file_reporters(morfs) # Prepare the formatting strings - max_name = max([len(cu.name) for cu in self.code_units] + [5]) + max_name = max([len(fr.name) for fr in self.file_reporters] + [5]) fmt_name = "%%- %ds " % max_name fmt_err = "%s %s: %s\n" header = (fmt_name % "Name") + " Stmts Miss" @@ -50,9 +50,9 @@ class SummaryReporter(Reporter): total = Numbers() - for cu in self.code_units: + for fr in self.file_reporters: try: - analysis = self.coverage._analyze(cu) + analysis = self.coverage._analyze(fr) nums = analysis.numbers if self.config.skip_covered: @@ -65,7 +65,7 @@ class SummaryReporter(Reporter): if no_missing_lines and no_missing_branches: continue - args = (cu.name, nums.n_statements, nums.n_missing) + args = (fr.name, nums.n_statements, nums.n_missing) if self.branches: args += (nums.n_branches, nums.n_partial_branches) args += (nums.pc_covered_str,) @@ -84,10 +84,10 @@ class SummaryReporter(Reporter): report_it = not self.config.ignore_errors if report_it: typ, msg = sys.exc_info()[:2] - if typ is NotPython and not cu.should_be_python(): + if typ is NotPython and not fr.should_be_python(): report_it = False if report_it: - outfile.write(fmt_err % (cu.name, typ.__name__, msg)) + outfile.write(fmt_err % (fr.name, typ.__name__, msg)) if total.n_files > 1: outfile.write(rule) diff --git a/coverage/templite.py b/coverage/templite.py index c102a8f2..9f882cf2 100644 --- a/coverage/templite.py +++ b/coverage/templite.py @@ -201,7 +201,7 @@ class Templite(object): for var_name in self.all_vars - self.loop_vars: vars_code.add_line("c_%s = context[%r]" % (var_name, var_name)) - code.add_line("return ''.join(result)") + code.add_line('return "".join(result)') code.dedent() self._render_function = code.get_globals()['render_function'] diff --git a/coverage/tracer.c b/coverage/tracer.c index d532dcce..1ce5ed20 100644 --- a/coverage/tracer.c +++ b/coverage/tracer.c @@ -22,7 +22,9 @@ #define MyText_Type PyUnicode_Type #define MyText_AS_BYTES(o) PyUnicode_AsASCIIString(o) -#define MyText_AS_STRING(o) PyBytes_AS_STRING(o) +#define MyBytes_AS_STRING(o) PyBytes_AS_STRING(o) +#define MyText_AsString(o) PyUnicode_AsUTF8(o) +#define MyText_FromFormat PyUnicode_FromFormat #define MyInt_FromInt(i) PyLong_FromLong((long)i) #define MyInt_AsInt(o) (int)PyLong_AsLong(o) @@ -32,7 +34,9 @@ #define MyText_Type PyString_Type #define MyText_AS_BYTES(o) (Py_INCREF(o), o) -#define MyText_AS_STRING(o) PyString_AS_STRING(o) +#define MyBytes_AS_STRING(o) PyString_AS_STRING(o) +#define MyText_AsString(o) PyString_AsString(o) +#define MyText_FromFormat PyUnicode_FromFormat #define MyInt_FromInt(i) PyInt_FromLong((long)i) #define MyInt_AsInt(o) (int)PyInt_AsLong(o) @@ -44,14 +48,32 @@ #define RET_OK 0 #define RET_ERROR -1 -/* An entry on the data stack. For each call frame, we need to record the - dictionary to capture data, and the last line number executed in that - frame. -*/ +/* Python C API helpers. */ + +static int +pyint_as_int(PyObject * pyint, int *pint) +{ + int the_int = MyInt_AsInt(pyint); + if (the_int == -1 && PyErr_Occurred()) { + return RET_ERROR; + } + + *pint = the_int; + return RET_OK; +} + + +/* An entry on the data stack. For each call frame, we need to record all + * the information needed for CTracer_handle_line to operate as quickly as + * possible. + */ typedef struct { /* The current file_data dictionary. Borrowed, owned by self->data. */ PyObject * file_data; + /* The disposition object for this frame. */ + PyObject * disposition; + /* The FileTracer handling this frame, or None if it's Python. */ PyObject * file_tracer; @@ -170,64 +192,33 @@ DataStack_grow(CTracer *self, DataStack *pdata_stack) } +static void CTracer_disable_plugin(CTracer *self, PyObject * disposition); + static int CTracer_init(CTracer *self, PyObject *args_unused, PyObject *kwds_unused) { int ret = RET_ERROR; PyObject * weakref = NULL; -#if COLLECT_STATS - self->stats.calls = 0; - self->stats.lines = 0; - self->stats.returns = 0; - self->stats.exceptions = 0; - self->stats.others = 0; - self->stats.new_files = 0; - self->stats.missed_returns = 0; - self->stats.stack_reallocs = 0; - self->stats.errors = 0; -#endif /* COLLECT_STATS */ - - self->should_trace = NULL; - self->check_include = NULL; - self->warn = NULL; - self->concur_id_func = NULL; - self->data = NULL; - self->plugin_data = NULL; - self->should_trace_cache = NULL; - self->arcs = NULL; - - self->started = 0; - self->tracing_arcs = 0; - - if (DataStack_init(self, &self->data_stack)) { + if (DataStack_init(self, &self->data_stack) < 0) { goto error; } weakref = PyImport_ImportModule("weakref"); if (weakref == NULL) { - STATS( self->stats.errors++; ) goto error; } self->data_stack_index = PyObject_CallMethod(weakref, "WeakKeyDictionary", NULL); Py_XDECREF(weakref); if (self->data_stack_index == NULL) { - STATS( self->stats.errors++; ) goto error; } - self->data_stacks = NULL; - self->data_stacks_alloc = 0; - self->data_stacks_used = 0; - self->pdata_stack = &self->data_stack; - self->cur_entry.file_data = NULL; self->cur_entry.last_line = -1; - self->last_exc_back = NULL; - ret = RET_OK; goto ok; @@ -299,7 +290,7 @@ showlog(int depth, int lineno, PyObject * filename, const char * msg) } if (filename) { PyObject *ascii = MyText_AS_BYTES(filename); - printf(" %s", MyText_AS_STRING(ascii)); + printf(" %s", MyBytes_AS_STRING(ascii)); Py_DECREF(ascii); } if (msg) { @@ -366,6 +357,9 @@ CTracer_set_pdata_stack(CTracer *self) /* A new concurrency object. Make a new data stack. */ the_index = self->data_stacks_used; stack_index = MyInt_FromInt(the_index); + if (stack_index == NULL) { + goto error; + } if (PyObject_SetItem(self->data_stack_index, co_obj, stack_index) < 0) { goto error; } @@ -383,7 +377,9 @@ CTracer_set_pdata_stack(CTracer *self) DataStack_init(self, &self->data_stacks[the_index]); } else { - the_index = MyInt_AsInt(stack_index); + if (pyint_as_int(stack_index, &the_index) < 0) { + goto error; + } } self->pdata_stack = &self->data_stacks[the_index]; @@ -424,7 +420,7 @@ CTracer_check_missing_return(CTracer *self, PyFrameObject *frame) we'll need to keep more of the missed frame's state. */ STATS( self->stats.missed_returns++; ) - if (CTracer_set_pdata_stack(self)) { + if (CTracer_set_pdata_stack(self) < 0) { goto error; } if (self->pdata_stack->depth >= 0) { @@ -452,12 +448,15 @@ static int CTracer_handle_call(CTracer *self, PyFrameObject *frame) { int ret = RET_ERROR; + int ret2; /* Owned references that we clean up at the very end of the function. */ PyObject * tracename = NULL; PyObject * disposition = NULL; PyObject * disp_trace = NULL; - PyObject * disp_file_tracer = NULL; + PyObject * file_tracer = NULL; + PyObject * plugin = NULL; + PyObject * plugin_name = NULL; PyObject * has_dynamic_filename = NULL; /* Borrowed references. */ @@ -466,10 +465,10 @@ CTracer_handle_call(CTracer *self, PyFrameObject *frame) STATS( self->stats.calls++; ) /* Grow the stack. */ - if (CTracer_set_pdata_stack(self)) { + if (CTracer_set_pdata_stack(self) < 0) { goto error; } - if (DataStack_grow(self, self->pdata_stack)) { + if (DataStack_grow(self, self->pdata_stack) < 0) { goto error; } @@ -480,6 +479,9 @@ CTracer_handle_call(CTracer *self, PyFrameObject *frame) filename = frame->f_code->co_filename; disposition = PyDict_GetItem(self->should_trace_cache, filename); if (disposition == NULL) { + if (PyErr_Occurred()) { + goto error; + } STATS( self->stats.new_files++; ) /* We've never considered this file before. */ /* Ask should_trace about it. */ @@ -507,10 +509,20 @@ CTracer_handle_call(CTracer *self, PyFrameObject *frame) if (tracename == NULL) { goto error; } - disp_file_tracer = PyObject_GetAttrString(disposition, "file_tracer"); - if (disp_file_tracer == NULL) { + file_tracer = PyObject_GetAttrString(disposition, "file_tracer"); + if (file_tracer == NULL) { goto error; } + if (file_tracer != Py_None) { + plugin = PyObject_GetAttrString(file_tracer, "_coverage_plugin"); + if (plugin == NULL) { + goto error; + } + plugin_name = PyObject_GetAttrString(plugin, "_coverage_plugin_name"); + if (plugin_name == NULL) { + goto error; + } + } has_dynamic_filename = PyObject_GetAttrString(disposition, "has_dynamic_filename"); if (has_dynamic_filename == NULL) { goto error; @@ -518,11 +530,16 @@ CTracer_handle_call(CTracer *self, PyFrameObject *frame) if (has_dynamic_filename == Py_True) { PyObject * next_tracename = NULL; next_tracename = PyObject_CallMethod( - disp_file_tracer, "dynamic_source_filename", + file_tracer, "dynamic_source_filename", "OO", tracename, frame ); if (next_tracename == NULL) { - goto error; + /* An exception from the function. Alert the user with a + * warning and a traceback. + */ + CTracer_disable_plugin(self, disposition); + /* Because we handled the error, goto ok. */ + goto ok; } Py_DECREF(tracename); tracename = next_tracename; @@ -532,6 +549,9 @@ CTracer_handle_call(CTracer *self, PyFrameObject *frame) PyObject * included = NULL; included = PyDict_GetItem(self->should_trace_cache, tracename); if (included == NULL) { + if (PyErr_Occurred()) { + goto error; + } STATS( self->stats.new_files++; ) included = PyObject_CallFunctionObjArgs(self->check_include, tracename, frame, NULL); if (included == NULL) { @@ -556,35 +576,32 @@ CTracer_handle_call(CTracer *self, PyFrameObject *frame) if (tracename != Py_None) { PyObject * file_data = PyDict_GetItem(self->data, tracename); - PyObject * disp_plugin_name = NULL; if (file_data == NULL) { + if (PyErr_Occurred()) { + goto error; + } file_data = PyDict_New(); if (file_data == NULL) { goto error; } - ret = PyDict_SetItem(self->data, tracename, file_data); + ret2 = PyDict_SetItem(self->data, tracename, file_data); Py_DECREF(file_data); - if (ret < 0) { + if (ret2 < 0) { goto error; } /* If the disposition mentions a plugin, record that. */ - if (disp_file_tracer != Py_None) { - disp_plugin_name = PyObject_GetAttrString(disp_file_tracer, "_coverage_plugin_name"); - if (disp_plugin_name == NULL) { - goto error; - } - ret = PyDict_SetItem(self->plugin_data, tracename, disp_plugin_name); - Py_DECREF(disp_plugin_name); - if (ret < 0) { + if (file_tracer != Py_None) { + ret2 = PyDict_SetItem(self->plugin_data, tracename, plugin_name); + if (ret2 < 0) { goto error; } } } self->cur_entry.file_data = file_data; - self->cur_entry.file_tracer = disp_file_tracer; + self->cur_entry.file_tracer = file_tracer; /* Make the frame right in case settrace(gettrace()) happens. */ Py_INCREF(self); @@ -597,28 +614,136 @@ CTracer_handle_call(CTracer *self, PyFrameObject *frame) SHOWLOG(self->pdata_stack->depth, frame->f_lineno, filename, "skipped"); } +<<<<<<< local + self->cur_entry.disposition = disposition; + self->cur_entry.last_line = -1; +======= /* A call event is really a "start frame" event, and can happen for * re-entering a generator also. f_lasti is -1 for a true call, and a * real byte offset for a generator re-entry. */ self->cur_entry.last_line = (frame->f_lasti < 0) ? -1 : frame->f_lineno; +>>>>>>> other +ok: ret = RET_OK; error: Py_XDECREF(tracename); Py_XDECREF(disposition); Py_XDECREF(disp_trace); - Py_XDECREF(disp_file_tracer); + Py_XDECREF(file_tracer); + Py_XDECREF(plugin); + Py_XDECREF(plugin_name); Py_XDECREF(has_dynamic_filename); return ret; } + +static void +CTracer_disable_plugin(CTracer *self, PyObject * disposition) +{ + PyObject * file_tracer = NULL; + PyObject * plugin = NULL; + PyObject * plugin_name = NULL; + PyObject * msg = NULL; + PyObject * ignored = NULL; + + file_tracer = PyObject_GetAttrString(disposition, "file_tracer"); + if (file_tracer == NULL) { + goto error; + } + if (file_tracer == Py_None) { + /* This shouldn't happen... */ + goto ok; + } + plugin = PyObject_GetAttrString(file_tracer, "_coverage_plugin"); + if (plugin == NULL) { + goto error; + } + plugin_name = PyObject_GetAttrString(plugin, "_coverage_plugin_name"); + if (plugin_name == NULL) { + goto error; + } + msg = MyText_FromFormat( + "Disabling plugin '%s' due to an exception:", + MyText_AsString(plugin_name) + ); + if (msg == NULL) { + goto error; + } + ignored = PyObject_CallFunctionObjArgs(self->warn, msg, NULL); + if (ignored == NULL) { + goto error; + } + + PyErr_Print(); + + /* Disable the plugin for future files, and stop tracing this file. */ + if (PyObject_SetAttrString(plugin, "_coverage_enabled", Py_False) < 0) { + goto error; + } + if (PyObject_SetAttrString(disposition, "trace", Py_False) < 0) { + goto error; + } + + goto ok; + +error: + /* This function doesn't return a status, so if an error happens, print it, + * but don't interrupt the flow. */ + /* PySys_WriteStderr is nicer, but is not in the public API. */ + fprintf(stderr, "Error occurred while disabling plugin:\n"); + PyErr_Print(); + +ok: + Py_XDECREF(file_tracer); + Py_XDECREF(plugin); + Py_XDECREF(plugin_name); + Py_XDECREF(msg); + Py_XDECREF(ignored); +} + + +static int +CTracer_unpack_pair(CTracer *self, PyObject *pair, int *p_one, int *p_two) +{ + int ret = RET_ERROR; + int the_int; + PyObject * pyint = NULL; + int index; + + if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2) { + PyErr_SetString( + PyExc_TypeError, + "line_number_range must return 2-tuple" + ); + goto error; + } + + for (index = 0; index < 2; index++) { + pyint = PyTuple_GetItem(pair, index); + if (pyint == NULL) { + goto error; + } + if (pyint_as_int(pyint, &the_int) < 0) { + goto error; + } + *(index == 0 ? p_one : p_two) = the_int; + } + + ret = RET_OK; + +error: + return ret; +} + static int CTracer_handle_line(CTracer *self, PyFrameObject *frame) { int ret = RET_ERROR; + int ret2; STATS( self->stats.lines++; ) if (self->pdata_stack->depth >= 0) { @@ -633,44 +758,46 @@ CTracer_handle_line(CTracer *self, PyFrameObject *frame) if (from_to == NULL) { goto error; } - /* TODO: error check bad returns. */ - lineno_from = MyInt_AsInt(PyTuple_GetItem(from_to, 0)); - lineno_to = MyInt_AsInt(PyTuple_GetItem(from_to, 1)); + ret2 = CTracer_unpack_pair(self, from_to, &lineno_from, &lineno_to); Py_DECREF(from_to); + if (ret2 < 0) { + CTracer_disable_plugin(self, self->cur_entry.disposition); + goto ok; + } } else { lineno_from = lineno_to = frame->f_lineno; } if (lineno_from != -1) { - if (self->tracing_arcs) { - /* Tracing arcs: key is (last_line,this_line). */ - /* TODO: this needs to deal with lineno_to also. */ - if (CTracer_record_pair(self, self->cur_entry.last_line, lineno_from) < 0) { - goto error; + for (; lineno_from <= lineno_to; lineno_from++) { + if (self->tracing_arcs) { + /* Tracing arcs: key is (last_line,this_line). */ + if (CTracer_record_pair(self, self->cur_entry.last_line, lineno_from) < 0) { + goto error; + } } - } - else { - /* Tracing lines: key is simply this_line. */ - while (lineno_from <= lineno_to) { + else { + /* Tracing lines: key is simply this_line. */ PyObject * this_line = MyInt_FromInt(lineno_from); if (this_line == NULL) { goto error; } - ret = PyDict_SetItem(self->cur_entry.file_data, this_line, Py_None); + + ret2 = PyDict_SetItem(self->cur_entry.file_data, this_line, Py_None); Py_DECREF(this_line); - if (ret < 0) { + if (ret2 < 0) { goto error; } - lineno_from++; } + + self->cur_entry.last_line = lineno_from; } } - - self->cur_entry.last_line = lineno_to; } } +ok: ret = RET_OK; error: @@ -685,7 +812,7 @@ CTracer_handle_return(CTracer *self, PyFrameObject *frame) STATS( self->stats.returns++; ) /* A near-copy of this code is above in the missing-return handler. */ - if (CTracer_set_pdata_stack(self)) { + if (CTracer_set_pdata_stack(self) < 0) { goto error; } if (self->pdata_stack->depth >= 0) { @@ -751,45 +878,45 @@ CTracer_trace(CTracer *self, PyFrameObject *frame, int what, PyObject *arg_unuse #if WHAT_LOG if (what <= sizeof(what_sym)/sizeof(const char *)) { ascii = MyText_AS_BYTES(frame->f_code->co_filename); - printf("trace: %s @ %s %d\n", what_sym[what], MyText_AS_STRING(ascii), frame->f_lineno); + printf("trace: %s @ %s %d\n", what_sym[what], MyBytes_AS_STRING(ascii), frame->f_lineno); Py_DECREF(ascii); } #endif #if TRACE_LOG ascii = MyText_AS_BYTES(frame->f_code->co_filename); - if (strstr(MyText_AS_STRING(ascii), start_file) && frame->f_lineno == start_line) { + if (strstr(MyBytes_AS_STRING(ascii), start_file) && frame->f_lineno == start_line) { logging = 1; } Py_DECREF(ascii); #endif /* See below for details on missing-return detection. */ - if (CTracer_check_missing_return(self, frame)) { + if (CTracer_check_missing_return(self, frame) < 0) { goto error; } switch (what) { case PyTrace_CALL: - if (CTracer_handle_call(self, frame)) { + if (CTracer_handle_call(self, frame) < 0) { goto error; } break; case PyTrace_RETURN: - if (CTracer_handle_return(self, frame)) { + if (CTracer_handle_return(self, frame) < 0) { goto error; } break; case PyTrace_LINE: - if (CTracer_handle_line(self, frame)) { + if (CTracer_handle_line(self, frame) < 0) { goto error; } break; case PyTrace_EXCEPTION: - if (CTracer_handle_exception(self, frame)) { + if (CTracer_handle_exception(self, frame) < 0) { goto error; } break; @@ -862,7 +989,7 @@ CTracer_call(CTracer *self, PyObject *args, PyObject *kwds) for the C function. */ for (what = 0; what_names[what]; what++) { PyObject *ascii = MyText_AS_BYTES(what_str); - int should_break = !strcmp(MyText_AS_STRING(ascii), what_names[what]); + int should_break = !strcmp(MyBytes_AS_STRING(ascii), what_names[what]); Py_DECREF(ascii); if (should_break) { break; @@ -909,7 +1036,7 @@ CTracer_stop(CTracer *self, PyObject *args_unused) self->started = 0; } - return Py_BuildValue(""); + Py_RETURN_NONE; } static PyObject * @@ -930,7 +1057,7 @@ CTracer_get_stats(CTracer *self) "errors", self->stats.errors ); #else - return Py_BuildValue(""); + Py_RETURN_NONE; #endif /* COLLECT_STATS */ } @@ -1054,7 +1181,11 @@ PyInit_tracer(void) } Py_INCREF(&CTracerType); - PyModule_AddObject(mod, "CTracer", (PyObject *)&CTracerType); + if (PyModule_AddObject(mod, "CTracer", (PyObject *)&CTracerType) < 0) { + Py_DECREF(mod); + Py_DECREF(&CTracerType); + return NULL; + } return mod; } diff --git a/coverage/version.py b/coverage/version.py index 304a54c3..51e1310f 100644 --- a/coverage/version.py +++ b/coverage/version.py @@ -1,9 +1,9 @@ """The version and URL for coverage.py""" # This file is exec'ed in setup.py, don't import anything! -__version__ = "4.0a5" # see detailed history in CHANGES.txt +__version__ = "4.0a6" # see detailed history in CHANGES.txt __url__ = "https://coverage.readthedocs.org" if max(__version__).isalpha(): # For pre-releases, use a version-specific URL. - __url__ += "/en/coverage-" + __version__ + __url__ += "/en/" + __version__ diff --git a/coverage/xmlreport.py b/coverage/xmlreport.py index f7ad2b8a..996f19a2 100644 --- a/coverage/xmlreport.py +++ b/coverage/xmlreport.py @@ -20,9 +20,10 @@ def rate(hit, num): class XmlReporter(Reporter): """A reporter for writing Cobertura-style XML coverage results.""" - def __init__(self, coverage, config): + def __init__(self, coverage, config, file_locator): super(XmlReporter, self).__init__(coverage, config) + self.file_locator = file_locator self.source_paths = set() self.packages = {} self.xml_out = None @@ -116,20 +117,20 @@ class XmlReporter(Reporter): pct = 100.0 * (lhits_tot + bhits_tot) / denom return pct - def xml_file(self, cu, analysis): + def xml_file(self, fr, analysis): """Add to the XML report for a single file.""" # Create the 'lines' and 'package' XML elements, which # are populated later. Note that a package == a directory. - filename = cu.file_locator.relative_filename(cu.filename) + filename = self.file_locator.relative_filename(fr.filename) filename = filename.replace("\\", "/") dirname = os.path.dirname(filename) or "." parts = dirname.split("/") dirname = "/".join(parts[:self.config.xml_package_depth]) package_name = dirname.replace("/", ".") - className = cu.name + className = fr.name - self.source_paths.add(cu.file_locator.relative_dir.rstrip('/')) + self.source_paths.add(self.file_locator.relative_dir.rstrip('/')) package = self.packages.setdefault(package_name, [{}, 0, 0, 0, 0]) xclass = self.xml_out.createElement("class") |