📄 coverage.py
字号:
start, end = pair if start == end: return "%d" % start else: return "%d-%d" % (start, end) ret = string.join(map(stringify, pairs), ", ") return ret # Backward compatibility with version 1. def analysis(self, morf): f, s, _, m, mf = self.analysis2(morf) return f, s, m, mf def analysis2(self, morf): filename, statements, excluded, line_map = self.analyze_morf(morf) self.canonicalize_filenames() if not self.cexecuted.has_key(filename): self.cexecuted[filename] = {} missing = [] for line in statements: lines = line_map.get(line, [line, line]) for l in range(lines[0], lines[1]+1): if self.cexecuted[filename].has_key(l): break else: missing.append(line) return (filename, statements, excluded, missing, self.format_lines(statements, missing)) def relative_filename(self, filename): """ Convert filename to relative filename from self.relative_dir. """ return filename.replace(self.relative_dir, "") def morf_name(self, morf): """ Return the name of morf as used in report. """ if isinstance(morf, types.ModuleType): return morf.__name__ else: return self.relative_filename(os.path.splitext(morf)[0]) def filter_by_prefix(self, morfs, omit_prefixes): """ Return list of morfs where the morf name does not begin with any one of the omit_prefixes. """ filtered_morfs = [] for morf in morfs: for prefix in omit_prefixes: if self.morf_name(morf).startswith(prefix): break else: filtered_morfs.append(morf) return filtered_morfs def morf_name_compare(self, x, y): return cmp(self.morf_name(x), self.morf_name(y)) def report(self, morfs, show_missing=1, ignore_errors=0, file=None, omit_prefixes=[]): if not isinstance(morfs, types.ListType): morfs = [morfs] # On windows, the shell doesn't expand wildcards. Do it here. globbed = [] for morf in morfs: if isinstance(morf, strclass): globbed.extend(glob.glob(morf)) else: globbed.append(morf) morfs = globbed morfs = self.filter_by_prefix(morfs, omit_prefixes) morfs.sort(self.morf_name_compare) max_name = max([5,] + map(len, map(self.morf_name, morfs))) fmt_name = "%%- %ds " % max_name fmt_err = fmt_name + "%s: %s" header = fmt_name % "Name" + " Stmts Exec Cover" fmt_coverage = fmt_name + "% 6d % 6d % 5d%%" if show_missing: header = header + " Missing" fmt_coverage = fmt_coverage + " %s" if not file: file = sys.stdout print >>file, header print >>file, "-" * len(header) total_statements = 0 total_executed = 0 for morf in morfs: name = self.morf_name(morf) try: _, statements, _, missing, readable = self.analysis2(morf) n = len(statements) m = n - len(missing) if n > 0: pc = 100.0 * m / n else: pc = 100.0 args = (name, n, m, pc) if show_missing: args = args + (readable,) print >>file, fmt_coverage % args total_statements = total_statements + n total_executed = total_executed + m except KeyboardInterrupt: #pragma: no cover raise except: if not ignore_errors: typ, msg = sys.exc_info()[0:2] print >>file, fmt_err % (name, typ, msg) if len(morfs) > 1: print >>file, "-" * len(header) if total_statements > 0: pc = 100.0 * total_executed / total_statements else: pc = 100.0 args = ("TOTAL", total_statements, total_executed, pc) if show_missing: args = args + ("",) print >>file, fmt_coverage % args # annotate(morfs, ignore_errors). blank_re = re.compile(r"\s*(#|$)") else_re = re.compile(r"\s*else\s*:\s*(#|$)") def annotate(self, morfs, directory=None, ignore_errors=0, omit_prefixes=[]): morfs = self.filter_by_prefix(morfs, omit_prefixes) for morf in morfs: try: filename, statements, excluded, missing, _ = self.analysis2(morf) self.annotate_file(filename, statements, excluded, missing, directory) except KeyboardInterrupt: raise except: if not ignore_errors: raise def annotate_file(self, filename, statements, excluded, missing, directory=None): source = open(filename, 'r') if directory: dest_file = os.path.join(directory, os.path.basename(filename) + ',cover') else: dest_file = filename + ',cover' dest = open(dest_file, 'w') lineno = 0 i = 0 j = 0 covered = 1 while 1: line = source.readline() if line == '': break lineno = lineno + 1 while i < len(statements) and statements[i] < lineno: i = i + 1 while j < len(missing) and missing[j] < lineno: j = j + 1 if i < len(statements) and statements[i] == lineno: covered = j >= len(missing) or missing[j] > lineno if self.blank_re.match(line): dest.write(' ') elif self.else_re.match(line): # Special logic for lines containing only 'else:'. # See [GDR 2001-12-04b, 3.2]. if i >= len(statements) and j >= len(missing): dest.write('! ') elif i >= len(statements) or j >= len(missing): dest.write('> ') elif statements[i] == missing[j]: dest.write('! ') else: dest.write('> ') elif lineno in excluded: dest.write('- ') elif covered: dest.write('> ') else: dest.write('! ') dest.write(line) source.close() dest.close()# Singleton object.the_coverage = coverage()# Module functions call methods in the singleton object.def use_cache(*args, **kw): return the_coverage.use_cache(*args, **kw)def start(*args, **kw): return the_coverage.start(*args, **kw)def stop(*args, **kw): return the_coverage.stop(*args, **kw)def erase(*args, **kw): return the_coverage.erase(*args, **kw)def begin_recursive(*args, **kw): return the_coverage.begin_recursive(*args, **kw)def end_recursive(*args, **kw): return the_coverage.end_recursive(*args, **kw)def exclude(*args, **kw): return the_coverage.exclude(*args, **kw)def analysis(*args, **kw): return the_coverage.analysis(*args, **kw)def analysis2(*args, **kw): return the_coverage.analysis2(*args, **kw)def report(*args, **kw): return the_coverage.report(*args, **kw)def annotate(*args, **kw): return the_coverage.annotate(*args, **kw)def annotate_file(*args, **kw): return the_coverage.annotate_file(*args, **kw)# Save coverage data when Python exits. (The atexit module wasn't# introduced until Python 2.0, so use sys.exitfunc when it's not# available.)try: import atexit atexit.register(the_coverage.save)except ImportError: sys.exitfunc = the_coverage.save# Command-line interface.if __name__ == '__main__': the_coverage.command_line(sys.argv[1:])# A. REFERENCES## [GDR 2001-12-04a] "Statement coverage for Python"; Gareth Rees;# Ravenbrook Limited; 2001-12-04;# <http://www.nedbatchelder.com/code/modules/rees-coverage.html>.## [GDR 2001-12-04b] "Statement coverage for Python: design and# analysis"; Gareth Rees; Ravenbrook Limited; 2001-12-04;# <http://www.nedbatchelder.com/code/modules/rees-design.html>.## [van Rossum 2001-07-20a] "Python Reference Manual (releae 2.1.1)";# Guide van Rossum; 2001-07-20;# <http://www.python.org/doc/2.1.1/ref/ref.html>.## [van Rossum 2001-07-20b] "Python Library Reference"; Guido van Rossum;# 2001-07-20; <http://www.python.org/doc/2.1.1/lib/lib.html>.### B. DOCUMENT HISTORY## 2001-12-04 GDR Created.## 2001-12-06 GDR Added command-line interface and source code# annotation.## 2001-12-09 GDR Moved design and interface to separate documents.## 2001-12-10 GDR Open cache file as binary on Windows. Allow# simultaneous -e and -x, or -a and -r.## 2001-12-12 GDR Added command-line help. Cache analysis so that it# only needs to be done once when you specify -a and -r.## 2001-12-13 GDR Improved speed while recording. Portable between# Python 1.5.2 and 2.1.1.## 2002-01-03 GDR Module-level functions work correctly.## 2002-01-07 GDR Update sys.path when running a file with the -x option,# so that it matches the value the program would get if it were run on# its own.## 2004-12-12 NMB Significant code changes.# - Finding executable statements has been rewritten so that docstrings and# other quirks of Python execution aren't mistakenly identified as missing# lines.# - Lines can be excluded from consideration, even entire suites of lines.# - The filesystem cache of covered lines can be disabled programmatically.# - Modernized the code.## 2004-12-14 NMB Minor tweaks. Return 'analysis' to its original behavior# and add 'analysis2'. Add a global for 'annotate', and factor it, adding# 'annotate_file'.## 2004-12-31 NMB Allow for keyword arguments in the module global functions.# Thanks, Allen.## 2005-12-02 NMB Call threading.settrace so that all threads are measured.# Thanks Martin Fuzzey. Add a file argument to report so that reports can be # captured to a different destination.## 2005-12-03 NMB coverage.py can now measure itself.## 2005-12-04 NMB Adapted Greg Rogers' patch for using relative filenames,# and sorting and omitting files to report on.## 2006-07-23 NMB Applied Joseph Tate's patch for function decorators.## 2006-08-21 NMB Applied Sigve Tjora and Mark van der Wal's fixes for argument# handling.## 2006-08-22 NMB Applied Geoff Bache's parallel mode patch.## 2006-08-23 NMB Refactorings to improve testability. Fixes to command-line# logic for parallel mode and collect.## 2006-08-25 NMB "#pragma: nocover" is excluded by default.## 2006-09-10 NMB Properly ignore docstrings and other constant expressions that# appear in the middle of a function, a problem reported by Tim Leslie.# Minor changes to avoid lint warnings.## 2006-09-17 NMB coverage.erase() shouldn't clobber the exclude regex.# Change how parallel mode is invoked, and fix erase() so that it erases the# cache when called programmatically.## 2007-07-21 NMB In reports, ignore code executed from strings, since we can't# do anything useful with it anyway.# Better file handling on Linux, thanks Guillaume Chazarain.# Better shell support on Windows, thanks Noel O'Boyle.# Python 2.2 support maintained, thanks Catherine Proulx.## 2007-07-22 NMB Python 2.5 now fully supported. The method of dealing with# multi-line statements is now less sensitive to the exact line that Python# reports during execution. Pass statements are handled specially so that their# disappearance during execution won't throw off the measurement.# C. COPYRIGHT AND LICENCE## Copyright 2001 Gareth Rees. All rights reserved.# Copyright 2004-2007 Ned Batchelder. All rights reserved.## Redistribution and use in source and binary forms, with or without# modification, are permitted provided that the following conditions are# met:## 1. Redistributions of source code must retain the above copyright# notice, this list of conditions and the following disclaimer.## 2. Redistributions in binary form must reproduce the above copyright# notice, this list of conditions and the following disclaimer in the# documentation and/or other materials provided with the# distribution.## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT# HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH# DAMAGE.## $Id: coverage.py 67 2007-07-21 19:51:07Z nedbat $
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -