From 5af852fb6be9d333ac90062569cabb25ed19c702 Mon Sep 17 00:00:00 2001 From: Mathieu Virbel Date: Fri, 21 Jan 2011 00:02:29 +0100 Subject: [PATCH] activate nosetests + reactivate coverage (ready for buildbot !) --- Makefile | 6 + README | 2 + kivy/tests/coverage/__init__.py | 88 -- kivy/tests/coverage/__main__.py | 3 - kivy/tests/coverage/annotate.py | 102 --- kivy/tests/coverage/backward.py | 72 -- kivy/tests/coverage/bytecode.py | 84 -- kivy/tests/coverage/cmdline.py | 648 -------------- kivy/tests/coverage/codeunit.py | 124 --- kivy/tests/coverage/collector.py | 363 -------- kivy/tests/coverage/config.py | 118 --- kivy/tests/coverage/control.py | 629 ------------- kivy/tests/coverage/data.py | 262 ------ kivy/tests/coverage/execfile.py | 74 -- kivy/tests/coverage/files.py | 141 --- kivy/tests/coverage/html.py | 185 ---- .../tests/coverage/htmlfiles/coverage_html.js | 87 -- kivy/tests/coverage/htmlfiles/index.html | 81 -- .../coverage/htmlfiles/jquery-1.3.2.min.js | 19 - .../htmlfiles/jquery.tablesorter.min.js | 2 - kivy/tests/coverage/htmlfiles/pyfile.html | 61 -- kivy/tests/coverage/htmlfiles/style.css | 230 ----- kivy/tests/coverage/misc.py | 85 -- kivy/tests/coverage/parser.py | 838 ------------------ kivy/tests/coverage/phystokens.py | 111 --- kivy/tests/coverage/report.py | 84 -- kivy/tests/coverage/results.py | 233 ----- kivy/tests/coverage/summary.py | 81 -- kivy/tests/coverage/templite.py | 169 ---- kivy/tests/coverage/tracer.c | 674 -------------- kivy/tests/coverage/xmlreport.py | 149 ---- setup.cfg | 5 +- 32 files changed, 10 insertions(+), 5800 deletions(-) delete mode 100644 kivy/tests/coverage/__init__.py delete mode 100644 kivy/tests/coverage/__main__.py delete mode 100644 kivy/tests/coverage/annotate.py delete mode 100644 kivy/tests/coverage/backward.py delete mode 100644 kivy/tests/coverage/bytecode.py delete mode 100644 kivy/tests/coverage/cmdline.py delete mode 100644 kivy/tests/coverage/codeunit.py delete mode 100644 kivy/tests/coverage/collector.py delete mode 100644 kivy/tests/coverage/config.py delete mode 100644 kivy/tests/coverage/control.py delete mode 100644 kivy/tests/coverage/data.py delete mode 100644 kivy/tests/coverage/execfile.py delete mode 100644 kivy/tests/coverage/files.py delete mode 100644 kivy/tests/coverage/html.py delete mode 100644 kivy/tests/coverage/htmlfiles/coverage_html.js delete mode 100644 kivy/tests/coverage/htmlfiles/index.html delete mode 100644 kivy/tests/coverage/htmlfiles/jquery-1.3.2.min.js delete mode 100644 kivy/tests/coverage/htmlfiles/jquery.tablesorter.min.js delete mode 100644 kivy/tests/coverage/htmlfiles/pyfile.html delete mode 100644 kivy/tests/coverage/htmlfiles/style.css delete mode 100644 kivy/tests/coverage/misc.py delete mode 100644 kivy/tests/coverage/parser.py delete mode 100644 kivy/tests/coverage/phystokens.py delete mode 100644 kivy/tests/coverage/report.py delete mode 100644 kivy/tests/coverage/results.py delete mode 100644 kivy/tests/coverage/summary.py delete mode 100644 kivy/tests/coverage/templite.py delete mode 100644 kivy/tests/coverage/tracer.c delete mode 100644 kivy/tests/coverage/xmlreport.py diff --git a/Makefile b/Makefile index 9e393dde16..26362ac64d 100644 --- a/Makefile +++ b/Makefile @@ -15,3 +15,9 @@ stylereport: hook: cp kivy/tools/pep8checker/pre-commit.githook .git/hooks/pre-commit chmod +x .git/hooks/pre-commit + +test: + python setup.py nosetests + +cover: + coverage html --include='kivy*' --omit 'kivy/lib/*,kivy/tools/*,kivy/tests/*' diff --git a/README b/README index 5407d2310d..d82d6d81b1 100644 --- a/README +++ b/README @@ -70,6 +70,8 @@ Here is what works best: * PIL * GST + PyGST * Cython + * nosetests >= 0.11 (for unittest) + * coverage >= 0.34 (for coverage) Dcoumentation, Examples & Tutorials diff --git a/kivy/tests/coverage/__init__.py b/kivy/tests/coverage/__init__.py deleted file mode 100644 index ad3b227769..0000000000 --- a/kivy/tests/coverage/__init__.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Code coverage measurement for Python. - -Ned Batchelder -http://nedbatchelder.com/code/coverage - -""" - -__version__ = "3.4" # see detailed history in CHANGES.txt - -__url__ = "http://nedbatchelder.com/code/coverage" -if 'b' in __version__: - # For beta, use a version-specific URL. - __url__ += "/" + __version__ - -from coverage.control import coverage, process_startup -from coverage.data import CoverageData -from coverage.cmdline import main, CoverageScript -from coverage.misc import CoverageException - - -# Module-level functions. The original API to this module was based on -# functions defined directly in the module, with a singleton of the coverage() -# class. That design hampered programmability, so the current api uses -# explicitly-created coverage objects. But for backward compatibility, here we -# define the top-level functions to create the singleton when they are first -# called. - -# Singleton object for use with module-level functions. The singleton is -# created as needed when one of the module-level functions is called. -_the_coverage = None - -def _singleton_method(name): - """Return a function to the `name` method on a singleton `coverage` object. - - The singleton object is created the first time one of these functions is - called. - - """ - def wrapper(*args, **kwargs): - """Singleton wrapper around a coverage method.""" - global _the_coverage - if not _the_coverage: - _the_coverage = coverage(auto_data=True) - return getattr(_the_coverage, name)(*args, **kwargs) - return wrapper - - -# Define the module-level functions. -use_cache = _singleton_method('use_cache') -start = _singleton_method('start') -stop = _singleton_method('stop') -erase = _singleton_method('erase') -exclude = _singleton_method('exclude') -analysis = _singleton_method('analysis') -analysis2 = _singleton_method('analysis2') -report = _singleton_method('report') -annotate = _singleton_method('annotate') - - -# COPYRIGHT AND LICENSE -# -# Copyright 2001 Gareth Rees. All rights reserved. -# Copyright 2004-2010 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. diff --git a/kivy/tests/coverage/__main__.py b/kivy/tests/coverage/__main__.py deleted file mode 100644 index af5fa9f681..0000000000 --- a/kivy/tests/coverage/__main__.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Coverage.py's main entrypoint.""" -from coverage.cmdline import main -main() diff --git a/kivy/tests/coverage/annotate.py b/kivy/tests/coverage/annotate.py deleted file mode 100644 index f8698dd482..0000000000 --- a/kivy/tests/coverage/annotate.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Source file annotation for Coverage.""" - -import os -import re - -from coverage.report import Reporter - -class AnnotateReporter(Reporter): - """Generate annotated source files showing line coverage. - - This reporter creates annotated copies of the measured source files. Each - .py file is copied as a .py,cover file, with a left-hand margin annotating - each line:: - - > def h(x): - - if 0: #pragma: no cover - - pass - > if x == 1: - ! a = 1 - > else: - > a = 2 - - > h(2) - - Executed lines use '>', lines not executed use '!', lines excluded from - consideration use '-'. - - """ - - def __init__(self, coverage, ignore_errors=False): - super(AnnotateReporter, self).__init__(coverage, ignore_errors) - self.directory = None - - blank_re = re.compile(r"\s*(#|$)") - else_re = re.compile(r"\s*else\s*:\s*(#|$)") - - def report(self, morfs, config, directory=None): - """Run the report. - - See `coverage.report()` for arguments. - - """ - self.report_files(self.annotate_file, morfs, config, directory) - - def annotate_file(self, cu, analysis): - """Annotate a single file. - - `cu` is the CodeUnit for the file to annotate. - - """ - if not cu.relative: - return - - filename = cu.filename - source = cu.source_file() - if self.directory: - dest_file = os.path.join(self.directory, cu.flat_rootname()) - dest_file += ".py,cover" - else: - dest_file = filename + ",cover" - dest = open(dest_file, 'w') - - statements = analysis.statements - missing = analysis.missing - excluded = analysis.excluded - - lineno = 0 - i = 0 - j = 0 - covered = True - while True: - line = source.readline() - if line == '': - break - lineno += 1 - while i < len(statements) and statements[i] < lineno: - i += 1 - while j < len(missing) and missing[j] < lineno: - 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:'. - 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() diff --git a/kivy/tests/coverage/backward.py b/kivy/tests/coverage/backward.py deleted file mode 100644 index 206e37a915..0000000000 --- a/kivy/tests/coverage/backward.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Add things to old Pythons so I can pretend they are newer.""" - -# This file does lots of tricky stuff, so disable a bunch of lintisms. -# pylint: disable-msg=F0401,W0611,W0622 -# F0401: Unable to import blah -# W0611: Unused import blah -# W0622: Redefining built-in blah - -import os -import sys - -# Python 2.3 doesn't have `set` -try: - set = set # new in 2.4 -except NameError: - from sets import Set as set - -# Python 2.3 doesn't have `sorted`. -try: - sorted = sorted -except NameError: - def sorted(iterable): - """A 2.3-compatible implementation of `sorted`.""" - lst = list(iterable) - lst.sort() - return lst - -# Pythons 2 and 3 differ on where to get StringIO -try: - from cStringIO import StringIO - BytesIO = StringIO -except ImportError: - from io import StringIO, BytesIO - -# What's a string called? -try: - string_class = basestring -except NameError: - string_class = str - -# Where do pickles come from? -try: - import cPickle as pickle -except ImportError: - import pickle - -# range or xrange? -try: - range = xrange -except NameError: - range = range - -# Exec is a statement in Py2, a function in Py3 -if sys.version_info >= (3, 0): - def exec_code_object(code, global_map): - """A wrapper around exec().""" - exec(code, global_map) -else: - # OK, this is pretty gross. In Py2, exec was a statement, but that will - # be a syntax error if we try to put it in a Py3 file, even if it is never - # executed. So hide it inside an evaluated string literal instead. - eval( - compile( - "def exec_code_object(code, global_map):\n" - " exec code in global_map\n", - "", "exec")) - -# ConfigParser was renamed to the more-standard configparser -try: - import configparser -except ImportError: - import ConfigParser as configparser diff --git a/kivy/tests/coverage/bytecode.py b/kivy/tests/coverage/bytecode.py deleted file mode 100644 index bbc31de40a..0000000000 --- a/kivy/tests/coverage/bytecode.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Bytecode manipulation for coverage.py""" - -import opcode -import sys -import types - - -class ByteCode(object): - """A single bytecode.""" - def __init__(self): - self.offset = -1 - self.op = -1 - self.arg = -1 - self.next_offset = -1 - self.jump_to = -1 - - -class ByteCodes(object): - """Iterator over byte codes in `code`. - - Returns `ByteCode` objects. - - """ - def __init__(self, code): - self.code = code - self.offset = 0 - - if sys.version_info >= (3, 0): - def __getitem__(self, i): - return self.code[i] - else: - def __getitem__(self, i): - return ord(self.code[i]) - - def __iter__(self): - return self - - def __next__(self): - if self.offset >= len(self.code): - raise StopIteration - - bc = ByteCode() - bc.op = self[self.offset] - bc.offset = self.offset - - next_offset = self.offset+1 - if bc.op >= opcode.HAVE_ARGUMENT: - bc.arg = self[self.offset+1] + 256*self[self.offset+2] - next_offset += 2 - - label = -1 - if bc.op in opcode.hasjrel: - label = next_offset + bc.arg - elif bc.op in opcode.hasjabs: - label = bc.arg - bc.jump_to = label - - bc.next_offset = self.offset = next_offset - return bc - - next = __next__ # Py2k uses an old-style non-dunder name. - - -class CodeObjects(object): - """Iterate over all the code objects in `code`.""" - def __init__(self, code): - self.stack = [code] - - def __iter__(self): - return self - - def __next__(self): - if self.stack: - # We're going to return the code object on the stack, but first - # push its children for later returning. - code = self.stack.pop() - for c in code.co_consts: - if isinstance(c, types.CodeType): - self.stack.append(c) - return code - - raise StopIteration - - next = __next__ diff --git a/kivy/tests/coverage/cmdline.py b/kivy/tests/coverage/cmdline.py deleted file mode 100644 index 3ee474651f..0000000000 --- a/kivy/tests/coverage/cmdline.py +++ /dev/null @@ -1,648 +0,0 @@ -"""Command-line support for Coverage.""" - -import optparse -import re -import sys -import traceback - -from coverage.backward import sorted # pylint: disable-msg=W0622 -from coverage.execfile import run_python_file -from coverage.misc import CoverageException, ExceptionDuringRun - - -class Opts(object): - """A namespace class for individual options we'll build parsers from.""" - - append = optparse.make_option( - '-a', '--append', action='store_false', dest="erase_first", - help="Append coverage data to .coverage, otherwise it is started " - "clean with each run.") - branch = optparse.make_option( - '', '--branch', action='store_true', - help="Measure branch coverage in addition to statement coverage.") - directory = optparse.make_option( - '-d', '--directory', action='store', - metavar="DIR", - help="Write the output files to DIR.") - help = optparse.make_option( - '-h', '--help', action='store_true', - help="Get help on this command.") - ignore_errors = optparse.make_option( - '-i', '--ignore-errors', action='store_true', - help="Ignore errors while reading source files.") - include = optparse.make_option( - '', '--include', action='store', - metavar="PAT1,PAT2,...", - help="Include files only when their filename path matches one of " - "these patterns. Usually needs quoting on the command line.") - pylib = optparse.make_option( - '-L', '--pylib', action='store_true', - help="Measure coverage even inside the Python installed library, " - "which isn't done by default.") - show_missing = optparse.make_option( - '-m', '--show-missing', action='store_true', - help="Show line numbers of statements in each module that weren't " - "executed.") - old_omit = optparse.make_option( - '-o', '--omit', action='store', - metavar="PAT1,PAT2,...", - help="Omit files when their filename matches one of these patterns. " - "Usually needs quoting on the command line.") - omit = optparse.make_option( - '', '--omit', action='store', - metavar="PAT1,PAT2,...", - help="Omit files when their filename matches one of these patterns. " - "Usually needs quoting on the command line.") - output_xml = optparse.make_option( - '-o', '', action='store', dest="outfile", - metavar="OUTFILE", - help="Write the XML report to this file. Defaults to 'coverage.xml'") - parallel_mode = optparse.make_option( - '-p', '--parallel-mode', action='store_true', - help="Append the machine name, process id and random number to the " - ".coverage data file name to simplify collecting data from " - "many processes.") - rcfile = optparse.make_option( - '', '--rcfile', action='store', - help="Specify configuration file. Defaults to '.coveragerc'") - source = optparse.make_option( - '', '--source', action='store', metavar="SRC1,SRC2,...", - help="A list of packages or directories of code to be measured.") - timid = optparse.make_option( - '', '--timid', action='store_true', - help="Use a simpler but slower trace method. Try this if you get ") - "seemingly impossible results!" - version = optparse.make_option( - '', '--version', action='store_true', - help="Display version information and exit.") - - -class CoverageOptionParser(optparse.OptionParser, object): - """Base OptionParser for coverage. - - Problems don't exit the program. - Defaults are initialized for all options. - - """ - - def __init__(self, *args, **kwargs): - super(CoverageOptionParser, self).__init__( - add_help_option=False, *args, **kwargs - ) - self.set_defaults( - actions=[], - branch=None, - directory=None, - help=None, - ignore_errors=None, - include=None, - omit=None, - parallel_mode=None, - pylib=None, - rcfile=True, - show_missing=None, - source=None, - timid=None, - erase_first=None, - version=None, - ) - - self.disable_interspersed_args() - self.help_fn = self.help_noop - - def help_noop(self, error=None, topic=None, parser=None): - """No-op help function.""" - pass - - class OptionParserError(Exception): - """Used to stop the optparse error handler ending the process.""" - pass - - def parse_args(self, args=None, options=None): - """Call optparse.parse_args, but return a triple: - - (ok, options, args) - - """ - try: - options, args = \ - super(CoverageOptionParser, self).parse_args(args, options) - except self.OptionParserError: - return False, None, None - return True, options, args - - def error(self, msg): - """Override optparse.error so sys.exit doesn't get called.""" - self.help_fn(msg) - raise self.OptionParserError - - -class ClassicOptionParser(CoverageOptionParser): - """Command-line parser for coverage.py classic arguments.""" - - def __init__(self): - super(ClassicOptionParser, self).__init__() - - self.add_action('-a', '--annotate', 'annotate') - self.add_action('-b', '--html', 'html') - self.add_action('-c', '--combine', 'combine') - self.add_action('-e', '--erase', 'erase') - self.add_action('-r', '--report', 'report') - self.add_action('-x', '--execute', 'execute') - - self.add_options([ - Opts.directory, - Opts.help, - Opts.ignore_errors, - Opts.pylib, - Opts.show_missing, - Opts.old_omit, - Opts.parallel_mode, - Opts.timid, - Opts.version, - ]) - - def add_action(self, dash, dashdash, action_code): - """Add a specialized option that is the action to execute.""" - option = self.add_option(dash, dashdash, action='callback', - callback=self._append_action - ) - option.action_code = action_code - - def _append_action(self, option, opt_unused, value_unused, parser): - """Callback for an option that adds to the `actions` list.""" - parser.values.actions.append(option.action_code) - - -class CmdOptionParser(CoverageOptionParser): - """Parse one of the new-style commands for coverage.py.""" - - def __init__(self, action, options=None, defaults=None, usage=None, - cmd=None, description=None - ): - """Create an OptionParser for a coverage command. - - `action` is the slug to put into `options.actions`. - `options` is a list of Option's for the command. - `defaults` is a dict of default value for options. - `usage` is the usage string to display in help. - `cmd` is the command name, if different than `action`. - `description` is the description of the command, for the help text. - - """ - if usage: - usage = "%prog " + usage - super(CmdOptionParser, self).__init__( - prog="coverage %s" % (cmd or action), - usage=usage, - description=description, - ) - self.set_defaults(actions=[action], **(defaults or {})) - if options: - self.add_options(options) - self.cmd = cmd or action - - def __eq__(self, other): - # A convenience equality, so that I can put strings in unit test - # results, and they will compare equal to objects. - return (other == "" % self.cmd) - -GLOBAL_ARGS = [ - Opts.rcfile, - Opts.help, - ] - -CMDS = { - 'annotate': CmdOptionParser("annotate", - [ - Opts.directory, - Opts.ignore_errors, - Opts.omit, - Opts.include, - ] + GLOBAL_ARGS, - usage = "[options] [modules]", - description = "Make annotated copies of the given files, marking " - "statements that are executed with > and statements that are " - "missed with !." - ), - - 'combine': CmdOptionParser("combine", GLOBAL_ARGS, - usage = " ", - description = "Combine data from multiple coverage files collected " - "with 'run -p'. The combined results are written to a single " - "file representing the union of the data." - ), - - 'debug': CmdOptionParser("debug", GLOBAL_ARGS, - usage = "", - description = "Display information on the internals of coverage.py, " - "for diagnosing problems. " - "Topics are 'data' to show a summary of the collected data, " - "or 'sys' to show installation information." - ), - - 'erase': CmdOptionParser("erase", GLOBAL_ARGS, - usage = " ", - description = "Erase previously collected coverage data." - ), - - 'help': CmdOptionParser("help", GLOBAL_ARGS, - usage = "[command]", - description = "Describe how to use coverage.py" - ), - - 'html': CmdOptionParser("html", - [ - Opts.directory, - Opts.ignore_errors, - Opts.omit, - Opts.include, - ] + GLOBAL_ARGS, - usage = "[options] [modules]", - description = "Create an HTML report of the coverage of the files. " - "Each file gets its own page, with the source decorated to show " - "executed, excluded, and missed lines." - ), - - 'report': CmdOptionParser("report", - [ - Opts.ignore_errors, - Opts.omit, - Opts.include, - Opts.show_missing, - ] + GLOBAL_ARGS, - usage = "[options] [modules]", - description = "Report coverage statistics on modules." - ), - - 'run': CmdOptionParser("execute", - [ - Opts.append, - Opts.branch, - Opts.pylib, - Opts.parallel_mode, - Opts.timid, - Opts.source, - Opts.omit, - Opts.include, - ] + GLOBAL_ARGS, - defaults = {'erase_first': True}, - cmd = "run", - usage = "[options] [program options]", - description = "Run a Python program, measuring code execution." - ), - - 'xml': CmdOptionParser("xml", - [ - Opts.ignore_errors, - Opts.omit, - Opts.include, - Opts.output_xml, - ] + GLOBAL_ARGS, - cmd = "xml", - defaults = {'outfile': 'coverage.xml'}, - usage = "[options] [modules]", - description = "Generate an XML report of coverage results." - ), - } - - -OK, ERR = 0, 1 - - -class CoverageScript(object): - """The command-line interface to Coverage.""" - - def __init__(self, _covpkg=None, _run_python_file=None, _help_fn=None): - # _covpkg is for dependency injection, so we can test this code. - if _covpkg: - self.covpkg = _covpkg - else: - import coverage - self.covpkg = coverage - - # _run_python_file is for dependency injection also. - self.run_python_file = _run_python_file or run_python_file - - # _help_fn is for dependency injection. - self.help_fn = _help_fn or self.help - - self.coverage = None - - def help(self, error=None, topic=None, parser=None): - """Display an error message, or the named topic.""" - assert error or topic or parser - if error: - print(error) - print("Use 'coverage help' for help.") - elif parser: - print(parser.format_help().strip()) - else: - # Parse out the topic we want from HELP_TOPICS - topic_list = re.split("(?m)^=+ (\w+) =+$", HELP_TOPICS) - topics = dict(zip(topic_list[1::2], topic_list[2::2])) - help_msg = topics.get(topic, '').strip() - if help_msg: - print(help_msg % self.covpkg.__dict__) - else: - print("Don't know topic %r" % topic) - - def command_line(self, argv): - """The bulk of the command line interface to Coverage. - - `argv` is the argument list to process. - - Returns 0 if all is well, 1 if something went wrong. - - """ - # Collect the command-line options. - - if not argv: - self.help_fn(topic='minimum_help') - return OK - - # The command syntax we parse depends on the first argument. Classic - # syntax always starts with an option. - classic = argv[0].startswith('-') - if classic: - parser = ClassicOptionParser() - else: - parser = CMDS.get(argv[0]) - if not parser: - self.help_fn("Unknown command: '%s'" % argv[0]) - return ERR - argv = argv[1:] - - parser.help_fn = self.help_fn - ok, options, args = parser.parse_args(argv) - if not ok: - return ERR - - # Handle help. - if options.help: - if classic: - self.help_fn(topic='help') - else: - self.help_fn(parser=parser) - return OK - - if "help" in options.actions: - if args: - for a in args: - parser = CMDS.get(a) - if parser: - self.help_fn(parser=parser) - else: - self.help_fn(topic=a) - else: - self.help_fn(topic='help') - return OK - - # Handle version. - if options.version: - self.help_fn(topic='version') - return OK - - # Check for conflicts and problems in the options. - for i in ['erase', 'execute']: - for j in ['annotate', 'html', 'report', 'combine']: - if (i in options.actions) and (j in options.actions): - self.help_fn("You can't specify the '%s' and '%s' " - "options at the same time." % (i, j)) - return ERR - - if not options.actions: - self.help_fn( - "You must specify at least one of -e, -x, -c, -r, -a, or -b." - ) - return ERR - args_allowed = ( - 'execute' in options.actions or - 'annotate' in options.actions or - 'html' in options.actions or - 'debug' in options.actions or - 'report' in options.actions or - 'xml' in options.actions - ) - if not args_allowed and args: - self.help_fn("Unexpected arguments: %s" % " ".join(args)) - return ERR - - if 'execute' in options.actions and not args: - self.help_fn("Nothing to do.") - return ERR - - # Listify the list options. - source = unshell_list(options.source) - omit = unshell_list(options.omit) - include = unshell_list(options.include) - - # Do something. - self.coverage = self.covpkg.coverage( - data_suffix = options.parallel_mode, - cover_pylib = options.pylib, - timid = options.timid, - branch = options.branch, - config_file = options.rcfile, - source = source, - omit = omit, - include = include, - ) - - if 'debug' in options.actions: - if not args: - self.help_fn("What information would you like: data, sys?") - return ERR - for info in args: - if info == 'sys': - print("-- sys ----------------------------------------") - for label, info in self.coverage.sysinfo(): - if info == []: - info = "-none-" - if isinstance(info, list): - print("%15s:" % label) - for e in info: - print("%15s %s" % ("", e)) - else: - print("%15s: %s" % (label, info)) - elif info == 'data': - print("-- data ---------------------------------------") - self.coverage.load() - print("path: %s" % self.coverage.data.filename) - print("has_arcs: %r" % self.coverage.data.has_arcs()) - summary = self.coverage.data.summary(fullpath=True) - if summary: - filenames = sorted(summary.keys()) - print("\n%d files:" % len(filenames)) - for f in filenames: - print("%s: %d lines" % (f, summary[f])) - else: - print("No data collected") - else: - self.help_fn("Don't know what you mean by %r" % info) - return ERR - return OK - - if 'erase' in options.actions or options.erase_first: - self.coverage.erase() - else: - self.coverage.load() - - if 'execute' in options.actions: - # Run the script. - self.coverage.start() - try: - self.run_python_file(args[0], args) - finally: - self.coverage.stop() - self.coverage.save() - - if 'combine' in options.actions: - self.coverage.combine() - self.coverage.save() - - # Remaining actions are reporting, with some common options. - report_args = dict( - morfs = args, - ignore_errors = options.ignore_errors, - omit = omit, - include = include, - ) - - if 'report' in options.actions: - self.coverage.report( - show_missing=options.show_missing, **report_args) - if 'annotate' in options.actions: - self.coverage.annotate( - directory=options.directory, **report_args) - if 'html' in options.actions: - self.coverage.html_report( - directory=options.directory, **report_args) - if 'xml' in options.actions: - outfile = options.outfile - self.coverage.xml_report(outfile=outfile, **report_args) - - return OK - - -def unshell_list(s): - """Turn a command-line argument into a list.""" - if not s: - return None - if sys.platform == 'win32': - # When running coverage as coverage.exe, some of the behavior - # of the shell is emulated: wildcards are expanded into a list of - # filenames. So you have to single-quote patterns on the command - # line, but (not) helpfully, the single quotes are included in the - # argument, so we have to strip them off here. - s = s.strip("'") - return s.split(',') - - -HELP_TOPICS = r""" - -== classic ==================================================================== -Coverage.py version %(__version__)s -Measure, collect, and report on code coverage in Python programs. - -Usage: - -coverage -x [-p] [-L] [--timid] MODULE.py [ARG1 ARG2 ...] - Execute the module, passing the given command-line arguments, collecting - coverage data. With the -p option, include the machine name and process - id in the .coverage file name. With -L, measure coverage even inside the - Python installed library, which isn't done by default. With --timid, use a - simpler but slower trace method. - -coverage -e - Erase collected coverage data. - -coverage -c - Combine data from multiple coverage files (as created by -p option above) - and store it into a single file representing the union of the coverage. - -coverage -r [-m] [-i] [-o DIR,...] [FILE1 FILE2 ...] - Report on the statement coverage for the given files. With the -m - option, show line numbers of the statements that weren't executed. - -coverage -b -d DIR [-i] [-o DIR,...] [FILE1 FILE2 ...] - Create an HTML report of the coverage of the given files. Each file gets - its own page, with the file listing decorated to show executed, excluded, - and missed lines. - -coverage -a [-d DIR] [-i] [-o DIR,...] [FILE1 FILE2 ...] - Make annotated copies of the given files, marking statements that - are executed with > and statements that are missed with !. - --d DIR - Write output files for -b or -a to this directory. - --i Ignore errors while reporting or annotating. - --o DIR,... - Omit reporting or annotating files when their filename path starts with - a directory listed in the omit list. - e.g. coverage -i -r -o c:\python25,lib\enthought\traits - -Coverage data is saved in the file .coverage by default. Set the -COVERAGE_FILE environment variable to save it somewhere else. - -== help ======================================================================= -Coverage.py, version %(__version__)s -Measure, collect, and report on code coverage in Python programs. - -usage: coverage [options] [args] - -Commands: - annotate Annotate source files with execution information. - combine Combine a number of data files. - erase Erase previously collected coverage data. - help Get help on using coverage.py. - html Create an HTML report. - report Report coverage stats on modules. - run Run a Python program and measure code execution. - xml Create an XML report of coverage results. - -Use "coverage help " for detailed help on any command. -Use "coverage help classic" for help on older command syntax. -For more information, see %(__url__)s - -== minimum_help =============================================================== -Code coverage for Python. Use 'coverage help' for help. - -== version ==================================================================== -Coverage.py, version %(__version__)s. %(__url__)s - -""" - - -def main(argv=None): - """The main entrypoint to Coverage. - - This is installed as the script entrypoint. - - """ - if argv is None: - argv = sys.argv[1:] - try: - status = CoverageScript().command_line(argv) - except ExceptionDuringRun: - # An exception was caught while running the product code. The - # sys.exc_info() return tuple is packed into an ExceptionDuringRun - # exception. - _, err, _ = sys.exc_info() - traceback.print_exception(*err.args) - status = ERR - except CoverageException: - # A controlled error inside coverage.py: print the message to the user. - _, err, _ = sys.exc_info() - print(err) - status = ERR - except SystemExit: - # The user called `sys.exit()`. Exit with their argument, if any. - _, err, _ = sys.exc_info() - if err.args: - status = err.args[0] - else: - status = None - return status diff --git a/kivy/tests/coverage/codeunit.py b/kivy/tests/coverage/codeunit.py deleted file mode 100644 index 834cde162f..0000000000 --- a/kivy/tests/coverage/codeunit.py +++ /dev/null @@ -1,124 +0,0 @@ -"""Code unit (module) handling for Coverage.""" - -import glob -import os - -from coverage.backward import string_class, StringIO -from coverage.misc import CoverageException - - -def code_unit_factory(morfs, file_locator): - """Construct a list of CodeUnits from polymorphic inputs. - - `morfs` is a module or a filename, or a list of same. - - `file_locator` is a FileLocator that can help resolve filenames. - - Returns a list of CodeUnit objects. - - """ - # Be sure we have a list. - if not isinstance(morfs, (list, tuple)): - morfs = [morfs] - - # On Windows, the shell doesn't expand wildcards. Do it here. - globbed = [] - for morf in morfs: - if isinstance(morf, string_class) and ('?' in morf or '*' in morf): - globbed.extend(glob.glob(morf)) - else: - globbed.append(morf) - morfs = globbed - - code_units = [CodeUnit(morf, file_locator) for morf in morfs] - - return code_units - - -class CodeUnit(object): - """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. - `relative` is a boolean. - - """ - def __init__(self, morf, file_locator): - self.file_locator = file_locator - - if hasattr(morf, '__file__'): - f = morf.__file__ - else: - f = morf - # .pyc files should always refer to a .py instead. - if f.endswith('.pyc'): - f = f[:-1] - self.filename = self.file_locator.canonical_filename(f) - - if hasattr(morf, '__name__'): - n = modname = morf.__name__ - self.relative = True - else: - n = os.path.splitext(morf)[0] - rel = self.file_locator.relative_filename(n) - if os.path.isabs(n): - self.relative = (rel != n) - else: - self.relative = True - n = rel - modname = None - self.name = n - self.modname = modname - - def __repr__(self): - return "" % (self.name, self.filename) - - # Annoying comparison operators. Py3k wants __lt__ etc, and Py2k needs all - # of them defined. - - def __lt__(self, other): - return self.name < other.name - def __le__(self, other): - return self.name <= other.name - def __eq__(self, other): - return self.name == other.name - def __ne__(self, other): - return self.name != other.name - def __gt__(self, other): - return self.name > other.name - def __ge__(self, other): - return self.name >= other.name - - def flat_rootname(self): - """A base for a flat filename to correspond to this code unit. - - Useful for writing files about the code where you want all the files in - the same directory, but need to differentiate same-named files from - different directories. - - For example, the file a/b/c.py might return 'a_b_c' - - """ - if self.modname: - return self.modname.replace('.', '_') - else: - root = os.path.splitdrive(self.name)[1] - return root.replace('\\', '_').replace('/', '_').replace('.', '_') - - def source_file(self): - """Return an open file for reading the source of the code unit.""" - if os.path.exists(self.filename): - # A regular text file: open it. - return open(self.filename) - - # Maybe it's in a zip file? - source = self.file_locator.get_zip_data(self.filename) - if source is not None: - return StringIO(source) - - # Couldn't find source. - raise CoverageException( - "No source for code %r." % self.filename - ) diff --git a/kivy/tests/coverage/collector.py b/kivy/tests/coverage/collector.py deleted file mode 100644 index da556100bf..0000000000 --- a/kivy/tests/coverage/collector.py +++ /dev/null @@ -1,363 +0,0 @@ -"""Raw data collector for Coverage.""" - -import sys -import threading - -try: - # Use the C extension code when we can, for speed. - from coverage.tracer import Tracer -except ImportError: - # Couldn't import the C extension, maybe it isn't built. - Tracer = None - - -class PyTracer(object): - """Python implementation of the raw data tracer.""" - - # Because of poor implementations of trace-function-manipulating tools, - # the Python trace function must be kept very simple. In particular, there - # must be only one function ever set as the trace function, both through - # sys.settrace, and as the return value from the trace function. Put - # another way, the trace function must always return itself. It cannot - # swap in other functions, or return None to avoid tracing a particular - # frame. - # - # The trace manipulator that introduced this restriction is DecoratorTools, - # which sets a trace function, and then later restores the pre-existing one - # by calling sys.settrace with a function it found in the current frame. - # - # Systems that use DecoratorTools (or similar trace manipulations) must use - # PyTracer to get accurate results. The command-line --timid argument is - # used to force the use of this tracer. - - def __init__(self): - self.data = None - self.should_trace = None - self.should_trace_cache = None - self.cur_file_data = None - self.last_line = 0 - self.data_stack = [] - self.last_exc_back = None - self.last_exc_firstlineno = 0 - self.arcs = False - - def _trace(self, frame, event, arg_unused): - """The trace function passed to sys.settrace.""" - - #print "trace event: %s %r @%d" % ( - # event, frame.f_code.co_filename, frame.f_lineno) - - if self.last_exc_back: - if frame == self.last_exc_back: - # Someone forgot a return event. - if self.arcs and self.cur_file_data: - pair = (self.last_line, -self.last_exc_firstlineno) - self.cur_file_data[pair] = None - self.cur_file_data, self.last_line = self.data_stack.pop() - self.last_exc_back = None - - if event == 'call': - # Entering a new function context. Decide if we should trace - # in this file. - self.data_stack.append((self.cur_file_data, self.last_line)) - filename = frame.f_code.co_filename - tracename = self.should_trace_cache.get(filename) - if tracename is None: - tracename = self.should_trace(filename, frame) - self.should_trace_cache[filename] = tracename - if tracename: - if tracename not in self.data: - self.data[tracename] = {} - self.cur_file_data = self.data[tracename] - else: - self.cur_file_data = None - # Set the last_line to -1 because the next arc will be entering a - # code block, indicated by (-1, n). - self.last_line = -1 - elif event == 'line': - # Record an executed line. - if self.cur_file_data is not None: - if self.arcs: - #print "lin", self.last_line, frame.f_lineno - self.cur_file_data[(self.last_line, frame.f_lineno)] = None - else: - #print "lin", frame.f_lineno - self.cur_file_data[frame.f_lineno] = None - self.last_line = frame.f_lineno - elif event == 'return': - if self.arcs and self.cur_file_data: - first = frame.f_code.co_firstlineno - self.cur_file_data[(self.last_line, -first)] = None - # Leaving this function, pop the filename stack. - self.cur_file_data, self.last_line = self.data_stack.pop() - elif event == 'exception': - #print "exc", self.last_line, frame.f_lineno - self.last_exc_back = frame.f_back - self.last_exc_firstlineno = frame.f_code.co_firstlineno - return self._trace - - def _profile(self, frame, event, func): - """The profile function passed to sys.settrace.""" - - if not frame.f_code.co_filename.endswith('pyx'): - return self._profile - - #print("profile event: %s %r @%d" % ( - # event, frame.f_code.co_filename, frame.f_lineno)) - if self.last_exc_back: - if frame == self.last_exc_back: - # Someone forgot a return event. - if self.arcs and self.cur_file_data: - pair = (self.last_line, -self.last_exc_firstlineno) - self.cur_file_data[pair] = None - self.cur_file_data, self.last_line = self.data_stack.pop() - self.last_exc_back = None - - elif event == 'call': - # Entering a new function context. Decide if we should trace - # in this file. - self.data_stack.append((self.cur_file_data, self.last_line)) - filename = frame.f_code.co_filename - tracename = self.should_trace_cache.get(filename) - if tracename is None: - tracename = self.should_trace(filename, frame) - self.should_trace_cache[filename] = tracename - #print("called, stack is %d deep, tracename is %r" % ( - # len(self.data_stack), tracename)) - if tracename: - if tracename not in self.data: - self.data[tracename] = {} - self.cur_file_data = self.data[tracename] - else: - self.cur_file_data = None - # Set the last_line to -1 because the next arc will be entering a - # code block, indicated by (-1, n). - self.last_line = -1 - - # Record an executed line. - if self.cur_file_data is not None: - if self.arcs: - #print("lin", self.last_line, frame.f_lineno) - self.cur_file_data[(self.last_line, frame.f_lineno)] = None - else: - #print("lin", frame.f_lineno) - self.cur_file_data[frame.f_lineno] = None - #self.last_line = frame.f_lineno - - # Record an executed line. - if self.cur_file_data is not None: - if self.arcs: - #print("lin", self.last_line, frame.f_lineno) - self.cur_file_data[(self.last_line, frame.f_lineno)] = None - else: - #print("lin", frame.f_lineno) - self.cur_file_data[frame.f_lineno] = None - self.last_line = frame.f_lineno - - elif event == 'return': - if self.arcs and self.cur_file_data: - first = frame.f_code.co_firstlineno - self.cur_file_data[(self.last_line, -first)] = None - # Leaving this function, pop the filename stack. - self.cur_file_data, self.last_line = self.data_stack.pop() - #print("returned, stack is %d deep" % (len(self.data_stack))) - - return self._profile - - def start(self): - """Start this Tracer. - - Return a Python function suitable for use with sys.settrace(). - - """ - sys.settrace(self._trace) - sys.setprofile(self._profile) - return self._trace - - def stop(self): - """Stop this Tracer.""" - sys.settrace(None) - sys.setprofile(None) - - def get_stats(self): - """Return a dictionary of statistics, or None.""" - return None - - -class Collector(object): - """Collects trace data. - - Creates a Tracer object for each thread, since they track stack - information. Each Tracer points to the same shared data, contributing - traced data points. - - When the Collector is started, it creates a Tracer for the current thread, - and installs a function to create Tracers for each new thread started. - When the Collector is stopped, all active Tracers are stopped. - - Threads started while the Collector is stopped will never have Tracers - associated with them. - - """ - - # The stack of active Collectors. Collectors are added here when started, - # and popped when stopped. Collectors on the stack are paused when not - # the top, and resumed when they become the top again. - _collectors = [] - - def __init__(self, should_trace, timid, branch): - """Create a collector. - - `should_trace` is a function, taking a filename, and returning a - canonicalized filename, or False depending on whether the file should - be traced or not. - - If `timid` is true, then a slower simpler trace function will be - used. This is important for some environments where manipulation of - tracing functions make the faster more sophisticated trace function not - operate properly. - - If `branch` is true, then branches will be measured. This involves - collecting data on which statements followed each other (arcs). Use - `get_arc_data` to get the arc data. - - """ - self.should_trace = should_trace - self.branch = branch - self.reset() - - if timid: - # Being timid: use the simple Python trace function. - self._trace_class = PyTracer - else: - # Being fast: use the C Tracer if it is available, else the Python - # trace function. - self._trace_class = Tracer or PyTracer - - def __repr__(self): - return "" % id(self) - - def tracer_name(self): - """Return the class name of the tracer we're using.""" - return self._trace_class.__name__ - - def reset(self): - """Clear collected data, and prepare to collect more.""" - # A dictionary mapping filenames to dicts with linenumber keys, - # or mapping filenames to dicts with linenumber pairs as keys. - self.data = {} - - # A cache of the results from should_trace, the decision about whether - # to trace execution in a file. A dict of filename to (filename or - # False). - self.should_trace_cache = {} - - # Our active Tracers. - self.tracers = [] - - def _start_tracer(self): - """Start a new Tracer object, and store it in self.tracers.""" - tracer = self._trace_class() - tracer.data = self.data - tracer.arcs = self.branch - tracer.should_trace = self.should_trace - tracer.should_trace_cache = self.should_trace_cache - fn = tracer.start() - self.tracers.append(tracer) - return fn - - # The trace function has to be set individually on each thread before - # execution begins. Ironically, the only support the threading module has - # for running code before the thread main is the tracing function. So we - # install this as a trace function, and the first time it's called, it does - # the real trace installation. - - def _installation_trace(self, frame_unused, event_unused, arg_unused): - """Called on new threads, installs the real tracer.""" - # Remove ourselves as the trace function - sys.settrace(None) - # Install the real tracer. - fn = self._start_tracer() - # Invoke the real trace function with the current event, to be sure - # not to lose an event. - if fn: - fn = fn(frame_unused, event_unused, arg_unused) - # Return the new trace function to continue tracing in this scope. - return fn - - def start(self): - """Start collecting trace information.""" - if self._collectors: - self._collectors[-1].pause() - self._collectors.append(self) - #print >>sys.stderr, "Started: %r" % self._collectors - # Install the tracer on this thread. - self._start_tracer() - # Install our installation tracer in threading, to jump start other - # threads. - threading.settrace(self._installation_trace) - - def stop(self): - """Stop collecting trace information.""" - #print >>sys.stderr, "Stopping: %r" % self._collectors - assert self._collectors - assert self._collectors[-1] is self - - self.pause() - self.tracers = [] - - # Remove this Collector from the stack, and resume the one underneath - # (if any). - self._collectors.pop() - if self._collectors: - self._collectors[-1].resume() - - def pause(self): - """Pause tracing, but be prepared to `resume`.""" - for tracer in self.tracers: - tracer.stop() - stats = tracer.get_stats() - if stats: - print("\nCoverage.py tracer stats:") - for k in sorted(stats.keys()): - print("%16s: %s" % (k, stats[k])) - threading.settrace(None) - - def resume(self): - """Resume tracing after a `pause`.""" - for tracer in self.tracers: - tracer.start() - threading.settrace(self._installation_trace) - - def get_line_data(self): - """Return the line data collected. - - Data is { filename: { lineno: None, ...}, ...} - - """ - if self.branch: - # If we were measuring branches, then we have to re-build the dict - # to show line data. - line_data = {} - for f, arcs in self.data.items(): - line_data[f] = ldf = {} - for l1, _ in list(arcs.keys()): - if l1: - ldf[l1] = None - return line_data - else: - return self.data - - def get_arc_data(self): - """Return the arc data collected. - - Data is { filename: { (l1, l2): None, ...}, ...} - - Note that no data is collected or returned if the Collector wasn't - created with `branch` true. - - """ - if self.branch: - return self.data - else: - return {} diff --git a/kivy/tests/coverage/config.py b/kivy/tests/coverage/config.py deleted file mode 100644 index 1f6a879fb2..0000000000 --- a/kivy/tests/coverage/config.py +++ /dev/null @@ -1,118 +0,0 @@ -"""Config file for coverage.py""" - -import os -from coverage.backward import configparser # pylint: disable-msg=W0622 - - -class CoverageConfig(object): - """Coverage.py configuration. - - The attributes of this class are the various settings that control the - operation of coverage.py. - - """ - - def __init__(self): - """Initialize the configuration attributes to their defaults.""" - # Defaults for [run] - self.branch = False - self.cover_pylib = False - self.data_file = ".coverage" - self.parallel = False - self.timid = False - self.source = None - - # Defaults for [report] - self.exclude_list = ['(?i)# *pragma[: ]*no *cover'] - self.ignore_errors = False - self.omit = None - self.include = None - self.precision = 0 - - # Defaults for [html] - self.html_dir = "htmlcov" - - # Defaults for [xml] - self.xml_output = "coverage.xml" - - def from_environment(self, env_var): - """Read configuration from the `env_var` environment variable.""" - # Timidity: for nose users, read an environment variable. This is a - # cheap hack, since the rest of the command line arguments aren't - # recognized, but it solves some users' problems. - env = os.environ.get(env_var, '') - if env: - self.timid = ('--timid' in env) - - def from_args(self, **kwargs): - """Read config values from `kwargs`.""" - for k, v in kwargs.items(): - if v is not None: - setattr(self, k, v) - - def from_file(self, *files): - """Read configuration from .rc files. - - Each argument in `files` is a file name to read. - - """ - cp = configparser.RawConfigParser() - cp.read(files) - - # [run] - if cp.has_option('run', 'branch'): - self.branch = cp.getboolean('run', 'branch') - if cp.has_option('run', 'cover_pylib'): - self.cover_pylib = cp.getboolean('run', 'cover_pylib') - if cp.has_option('run', 'data_file'): - self.data_file = cp.get('run', 'data_file') - if cp.has_option('run', 'parallel'): - self.parallel = cp.getboolean('run', 'parallel') - if cp.has_option('run', 'timid'): - self.timid = cp.getboolean('run', 'timid') - if cp.has_option('run', 'source'): - self.source = self.get_list(cp, 'run', 'source') - if cp.has_option('run', 'omit'): - self.omit = self.get_list(cp, 'run', 'omit') - if cp.has_option('run', 'include'): - self.include = self.get_list(cp, 'run', 'include') - - # [report] - if cp.has_option('report', 'exclude_lines'): - # exclude_lines is a list of lines, leave out the blank ones. - exclude_list = cp.get('report', 'exclude_lines') - self.exclude_list = list(filter(None, exclude_list.split('\n'))) - if cp.has_option('report', 'ignore_errors'): - self.ignore_errors = cp.getboolean('report', 'ignore_errors') - if cp.has_option('report', 'omit'): - self.omit = self.get_list(cp, 'report', 'omit') - if cp.has_option('report', 'include'): - self.include = self.get_list(cp, 'report', 'include') - if cp.has_option('report', 'precision'): - self.precision = cp.getint('report', 'precision') - - # [html] - if cp.has_option('html', 'directory'): - self.html_dir = cp.get('html', 'directory') - - # [xml] - if cp.has_option('xml', 'output'): - self.xml_output = cp.get('xml', 'output') - - def get_list(self, cp, section, option): - """Read a list of strings from the ConfigParser `cp`. - - The value of `section` and `option` is treated as a comma- and newline- - separated list of strings. Each value is stripped of whitespace. - - Returns the list of strings. - - """ - value_list = cp.get(section, option) - values = [] - for value_line in value_list.split('\n'): - for value in value_line.split(','): - value = value.strip() - if value: - values.append(value) - return values diff --git a/kivy/tests/coverage/control.py b/kivy/tests/coverage/control.py deleted file mode 100644 index d2c24e117d..0000000000 --- a/kivy/tests/coverage/control.py +++ /dev/null @@ -1,629 +0,0 @@ -"""Core control stuff for Coverage.""" - -import atexit -import os -import random -import socket -import sys - -from coverage.annotate import AnnotateReporter -from coverage.backward import string_class -from coverage.codeunit import code_unit_factory, CodeUnit -from coverage.collector import Collector -from coverage.config import CoverageConfig -from coverage.data import CoverageData -from coverage.files import FileLocator, TreeMatcher, FnmatchMatcher -from coverage.files import find_python_files -from coverage.html import HtmlReporter -from coverage.misc import CoverageException, bool_or_none -from coverage.results import Analysis, Numbers -from coverage.summary import SummaryReporter -from coverage.xmlreport import XmlReporter - -class coverage(object): - """Programmatic access to Coverage. - - To use:: - - from coverage import coverage - - cov = coverage() - cov.start() - #.. blah blah (run your code) blah blah .. - cov.stop() - cov.html_report(directory='covhtml') - - """ - def __init__(self, data_file=None, data_suffix=None, cover_pylib=None, - auto_data=False, timid=None, branch=None, config_file=True, - source=None, omit=None, include=None): - """ - `data_file` is the base name of the data file to use, defaulting to - ".coverage". `data_suffix` is appended (with a dot) to `data_file` to - create the final file name. If `data_suffix` is simply True, then a - suffix is created with the machine and process identity included. - - `cover_pylib` is a boolean determining whether Python code installed - with the Python interpreter is measured. This includes the Python - standard library and any packages installed with the interpreter. - - If `auto_data` is true, then any existing data file will be read when - coverage measurement starts, and data will be saved automatically when - measurement stops. - - If `timid` is true, then a slower and simpler trace function will be - used. This is important for some environments where manipulation of - tracing functions breaks the faster trace function. - - If `branch` is true, then branch coverage will be measured in addition - to the usual statement coverage. - - `config_file` determines what config file to read. If it is a string, - it is the name of the config file to read. If it is True, then a - standard file is read (".coveragerc"). If it is False, then no file is - read. - - `source` is a list of file paths or package names. Only code located - in the trees indicated by the file paths or package names will be - measured. - - `include` and `omit` are lists of filename patterns. Files that match - `include` will be measured, files that match `omit` will not. - - """ - from coverage import __version__ - - # Build our configuration from a number of sources: - # 1: defaults: - self.config = CoverageConfig() - - # 2: from the coveragerc file: - if config_file: - if config_file is True: - config_file = ".coveragerc" - try: - self.config.from_file(config_file) - except ValueError: - _, err, _ = sys.exc_info() - raise CoverageException( - "Couldn't read config file %s: %s" % (config_file, err) - ) - - # 3: from environment variables: - self.config.from_environment('COVERAGE_OPTIONS') - env_data_file = os.environ.get('COVERAGE_FILE') - if env_data_file: - self.config.data_file = env_data_file - - # 4: from constructor arguments: - self.config.from_args( - data_file=data_file, cover_pylib=cover_pylib, timid=timid, - branch=branch, parallel=bool_or_none(data_suffix), - source=source, omit=omit, include=include - ) - - self.auto_data = auto_data - self.atexit_registered = False - - self.exclude_re = "" - self._compile_exclude() - - self.file_locator = FileLocator() - - # The source argument can be directories or package names. - self.source = [] - self.source_pkgs = [] - for src in self.config.source or []: - if os.path.exists(src): - self.source.append(self.file_locator.canonical_filename(src)) - else: - self.source_pkgs.append(src) - - self.omit = self._abs_files(self.config.omit) - self.include = self._abs_files(self.config.include) - - self.collector = Collector( - self._should_trace, timid=self.config.timid, - branch=self.config.branch - ) - - # 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 - # `self.run_suffix` now, and promote it to `self.data_suffix` if we - # find that we are collecting data later. - if data_suffix or self.config.parallel: - if not isinstance(data_suffix, string_class): - # if data_suffix=True, use .machinename.pid.random - data_suffix = True - else: - data_suffix = None - self.data_suffix = None - self.run_suffix = data_suffix - - # Create the data file. We do this at construction time so that the - # data file will be written into the directory where the process - # started rather than wherever the process eventually chdir'd to. - self.data = CoverageData( - basename=self.config.data_file, - collector="coverage v%s" % __version__ - ) - - # The dirs for files considered "installed with the interpreter". - self.pylib_dirs = [] - if not self.config.cover_pylib: - # Look at where some standard modules are located. That's the - # indication for "installed with the interpreter". In some - # environments (virtualenv, for example), these modules may be - # spread across a few locations. Look at all the candidate modules - # we've imported, and take all the different ones. - for m in (atexit, os, random, socket): - if hasattr(m, "__file__"): - m_dir = self._canonical_dir(m.__file__) - if m_dir not in self.pylib_dirs: - self.pylib_dirs.append(m_dir) - - # To avoid tracing the coverage code itself, we skip anything located - # where we are. - self.cover_dir = self._canonical_dir(__file__) - - # The matchers for _should_trace, created when tracing starts. - self.source_match = None - self.pylib_match = self.cover_match = None - self.include_match = self.omit_match = None - - # Only _harvest_data once per measurement cycle. - self._harvested = False - - # Set the reporting precision. - Numbers.set_precision(self.config.precision) - - # When tearing down the coverage object, modules can become None. - # Saving the modules as object attributes avoids problems, but it is - # quite ad-hoc which modules need to be saved and which references - # need to use the object attributes. - self.socket = socket - self.os = os - self.random = random - - def _canonical_dir(self, f): - """Return the canonical directory of the file `f`.""" - return os.path.split(self.file_locator.canonical_filename(f))[0] - - def _source_for_file(self, filename): - """Return the source file for `filename`.""" - if not filename.endswith(".py"): - if filename[-4:-1] == ".py": - filename = filename[:-1] - return filename - - def _should_trace(self, filename, frame): - """Decide whether to trace execution in `filename` - - This function is called from the trace function. As each new file name - is encountered, this function determines whether it is traced or not. - - Returns a canonicalized filename if it should be traced, False if it - should not. - - """ - if os is None: - return False - - if filename.startswith('<'): - # Lots of non-file execution is represented with artificial - # filenames like "", "", or - # "". Don't ever trace these executions, since we - # can't do anything with the data later anyway. - return False - - if filename.endswith(".html"): - # Jinja and maybe other templating systems compile templates into - # Python code, but use the template filename as the filename in - # the compiled code. Of course, those filenames are useless later - # so don't bother collecting. TODO: How should we really separate - # out good file extensions from bad? - return False - - self._check_for_packages() - - # Compiled Python files have two filenames: frame.f_code.co_filename is - # the filename at the time the .pyc was compiled. The second name - # is __file__, which is where the .pyc was actually loaded from. Since - # .pyc files can be moved after compilation (for example, by being - # installed), we look for __file__ in the frame and prefer it to the - # co_filename value. - dunder_file = frame.f_globals.get('__file__') - if dunder_file: - filename = self._source_for_file(dunder_file) - canonical = self.file_locator.canonical_filename(filename) - - # If the user specified source, then that's authoritative about what to - # measure. If they didn't, then we have to exclude the stdlib and - # coverage.py directories. - if self.source_match: - if not self.source_match.match(canonical): - return False - else: - # If we aren't supposed to trace installed code, then check if this - # is near the Python standard library and skip it if so. - if self.pylib_match and self.pylib_match.match(canonical): - return False - - # We exclude the coverage code itself, since a little of it will be - # measured otherwise. - if self.cover_match and self.cover_match.match(canonical): - return False - - # Check the file against the include and omit patterns. - if self.include_match and not self.include_match.match(canonical): - return False - if self.omit_match and self.omit_match.match(canonical): - return False - - return canonical - - # To log what should_trace returns, change this to "if 1:" - if 0: - _real_should_trace = _should_trace - def _should_trace(self, filename, frame): # pylint: disable-msg=E0102 - """A logging decorator around the real _should_trace function.""" - ret = self._real_should_trace(filename, frame) - print("should_trace: %r -> %r" % (filename, ret)) - return ret - - def _warn(self, msg): - """Use `msg` as a warning.""" - sys.stderr.write("Coverage.py warning: " + msg + "\n") - - def _abs_files(self, files): - """Return a list of absolute file names for the names in `files`.""" - files = files or [] - return [self.file_locator.abs_file(f) for f in files] - - def _check_for_packages(self): - """Update the source_match matcher with latest imported packages.""" - # Our self.source_pkgs attribute is a list of package names we want to - # measure. Each time through here, we see if we've imported any of - # them yet. If so, we add its file to source_match, and we don't have - # to look for that package any more. - if self.source_pkgs: - found = [] - for pkg in self.source_pkgs: - try: - mod = sys.modules[pkg] - except KeyError: - continue - - found.append(pkg) - - try: - pkg_file = mod.__file__ - except AttributeError: - self._warn("Module %s has no python source." % pkg) - else: - d, f = os.path.split(pkg_file) - if f.startswith('__init__.'): - # This is actually a package, return the directory. - pkg_file = d - else: - pkg_file = self._source_for_file(pkg_file) - pkg_file = self.file_locator.canonical_filename(pkg_file) - self.source.append(pkg_file) - self.source_match.add(pkg_file) - - for pkg in found: - self.source_pkgs.remove(pkg) - - def use_cache(self, usecache): - """Control the use of a data file (incorrectly called a cache). - - `usecache` is true or false, whether to read and write data on disk. - - """ - self.data.usefile(usecache) - - def load(self): - """Load previously-collected coverage data from the data file.""" - self.collector.reset() - self.data.read() - - def start(self): - """Start measuring code coverage.""" - if self.run_suffix: - # Calling start() means we're running code, so use the run_suffix - # as the data_suffix when we eventually save the data. - self.data_suffix = self.run_suffix - if self.auto_data: - self.load() - # Save coverage data when Python exits. - if not self.atexit_registered: - atexit.register(self.save) - self.atexit_registered = True - - # Create the matchers we need for _should_trace - if self.source or self.source_pkgs: - self.source_match = TreeMatcher(self.source) - else: - if self.cover_dir: - self.cover_match = TreeMatcher([self.cover_dir]) - if self.pylib_dirs: - self.pylib_match = TreeMatcher(self.pylib_dirs) - if self.include: - self.include_match = FnmatchMatcher(self.include) - if self.omit: - self.omit_match = FnmatchMatcher(self.omit) - - self._harvested = False - self.collector.start() - - def stop(self): - """Stop measuring code coverage.""" - self.collector.stop() - self._harvest_data() - - def erase(self): - """Erase previously-collected coverage data. - - This removes the in-memory data collected in this session as well as - discarding the data file. - - """ - self.collector.reset() - self.data.erase() - - def clear_exclude(self): - """Clear the exclude list.""" - self.config.exclude_list = [] - self.exclude_re = "" - - def exclude(self, regex): - """Exclude source lines from execution consideration. - - `regex` is a regular expression. Lines matching this expression are - not considered executable when reporting code coverage. A list of - regexes is maintained; this function adds a new regex to the list. - Matching any of the regexes excludes a source line. - - """ - self.config.exclude_list.append(regex) - self._compile_exclude() - - def _compile_exclude(self): - """Build the internal usable form of the exclude list.""" - self.exclude_re = "(" + ")|(".join(self.config.exclude_list) + ")" - - def get_exclude_list(self): - """Return the list of excluded regex patterns.""" - return self.config.exclude_list - - def save(self): - """Save the collected coverage data to the data file.""" - data_suffix = self.data_suffix - if data_suffix is True: - # If data_suffix was a simple true value, then make a suffix with - # plenty of distinguishing information. We do this here in - # `save()` at the last minute so that the pid will be correct even - # if the process forks. - data_suffix = "%s.%s.%06d" % ( - self.socket.gethostname(), self.os.getpid(), - self.random.randint(0, 99999) - ) - - self._harvest_data() - self.data.write(suffix=data_suffix) - - def combine(self): - """Combine together a number of similarly-named coverage data files. - - All coverage data files whose name starts with `data_file` (from the - coverage() constructor) will be read, and combined together into the - current measurements. - - """ - self.data.combine_parallel_data() - - def _harvest_data(self): - """Get the collected data and reset the collector. - - Also warn about various problems collecting data. - - """ - if not self._harvested: - self.data.add_line_data(self.collector.get_line_data()) - self.data.add_arc_data(self.collector.get_arc_data()) - self.collector.reset() - - # If there are still entries in the source_pkgs list, then we never - # encountered those packages. - for pkg in self.source_pkgs: - self._warn("Source module %s was never encountered." % pkg) - - # Find out if we got any data. - summary = self.data.summary() - if not summary: - self._warn("No data was collected.") - - # Find files that were never executed at all. - for src in self.source: - for py_file in find_python_files(src): - self.data.touch_file(py_file) - - self._harvested = True - - # Backward compatibility with version 1. - def analysis(self, morf): - """Like `analysis2` but doesn't return excluded line numbers.""" - f, s, _, m, mf = self.analysis2(morf) - return f, s, m, mf - - def analysis2(self, morf): - """Analyze a module. - - `morf` is a module or a filename. It will be analyzed to determine - its coverage statistics. The return value is a 5-tuple: - - * The filename for the module. - * A list of line numbers of executable statements. - * A list of line numbers of excluded statements. - * A list of line numbers of statements not run (missing from - execution). - * A readable formatted string of the missing line numbers. - - The analysis uses the source file itself and the current measured - coverage data. - - """ - analysis = self._analyze(morf) - return ( - analysis.filename, analysis.statements, analysis.excluded, - analysis.missing, analysis.missing_formatted() - ) - - def _analyze(self, it): - """Analyze a single morf or code unit. - - Returns an `Analysis` object. - - """ - if not isinstance(it, CodeUnit): - it = code_unit_factory(it, self.file_locator)[0] - - return Analysis(self, it) - - def report(self, morfs=None, show_missing=True, ignore_errors=None, - file=None, # pylint: disable-msg=W0622 - omit=None, include=None - ): - """Write a summary report to `file`. - - 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. - - """ - self.config.from_args( - ignore_errors=ignore_errors, omit=omit, include=include - ) - reporter = SummaryReporter( - self, show_missing, self.config.ignore_errors - ) - reporter.report(morfs, outfile=file, config=self.config) - - def annotate(self, morfs=None, directory=None, ignore_errors=None, - omit=None, include=None): - """Annotate a list of modules. - - Each module in `morfs` is annotated. The source is written to a new - file, named with a ",cover" suffix, with each line prefixed with a - marker to indicate the coverage of the line. Covered lines have ">", - excluded lines have "-", and missing lines have "!". - - See `coverage.report()` for other arguments. - - """ - self.config.from_args( - ignore_errors=ignore_errors, omit=omit, include=include - ) - reporter = AnnotateReporter(self, self.config.ignore_errors) - reporter.report(morfs, config=self.config, directory=directory) - - def html_report(self, morfs=None, directory=None, ignore_errors=None, - omit=None, include=None): - """Generate an HTML report. - - See `coverage.report()` for other arguments. - - """ - self.config.from_args( - ignore_errors=ignore_errors, omit=omit, include=include, - html_dir=directory, - ) - reporter = HtmlReporter(self, self.config.ignore_errors) - reporter.report(morfs, config=self.config) - - def xml_report(self, morfs=None, outfile=None, ignore_errors=None, - omit=None, include=None): - """Generate an XML report of coverage results. - - The report is compatible with Cobertura reports. - - Each module in `morfs` is included in the report. `outfile` is the - path to write the file to, "-" will write to stdout. - - See `coverage.report()` for other arguments. - - """ - self.config.from_args( - ignore_errors=ignore_errors, omit=omit, include=include, - xml_output=outfile, - ) - file_to_close = None - if self.config.xml_output: - if self.config.xml_output == '-': - outfile = sys.stdout - else: - outfile = open(self.config.xml_output, "w") - file_to_close = outfile - try: - reporter = XmlReporter(self, self.config.ignore_errors) - reporter.report(morfs, outfile=outfile, config=self.config) - finally: - if file_to_close: - file_to_close.close() - - def sysinfo(self): - """Return a list of (key, value) pairs showing internal information.""" - - import coverage as covmod - import platform - import re - - info = [ - ('version', covmod.__version__), - ('coverage', covmod.__file__), - ('cover_dir', self.cover_dir), - ('pylib_dirs', self.pylib_dirs), - ('tracer', self.collector.tracer_name()), - ('data_path', self.data.filename), - ('python', sys.version.replace('\n', '')), - ('platform', platform.platform()), - ('cwd', os.getcwd()), - ('path', sys.path), - ('environment', [ - ("%s = %s" % (k, v)) for k, v in os.environ.items() - if re.search("^COV|^PY", k) - ]), - ] - return info - - -def process_startup(): - """Call this at Python startup to perhaps measure coverage. - - If the environment variable COVERAGE_PROCESS_START is defined, coverage - measurement is started. The value of the variable is the config file - to use. - - There are two ways to configure your Python installation to invoke this - function when Python starts: - - #. Create or append to sitecustomize.py to add these lines:: - - import coverage - coverage.process_startup() - - #. Create a .pth file in your Python installation containing:: - - import coverage; coverage.process_startup() - - """ - cps = os.environ.get("COVERAGE_PROCESS_START") - if cps: - cov = coverage(config_file=cps, auto_data=True) - if os.environ.get("COVERAGE_COVERAGE"): - # Measuring coverage within coverage.py takes yet more trickery. - cov.cover_dir = "Please measure coverage.py!" - cov.start() diff --git a/kivy/tests/coverage/data.py b/kivy/tests/coverage/data.py deleted file mode 100644 index 9c4e64f2f4..0000000000 --- a/kivy/tests/coverage/data.py +++ /dev/null @@ -1,262 +0,0 @@ -"""Coverage data for Coverage.""" - -import os - -from coverage.backward import pickle, sorted # pylint: disable-msg=W0622 - - -class CoverageData(object): - """Manages collected coverage data, including file storage. - - The data file format is a pickled dict, with these keys: - - * collector: a string identifying the collecting software - - * lines: a dict mapping filenames to sorted lists of line numbers - executed: - { 'file1': [17,23,45], 'file2': [1,2,3], ... } - - * arcs: a dict mapping filenames to sorted lists of line number pairs: - { 'file1': [(17,23), (17,25), (25,26)], ... } - - """ - - def __init__(self, basename=None, collector=None): - """Create a CoverageData. - - `basename` is the name of the file to use for storing data. - - `collector` is a string describing the coverage measurement software. - - """ - self.collector = collector or 'unknown' - - self.use_file = True - - # Construct the filename that will be used for data file storage, if we - # ever do any file storage. - self.filename = basename or ".coverage" - self.filename = os.path.abspath(self.filename) - - # A map from canonical Python source file name to a dictionary in - # which there's an entry for each line number that has been - # executed: - # - # { - # 'filename1.py': { 12: None, 47: None, ... }, - # ... - # } - # - self.lines = {} - - # A map from canonical Python source file name to a dictionary with an - # entry for each pair of line numbers forming an arc: - # - # { - # 'filename1.py': { (12,14): None, (47,48): None, ... }, - # ... - # } - # - self.arcs = {} - - self.os = os - self.sorted = sorted - self.pickle = pickle - - def usefile(self, use_file=True): - """Set whether or not to use a disk file for data.""" - self.use_file = use_file - - def read(self): - """Read coverage data from the coverage data file (if it exists).""" - if self.use_file: - self.lines, self.arcs = self._read_file(self.filename) - else: - self.lines, self.arcs = {}, {} - - def write(self, suffix=None): - """Write the collected coverage data to a file. - - `suffix` is a suffix to append to the base file name. This can be used - for multiple or parallel execution, so that many coverage data files - can exist simultaneously. A dot will be used to join the base name and - the suffix. - - """ - if self.use_file: - filename = self.filename - if suffix: - filename += "." + suffix - self.write_file(filename) - - def erase(self): - """Erase the data, both in this object, and from its file storage.""" - if self.use_file: - if self.filename and os.path.exists(self.filename): - os.remove(self.filename) - self.lines = {} - self.arcs = {} - - def line_data(self): - """Return the map from filenames to lists of line numbers executed.""" - return dict( - [(f, self.sorted(lmap.keys())) for f, lmap in self.lines.items()] - ) - - def arc_data(self): - """Return the map from filenames to lists of line number pairs.""" - return dict( - [(f, self.sorted(amap.keys())) for f, amap in self.arcs.items()] - ) - - def write_file(self, filename): - """Write the coverage data to `filename`.""" - - # Create the file data. - data = {} - - data['lines'] = self.line_data() - arcs = self.arc_data() - if arcs: - data['arcs'] = arcs - - if self.collector: - data['collector'] = self.collector - - # Write the pickle to the file. - fdata = open(filename, 'wb') - try: - self.pickle.dump(data, fdata, 2) - finally: - fdata.close() - - def read_file(self, filename): - """Read the coverage data from `filename`.""" - self.lines, self.arcs = self._read_file(filename) - - def raw_data(self, filename): - """Return the raw pickled data from `filename`.""" - fdata = open(filename, 'rb') - try: - data = pickle.load(fdata) - finally: - fdata.close() - return data - - def _read_file(self, filename): - """Return the stored coverage data from the given file. - - Returns two values, suitable for assigning to `self.lines` and - `self.arcs`. - - """ - lines = {} - arcs = {} - try: - data = self.raw_data(filename) - if isinstance(data, dict): - # Unpack the 'lines' item. - lines = dict([ - (f, dict.fromkeys(linenos, None)) - for f, linenos in data.get('lines', {}).items() - ]) - # Unpack the 'arcs' item. - arcs = dict([ - (f, dict.fromkeys(arcpairs, None)) - for f, arcpairs in data.get('arcs', {}).items() - ]) - except Exception: - pass - return lines, arcs - - def combine_parallel_data(self): - """Combine a number of data files together. - - Treat `self.filename` as a file prefix, and combine the data from all - of the data files starting with that prefix plus a dot. - - """ - data_dir, local = os.path.split(self.filename) - localdot = local + '.' - for f in os.listdir(data_dir or '.'): - if f.startswith(localdot): - full_path = os.path.join(data_dir, f) - new_lines, new_arcs = self._read_file(full_path) - for filename, file_data in new_lines.items(): - self.lines.setdefault(filename, {}).update(file_data) - for filename, file_data in new_arcs.items(): - self.arcs.setdefault(filename, {}).update(file_data) - if f != local: - os.remove(full_path) - - def add_line_data(self, line_data): - """Add executed line data. - - `line_data` is { filename: { lineno: None, ... }, ...} - - """ - for filename, linenos in line_data.items(): - self.lines.setdefault(filename, {}).update(linenos) - - def add_arc_data(self, arc_data): - """Add measured arc data. - - `arc_data` is { filename: { (l1,l2): None, ... }, ...} - - """ - for filename, arcs in arc_data.items(): - self.arcs.setdefault(filename, {}).update(arcs) - - def touch_file(self, filename): - """Ensure that `filename` appears in the data, empty if needed.""" - self.lines.setdefault(filename, {}) - - def measured_files(self): - """A list of all files that had been measured.""" - return list(self.lines.keys()) - - def executed_lines(self, filename): - """A map containing all the line numbers executed in `filename`. - - If `filename` hasn't been collected at all (because it wasn't executed) - then return an empty map. - - """ - return self.lines.get(filename) or {} - - def executed_arcs(self, filename): - """A map containing all the arcs executed in `filename`.""" - return self.arcs.get(filename) or {} - - def summary(self, fullpath=False): - """Return a dict summarizing the coverage data. - - Keys are based on the filenames, and values are the number of executed - lines. If `fullpath` is true, then the keys are the full pathnames of - the files, otherwise they are the basenames of the files. - - """ - summ = {} - if fullpath: - filename_fn = lambda f: f - else: - filename_fn = self.os.path.basename - for filename, lines in self.lines.items(): - summ[filename_fn(filename)] = len(lines) - return summ - - def has_arcs(self): - """Does this data have arcs?""" - return bool(self.arcs) - - -if __name__ == '__main__': - # Ad-hoc: show the raw data in a data file. - import pprint - import sys - covdata = CoverageData() - if sys.argv[1:]: - fname = sys.argv[1] - else: - fname = covdata.filename - pprint.pprint(covdata.raw_data(fname)) diff --git a/kivy/tests/coverage/execfile.py b/kivy/tests/coverage/execfile.py deleted file mode 100644 index dd04a0441f..0000000000 --- a/kivy/tests/coverage/execfile.py +++ /dev/null @@ -1,74 +0,0 @@ -"""Execute files of Python code.""" - -import imp -import os -import sys - -from coverage.backward import exec_code_object -from coverage.misc import NoSource, ExceptionDuringRun - - -try: - # In Py 2.x, the builtins were in __builtin__ - BUILTINS = sys.modules['__builtin__'] -except KeyError: - # In Py 3.x, they're in builtins - BUILTINS = sys.modules['builtins'] - - -def run_python_file(filename, args): - """Run a python file as if it were the main program on the command line. - - `filename` is the path to the file to execute, it need not be a .py file. - `args` is the argument array to present as sys.argv, including the first - element representing the file being executed. - - """ - # Create a module to serve as __main__ - old_main_mod = sys.modules['__main__'] - main_mod = imp.new_module('__main__') - sys.modules['__main__'] = main_mod - main_mod.__file__ = filename - main_mod.__builtins__ = BUILTINS - - # Set sys.argv and the first path element properly. - old_argv = sys.argv - old_path0 = sys.path[0] - sys.argv = args - sys.path[0] = os.path.dirname(filename) - - try: - # Open the source file. - try: - source = open(filename, 'rU').read() - except IOError: - raise NoSource("No file to run: %r" % filename) - - # We have the source. `compile` still needs the last line to be clean, - # so make sure it is, then compile a code object from it. - if source[-1] != '\n': - source += '\n' - code = compile(source, filename, "exec") - - # Execute the source file. - try: - exec_code_object(code, main_mod.__dict__) - except SystemExit: - # The user called sys.exit(). Just pass it along to the upper - # layers, where it will be handled. - raise - except: - # Something went wrong while executing the user code. - # Get the exc_info, and pack them into an exception that we can - # throw up to the outer loop. We peel two layers off the traceback - # so that the coverage.py code doesn't appear in the final printed - # traceback. - typ, err, tb = sys.exc_info() - raise ExceptionDuringRun(typ, err, tb.tb_next.tb_next) - finally: - # Restore the old __main__ - sys.modules['__main__'] = old_main_mod - - # Restore the old argv and path - sys.argv = old_argv - sys.path[0] = old_path0 diff --git a/kivy/tests/coverage/files.py b/kivy/tests/coverage/files.py deleted file mode 100644 index 5a10db720f..0000000000 --- a/kivy/tests/coverage/files.py +++ /dev/null @@ -1,141 +0,0 @@ -"""File wrangling.""" - -import fnmatch -import os -import sys - -class FileLocator(object): - """Understand how filenames work.""" - - def __init__(self): - # The absolute path to our current directory. - self.relative_dir = self.abs_file(os.curdir) + os.sep - - # Cache of results of calling the canonical_filename() method, to - # avoid duplicating work. - self.canonical_filename_cache = {} - - def abs_file(self, filename): - """Return the absolute normalized form of `filename`.""" - return os.path.normcase(os.path.abspath(os.path.realpath(filename))) - - def relative_filename(self, filename): - """Return the relative form of `filename`. - - The filename will be relative to the current directory when the - `FileLocator` was constructed. - - """ - if filename.startswith(self.relative_dir): - filename = filename.replace(self.relative_dir, "") - return filename - - def canonical_filename(self, filename): - """Return a canonical filename for `filename`. - - An absolute path with no redundant components and normalized case. - - """ - if filename not in self.canonical_filename_cache: - f = filename - if os.path.isabs(f) and not os.path.exists(f): - if self.get_zip_data(f) is None: - f = os.path.basename(f) - if not os.path.isabs(f): - for path in [os.curdir] + sys.path: - if path is None: - continue - g = os.path.join(path, f) - if g.endswith('.so'): - if os.path.exists(g[:-3]+'.pyx'): - f = g[:-3]+'.pyx' - break - elif os.path.exists(g[:-3]+'.c'): - f = g[:-3]+'.c' - break - if os.path.exists(g): - f = g - break - cf = self.abs_file(f) - self.canonical_filename_cache[filename] = cf - return self.canonical_filename_cache[filename] - - def get_zip_data(self, filename): - """Get data from `filename` if it is a zip file path. - - Returns the string data read from the zip file, or None if no zip file - could be found or `filename` isn't in it. The data returned will be - an empty string if the file is empty. - - """ - import zipimport - markers = ['.zip'+os.sep, '.egg'+os.sep] - for marker in markers: - if marker in filename: - parts = filename.split(marker) - try: - zi = zipimport.zipimporter(parts[0]+marker[:-1]) - except zipimport.ZipImportError: - continue - try: - data = zi.get_data(parts[1]) - except IOError: - continue - if sys.version_info >= (3, 0): - data = data.decode('utf8') # TODO: How to do this properly? - return data - return None - - -class TreeMatcher(object): - """A matcher for files in a tree.""" - def __init__(self, directories): - self.dirs = directories[:] - - def __repr__(self): - return "" % self.dirs - - def add(self, directory): - """Add another directory to the list we match for.""" - self.dirs.append(directory) - - def match(self, fpath): - """Does `fpath` indicate a file in one of our trees?""" - for d in self.dirs: - if fpath.startswith(d): - if fpath == d: - # This is the same file! - return True - if fpath[len(d)] == os.sep: - # This is a file in the directory - return True - return False - - -class FnmatchMatcher(object): - """A matcher for files by filename pattern.""" - def __init__(self, pats): - self.pats = pats[:] - - def __repr__(self): - return "" % self.pats - - def match(self, fpath): - """Does `fpath` match one of our filename patterns?""" - for pat in self.pats: - if fnmatch.fnmatch(fpath, pat): - return True - return False - - -def find_python_files(dirname): - """Yield all of the importable Python files in `dirname`, recursively.""" - for dirpath, dirnames, filenames in os.walk(dirname, topdown=True): - if '__init__.py' not in filenames: - # If a directory doesn't have __init__.py, then it isn't - # importable and neither are its files - del dirnames[:] - continue - for filename in filenames: - if fnmatch.fnmatch(filename, "*.py"): - yield os.path.join(dirpath, filename) diff --git a/kivy/tests/coverage/html.py b/kivy/tests/coverage/html.py deleted file mode 100644 index 59f8a76516..0000000000 --- a/kivy/tests/coverage/html.py +++ /dev/null @@ -1,185 +0,0 @@ -"""HTML reporting for Coverage.""" - -import os -import re -import shutil - -from coverage import __url__, __version__ # pylint: disable-msg=W0611 -from coverage.misc import CoverageException -from coverage.phystokens import source_token_lines -from coverage.report import Reporter -from coverage.templite import Templite - -# Disable pylint msg W0612, because a bunch of variables look unused, but -# they're accessed in a Templite context via locals(). -# pylint: disable-msg=W0612 - -def data_filename(fname): - """Return the path to a data file of ours.""" - return os.path.join(os.path.split(__file__)[0], fname) - -def data(fname): - """Return the contents of a data file of ours.""" - return open(data_filename(fname)).read() - - -class HtmlReporter(Reporter): - """HTML reporting.""" - - def __init__(self, coverage, ignore_errors=False): - super(HtmlReporter, self).__init__(coverage, ignore_errors) - self.directory = None - self.source_tmpl = Templite(data("htmlfiles/pyfile.html"), globals()) - - self.files = [] - self.arcs = coverage.data.has_arcs() - - def report(self, morfs, config=None): - """Generate an HTML report for `morfs`. - - `morfs` is a list of modules or filenames. `config` is a - CoverageConfig instance. - - """ - assert config.html_dir, "must provide a directory for html reporting" - - # Process all the files. - self.report_files(self.html_file, morfs, config, config.html_dir) - - if not self.files: - raise CoverageException("No data to report.") - - # Write the index file. - self.index_file() - - # Create the once-per-directory files. - for static in [ - "style.css", "coverage_html.js", - "jquery-1.3.2.min.js", "jquery.tablesorter.min.js" - ]: - shutil.copyfile( - data_filename("htmlfiles/" + static), - os.path.join(self.directory, static) - ) - - def html_file(self, cu, analysis): - """Generate an HTML file for one source file.""" - - source = cu.source_file().read() - - nums = analysis.numbers - - missing_branch_arcs = analysis.missing_branch_arcs() - n_par = 0 # accumulated below. - arcs = self.arcs - - # These classes determine which lines are highlighted by default. - c_run = "run hide_run" - c_exc = "exc" - c_mis = "mis" - c_par = "par " + c_run - - lines = [] - - for lineno, line in enumerate(source_token_lines(source)): - lineno += 1 # 1-based line numbers. - # Figure out how to mark this line. - line_class = [] - annotate_html = "" - annotate_title = "" - if lineno in analysis.statements: - line_class.append("stm") - if lineno in analysis.excluded: - line_class.append(c_exc) - elif lineno in analysis.missing: - line_class.append(c_mis) - elif self.arcs and lineno in missing_branch_arcs: - line_class.append(c_par) - n_par += 1 - annlines = [] - for b in missing_branch_arcs[lineno]: - if b < 0: - annlines.append("exit") - else: - annlines.append(str(b)) - annotate_html = "   ".join(annlines) - if len(annlines) > 1: - annotate_title = "no jumps to these line numbers" - elif len(annlines) == 1: - annotate_title = "no jump to this line number" - elif lineno in analysis.statements: - line_class.append(c_run) - - # Build the HTML for the line - html = [] - for tok_type, tok_text in line: - if tok_type == "ws": - html.append(escape(tok_text)) - else: - tok_html = escape(tok_text) or ' ' - html.append( - "%s" % (tok_type, tok_html) - ) - - lines.append({ - 'html': ''.join(html), - 'number': lineno, - 'class': ' '.join(line_class) or "pln", - 'annotate': annotate_html, - 'annotate_title': annotate_title, - }) - - # Write the HTML page for this file. - html_filename = cu.flat_rootname() + ".html" - html_path = os.path.join(self.directory, html_filename) - html = spaceless(self.source_tmpl.render(locals())) - fhtml = open(html_path, 'w') - fhtml.write(html) - fhtml.close() - - # Save this file's information for the index file. - self.files.append({ - 'nums': nums, - 'par': n_par, - 'html_filename': html_filename, - 'cu': cu, - }) - - def index_file(self): - """Write the index.html file for this report.""" - index_tmpl = Templite(data("htmlfiles/index.html"), globals()) - - files = self.files - arcs = self.arcs - - totals = sum([f['nums'] for f in files]) - - fhtml = open(os.path.join(self.directory, "index.html"), "w") - fhtml.write(index_tmpl.render(locals())) - fhtml.close() - - -# Helpers for templates and generating HTML - -def escape(t): - """HTML-escape the text in `t`.""" - return (t - # Convert HTML special chars into HTML entities. - .replace("&", "&").replace("<", "<").replace(">", ">") - .replace("'", "'").replace('"', """) - # Convert runs of spaces: "......" -> " . . ." - .replace(" ", "  ") - # To deal with odd-length runs, convert the final pair of spaces - # so that "....." -> " .  ." - .replace(" ", "  ") - ) - -def spaceless(html): - """Squeeze out some annoying extra space from an HTML string. - - Nicely-formatted templates mean lots of extra space in the result. - Get rid of some. - - """ - html = re.sub(">\s+

\n

-1) { - cookies = document.cookie.split(";"); - for (var i=0; i < cookies.length; i++) { - parts = cookies[i].split("=") - - if ($.trim(parts[0]) == cookie_name && parts[1]) { - sort_list = eval("[[" + parts[1] + "]]"); - break; - } - } - } - - // Create a new widget which exists only to save and restore - // the sort order: - $.tablesorter.addWidget({ - id: "persistentSort", - - // Format is called by the widget before displaying: - format: function(table) { - if (table.config.sortList.length == 0 && sort_list.length > 0) { - // This table hasn't been sorted before - we'll use - // our stored settings: - $(table).trigger('sorton', [sort_list]); - } - else { - // This is not the first load - something has - // already defined sorting so we'll just update - // our stored value to match: - sort_list = table.config.sortList; - } - } - }); - - // Configure our tablesorter to handle the variable number of - // columns produced depending on report options: - var headers = {}; - var col_count = $("table.index > thead > tr > th").length; - - headers[0] = { sorter: 'text' }; - for (var i = 1; i < col_count-1; i++) { - headers[i] = { sorter: 'digit' }; - } - headers[col_count-1] = { sorter: 'percent' }; - - // Enable the table sorter: - $("table.index").tablesorter({ - widgets: ['persistentSort'], - headers: headers - }); - - // Watch for page unload events so we can save the final sort settings: - $(window).unload(function() { - document.cookie = cookie_name + "=" + sort_list.toString() + "; path=/" - }); -} - -// -- pyfile stuff -- - -function pyfile_ready($) { - // If we're directed to a particular line number, highlight the line. - var frag = location.hash; - if (frag.length > 2 && frag[1] == 'n') { - $(frag).addClass('highlight'); - } -} - -function toggle_lines(btn, cls) { - btn = $(btn); - var hide = "hide_"+cls; - if (btn.hasClass(hide)) { - $("#source ."+cls).removeClass(hide); - btn.removeClass(hide); - } - else { - $("#source ."+cls).addClass(hide); - btn.addClass(hide); - } -} diff --git a/kivy/tests/coverage/htmlfiles/index.html b/kivy/tests/coverage/htmlfiles/index.html deleted file mode 100644 index bec2584f27..0000000000 --- a/kivy/tests/coverage/htmlfiles/index.html +++ /dev/null @@ -1,81 +0,0 @@ - - - - - Coverage report - - - - - - - - -

- -
- - - {# The title='' attr doesn't work in Safari. #} - - - - - - {% if arcs %} - - - {% endif %} - - - - {# HTML syntax requires thead, tfoot, tbody #} - - - - - - - {% if arcs %} - - - {% endif %} - - - - - {% for file in files %} - - - - - - {% if arcs %} - - - {% endif %} - - - {% endfor %} - -
Modulestatementsmissingexcludedbranchespartialcoverage
Total{{totals.n_statements}}{{totals.n_missing}}{{totals.n_excluded}}{{totals.n_branches}}{{totals.n_missing_branches}}{{totals.pc_covered_str}}%
{{file.cu.name}}{{file.nums.n_statements}}{{file.nums.n_missing}}{{file.nums.n_excluded}}{{file.nums.n_branches}}{{file.nums.n_missing_branches}}{{file.nums.pc_covered_str}}%
-
- - - - - diff --git a/kivy/tests/coverage/htmlfiles/jquery-1.3.2.min.js b/kivy/tests/coverage/htmlfiles/jquery-1.3.2.min.js deleted file mode 100644 index b1ae21d8b2..0000000000 --- a/kivy/tests/coverage/htmlfiles/jquery-1.3.2.min.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * jQuery JavaScript Library v1.3.2 - * http://jquery.com/ - * - * Copyright (c) 2009 John Resig - * Dual licensed under the MIT and GPL licenses. - * http://docs.jquery.com/License - * - * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) - * Revision: 6246 - */ -(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("",""]||!O.indexOf("",""]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!O.indexOf("",""]||(!O.indexOf("",""]||!O.indexOf("",""]||!o.support.htmlSerialize&&[1,"div
","
"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}}); -/* - * Sizzle CSS Selector Engine - v0.9.3 - * Copyright 2009, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return UT[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="

";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="
";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("
").append(M.responseText.replace(//g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='
';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/kivy/tests/coverage/htmlfiles/jquery.tablesorter.min.js b/kivy/tests/coverage/htmlfiles/jquery.tablesorter.min.js deleted file mode 100644 index 64c7007129..0000000000 --- a/kivy/tests/coverage/htmlfiles/jquery.tablesorter.min.js +++ /dev/null @@ -1,2 +0,0 @@ - -(function($){$.extend({tablesorter:new function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'.',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}var rows=table.tBodies[0].rows;if(table.tBodies[0].rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;ib)?1:0));};function sortTextDesc(a,b){return((ba)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){$this.trigger("sortStart");var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){var $cell=$(this);var i=this.column;this.order=this.count++%2;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i - - - - {# 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 #} - - Coverage for {{cu.name|escape}}: {{nums.pc_covered_str}}% - - - - - - - - - -
- - - - - -
- {% for line in lines %} -

{{line.number}}

- {% endfor %} -
- {% for line in lines %} -

{% if line.annotate %}{{line.annotate}}{% endif %}{{line.html}} 

- {% endfor %} -
-
- - - - - diff --git a/kivy/tests/coverage/htmlfiles/style.css b/kivy/tests/coverage/htmlfiles/style.css deleted file mode 100644 index 9a06a2b42b..0000000000 --- a/kivy/tests/coverage/htmlfiles/style.css +++ /dev/null @@ -1,230 +0,0 @@ -/* CSS styles for Coverage. */ -/* Page-wide styles */ -html, body, h1, h2, h3, p, td, th { - margin: 0; - padding: 0; - border: 0; - outline: 0; - font-weight: inherit; - font-style: inherit; - font-size: 100%; - font-family: inherit; - vertical-align: baseline; - } - -/* Set baseline grid to 16 pt. */ -body { - font-family: georgia, serif; - font-size: 1em; - } - -html>body { - font-size: 16px; - } - -/* Set base font size to 12/16 */ -p { - font-size: .75em; /* 12/16 */ - line-height: 1.3333em; /* 16/12 */ - } - -table { - border-collapse: collapse; - } - -a.nav { - text-decoration: none; - color: inherit; - } -a.nav:hover { - text-decoration: underline; - color: inherit; - } - -/* Page structure */ -#header { - background: #f8f8f8; - width: 100%; - border-bottom: 1px solid #eee; - } - -#source { - padding: 1em; - font-family: "courier new", monospace; - } - -#indexfile #footer { - margin: 1em 3em; - } - -#pyfile #footer { - margin: 1em 1em; - } - -#footer .content { - padding: 0; - font-size: 85%; - font-family: verdana, sans-serif; - color: #666666; - font-style: italic; - } - -#index { - margin: 1em 0 0 3em; - } - -/* Header styles */ -#header .content { - padding: 1em 3em; - } - -h1 { - font-size: 1.25em; -} - -h2.stats { - margin-top: .5em; - font-size: 1em; -} -.stats span { - border: 1px solid; - padding: .1em .25em; - margin: 0 .1em; - cursor: pointer; - border-color: #999 #ccc #ccc #999; -} -.stats span.hide_run, .stats span.hide_exc, -.stats span.hide_mis, .stats span.hide_par, -.stats span.par.hide_run.hide_par { - border-color: #ccc #999 #999 #ccc; -} -.stats span.par.hide_run { - border-color: #999 #ccc #ccc #999; -} - -/* Source file styles */ -.linenos p { - text-align: right; - margin: 0; - padding: 0 .5em; - color: #999999; - font-family: verdana, sans-serif; - font-size: .625em; /* 10/16 */ - line-height: 1.6em; /* 16/10 */ - } -.linenos p.highlight { - background: #ffdd00; - } -.linenos p a { - text-decoration: none; - color: #999999; - } -.linenos p a:hover { - text-decoration: underline; - color: #999999; - } - -td.text { - width: 100%; - } -.text p { - margin: 0; - padding: 0 0 0 .5em; - border-left: 2px solid #ffffff; - white-space: nowrap; - } - -.text p.mis { - background: #ffdddd; - border-left: 2px solid #ff0000; - } -.text p.run, .text p.run.hide_par { - background: #ddffdd; - border-left: 2px solid #00ff00; - } -.text p.exc { - background: #eeeeee; - border-left: 2px solid #808080; - } -.text p.par, .text p.par.hide_run { - background: #ffffaa; - border-left: 2px solid #eeee99; - } -.text p.hide_run, .text p.hide_exc, .text p.hide_mis, .text p.hide_par, -.text p.hide_run.hide_par { - background: inherit; - } - -.text span.annotate { - font-family: georgia; - font-style: italic; - color: #666; - float: right; - padding-right: .5em; - } -.text p.hide_par span.annotate { - display: none; - } - -/* Syntax coloring */ -.text .com { - color: green; - font-style: italic; - line-height: 1px; - } -.text .key { - font-weight: bold; - line-height: 1px; - } -.text .str { - color: #000080; - } - -/* index styles */ -#index td, #index th { - text-align: right; - width: 5em; - padding: .25em .5em; - border-bottom: 1px solid #eee; - } -#index th { - font-style: italic; - color: #333; - border-bottom: 1px solid #ccc; - cursor: pointer; - } -#index th:hover { - background: #eee; - border-bottom: 1px solid #999; - } -#index td.left, #index th.left { - padding-left: 0; - } -#index td.right, #index th.right { - padding-right: 0; - } -#index th.headerSortDown, #index th.headerSortUp { - border-bottom: 1px solid #000; - } -#index td.name, #index th.name { - text-align: left; - width: auto; - } -#index td.name a { - text-decoration: none; - color: #000; - } -#index td.name a:hover { - text-decoration: underline; - color: #000; - } -#index tr.total { - } -#index tr.total td { - font-weight: bold; - border-top: 1px solid #ccc; - border-bottom: none; - } -#index tr.file:hover { - background: #eeeeee; - } diff --git a/kivy/tests/coverage/misc.py b/kivy/tests/coverage/misc.py deleted file mode 100644 index 124f5e324c..0000000000 --- a/kivy/tests/coverage/misc.py +++ /dev/null @@ -1,85 +0,0 @@ -"""Miscellaneous stuff for Coverage.""" - -def nice_pair(pair): - """Make a nice string representation of a pair of numbers. - - If the numbers are equal, just return the number, otherwise return the pair - with a dash between them, indicating the range. - - """ - start, end = pair - if start == end: - return "%d" % start - else: - return "%d-%d" % (start, end) - - -def format_lines(statements, lines): - """Nicely format a list of line numbers. - - Format a list of line numbers for printing by coalescing groups of lines as - long as the lines represent consecutive statements. This will coalesce - even if there are gaps between statements. - - For example, if `statements` is [1,2,3,4,5,10,11,12,13,14] and - `lines` is [1,2,5,10,11,13,14] then the result will be "1-2, 5-11, 13-14". - - """ - pairs = [] - i = 0 - j = 0 - start = None - while i < len(statements) and j < len(lines): - if statements[i] == lines[j]: - if start is None: - start = lines[j] - end = lines[j] - j += 1 - elif start: - pairs.append((start, end)) - start = None - i += 1 - if start: - pairs.append((start, end)) - ret = ', '.join(map(nice_pair, pairs)) - return ret - - -def expensive(fn): - """A decorator to cache the result of an expensive operation. - - Only applies to methods with no arguments. - - """ - attr = "_cache_" + fn.__name__ - def _wrapped(self): - """Inner fn that checks the cache.""" - if not hasattr(self, attr): - setattr(self, attr, fn(self)) - return getattr(self, attr) - return _wrapped - - -def bool_or_none(b): - """Return bool(b), but preserve None.""" - if b is None: - return None - else: - return bool(b) - - -class CoverageException(Exception): - """An exception specific to Coverage.""" - pass - -class NoSource(CoverageException): - """Used to indicate we couldn't find the source for a module.""" - pass - -class ExceptionDuringRun(CoverageException): - """An exception happened while running customer code. - - Construct it with three arguments, the values from `sys.exc_info`. - - """ - pass diff --git a/kivy/tests/coverage/parser.py b/kivy/tests/coverage/parser.py deleted file mode 100644 index 4fbbf53556..0000000000 --- a/kivy/tests/coverage/parser.py +++ /dev/null @@ -1,838 +0,0 @@ -"""Code parsing for Coverage.""" - -import glob -import opcode -import os -import re -import sys -import token -import tokenize - -from coverage.backward import set, sorted, StringIO # pylint: disable-msg=W0622 -from coverage.bytecode import ByteCodes, CodeObjects -from coverage.misc import nice_pair, CoverageException, NoSource, expensive - - -class CodeParser(object): - """Parse code to find executable lines, excluded lines, etc.""" - - def __init__(self, text=None, filename=None, exclude=None): - """ - Source can be provided as `text`, the text itself, or `filename`, from - which text will be read. Excluded lines are those that match - `exclude`, a regex. - - """ - assert text or filename, "CodeParser needs either text or filename" - self.filename = filename or "" - self.text = text - if not self.text: - try: - sourcef = open(self.filename, 'rU') - self.text = sourcef.read() - sourcef.close() - except IOError: - _, err, _ = sys.exc_info() - raise NoSource( - "No source for code: %r: %s" % (self.filename, err) - ) - self.text = self.text.replace('\r\n', '\n') - - self.exclude = exclude - - self.show_tokens = False - - # The text lines of the parsed code. - self.lines = self.text.split('\n') - - # The line numbers of excluded lines of code. - self.excluded = set() - - # The line numbers of docstring lines. - self.docstrings = set() - - # The line numbers of class definitions. - self.classdefs = set() - - # A dict mapping line numbers to (lo,hi) for multi-line statements. - self.multiline = {} - - # The line numbers that start statements. - self.statement_starts = set() - - # Lazily-created ByteParser - self._byte_parser = None - - def _get_byte_parser(self): - """Create a ByteParser on demand.""" - if not self._byte_parser: - self._byte_parser = \ - ByteParser(text=self.text, filename=self.filename) - return self._byte_parser - byte_parser = property(_get_byte_parser) - - def _raw_parse(self): - """Parse the source to find the interesting facts about its lines. - - A handful of member fields are updated. - - """ - # Find lines which match an exclusion pattern. - if self.exclude: - re_exclude = re.compile(self.exclude) - for i, ltext in enumerate(self.lines): - if re_exclude.search(ltext): - self.excluded.add(i+1) - - # Tokenize, to find excluded suites, to find docstrings, and to find - # multi-line statements. - indent = 0 - exclude_indent = 0 - excluding = False - prev_toktype = token.INDENT - first_line = None - empty = True - - tokgen = tokenize.generate_tokens(StringIO(self.text).readline) - for toktype, ttext, (slineno, _), (elineno, _), ltext in tokgen: - if self.show_tokens: # pragma: no cover - print("%10s %5s %-20r %r" % ( - tokenize.tok_name.get(toktype, toktype), - nice_pair((slineno, elineno)), ttext, ltext - )) - if toktype == token.INDENT: - indent += 1 - elif toktype == token.DEDENT: - indent -= 1 - elif toktype == token.NAME and ttext == 'class': - # Class definitions look like branches in the byte code, so - # we need to exclude them. The simplest way is to note the - # lines with the 'class' keyword. - self.classdefs.add(slineno) - elif toktype == token.OP and ttext == ':': - if not excluding and elineno in self.excluded: - # Start excluding a suite. We trigger off of the colon - # token so that the #pragma comment will be recognized on - # the same line as the colon. - exclude_indent = indent - excluding = True - elif toktype == token.STRING and prev_toktype == token.INDENT: - # Strings that are first on an indented line are docstrings. - # (a trick from trace.py in the stdlib.) This works for - # 99.9999% of cases. For the rest (!) see: - # http://stackoverflow.com/questions/1769332/x/1769794#1769794 - for i in range(slineno, elineno+1): - self.docstrings.add(i) - elif toktype == token.NEWLINE: - if first_line is not None and elineno != first_line: - # We're at the end of a line, and we've ended on a - # different line than the first line of the statement, - # so record a multi-line range. - rng = (first_line, elineno) - for l in range(first_line, elineno+1): - self.multiline[l] = rng - first_line = None - - if ttext.strip() and toktype != tokenize.COMMENT: - # A non-whitespace token. - empty = False - if first_line is None: - # The token is not whitespace, and is the first in a - # statement. - first_line = slineno - # Check whether to end an excluded suite. - if excluding and indent <= exclude_indent: - excluding = False - if excluding: - self.excluded.add(elineno) - - prev_toktype = toktype - - # Find the starts of the executable statements. - if not empty: - self.statement_starts.update(self.byte_parser._find_statements()) - - def _parse_pyx(self): - """Parse cython pyx files to find the functions defined. - - A handful of member fields are updated. - - """ - # Find lines which match an exclusion pattern. - if self.exclude: - re_exclude = re.compile(self.exclude) - for i, ltext in enumerate(self.lines): - if re_exclude.search(ltext): - self.excluded.add(i+1) - - # Tokenize, to find excluded suites, to find docstrings, and to find - # multi-line statements. - indent = 0 - exclude_indent = 0 - excluding = False - prev_toktype = token.INDENT - first_line = None - empty = True - - func_pattern = r'(?ms)(?P[c]?[p]?def)\s*(?P\S*?)\s*?(?P\S+?)\((?P.*?)\)\s*:' - - linestarts = [0] - for line in StringIO(self.text): - linestarts.append(linestarts[-1]+len(line)) - classdefs = range(1, len(linestarts)) - #print len(linestarts), linestarts - lno = 0 - func_starts = [] - for match in re.finditer(func_pattern, self.text): - while linestarts[lno] <= match.start(): - lno += 1 - #print lno, match.group('def'), match.group('rtype'), match.group('name')+'()'#, match.groups() - if match.group('rtype') == 'class': - lno -= 1 - continue - func_starts.append(lno) - classdefs.remove(lno) - lno -= 1 - self.classdefs = classdefs - self.statement_starts.update(func_starts) - - def first_line(self, line): - """Return the first line number of the statement including `line`.""" - rng = self.multiline.get(line) - if rng: - first_line = rng[0] - else: - first_line = line - return first_line - - def first_lines(self, lines, ignore=None): - """Map the line numbers in `lines` to the correct first line of the - statement. - - Skip any line mentioned in `ignore`. - - Returns a sorted list of the first lines. - - """ - ignore = ignore or [] - lset = set() - for l in lines: - if l in ignore: - continue - new_l = self.first_line(l) - if new_l not in ignore: - lset.add(new_l) - return sorted(lset) - - def parse_source(self): - """Parse source text to find executable lines, excluded lines, etc. - - Return values are 1) a sorted list of executable line numbers, and - 2) a sorted list of excluded line numbers. - - Reported line numbers are normalized to the first line of multi-line - statements. - - """ - if self.filename.endswith('.pyx'): - self._parse_pyx() - else: - self._raw_parse() - - excluded_lines = self.first_lines(self.excluded) - ignore = excluded_lines + list(self.docstrings) - lines = self.first_lines(self.statement_starts, ignore) - - return lines, excluded_lines - - def arcs(self): - """Get information about the arcs available in the code. - - Returns a sorted list of line number pairs. Line numbers have been - normalized to the first line of multiline statements. - - """ - all_arcs = [] - if self.filename.endswith('.pyx'): - return all_arcs - for l1, l2 in self.byte_parser._all_arcs(): - fl1 = self.first_line(l1) - fl2 = self.first_line(l2) - if fl1 != fl2: - all_arcs.append((fl1, fl2)) - return sorted(all_arcs) - arcs = expensive(arcs) - - def exit_counts(self): - """Get a mapping from line numbers to count of exits from that line. - - Excluded lines are excluded. - - """ - excluded_lines = self.first_lines(self.excluded) - exit_counts = {} - for l1, l2 in self.arcs(): - if l1 < 0: - # Don't ever report -1 as a line number - continue - if l1 in excluded_lines: - # Don't report excluded lines as line numbers. - continue - if l2 in excluded_lines: - # Arcs to excluded lines shouldn't count. - continue - if l1 not in exit_counts: - exit_counts[l1] = 0 - exit_counts[l1] += 1 - - # Class definitions have one extra exit, so remove one for each: - for l in self.classdefs: - # Ensure key is there: classdefs can include excluded lines. - if l in exit_counts: - exit_counts[l] -= 1 - - return exit_counts - exit_counts = expensive(exit_counts) - - -## Opcodes that guide the ByteParser. - -def _opcode(name): - """Return the opcode by name from the opcode module.""" - return opcode.opmap[name] - -def _opcode_set(*names): - """Return a set of opcodes by the names in `names`.""" - s = set() - for name in names: - try: - s.add(_opcode(name)) - except KeyError: - pass - return s - -# Opcodes that leave the code object. -OPS_CODE_END = _opcode_set('RETURN_VALUE') - -# Opcodes that unconditionally end the code chunk. -OPS_CHUNK_END = _opcode_set( - 'JUMP_ABSOLUTE', 'JUMP_FORWARD', 'RETURN_VALUE', 'RAISE_VARARGS', - 'BREAK_LOOP', 'CONTINUE_LOOP', - ) - -# Opcodes that unconditionally begin a new code chunk. By starting new chunks -# with unconditional jump instructions, we neatly deal with jumps to jumps -# properly. -OPS_CHUNK_BEGIN = _opcode_set('JUMP_ABSOLUTE', 'JUMP_FORWARD') - -# Opcodes that push a block on the block stack. -OPS_PUSH_BLOCK = _opcode_set( - 'SETUP_LOOP', 'SETUP_EXCEPT', 'SETUP_FINALLY', 'SETUP_WITH' - ) - -# Block types for exception handling. -OPS_EXCEPT_BLOCKS = _opcode_set('SETUP_EXCEPT', 'SETUP_FINALLY') - -# Opcodes that pop a block from the block stack. -OPS_POP_BLOCK = _opcode_set('POP_BLOCK') - -# Opcodes that have a jump destination, but aren't really a jump. -OPS_NO_JUMP = _opcode_set('SETUP_EXCEPT', 'SETUP_FINALLY') - -# Individual opcodes we need below. -OP_BREAK_LOOP = _opcode('BREAK_LOOP') -OP_END_FINALLY = _opcode('END_FINALLY') -OP_COMPARE_OP = _opcode('COMPARE_OP') -COMPARE_EXCEPTION = 10 # just have to get this const from the code. -OP_LOAD_CONST = _opcode('LOAD_CONST') -OP_RETURN_VALUE = _opcode('RETURN_VALUE') - - -class ByteParser(object): - """Parse byte codes to understand the structure of code.""" - - def __init__(self, code=None, text=None, filename=None): - if code: - self.code = code - else: - if not text: - assert filename, "If no code or text, need a filename" - sourcef = open(filename, 'rU') - text = sourcef.read() - sourcef.close() - - try: - # Python 2.3 and 2.4 don't like partial last lines, so be sure - # the text ends nicely for them. - self.code = compile(text + '\n', filename, "exec") - except SyntaxError: - _, synerr, _ = sys.exc_info() - raise CoverageException( - "Couldn't parse '%s' as Python source: '%s' at line %d" % - (filename, synerr.msg, synerr.lineno) - ) - - # Alternative Python implementations don't always provide all the - # attributes on code objects that we need to do the analysis. - for attr in ['co_lnotab', 'co_firstlineno', 'co_consts', 'co_code']: - if not hasattr(self.code, attr): - raise CoverageException( - "This implementation of Python doesn't support code " - "analysis.\n" - "Run coverage.py under CPython for this command." - ) - - def child_parsers(self): - """Iterate over all the code objects nested within this one. - - The iteration includes `self` as its first value. - - """ - return map(lambda c: ByteParser(code=c), CodeObjects(self.code)) - - # Getting numbers from the lnotab value changed in Py3.0. - if sys.version_info >= (3, 0): - def _lnotab_increments(self, lnotab): - """Return a list of ints from the lnotab bytes in 3.x""" - return list(lnotab) - else: - def _lnotab_increments(self, lnotab): - """Return a list of ints from the lnotab string in 2.x""" - return [ord(c) for c in lnotab] - - def _bytes_lines(self): - """Map byte offsets to line numbers in `code`. - - Uses co_lnotab described in Python/compile.c to map byte offsets to - line numbers. Returns a list: [(b0, l0), (b1, l1), ...] - - """ - # Adapted from dis.py in the standard library. - byte_increments = self._lnotab_increments(self.code.co_lnotab[0::2]) - line_increments = self._lnotab_increments(self.code.co_lnotab[1::2]) - - bytes_lines = [] - last_line_num = None - line_num = self.code.co_firstlineno - byte_num = 0 - for byte_incr, line_incr in zip(byte_increments, line_increments): - if byte_incr: - if line_num != last_line_num: - bytes_lines.append((byte_num, line_num)) - last_line_num = line_num - byte_num += byte_incr - line_num += line_incr - if line_num != last_line_num: - bytes_lines.append((byte_num, line_num)) - return bytes_lines - - def _find_statements(self): - """Find the statements in `self.code`. - - Return a set of line numbers that start statements. Recurses into all - code objects reachable from `self.code`. - - """ - stmts = set() - for bp in self.child_parsers(): - # Get all of the lineno information from this code. - for _, l in bp._bytes_lines(): - stmts.add(l) - return stmts - - def _disassemble(self): # pragma: no cover - """Disassemble code, for ad-hoc experimenting.""" - - import dis - - for bp in self.child_parsers(): - print("\n%s: " % bp.code) - dis.dis(bp.code) - print("Bytes lines: %r" % bp._bytes_lines()) - - print("") - - def _split_into_chunks(self): - """Split the code object into a list of `Chunk` objects. - - Each chunk is only entered at its first instruction, though there can - be many exits from a chunk. - - Returns a list of `Chunk` objects. - - """ - - # The list of chunks so far, and the one we're working on. - chunks = [] - chunk = None - bytes_lines_map = dict(self._bytes_lines()) - - # The block stack: loops and try blocks get pushed here for the - # implicit jumps that can occur. - # Each entry is a tuple: (block type, destination) - block_stack = [] - - # Some op codes are followed by branches that should be ignored. This - # is a count of how many ignores are left. - ignore_branch = 0 - - # We have to handle the last two bytecodes specially. - ult = penult = None - - for bc in ByteCodes(self.code.co_code): - # Maybe have to start a new chunk - if bc.offset in bytes_lines_map: - # Start a new chunk for each source line number. - if chunk: - chunk.exits.add(bc.offset) - chunk = Chunk(bc.offset, bytes_lines_map[bc.offset]) - chunks.append(chunk) - elif bc.op in OPS_CHUNK_BEGIN: - # Jumps deserve their own unnumbered chunk. This fixes - # problems with jumps to jumps getting confused. - if chunk: - chunk.exits.add(bc.offset) - chunk = Chunk(bc.offset) - chunks.append(chunk) - - if not chunk: - chunk = Chunk(bc.offset) - chunks.append(chunk) - - # Look at the opcode - if bc.jump_to >= 0 and bc.op not in OPS_NO_JUMP: - if ignore_branch: - # Someone earlier wanted us to ignore this branch. - ignore_branch -= 1 - else: - # The opcode has a jump, it's an exit for this chunk. - chunk.exits.add(bc.jump_to) - - if bc.op in OPS_CODE_END: - # The opcode can exit the code object. - chunk.exits.add(-self.code.co_firstlineno) - if bc.op in OPS_PUSH_BLOCK: - # The opcode adds a block to the block_stack. - block_stack.append((bc.op, bc.jump_to)) - if bc.op in OPS_POP_BLOCK: - # The opcode pops a block from the block stack. - block_stack.pop() - if bc.op in OPS_CHUNK_END: - # This opcode forces the end of the chunk. - if bc.op == OP_BREAK_LOOP: - # A break is implicit: jump where the top of the - # block_stack points. - chunk.exits.add(block_stack[-1][1]) - chunk = None - if bc.op == OP_END_FINALLY: - if block_stack: - # A break that goes through a finally will jump to whatever - # block is on top of the stack. - chunk.exits.add(block_stack[-1][1]) - # For the finally clause we need to find the closest exception - # block, and use its jump target as an exit. - for iblock in range(len(block_stack)-1, -1, -1): - if block_stack[iblock][0] in OPS_EXCEPT_BLOCKS: - chunk.exits.add(block_stack[iblock][1]) - break - if bc.op == OP_COMPARE_OP and bc.arg == COMPARE_EXCEPTION: - # This is an except clause. We want to overlook the next - # branch, so that except's don't count as branches. - ignore_branch += 1 - - penult = ult - ult = bc - - if chunks: - # The last two bytecodes could be a dummy "return None" that - # shouldn't be counted as real code. Every Python code object seems - # to end with a return, and a "return None" is inserted if there - # isn't an explicit return in the source. - if ult and penult: - if penult.op == OP_LOAD_CONST and ult.op == OP_RETURN_VALUE: - if self.code.co_consts[penult.arg] is None: - # This is "return None", but is it dummy? A real line - # would be a last chunk all by itself. - if chunks[-1].byte != penult.offset: - ex = -self.code.co_firstlineno - # Split the last chunk - last_chunk = chunks[-1] - last_chunk.exits.remove(ex) - last_chunk.exits.add(penult.offset) - chunk = Chunk(penult.offset) - chunk.exits.add(ex) - chunks.append(chunk) - - # Give all the chunks a length. - chunks[-1].length = bc.next_offset - chunks[-1].byte - for i in range(len(chunks)-1): - chunks[i].length = chunks[i+1].byte - chunks[i].byte - - return chunks - - def _arcs(self): - """Find the executable arcs in the code. - - Returns a set of pairs, (from,to). From and to are integer line - numbers. If from is < 0, then the arc is an entrance into the code - object. If to is < 0, the arc is an exit from the code object. - - """ - chunks = self._split_into_chunks() - - # A map from byte offsets to chunks jumped into. - byte_chunks = dict([(c.byte, c) for c in chunks]) - - # Build a map from byte offsets to actual lines reached. - byte_lines = {} - bytes_to_add = set([c.byte for c in chunks]) - - while bytes_to_add: - byte_to_add = bytes_to_add.pop() - if byte_to_add in byte_lines or byte_to_add < 0: - continue - - # Which lines does this chunk lead to? - bytes_considered = set() - bytes_to_consider = [byte_to_add] - lines = set() - - while bytes_to_consider: - byte = bytes_to_consider.pop() - bytes_considered.add(byte) - - # Find chunk for byte - try: - ch = byte_chunks[byte] - except KeyError: - for ch in chunks: - if ch.byte <= byte < ch.byte + ch.length: - break - else: - # No chunk for this byte! - raise Exception("Couldn't find chunk @ %d" % byte) - byte_chunks[byte] = ch - - if ch.line: - lines.add(ch.line) - else: - for ex in ch.exits: - if ex < 0: - lines.add(ex) - elif ex not in bytes_considered: - bytes_to_consider.append(ex) - - bytes_to_add.update(ch.exits) - - byte_lines[byte_to_add] = lines - - # Figure out for each chunk where the exits go. - arcs = set() - for chunk in chunks: - if chunk.line: - for ex in chunk.exits: - if ex < 0: - exit_lines = [ex] - else: - exit_lines = byte_lines[ex] - for exit_line in exit_lines: - if chunk.line != exit_line: - arcs.add((chunk.line, exit_line)) - for line in byte_lines[0]: - arcs.add((-1, line)) - - return arcs - - def _all_chunks(self): - """Returns a list of `Chunk` objects for this code and its children. - - See `_split_into_chunks` for details. - - """ - chunks = [] - for bp in self.child_parsers(): - chunks.extend(bp._split_into_chunks()) - - return chunks - - def _all_arcs(self): - """Get the set of all arcs in this code object and its children. - - See `_arcs` for details. - - """ - arcs = set() - for bp in self.child_parsers(): - arcs.update(bp._arcs()) - - return arcs - - -class Chunk(object): - """A sequence of bytecodes with a single entrance. - - To analyze byte code, we have to divide it into chunks, sequences of byte - codes such that each basic block has only one entrance, the first - instruction in the block. - - This is almost the CS concept of `basic block`_, except that we're willing - to have many exits from a chunk, and "basic block" is a more cumbersome - term. - - .. _basic block: http://en.wikipedia.org/wiki/Basic_block - - An exit < 0 means the chunk can leave the code (return). The exit is - the negative of the starting line number of the code block. - - """ - def __init__(self, byte, line=0): - self.byte = byte - self.line = line - self.length = 0 - self.exits = set() - - def __repr__(self): - return "<%d+%d @%d %r>" % ( - self.byte, self.length, self.line, list(self.exits) - ) - - -class AdHocMain(object): # pragma: no cover - """An ad-hoc main for code parsing experiments.""" - - def main(self, args): - """A main function for trying the code from the command line.""" - - from optparse import OptionParser - - parser = OptionParser() - parser.add_option( - "-c", action="store_true", dest="chunks", - help="Show basic block chunks" - ) - parser.add_option( - "-d", action="store_true", dest="dis", - help="Disassemble" - ) - parser.add_option( - "-R", action="store_true", dest="recursive", - help="Recurse to find source files" - ) - parser.add_option( - "-s", action="store_true", dest="source", - help="Show analyzed source" - ) - parser.add_option( - "-t", action="store_true", dest="tokens", - help="Show tokens" - ) - - options, args = parser.parse_args() - if options.recursive: - if args: - root = args[0] - else: - root = "." - for root, _, _ in os.walk(root): - for f in glob.glob(root + "/*.py"): - self.adhoc_one_file(options, f) - else: - self.adhoc_one_file(options, args[0]) - - def adhoc_one_file(self, options, filename): - """Process just one file.""" - - if options.dis or options.chunks: - try: - bp = ByteParser(filename=filename) - except CoverageException: - _, err, _ = sys.exc_info() - print("%s" % (err,)) - return - - if options.dis: - print("Main code:") - bp._disassemble() - - if options.chunks: - chunks = bp._all_chunks() - if options.recursive: - print("%6d: %s" % (len(chunks), filename)) - else: - print("Chunks: %r" % chunks) - arcs = bp._all_arcs() - print("Arcs: %r" % sorted(arcs)) - - if options.source or options.tokens: - cp = CodeParser(filename=filename, exclude=r"no\s*cover") - cp.show_tokens = options.tokens - cp.parse_source() - - if options.source: - if options.chunks: - arc_width, arc_chars = self.arc_ascii_art(arcs) - else: - arc_width, arc_chars = 0, {} - - exit_counts = cp.exit_counts() - - for i, ltext in enumerate(cp.lines): - lineno = i+1 - m0 = m1 = m2 = m3 = a = ' ' - if lineno in cp.statement_starts: - m0 = '-' - exits = exit_counts.get(lineno, 0) - if exits > 1: - m1 = str(exits) - if lineno in cp.docstrings: - m2 = '"' - if lineno in cp.classdefs: - m2 = 'C' - if lineno in cp.excluded: - m3 = 'x' - a = arc_chars.get(lineno, '').ljust(arc_width) - print("%4d %s%s%s%s%s %s" % - (lineno, m0, m1, m2, m3, a, ltext) - ) - - def arc_ascii_art(self, arcs): - """Draw arcs as ascii art. - - Returns a width of characters needed to draw all the arcs, and a - dictionary mapping line numbers to ascii strings to draw for that line. - - """ - arc_chars = {} - for lfrom, lto in sorted(arcs): - if lfrom < 0: - arc_chars[lto] = arc_chars.get(lto, '') + 'v' - elif lto < 0: - arc_chars[lfrom] = arc_chars.get(lfrom, '') + '^' - else: - if lfrom == lto - 1: - # Don't show obvious arcs. - continue - if lfrom < lto: - l1, l2 = lfrom, lto - else: - l1, l2 = lto, lfrom - w = max([len(arc_chars.get(l, '')) for l in range(l1, l2+1)]) - for l in range(l1, l2+1): - if l == lfrom: - ch = '<' - elif l == lto: - ch = '>' - else: - ch = '|' - arc_chars[l] = arc_chars.get(l, '').ljust(w) + ch - arc_width = 0 - - if arc_chars: - arc_width = max([len(a) for a in arc_chars.values()]) - else: - arc_width = 0 - - return arc_width, arc_chars - -if __name__ == '__main__': - AdHocMain().main(sys.argv[1:]) diff --git a/kivy/tests/coverage/phystokens.py b/kivy/tests/coverage/phystokens.py deleted file mode 100644 index 14d4ebbed3..0000000000 --- a/kivy/tests/coverage/phystokens.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Better tokenizing for coverage.py.""" - -import keyword -import re -import token -import tokenize -from coverage.backward import StringIO # pylint: disable-msg=W0622 - -def phys_tokens(toks): - """Return all physical tokens, even line continuations. - - tokenize.generate_tokens() doesn't return a token for the backslash that - continues lines. This wrapper provides those tokens so that we can - re-create a faithful representation of the original source. - - Returns the same values as generate_tokens() - - """ - last_line = None - last_lineno = -1 - last_ttype = None - for ttype, ttext, (slineno, scol), (elineno, ecol), ltext in toks: - if last_lineno != elineno: - if last_line and last_line[-2:] == "\\\n": - # We are at the beginning of a new line, and the last line - # ended with a backslash. We probably have to inject a - # backslash token into the stream. Unfortunately, there's more - # to figure out. This code:: - # - # usage = """\ - # HEY THERE - # """ - # - # triggers this condition, but the token text is:: - # - # '"""\\\nHEY THERE\n"""' - # - # so we need to figure out if the backslash is already in the - # string token or not. - inject_backslash = True - if last_ttype == tokenize.COMMENT: - # Comments like this \ - # should never result in a new token. - inject_backslash = False - elif ttype == token.STRING: - if "\n" in ttext and ttext.split('\n', 1)[0][-1] == '\\': - # It's a multiline string and the first line ends with - # a backslash, so we don't need to inject another. - inject_backslash = False - if inject_backslash: - # Figure out what column the backslash is in. - ccol = len(last_line.split("\n")[-2]) - 1 - # Yield the token, with a fake token type. - yield ( - 99999, "\\\n", - (slineno, ccol), (slineno, ccol+2), - last_line - ) - last_line = ltext - last_ttype = ttype - yield ttype, ttext, (slineno, scol), (elineno, ecol), ltext - last_lineno = elineno - - -def source_token_lines(source): - """Generate a series of lines, one for each line in `source`. - - Each line is a list of pairs, each pair is a token:: - - [('key', 'def'), ('ws', ' '), ('nam', 'hello'), ('op', '('), ... ] - - Each pair has a token class, and the token text. - - If you concatenate all the token texts, and then join them with newlines, - you should have your original `source` back, with two differences: - trailing whitespace is not preserved, and a final line with no newline - is indistinguishable from a final line with a newline. - - """ - ws_tokens = [token.INDENT, token.DEDENT, token.NEWLINE, tokenize.NL] - line = [] - col = 0 - source = source.expandtabs(8).replace('\r\n', '\n') - tokgen = tokenize.generate_tokens(StringIO(source).readline) - for ttype, ttext, (_, scol), (_, ecol), _ in phys_tokens(tokgen): - mark_start = True - for part in re.split('(\n)', ttext): - if part == '\n': - yield line - line = [] - col = 0 - mark_end = False - elif part == '': - mark_end = False - elif ttype in ws_tokens: - mark_end = False - else: - if mark_start and scol > col: - line.append(("ws", " " * (scol - col))) - mark_start = False - tok_class = tokenize.tok_name.get(ttype, 'xx').lower()[:3] - if ttype == token.NAME and keyword.iskeyword(ttext): - tok_class = "key" - line.append((tok_class, part)) - mark_end = True - scol = 0 - if mark_end: - col = ecol - - if line: - yield line diff --git a/kivy/tests/coverage/report.py b/kivy/tests/coverage/report.py deleted file mode 100644 index a7014774a6..0000000000 --- a/kivy/tests/coverage/report.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Reporter foundation for Coverage.""" - -import fnmatch -import os -from coverage.codeunit import code_unit_factory -from coverage.misc import CoverageException, NoSource - -class Reporter(object): - """A base class for all reporters.""" - - def __init__(self, coverage, ignore_errors=False): - """Create a reporter. - - `coverage` is the coverage instance. `ignore_errors` controls how - skittish the reporter will be during file processing. - - """ - self.coverage = coverage - self.ignore_errors = ignore_errors - - # The code units to report on. Set by find_code_units. - self.code_units = [] - - # The directory into which to place the report, used by some derived - # classes. - self.directory = None - - def find_code_units(self, morfs, config): - """Find the code units we'll report on. - - `morfs` is a list of modules or filenames. `config` is a - CoverageConfig instance. - - """ - morfs = morfs or self.coverage.data.measured_files() - file_locator = self.coverage.file_locator - self.code_units = code_unit_factory(morfs, file_locator) - - if config.include: - patterns = [file_locator.abs_file(p) for p in config.include] - filtered = [] - for cu in self.code_units: - for pattern in patterns: - if fnmatch.fnmatch(cu.filename, pattern): - filtered.append(cu) - break - self.code_units = filtered - - if config.omit: - patterns = [file_locator.abs_file(p) for p in config.omit] - filtered = [] - for cu in self.code_units: - for pattern in patterns: - if fnmatch.fnmatch(cu.filename, pattern): - break - else: - filtered.append(cu) - self.code_units = filtered - - self.code_units.sort() - - def report_files(self, report_fn, morfs, config, directory=None): - """Run a reporting function on a number of morfs. - - `report_fn` is called for each relative morf in `morfs`. - - `config` is a CoverageConfig instance. - - """ - self.find_code_units(morfs, config) - - if not self.code_units: - 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: - try: - report_fn(cu, self.coverage._analyze(cu)) - except NoSource: - if not self.ignore_errors: - raise diff --git a/kivy/tests/coverage/results.py b/kivy/tests/coverage/results.py deleted file mode 100644 index 6f8f322303..0000000000 --- a/kivy/tests/coverage/results.py +++ /dev/null @@ -1,233 +0,0 @@ -"""Results of coverage measurement.""" - -import os - -from coverage.backward import set, sorted # pylint: disable-msg=W0622 -from coverage.misc import format_lines, NoSource -from coverage.parser import CodeParser - - -class Analysis(object): - """The results of analyzing a code unit.""" - - def __init__(self, cov, code_unit): - self.coverage = cov - self.code_unit = code_unit - - self.filename = self.code_unit.filename - ext = os.path.splitext(self.filename)[1] - source = None - if ext == '.py': - if not os.path.exists(self.filename): - source = self.coverage.file_locator.get_zip_data(self.filename) - if not source: - raise NoSource("No source for code: %r" % self.filename) - - self.parser = CodeParser( - text=source, filename=self.filename, - exclude=self.coverage.exclude_re - ) - self.statements, self.excluded = self.parser.parse_source() - - # Identify missing statements. - executed = self.coverage.data.executed_lines(self.filename) - exec1 = self.parser.first_lines(executed) - self.missing = sorted(set(self.statements) - set(exec1)) - - if self.coverage.data.has_arcs(): - n_branches = self.total_branches() - mba = self.missing_branch_arcs() - n_missing_branches = sum([len(v) for v in mba.values()]) - else: - n_branches = n_missing_branches = 0 - - self.numbers = Numbers( - n_files=1, - n_statements=len(self.statements), - n_excluded=len(self.excluded), - n_missing=len(self.missing), - n_branches=n_branches, - n_missing_branches=n_missing_branches, - ) - - def missing_formatted(self): - """The missing line numbers, formatted nicely. - - Returns a string like "1-2, 5-11, 13-14". - - """ - return format_lines(self.statements, self.missing) - - def has_arcs(self): - """Were arcs measured in this result?""" - return self.coverage.data.has_arcs() - - def arc_possibilities(self): - """Returns a sorted list of the arcs in the code.""" - return self.parser.arcs() - - def arcs_executed(self): - """Returns a sorted list of the arcs actually executed in the code.""" - executed = self.coverage.data.executed_arcs(self.filename) - m2fl = self.parser.first_line - executed = [(m2fl(l1), m2fl(l2)) for (l1,l2) in executed] - return sorted(executed) - - def arcs_missing(self): - """Returns a sorted list of the arcs in the code not executed.""" - possible = self.arc_possibilities() - executed = self.arcs_executed() - missing = [p for p in possible if p not in executed] - return sorted(missing) - - def arcs_unpredicted(self): - """Returns a sorted list of the executed arcs missing from the code.""" - possible = self.arc_possibilities() - executed = self.arcs_executed() - # Exclude arcs here which connect a line to itself. They can occur - # in executed data in some cases. This is where they can cause - # trouble, and here is where it's the least burden to remove them. - unpredicted = [ - e for e in executed - if e not in possible and e[0] != e[1] - ] - return sorted(unpredicted) - - def branch_lines(self): - """Returns a list of line numbers that have more than one exit.""" - exit_counts = self.parser.exit_counts() - return [l1 for l1,count in exit_counts.items() if count > 1] - - def total_branches(self): - """How many total branches are there?""" - exit_counts = self.parser.exit_counts() - return sum([count for count in exit_counts.values() if count > 1]) - - def missing_branch_arcs(self): - """Return arcs that weren't executed from branch lines. - - Returns {l1:[l2a,l2b,...], ...} - - """ - missing = self.arcs_missing() - branch_lines = set(self.branch_lines()) - mba = {} - for l1, l2 in missing: - if l1 in branch_lines: - if l1 not in mba: - mba[l1] = [] - mba[l1].append(l2) - return mba - - def branch_stats(self): - """Get stats about branches. - - Returns a dict mapping line numbers to a tuple: - (total_exits, taken_exits). - """ - - exit_counts = self.parser.exit_counts() - missing_arcs = self.missing_branch_arcs() - stats = {} - for lnum in self.branch_lines(): - exits = exit_counts[lnum] - try: - missing = len(missing_arcs[lnum]) - except KeyError: - missing = 0 - stats[lnum] = (exits, exits - missing) - return stats - - -class Numbers(object): - """The numerical results of measuring coverage. - - This holds the basic statistics from `Analysis`, and is used to roll - up statistics across files. - - """ - # A global to determine the precision on coverage percentages, the number - # of decimal places. - _precision = 0 - _near0 = 1.0 # These will change when _precision is changed. - _near100 = 99.0 - - def __init__(self, n_files=0, n_statements=0, n_excluded=0, n_missing=0, - n_branches=0, n_missing_branches=0 - ): - self.n_files = n_files - self.n_statements = n_statements - self.n_excluded = n_excluded - self.n_missing = n_missing - self.n_branches = n_branches - self.n_missing_branches = n_missing_branches - - def set_precision(cls, precision): - """Set the number of decimal places used to report percentages.""" - assert 0 <= precision < 10 - cls._precision = precision - cls._near0 = 1.0 / 10 ** precision - cls._near100 = 100.0 - cls._near0 - set_precision = classmethod(set_precision) - - def _get_n_executed(self): - """Returns the number of executed statements.""" - return self.n_statements - self.n_missing - n_executed = property(_get_n_executed) - - def _get_n_executed_branches(self): - """Returns the number of executed branches.""" - return self.n_branches - self.n_missing_branches - n_executed_branches = property(_get_n_executed_branches) - - def _get_pc_covered(self): - """Returns a single percentage value for coverage.""" - if self.n_statements > 0: - pc_cov = (100.0 * (self.n_executed + self.n_executed_branches) / - (self.n_statements + self.n_branches)) - else: - pc_cov = 100.0 - return pc_cov - pc_covered = property(_get_pc_covered) - - def _get_pc_covered_str(self): - """Returns the percent covered, as a string, without a percent sign. - - The important thing here is that "0" only be returned when it's truly - zero, and "100" only be returned when it's truly 100. - - """ - pc = self.pc_covered - if 0 < pc < self._near0: - pc = self._near0 - elif self._near100 < pc < 100: - pc = self._near100 - else: - pc = round(pc, self._precision) - return "%.*f" % (self._precision, pc) - pc_covered_str = property(_get_pc_covered_str) - - def pc_str_width(cls): - """How many characters wide can pc_covered_str be?""" - width = 3 # "100" - if cls._precision > 0: - width += 1 + cls._precision - return width - pc_str_width = classmethod(pc_str_width) - - def __add__(self, other): - nums = Numbers() - nums.n_files = self.n_files + other.n_files - nums.n_statements = self.n_statements + other.n_statements - nums.n_excluded = self.n_excluded + other.n_excluded - nums.n_missing = self.n_missing + other.n_missing - nums.n_branches = self.n_branches + other.n_branches - nums.n_missing_branches = (self.n_missing_branches + - other.n_missing_branches) - return nums - - def __radd__(self, other): - # Implementing 0+Numbers allows us to sum() a list of Numbers. - if other == 0: - return self - raise NotImplemented diff --git a/kivy/tests/coverage/summary.py b/kivy/tests/coverage/summary.py deleted file mode 100644 index 599ae78221..0000000000 --- a/kivy/tests/coverage/summary.py +++ /dev/null @@ -1,81 +0,0 @@ -"""Summary reporting""" - -import sys - -from coverage.report import Reporter -from coverage.results import Numbers - - -class SummaryReporter(Reporter): - """A reporter for writing the summary report.""" - - def __init__(self, coverage, show_missing=True, ignore_errors=False): - super(SummaryReporter, self).__init__(coverage, ignore_errors) - self.show_missing = show_missing - self.branches = coverage.data.has_arcs() - - def report(self, morfs, outfile=None, config=None): - """Writes a report summarizing coverage statistics per module. - - `outfile` is a file object to write the summary to. `config` is a - CoverageConfig instance. - - """ - self.find_code_units(morfs, config) - - # Prepare the formatting strings - max_name = max([len(cu.name) for cu in self.code_units] + [5]) - fmt_name = "%%- %ds " % max_name - fmt_err = "%s %s: %s\n" - header = (fmt_name % "Name") + " Stmts Miss" - fmt_coverage = fmt_name + "%6d %6d" - if self.branches: - header += " Branch BrPart" - fmt_coverage += " %6d %6d" - width100 = Numbers.pc_str_width() - header += "%*s" % (width100+4, "Cover") - fmt_coverage += "%%%ds%%%%" % (width100+3,) - if self.show_missing: - header += " Missing" - fmt_coverage += " %s" - rule = "-" * len(header) + "\n" - header += "\n" - fmt_coverage += "\n" - - if not outfile: - outfile = sys.stdout - - # Write the header - outfile.write(header) - outfile.write(rule) - - total = Numbers() - - for cu in self.code_units: - try: - analysis = self.coverage._analyze(cu) - nums = analysis.numbers - args = (cu.name, nums.n_statements, nums.n_missing) - if self.branches: - args += (nums.n_branches, nums.n_missing_branches) - args += (nums.pc_covered_str,) - if self.show_missing: - args += (analysis.missing_formatted(),) - outfile.write(fmt_coverage % args) - total += nums - except KeyboardInterrupt: # pragma: no cover - raise - except: - if not self.ignore_errors: - typ, msg = sys.exc_info()[:2] - outfile.write(fmt_err % (cu.name, typ.__name__, msg)) - - if total.n_files > 1: - outfile.write(rule) - args = ("TOTAL", total.n_statements, total.n_missing) - if self.branches: - args += (total.n_branches, total.n_missing_branches) - args += (total.pc_covered_str,) - if self.show_missing: - args += ("",) - outfile.write(fmt_coverage % args) diff --git a/kivy/tests/coverage/templite.py b/kivy/tests/coverage/templite.py deleted file mode 100644 index 430b6b533b..0000000000 --- a/kivy/tests/coverage/templite.py +++ /dev/null @@ -1,169 +0,0 @@ -"""A simple Python template renderer, for a nano-subset of Django syntax.""" - -# Coincidentally named the same as http://code.activestate.com/recipes/496702/ - -import re -import sys - - -class Templite(object): - """A simple template renderer, for a nano-subset of Django syntax. - - Supported constructs are extended variable access:: - - {{var.modifer.modifier|filter|filter}} - - loops:: - - {% for var in list %}...{% endfor %} - - and ifs:: - - {% if var %}...{% endif %} - - Comments are within curly-hash markers:: - - {# This will be ignored #} - - Construct a Templite with the template text, then use `render` against a - dictionary context to create a finished string. - - """ - def __init__(self, text, *contexts): - """Construct a Templite with the given `text`. - - `contexts` are dictionaries of values to use for future renderings. - These are good for filters and global values. - - """ - self.text = text - self.context = {} - for context in contexts: - self.context.update(context) - - # Split the text to form a list of tokens. - toks = re.split(r"(?s)({{.*?}}|{%.*?%}|{#.*?#})", text) - - # Parse the tokens into a nested list of operations. Each item in the - # list is a tuple with an opcode, and arguments. They'll be - # interpreted by TempliteEngine. - # - # When parsing an action tag with nested content (if, for), the current - # ops list is pushed onto ops_stack, and the parsing continues in a new - # ops list that is part of the arguments to the if or for op. - ops = [] - ops_stack = [] - for tok in toks: - if tok.startswith('{{'): - # Expression: ('exp', expr) - ops.append(('exp', tok[2:-2].strip())) - elif tok.startswith('{#'): - # Comment: ignore it and move on. - continue - elif tok.startswith('{%'): - # Action tag: split into words and parse further. - words = tok[2:-2].strip().split() - if words[0] == 'if': - # If: ('if', (expr, body_ops)) - if_ops = [] - assert len(words) == 2 - ops.append(('if', (words[1], if_ops))) - ops_stack.append(ops) - ops = if_ops - elif words[0] == 'for': - # For: ('for', (varname, listexpr, body_ops)) - assert len(words) == 4 and words[2] == 'in' - for_ops = [] - ops.append(('for', (words[1], words[3], for_ops))) - ops_stack.append(ops) - ops = for_ops - elif words[0].startswith('end'): - # Endsomething. Pop the ops stack - ops = ops_stack.pop() - assert ops[-1][0] == words[0][3:] - else: - raise SyntaxError("Don't understand tag %r" % words) - else: - ops.append(('lit', tok)) - - assert not ops_stack, "Unmatched action tag: %r" % ops_stack[-1][0] - self.ops = ops - - def render(self, context=None): - """Render this template by applying it to `context`. - - `context` is a dictionary of values to use in this rendering. - - """ - # Make the complete context we'll use. - ctx = dict(self.context) - if context: - ctx.update(context) - - # Run it through an engine, and return the result. - engine = _TempliteEngine(ctx) - engine.execute(self.ops) - return "".join(engine.result) - - -class _TempliteEngine(object): - """Executes Templite objects to produce strings.""" - def __init__(self, context): - self.context = context - self.result = [] - - def execute(self, ops): - """Execute `ops` in the engine. - - Called recursively for the bodies of if's and loops. - - """ - for op, args in ops: - if op == 'lit': - self.result.append(args) - elif op == 'exp': - try: - self.result.append(str(self.evaluate(args))) - except: - exc_class, exc, _ = sys.exc_info() - new_exc = exc_class("Couldn't evaluate {{ %s }}: %s" - % (args, exc)) - raise new_exc - elif op == 'if': - expr, body = args - if self.evaluate(expr): - self.execute(body) - elif op == 'for': - var, lis, body = args - vals = self.evaluate(lis) - for val in vals: - self.context[var] = val - self.execute(body) - else: - raise AssertionError("TempliteEngine doesn't grok op %r" % op) - - def evaluate(self, expr): - """Evaluate an expression. - - `expr` can have pipes and dots to indicate data access and filtering. - - """ - if "|" in expr: - pipes = expr.split("|") - value = self.evaluate(pipes[0]) - for func in pipes[1:]: - value = self.evaluate(func)(value) - elif "." in expr: - dots = expr.split('.') - value = self.evaluate(dots[0]) - for dot in dots[1:]: - try: - value = getattr(value, dot) - except AttributeError: - value = value[dot] - if hasattr(value, '__call__'): - value = value() - else: - value = self.context[expr] - return value - diff --git a/kivy/tests/coverage/tracer.c b/kivy/tests/coverage/tracer.c deleted file mode 100644 index 9eb3cca1e1..0000000000 --- a/kivy/tests/coverage/tracer.c +++ /dev/null @@ -1,674 +0,0 @@ -/* C-based Tracer for Coverage. */ - -#include "Python.h" -#include "compile.h" /* in 2.3, this wasn't part of Python.h */ -#include "eval.h" /* or this. */ -#include "structmember.h" -#include "frameobject.h" - -/* Compile-time debugging helpers */ -#undef WHAT_LOG /* Define to log the WHAT params in the trace function. */ -#undef TRACE_LOG /* Define to log our bookkeeping. */ -#undef COLLECT_STATS /* Collect counters: stats are printed when tracer is stopped. */ - -#if COLLECT_STATS -#define STATS(x) x -#else -#define STATS(x) -#endif - -/* Py 2.x and 3.x compatibility */ - -#ifndef Py_TYPE -#define Py_TYPE(o) (((PyObject*)(o))->ob_type) -#endif - -#if PY_MAJOR_VERSION >= 3 - -#define MyText_Type PyUnicode_Type -#define MyText_Check(o) PyUnicode_Check(o) -#define MyText_AS_STRING(o) PyBytes_AS_STRING(PyUnicode_AsASCIIString(o)) -#define MyInt_FromLong(l) PyLong_FromLong(l) - -#define MyType_HEAD_INIT PyVarObject_HEAD_INIT(NULL, 0) - -#else - -#define MyText_Type PyString_Type -#define MyText_Check(o) PyString_Check(o) -#define MyText_AS_STRING(o) PyString_AS_STRING(o) -#define MyInt_FromLong(l) PyInt_FromLong(l) - -#define MyType_HEAD_INIT PyObject_HEAD_INIT(NULL) 0, - -#endif /* Py3k */ - -/* The values returned to indicate ok or error. */ -#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. -*/ -typedef struct { - PyObject * file_data; /* PyMem_Malloc'ed, a borrowed ref. */ - int last_line; -} DataStackEntry; - -/* The Tracer type. */ - -typedef struct { - PyObject_HEAD - - /* Python objects manipulated directly by the Collector class. */ - PyObject * should_trace; - PyObject * data; - PyObject * should_trace_cache; - PyObject * arcs; - - /* Has the tracer been started? */ - int started; - /* Are we tracing arcs, or just lines? */ - int tracing_arcs; - - /* - The data stack is a stack of dictionaries. Each dictionary collects - data for a single source file. The data stack parallels the call stack: - each call pushes the new frame's file data onto the data stack, and each - return pops file data off. - - The file data is a dictionary whose form depends on the tracing options. - If tracing arcs, the keys are line number pairs. If not tracing arcs, - the keys are line numbers. In both cases, the value is irrelevant - (None). - */ - /* The index of the last-used entry in data_stack. */ - int depth; - /* The file data at each level, or NULL if not recording. */ - DataStackEntry * data_stack; - int data_stack_alloc; /* number of entries allocated at data_stack. */ - - /* The current file_data dictionary. Borrowed. */ - PyObject * cur_file_data; - - /* The line number of the last line recorded, for tracing arcs. - -1 means there was no previous line, as when entering a code object. - */ - int last_line; - - /* The parent frame for the last exception event, to fix missing returns. */ - PyFrameObject * last_exc_back; - int last_exc_firstlineno; - -#if COLLECT_STATS - struct { - unsigned int calls; - unsigned int lines; - unsigned int returns; - unsigned int exceptions; - unsigned int others; - unsigned int new_files; - unsigned int missed_returns; - unsigned int stack_reallocs; - unsigned int errors; - } stats; -#endif /* COLLECT_STATS */ -} Tracer; - -#define STACK_DELTA 100 - -static int -Tracer_init(Tracer *self, PyObject *args_unused, PyObject *kwds_unused) -{ -#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->data = NULL; - self->should_trace_cache = NULL; - self->arcs = NULL; - - self->started = 0; - self->tracing_arcs = 0; - - self->depth = -1; - self->data_stack = PyMem_Malloc(STACK_DELTA*sizeof(DataStackEntry)); - if (self->data_stack == NULL) { - STATS( self->stats.errors++; ) - PyErr_NoMemory(); - return RET_ERROR; - } - self->data_stack_alloc = STACK_DELTA; - - self->cur_file_data = NULL; - self->last_line = -1; - - self->last_exc_back = NULL; - - return RET_OK; -} - -static void -Tracer_dealloc(Tracer *self) -{ - if (self->started) { - PyEval_SetTrace(NULL, NULL); - } - - Py_XDECREF(self->should_trace); - Py_XDECREF(self->data); - Py_XDECREF(self->should_trace_cache); - - PyMem_Free(self->data_stack); - - Py_TYPE(self)->tp_free((PyObject*)self); -} - -#if TRACE_LOG -static const char * -indent(int n) -{ - static const char * spaces = - " " - " " - " " - " " - ; - return spaces + strlen(spaces) - n*2; -} - -static int logging = 0; -/* Set these constants to be a file substring and line number to start logging. */ -static const char * start_file = "tests/views"; -static int start_line = 27; - -static void -showlog(int depth, int lineno, PyObject * filename, const char * msg) -{ - if (logging) { - printf("%s%3d ", indent(depth), depth); - if (lineno) { - printf("%4d", lineno); - } - else { - printf(" "); - } - if (filename) { - printf(" %s", MyText_AS_STRING(filename)); - } - if (msg) { - printf(" %s", msg); - } - printf("\n"); - } -} - -#define SHOWLOG(a,b,c,d) showlog(a,b,c,d) -#else -#define SHOWLOG(a,b,c,d) -#endif /* TRACE_LOG */ - -#if WHAT_LOG -static const char * what_sym[] = {"CALL", "EXC ", "LINE", "RET "}; -#endif - -/* Record a pair of integers in self->cur_file_data. */ -static int -Tracer_record_pair(Tracer *self, int l1, int l2) -{ - int ret = RET_OK; - - PyObject * t = PyTuple_New(2); - if (t != NULL) { - PyTuple_SET_ITEM(t, 0, MyInt_FromLong(l1)); - PyTuple_SET_ITEM(t, 1, MyInt_FromLong(l2)); - if (PyDict_SetItem(self->cur_file_data, t, Py_None) < 0) { - STATS( self->stats.errors++; ) - ret = RET_ERROR; - } - Py_DECREF(t); - } - else { - STATS( self->stats.errors++; ) - ret = RET_ERROR; - } - return ret; -} - -/* - * The Trace Function - */ -static int -Tracer_trace(Tracer *self, PyFrameObject *frame, int what, PyObject *arg_unused) -{ - int ret = RET_OK; - PyObject * filename = NULL; - PyObject * tracename = NULL; - - #if WHAT_LOG - if (what <= sizeof(what_sym)/sizeof(const char *)) { - printf("trace: %s @ %s %d\n", what_sym[what], MyText_AS_STRING(frame->f_code->co_filename), frame->f_lineno); - } - #endif - - #if TRACE_LOG - if (strstr(MyText_AS_STRING(frame->f_code->co_filename), start_file) && frame->f_lineno == start_line) { - logging = 1; - } - #endif - - /* See below for details on missing-return detection. */ - if (self->last_exc_back) { - if (frame == self->last_exc_back) { - /* Looks like someone forgot to send a return event. We'll clear - the exception state and do the RETURN code here. Notice that the - frame we have in hand here is not the correct frame for the RETURN, - that frame is gone. Our handling for RETURN doesn't need the - actual frame, but we do log it, so that will look a little off if - you're looking at the detailed log. - - If someday we need to examine the frame when doing RETURN, then - we'll need to keep more of the missed frame's state. - */ - STATS( self->stats.missed_returns++; ) - if (self->depth >= 0) { - if (self->tracing_arcs && self->cur_file_data) { - if (Tracer_record_pair(self, self->last_line, -self->last_exc_firstlineno) < 0) { - return RET_ERROR; - } - } - SHOWLOG(self->depth, frame->f_lineno, frame->f_code->co_filename, "missedreturn"); - self->cur_file_data = self->data_stack[self->depth].file_data; - self->last_line = self->data_stack[self->depth].last_line; - self->depth--; - } - } - self->last_exc_back = NULL; - } - - - switch (what) { - case PyTrace_CALL: /* 0 */ - STATS( self->stats.calls++; ) - /* Grow the stack. */ - self->depth++; - if (self->depth >= self->data_stack_alloc) { - STATS( self->stats.stack_reallocs++; ) - /* We've outgrown our data_stack array: make it bigger. */ - int bigger = self->data_stack_alloc + STACK_DELTA; - DataStackEntry * bigger_data_stack = PyMem_Realloc(self->data_stack, bigger * sizeof(DataStackEntry)); - if (bigger_data_stack == NULL) { - STATS( self->stats.errors++; ) - PyErr_NoMemory(); - self->depth--; - return RET_ERROR; - } - self->data_stack = bigger_data_stack; - self->data_stack_alloc = bigger; - } - - /* Push the current state on the stack. */ - self->data_stack[self->depth].file_data = self->cur_file_data; - self->data_stack[self->depth].last_line = self->last_line; - - /* Check if we should trace this line. */ - filename = frame->f_code->co_filename; - tracename = PyDict_GetItem(self->should_trace_cache, filename); - if (tracename == NULL) { - STATS( self->stats.new_files++; ) - /* We've never considered this file before. */ - /* Ask should_trace about it. */ - PyObject * args = Py_BuildValue("(OO)", filename, frame); - tracename = PyObject_Call(self->should_trace, args, NULL); - Py_DECREF(args); - if (tracename == NULL) { - /* An error occurred inside should_trace. */ - STATS( self->stats.errors++; ) - return RET_ERROR; - } - if (PyDict_SetItem(self->should_trace_cache, filename, tracename) < 0) { - STATS( self->stats.errors++; ) - return RET_ERROR; - } - } - else { - Py_INCREF(tracename); - } - - /* If tracename is a string, then we're supposed to trace. */ - if (MyText_Check(tracename)) { - PyObject * file_data = PyDict_GetItem(self->data, tracename); - if (file_data == NULL) { - file_data = PyDict_New(); - if (file_data == NULL) { - STATS( self->stats.errors++; ) - return RET_ERROR; - } - ret = PyDict_SetItem(self->data, tracename, file_data); - Py_DECREF(file_data); - if (ret < 0) { - STATS( self->stats.errors++; ) - return RET_ERROR; - } - } - self->cur_file_data = file_data; - SHOWLOG(self->depth, frame->f_lineno, filename, "traced"); - } - else { - self->cur_file_data = NULL; - SHOWLOG(self->depth, frame->f_lineno, filename, "skipped"); - } - - Py_DECREF(tracename); - - self->last_line = -1; - break; - - case PyTrace_RETURN: /* 3 */ - STATS( self->stats.returns++; ) - /* A near-copy of this code is above in the missing-return handler. */ - if (self->depth >= 0) { - if (self->tracing_arcs && self->cur_file_data) { - int first = frame->f_code->co_firstlineno; - if (Tracer_record_pair(self, self->last_line, -first) < 0) { - return RET_ERROR; - } - } - - SHOWLOG(self->depth, frame->f_lineno, frame->f_code->co_filename, "return"); - self->cur_file_data = self->data_stack[self->depth].file_data; - self->last_line = self->data_stack[self->depth].last_line; - self->depth--; - } - break; - - case PyTrace_LINE: /* 2 */ - STATS( self->stats.lines++; ) - if (self->depth >= 0) { - SHOWLOG(self->depth, frame->f_lineno, frame->f_code->co_filename, "line"); - if (self->cur_file_data) { - /* We're tracing in this frame: record something. */ - if (self->tracing_arcs) { - /* Tracing arcs: key is (last_line,this_line). */ - if (Tracer_record_pair(self, self->last_line, frame->f_lineno) < 0) { - return RET_ERROR; - } - } - else { - /* Tracing lines: key is simply this_line. */ - PyObject * this_line = MyInt_FromLong(frame->f_lineno); - if (this_line == NULL) { - STATS( self->stats.errors++; ) - return RET_ERROR; - } - ret = PyDict_SetItem(self->cur_file_data, this_line, Py_None); - Py_DECREF(this_line); - if (ret < 0) { - STATS( self->stats.errors++; ) - return RET_ERROR; - } - } - } - self->last_line = frame->f_lineno; - } - break; - - case PyTrace_EXCEPTION: - /* Some code (Python 2.3, and pyexpat anywhere) fires an exception event - without a return event. To detect that, we'll keep a copy of the - parent frame for an exception event. If the next event is in that - frame, then we must have returned without a return event. We can - synthesize the missing event then. - - Python itself fixed this problem in 2.4. Pyexpat still has the bug. - I've reported the problem with pyexpat as http://bugs.python.org/issue6359 . - If it gets fixed, this code should still work properly. Maybe some day - the bug will be fixed everywhere coverage.py is supported, and we can - remove this missing-return detection. - - More about this fix: http://nedbatchelder.com/blog/200907/a_nasty_little_bug.html - */ - STATS( self->stats.exceptions++; ) - self->last_exc_back = frame->f_back; - self->last_exc_firstlineno = frame->f_code->co_firstlineno; - break; - - default: - STATS( self->stats.others++; ) - break; - } - - return RET_OK; -} - -/* - * A sys.settrace-compatible function that invokes our C trace function. - */ -static PyObject * -Tracer_pytrace(Tracer *self, PyObject *args) -{ - PyFrameObject *frame; - PyObject *what_str; - PyObject *arg_unused; - int what; - static char *what_names[] = { - "call", "exception", "line", "return", - "c_call", "c_exception", "c_return", - NULL - }; - - if (!PyArg_ParseTuple(args, "O!O!O:Tracer_pytrace", - &PyFrame_Type, &frame, &MyText_Type, &what_str, &arg_unused)) { - goto done; - } - - /* In Python, the what argument is a string, we need to find an int - for the C function. */ - for (what = 0; what_names[what]; what++) { - if (!strcmp(MyText_AS_STRING(what_str), what_names[what])) { - break; - } - } - - /* Invoke the C function, and return ourselves. */ - if (Tracer_trace(self, frame, what, arg_unused) == RET_OK) { - return PyObject_GetAttrString((PyObject*)self, "pytrace"); - } - -done: - return NULL; -} - -static PyObject * -Tracer_start(Tracer *self, PyObject *args_unused) -{ - PyEval_SetTrace((Py_tracefunc)Tracer_trace, (PyObject*)self); - self->started = 1; - self->tracing_arcs = self->arcs && PyObject_IsTrue(self->arcs); - self->last_line = -1; - - /* start() returns a trace function usable with sys.settrace() */ - return PyObject_GetAttrString((PyObject*)self, "pytrace"); -} - -static PyObject * -Tracer_stop(Tracer *self, PyObject *args_unused) -{ - if (self->started) { - PyEval_SetTrace(NULL, NULL); - self->started = 0; - } - - return Py_BuildValue(""); -} - -static PyObject * -Tracer_get_stats(Tracer *self) -{ -#if COLLECT_STATS - return Py_BuildValue( - "{sI,sI,sI,sI,sI,sI,sI,sI,si,sI}", - "calls", self->stats.calls, - "lines", self->stats.lines, - "returns", self->stats.returns, - "exceptions", self->stats.exceptions, - "others", self->stats.others, - "new_files", self->stats.new_files, - "missed_returns", self->stats.missed_returns, - "stack_reallocs", self->stats.stack_reallocs, - "stack_alloc", self->data_stack_alloc, - "errors", self->stats.errors - ); -#else - return Py_BuildValue(""); -#endif /* COLLECT_STATS */ -} - -static PyMemberDef -Tracer_members[] = { - { "should_trace", T_OBJECT, offsetof(Tracer, should_trace), 0, - PyDoc_STR("Function indicating whether to trace a file.") }, - - { "data", T_OBJECT, offsetof(Tracer, data), 0, - PyDoc_STR("The raw dictionary of trace data.") }, - - { "should_trace_cache", T_OBJECT, offsetof(Tracer, should_trace_cache), 0, - PyDoc_STR("Dictionary caching should_trace results.") }, - - { "arcs", T_OBJECT, offsetof(Tracer, arcs), 0, - PyDoc_STR("Should we trace arcs, or just lines?") }, - - { NULL } -}; - -static PyMethodDef -Tracer_methods[] = { - { "pytrace", (PyCFunction) Tracer_pytrace, METH_VARARGS, - PyDoc_STR("A trace function compatible with sys.settrace()") }, - - { "start", (PyCFunction) Tracer_start, METH_VARARGS, - PyDoc_STR("Start the tracer") }, - - { "stop", (PyCFunction) Tracer_stop, METH_VARARGS, - PyDoc_STR("Stop the tracer") }, - - { "get_stats", (PyCFunction) Tracer_get_stats, METH_VARARGS, - PyDoc_STR("Get statistics about the tracing") }, - - { NULL } -}; - -static PyTypeObject -TracerType = { - MyType_HEAD_INIT - "coverage.Tracer", /*tp_name*/ - sizeof(Tracer), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - (destructor)Tracer_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - "Tracer objects", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - Tracer_methods, /* tp_methods */ - Tracer_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)Tracer_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ -}; - -/* Module definition */ - -#define MODULE_DOC PyDoc_STR("Fast coverage tracer.") - -#if PY_MAJOR_VERSION >= 3 - -static PyModuleDef -moduledef = { - PyModuleDef_HEAD_INIT, - "coverage.tracer", - MODULE_DOC, - -1, - NULL, /* methods */ - NULL, - NULL, /* traverse */ - NULL, /* clear */ - NULL -}; - - -PyObject * -PyInit_tracer(void) -{ - PyObject * mod = PyModule_Create(&moduledef); - if (mod == NULL) { - return NULL; - } - - TracerType.tp_new = PyType_GenericNew; - if (PyType_Ready(&TracerType) < 0) { - Py_DECREF(mod); - return NULL; - } - - Py_INCREF(&TracerType); - PyModule_AddObject(mod, "Tracer", (PyObject *)&TracerType); - - return mod; -} - -#else - -void -inittracer(void) -{ - PyObject * mod; - - mod = Py_InitModule3("coverage.tracer", NULL, MODULE_DOC); - if (mod == NULL) { - return; - } - - TracerType.tp_new = PyType_GenericNew; - if (PyType_Ready(&TracerType) < 0) { - return; - } - - Py_INCREF(&TracerType); - PyModule_AddObject(mod, "Tracer", (PyObject *)&TracerType); -} - -#endif /* Py3k */ diff --git a/kivy/tests/coverage/xmlreport.py b/kivy/tests/coverage/xmlreport.py deleted file mode 100644 index ada38e77a5..0000000000 --- a/kivy/tests/coverage/xmlreport.py +++ /dev/null @@ -1,149 +0,0 @@ -"""XML reporting for coverage.py""" - -import os -import sys -import time -import xml.dom.minidom - -from coverage import __url__, __version__ -from coverage.backward import sorted # pylint: disable-msg=W0622 -from coverage.report import Reporter - -def rate(hit, num): - """Return the fraction of `hit`/`num`, as a string.""" - return "%.4g" % (float(hit) / (num or 1.0)) - - -class XmlReporter(Reporter): - """A reporter for writing Cobertura-style XML coverage results.""" - - def __init__(self, coverage, ignore_errors=False): - super(XmlReporter, self).__init__(coverage, ignore_errors) - - self.packages = None - self.xml_out = None - self.arcs = coverage.data.has_arcs() - - def report(self, morfs, outfile=None, config=None): - """Generate a Cobertura-compatible XML report for `morfs`. - - `morfs` is a list of modules or filenames. - - `outfile` is a file object to write the XML to. `config` is a - CoverageConfig instance. - - """ - # Initial setup. - outfile = outfile or sys.stdout - - # Create the DOM that will store the data. - impl = xml.dom.minidom.getDOMImplementation() - docType = impl.createDocumentType( - "coverage", None, - "http://cobertura.sourceforge.net/xml/coverage-03.dtd" - ) - self.xml_out = impl.createDocument(None, "coverage", docType) - - # Write header stuff. - xcoverage = self.xml_out.documentElement - xcoverage.setAttribute("version", __version__) - xcoverage.setAttribute("timestamp", str(int(time.time()*1000))) - xcoverage.appendChild(self.xml_out.createComment( - " Generated by coverage.py: %s " % __url__ - )) - xpackages = self.xml_out.createElement("packages") - xcoverage.appendChild(xpackages) - - # Call xml_file for each file in the data. - self.packages = {} - self.report_files(self.xml_file, morfs, config) - - lnum_tot, lhits_tot = 0, 0 - bnum_tot, bhits_tot = 0, 0 - - # Populate the XML DOM with the package info. - for pkg_name in sorted(self.packages.keys()): - pkg_data = self.packages[pkg_name] - class_elts, lhits, lnum, bhits, bnum = pkg_data - xpackage = self.xml_out.createElement("package") - xpackages.appendChild(xpackage) - xclasses = self.xml_out.createElement("classes") - xpackage.appendChild(xclasses) - for class_name in sorted(class_elts.keys()): - xclasses.appendChild(class_elts[class_name]) - xpackage.setAttribute("name", pkg_name.replace(os.sep, '.')) - xpackage.setAttribute("line-rate", rate(lhits, lnum)) - xpackage.setAttribute("branch-rate", rate(bhits, bnum)) - xpackage.setAttribute("complexity", "0") - - lnum_tot += lnum - lhits_tot += lhits - bnum_tot += bnum - bhits_tot += bhits - - xcoverage.setAttribute("line-rate", rate(lhits_tot, lnum_tot)) - xcoverage.setAttribute("branch-rate", rate(bhits_tot, bnum_tot)) - - # Use the DOM to write the output file. - outfile.write(self.xml_out.toprettyxml()) - - def xml_file(self, cu, 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. - dirname, fname = os.path.split(cu.name) - dirname = dirname or '.' - package = self.packages.setdefault(dirname, [{}, 0, 0, 0, 0 ]) - - xclass = self.xml_out.createElement("class") - - xclass.appendChild(self.xml_out.createElement("methods")) - - xlines = self.xml_out.createElement("lines") - xclass.appendChild(xlines) - className = fname.replace('.', '_') - xclass.setAttribute("name", className) - ext = os.path.splitext(cu.filename)[1] - xclass.setAttribute("filename", cu.name + ext) - xclass.setAttribute("complexity", "0") - - branch_stats = analysis.branch_stats() - - # For each statement, create an XML 'line' element. - for line in analysis.statements: - xline = self.xml_out.createElement("line") - xline.setAttribute("number", str(line)) - - # Q: can we get info about the number of times a statement is - # executed? If so, that should be recorded here. - xline.setAttribute("hits", str(int(not line in analysis.missing))) - - if self.arcs: - if line in branch_stats: - total, taken = branch_stats[line] - xline.setAttribute("branch", "true") - xline.setAttribute("condition-coverage", - "%d%% (%d/%d)" % (100*taken/total, taken, total) - ) - xlines.appendChild(xline) - - class_lines = len(analysis.statements) - class_hits = class_lines - len(analysis.missing) - - if self.arcs: - class_branches = sum([t for t,k in branch_stats.values()]) - missing_branches = sum([t-k for t,k in branch_stats.values()]) - class_br_hits = class_branches - missing_branches - else: - class_branches = 0.0 - class_br_hits = 0.0 - - # Finalize the statistics that are collected in the XML DOM. - xclass.setAttribute("line-rate", rate(class_hits, class_lines)) - xclass.setAttribute("branch-rate", rate(class_br_hits, class_branches)) - package[0][className] = xclass - package[1] += class_hits - package[2] += class_lines - package[3] += class_br_hits - package[4] += class_branches diff --git a/setup.cfg b/setup.cfg index 43162babe2..47902c3254 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,7 +1,6 @@ [nosetests] -with-coverage=0 +with-coverage=1 cover-package=kivy +cover-inclusive=1 with-id=1 verbosity=2 -logging-clear-handlers=0 -debug-log=/dev/null