From 7c40a5e2bbc216e276ce49dc0ea1ec84062bd6a7 Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Sun, 29 Nov 2009 07:17:18 -0500 Subject: Always more ideas. --- TODO.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO.txt b/TODO.txt index 6c5dc46f..30d2a2ef 100644 --- a/TODO.txt +++ b/TODO.txt @@ -97,6 +97,7 @@ x Why can't you specify execute (-x) and report (-r) in the same invocation? - Some way to focus in on red and yellow - Show only lines near highlights? - Jump to next highlight? + - Cookie for changes to pyfile.html state. + Clickable column headers on the index page. + Syntax coloring in HTML report. + Dynamic effects in HTML report. @@ -123,6 +124,7 @@ x Why can't you specify execute (-x) and report (-r) in the same invocation? - Double function decorators: all decorator lines count as executable code. - Document the .coverage file format. + HTML reporting. + - Much more detail about what's in the report. - References between pages are off: - They have tags around them. - They use #anchors that don't survive the px->html conversion. -- cgit v1.2.1 From 7fb8e7193f775775dff1b1a27c948797c6fc836d Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Sun, 29 Nov 2009 07:18:07 -0500 Subject: Fix some self-measurement problems. Now coverage_coverage.py works again (had to be sure to stop coverage if check_coverage threw an exception). --- coverage/collector.py | 5 +++++ coverage/control.py | 10 ++++++---- test/coverage_coverage.py | 6 +++++- test/coveragetest.py | 13 +++++++------ test/test_api.py | 3 +++ 5 files changed, 26 insertions(+), 11 deletions(-) diff --git a/coverage/collector.py b/coverage/collector.py index 5bbd02e0..6ea419ee 100644 --- a/coverage/collector.py +++ b/coverage/collector.py @@ -148,6 +148,9 @@ class Collector(object): # 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__ @@ -196,6 +199,7 @@ class Collector(object): 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 @@ -204,6 +208,7 @@ class Collector(object): def stop(self): """Stop collecting trace information.""" + #print >>sys.stderr, "Stopping: %r" % self._collectors assert self._collectors assert self._collectors[-1] is self diff --git a/coverage/control.py b/coverage/control.py index 674bb15e..7efc3492 100644 --- a/coverage/control.py +++ b/coverage/control.py @@ -1,6 +1,6 @@ """Core control stuff for Coverage.""" -import os, socket +import atexit, os, socket from coverage.annotate import AnnotateReporter from coverage.backward import string_class # pylint: disable-msg=W0622 @@ -56,7 +56,8 @@ class coverage(object): self.cover_pylib = cover_pylib self.auto_data = auto_data - + self.atexit_registered = False + self.exclude_re = "" self.exclude_list = [] @@ -168,8 +169,9 @@ class coverage(object): if self.auto_data: self.load() # Save coverage data when Python exits. - import atexit - atexit.register(self.save) + if not self.atexit_registered: + atexit.register(self.save) + self.atexit_registered = True self.collector.start() def stop(self): diff --git a/test/coverage_coverage.py b/test/coverage_coverage.py index e1e7674f..64380ab7 100644 --- a/test/coverage_coverage.py +++ b/test/coverage_coverage.py @@ -30,12 +30,16 @@ import coverage # don't warn about re-import: pylint: disable-msg=W0404 sys.modules.update(covmods) # Run nosetests, with the arguments from our command line. +nose_args = sys.argv[1:] +print(":: Running nosetests %s" % " ".join(nose_args)) import nose -nose.run(sys.argv[1:]) +nose.run(nose_args) cov.stop() +print(":: Saving .coverage") cov.save() +print(":: Writing HTML report to %s/index.html" % HTML_DIR) cov.clear_exclude() cov.exclude("#pragma: no cover") cov.exclude("def __repr__") diff --git a/test/coveragetest.py b/test/coveragetest.py index 1fb04721..073dc39f 100644 --- a/test/coveragetest.py +++ b/test/coveragetest.py @@ -168,12 +168,13 @@ class CoverageTest(TestCase): cov.exclude(exc) cov.start() - # Import the python file, executing it. - mod = self.import_module(modname) - - # Stop Coverage. - cov.stop() - + try: + # Import the python file, executing it. + mod = self.import_module(modname) + finally: + # Stop Coverage. + cov.stop() + # Clean up our side effects del sys.modules[modname] diff --git a/test/test_api.py b/test/test_api.py index 932606fd..7308cdc6 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -8,6 +8,9 @@ from coverage.backward import StringIO sys.path.insert(0, os.path.split(__file__)[0]) # Force relative import for Py3k from coveragetest import CoverageTest +# This file uses the singleton module interface. Prevent it from writing +# .coverage files at exit. +coverage.use_cache(0) class ApiTest(CoverageTest): """Api-oriented tests for Coverage.""" -- cgit v1.2.1 From 8f4bb15bf8bb6c8510051a865814cc5c2bf53e70 Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Sun, 29 Nov 2009 07:31:30 -0500 Subject: Don't measure mock.py when we measure our coverage. --- coverage/codeunit.py | 1 + test/coverage_coverage.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/coverage/codeunit.py b/coverage/codeunit.py index e3107052..6d156da7 100644 --- a/coverage/codeunit.py +++ b/coverage/codeunit.py @@ -34,6 +34,7 @@ def code_unit_factory(morfs, file_locator, omit_prefixes=None): code_units = [CodeUnit(morf, file_locator) for morf in morfs] if omit_prefixes: + assert not isinstance(omit_prefixes, string_class) # common mistake prefixes = [file_locator.abs_file(p) for p in omit_prefixes] filtered = [] for cu in code_units: diff --git a/test/coverage_coverage.py b/test/coverage_coverage.py index 64380ab7..874cdd6f 100644 --- a/test/coverage_coverage.py +++ b/test/coverage_coverage.py @@ -46,4 +46,4 @@ cov.exclude("def __repr__") cov.exclude("if __name__ == .__main__.:") cov.exclude("raise AssertionError") -cov.html_report(directory=HTML_DIR, ignore_errors=True) +cov.html_report(directory=HTML_DIR, ignore_errors=True, omit_prefixes=["mock"]) -- cgit v1.2.1 From f4fd807e53113a76173112e3ae0b8d35797b9b73 Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Sun, 29 Nov 2009 09:51:40 -0500 Subject: coverage_coverage.py now writes separate data files for each run of the test suite, and combines them for reporting. --- allcoverage.cmd | 44 ++++++++++++++++++ test/coverage_coverage.py | 111 +++++++++++++++++++++++++++++----------------- 2 files changed, 114 insertions(+), 41 deletions(-) create mode 100644 allcoverage.cmd diff --git a/allcoverage.cmd b/allcoverage.cmd new file mode 100644 index 00000000..5da7e15f --- /dev/null +++ b/allcoverage.cmd @@ -0,0 +1,44 @@ +@echo off +make --quiet testdata + +call \ned\bin\switchpy 23 +python setup.py -q develop +set COVERAGE_TEST_TRACER=c +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 +del coverage\tracer.pyd +set COVERAGE_TEST_TRACER=py +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 + +call \ned\bin\switchpy 24 +python setup.py -q develop +set COVERAGE_TEST_TRACER=c +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 +del coverage\tracer.pyd +set COVERAGE_TEST_TRACER=py +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 + +call \ned\bin\switchpy 25 +python setup.py -q develop +set COVERAGE_TEST_TRACER=c +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 +del coverage\tracer.pyd +set COVERAGE_TEST_TRACER=py +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 + +call \ned\bin\switchpy 26 +python setup.py -q develop +set COVERAGE_TEST_TRACER=c +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 +del coverage\tracer.pyd +set COVERAGE_TEST_TRACER=py +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 + +call \ned\bin\switchpy 31 +python setup.py -q install +set COVERAGE_TEST_TRACER=c +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 +del \python31\lib\site-packages\coverage\tracer.pyd +set COVERAGE_TEST_TRACER=py +python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 + +python test\coverage_coverage.py report diff --git a/test/coverage_coverage.py b/test/coverage_coverage.py index 874cdd6f..a1cb13fc 100644 --- a/test/coverage_coverage.py +++ b/test/coverage_coverage.py @@ -1,49 +1,78 @@ -"""Coverage-test Coverage itself.""" +"""Coverage-test Coverage.py itself.""" -import coverage import os, shutil, sys +import nose HTML_DIR = "htmlcov" -if os.path.exists(HTML_DIR): - shutil.rmtree(HTML_DIR) - -cov = coverage.coverage(branch=True) -# Cheap trick: the coverage code itself is excluded from measurement, but if -# we clobber the cover_prefix in the coverage object, we can defeat the -# self-detection. -cov.cover_prefix = "Please measure coverage.py!" -cov.erase() -cov.start() - -# Re-import coverage to get it coverage tested! I don't understand all the -# mechanics here, but if I don't carry over the imported modules (in covmods), -# then things go haywire (os == None eventually). -covmods = {} -covdir = os.path.split(coverage.__file__) -for name, mod in sys.modules.items(): - if name.startswith('coverage'): - if hasattr(mod, '__file__') and mod.__file__.startswith(covdir): - covmods[name] = mod - del sys.modules[name] -import coverage # don't warn about re-import: pylint: disable-msg=W0404 -sys.modules.update(covmods) - -# Run nosetests, with the arguments from our command line. -nose_args = sys.argv[1:] -print(":: Running nosetests %s" % " ".join(nose_args)) -import nose -nose.run(nose_args) +def run_tests_with_coverage(): + import coverage + + tracer = os.environ.get('COVERAGE_TEST_TRACER', 'c') + version = "%s%s" % sys.version_info[:2] + suffix = ".%s_%s" % (version, tracer) + + cov = coverage.coverage(branch=True, data_suffix=suffix) + # Cheap trick: the coverage code itself is excluded from measurement, but + # if we clobber the cover_prefix in the coverage object, we can defeat the + # self-detection. + cov.cover_prefix = "Please measure coverage.py!" + cov.erase() + cov.start() + + # Re-import coverage to get it coverage tested! I don't understand all the + # mechanics here, but if I don't carry over the imported modules (in + # covmods), then things go haywire (os == None, eventually). + covmods = {} + covdir = os.path.split(coverage.__file__)[0] + # We have to make a list since we'll be deleting in the loop. + modules = list(sys.modules.items()) + for name, mod in modules: + if name.startswith('coverage'): + if hasattr(mod, '__file__') and mod.__file__.startswith(covdir): + covmods[name] = mod + del sys.modules[name] + import coverage # don't warn about re-import: pylint: disable-msg=W0404 + sys.modules.update(covmods) + + # Run nosetests, with the arguments from our command line. + print(":: Running nosetests %s" % " ".join(sys.argv[1:])) + nose.run() + + cov.stop() + print(":: Saving .coverage%s" % suffix) + cov.save() + +def report_on_combined_files(): + + if os.path.exists(HTML_DIR): + shutil.rmtree(HTML_DIR) -cov.stop() -print(":: Saving .coverage") -cov.save() + print(":: Writing HTML report to %s/index.html" % HTML_DIR) + import coverage + cov = coverage.coverage() + cov.combine() + cov.save() + cov.clear_exclude() + cov.exclude("#pragma: no cover") + cov.exclude("def __repr__") + cov.exclude("if __name__ == .__main__.:") + cov.exclude("raise AssertionError") + + cov.html_report(directory=HTML_DIR, ignore_errors=True, omit_prefixes=["mock"]) -print(":: Writing HTML report to %s/index.html" % HTML_DIR) -cov.clear_exclude() -cov.exclude("#pragma: no cover") -cov.exclude("def __repr__") -cov.exclude("if __name__ == .__main__.:") -cov.exclude("raise AssertionError") -cov.html_report(directory=HTML_DIR, ignore_errors=True, omit_prefixes=["mock"]) +try: + cmd = sys.argv[1] +except IndexError: + cmd = '' + +if cmd == 'run': + # Ugly hack: nose.run reads sys.argv directly, so here I delete my command + # argument so that sys.argv is left as just nose arguments. + del sys.argv[1] + run_tests_with_coverage() +elif cmd == 'report': + report_on_combined_files() +else: + print("Need 'run' or 'report'") -- cgit v1.2.1 From 7abb46ad6a6e511bc10646dd3f30cb93eb44c8d8 Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Sun, 29 Nov 2009 21:26:50 -0500 Subject: Ideas --- TODO.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/TODO.txt b/TODO.txt index 30d2a2ef..2a528879 100644 --- a/TODO.txt +++ b/TODO.txt @@ -64,7 +64,9 @@ x Tricky swapping of collector like figleaf, pycov, et al. (Don't need to do - Track callers of functions (ala std module trace) - Method/Class/Module coverage reporting. - .coverage files that can be kept separate, rather than accumulated. - +- test/coverage map: http://rbtcollins.wordpress.com/2009/09/16/back-from-hiatus/ + - Similar to figleaf's sections. + * Convenience -- cgit v1.2.1 From 61eb3e5f2d1bc9c6997073dca8db888b3d6eb410 Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Mon, 30 Nov 2009 06:58:57 -0500 Subject: Use Distribute for 3.x, stick with setuptools for 2.x --- MANIFEST.in | 1 + Makefile | 8 +- checkeol.py | 1 - distribute_setup.py | 458 ++++++++++++++++++++++++++++++++++++++++++++++++++++ scripts/coverage | 10 -- setup.py | 45 +++--- 6 files changed, 479 insertions(+), 44 deletions(-) create mode 100644 distribute_setup.py delete mode 100644 scripts/coverage diff --git a/MANIFEST.in b/MANIFEST.in index ce340f66..907d9d0d 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -2,6 +2,7 @@ include coverage.egg-info/*.* include coverage/*.py include coverage/htmlfiles/*.* +include distribute_setup.py include ez_setup.py include setup.py include README.txt diff --git a/Makefile b/Makefile index b493483d..84c75ce5 100644 --- a/Makefile +++ b/Makefile @@ -21,15 +21,11 @@ clean: -rm -f setuptools-*.egg -rm -rf doc/_build/* -LINTABLE = \ - coverage \ - scripts/coverage \ - setup.py \ - test +LINTABLE = coverage setup.py test lint: -python -x /Python25/Scripts/pylint.bat --rcfile=.pylintrc $(LINTABLE) - python /Python25/Lib/tabnanny.py coverage scripts test setup.py + python /Python25/Lib/tabnanny.py $(LINTABLE) python checkeol.py testready: testdata devinst diff --git a/checkeol.py b/checkeol.py index 8b6f60c0..68efc2fa 100644 --- a/checkeol.py +++ b/checkeol.py @@ -20,6 +20,5 @@ def check_files(root, patterns): dirs.remove('.svn') check_files("coverage", ["*.py"]) -check_files("scripts", ["*"]) check_files("test", ["*.py", "*,cover"]) check_file("setup.py") diff --git a/distribute_setup.py b/distribute_setup.py new file mode 100644 index 00000000..cfb3bbef --- /dev/null +++ b/distribute_setup.py @@ -0,0 +1,458 @@ +#!python +"""Bootstrap distribute installation + +If you want to use setuptools in your package's setup.py, just include this +file in the same directory with it, and add this to the top of your setup.py:: + + from distribute_setup import use_setuptools + use_setuptools() + +If you want to require a specific version of setuptools, set a download +mirror, or use an alternate download directory, you can do so by supplying +the appropriate options to ``use_setuptools()``. + +This file can also be run as a script to install or upgrade setuptools. +""" +import os +import sys +import time +import fnmatch +import tempfile +import tarfile +from distutils import log + +try: + from site import USER_SITE +except ImportError: + USER_SITE = None + +try: + import subprocess + + def _python_cmd(*args): + args = (sys.executable,) + args + return subprocess.call(args) == 0 + +except ImportError: + # will be used for python 2.3 + def _python_cmd(*args): + args = (sys.executable,) + args + # quoting arguments if windows + if sys.platform == 'win32': + def quote(arg): + if ' ' in arg: + return '"%s"' % arg + return arg + args = [quote(arg) for arg in args] + return os.spawnl(os.P_WAIT, sys.executable, *args) == 0 + +DEFAULT_VERSION = "0.6.8" +DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/" +SETUPTOOLS_PKG_INFO = """\ +Metadata-Version: 1.0 +Name: setuptools +Version: 0.6c9 +Summary: xxxx +Home-page: xxx +Author: xxx +Author-email: xxx +License: xxx +Description: xxx +""" + + +def _install(tarball): + # extracting the tarball + tmpdir = tempfile.mkdtemp() + log.warn('Extracting in %s', tmpdir) + old_wd = os.getcwd() + try: + os.chdir(tmpdir) + tar = tarfile.open(tarball) + _extractall(tar) + tar.close() + + # going in the directory + subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) + os.chdir(subdir) + log.warn('Now working in %s', subdir) + + # installing + log.warn('Installing Distribute') + assert _python_cmd('setup.py', 'install') + finally: + os.chdir(old_wd) + + +def _build_egg(egg, tarball, to_dir): + # extracting the tarball + tmpdir = tempfile.mkdtemp() + log.warn('Extracting in %s', tmpdir) + old_wd = os.getcwd() + try: + os.chdir(tmpdir) + tar = tarfile.open(tarball) + _extractall(tar) + tar.close() + + # going in the directory + subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) + os.chdir(subdir) + log.warn('Now working in %s', subdir) + + # building an egg + log.warn('Building a Distribute egg in %s', to_dir) + _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) + + finally: + os.chdir(old_wd) + # returning the result + log.warn(egg) + if not os.path.exists(egg): + raise IOError('Could not build the egg.') + + +def _do_download(version, download_base, to_dir, download_delay): + egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg' + % (version, sys.version_info[0], sys.version_info[1])) + if not os.path.exists(egg): + tarball = download_setuptools(version, download_base, + to_dir, download_delay) + _build_egg(egg, tarball, to_dir) + sys.path.insert(0, egg) + import setuptools + setuptools.bootstrap_install_from = egg + + +def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, + to_dir=os.curdir, download_delay=15, no_fake=True): + # making sure we use the absolute path + to_dir = os.path.abspath(to_dir) + was_imported = 'pkg_resources' in sys.modules or \ + 'setuptools' in sys.modules + try: + try: + import pkg_resources + if not hasattr(pkg_resources, '_distribute'): + if not no_fake: + _fake_setuptools() + raise ImportError + except ImportError: + return _do_download(version, download_base, to_dir, download_delay) + try: + pkg_resources.require("distribute>="+version) + return + except pkg_resources.VersionConflict: + e = sys.exc_info()[1] + if was_imported: + sys.stderr.write( + "The required version of distribute (>=%s) is not available,\n" + "and can't be installed while this script is running. Please\n" + "install a more recent version first, using\n" + "'easy_install -U distribute'." + "\n\n(Currently using %r)\n" % (version, e.args[0])) + sys.exit(2) + else: + del pkg_resources, sys.modules['pkg_resources'] # reload ok + return _do_download(version, download_base, to_dir, + download_delay) + except pkg_resources.DistributionNotFound: + return _do_download(version, download_base, to_dir, + download_delay) + finally: + if not no_fake: + _create_fake_setuptools_pkg_info(to_dir) + +def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, + to_dir=os.curdir, delay=15): + """Download distribute from a specified location and return its filename + + `version` should be a valid distribute version number that is available + as an egg for download under the `download_base` URL (which should end + with a '/'). `to_dir` is the directory where the egg will be downloaded. + `delay` is the number of seconds to pause before an actual download + attempt. + """ + # making sure we use the absolute path + to_dir = os.path.abspath(to_dir) + try: + from urllib.request import urlopen + except ImportError: + from urllib2 import urlopen + tgz_name = "distribute-%s.tar.gz" % version + url = download_base + tgz_name + saveto = os.path.join(to_dir, tgz_name) + src = dst = None + if not os.path.exists(saveto): # Avoid repeated downloads + try: + log.warn("Downloading %s", url) + src = urlopen(url) + # Read/write all in one block, so we don't create a corrupt file + # if the download is interrupted. + data = src.read() + dst = open(saveto, "wb") + dst.write(data) + finally: + if src: + src.close() + if dst: + dst.close() + return os.path.realpath(saveto) + + +def _patch_file(path, content): + """Will backup the file then patch it""" + existing_content = open(path).read() + if existing_content == content: + # already patched + log.warn('Already patched.') + return False + log.warn('Patching...') + _rename_path(path) + f = open(path, 'w') + try: + f.write(content) + finally: + f.close() + return True + + +def _same_content(path, content): + return open(path).read() == content + + +def _rename_path(path): + new_name = path + '.OLD.%s' % time.time() + log.warn('Renaming %s into %s', path, new_name) + try: + from setuptools.sandbox import DirectorySandbox + def _violation(*args): + pass + DirectorySandbox._violation = _violation + except ImportError: + pass + + os.rename(path, new_name) + return new_name + + +def _remove_flat_installation(placeholder): + if not os.path.isdir(placeholder): + log.warn('Unkown installation at %s', placeholder) + return False + found = False + for file in os.listdir(placeholder): + if fnmatch.fnmatch(file, 'setuptools*.egg-info'): + found = True + break + if not found: + log.warn('Could not locate setuptools*.egg-info') + return + + log.warn('Removing elements out of the way...') + pkg_info = os.path.join(placeholder, file) + if os.path.isdir(pkg_info): + patched = _patch_egg_dir(pkg_info) + else: + patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO) + + if not patched: + log.warn('%s already patched.', pkg_info) + return False + # now let's move the files out of the way + for element in ('setuptools', 'pkg_resources.py', 'site.py'): + element = os.path.join(placeholder, element) + if os.path.exists(element): + _rename_path(element) + else: + log.warn('Could not find the %s element of the ' + 'Setuptools distribution', element) + return True + + +def _after_install(dist): + log.warn('After install bootstrap.') + placeholder = dist.get_command_obj('install').install_purelib + _create_fake_setuptools_pkg_info(placeholder) + +def _create_fake_setuptools_pkg_info(placeholder): + if not placeholder or not os.path.exists(placeholder): + log.warn('Could not find the install location') + return + pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1]) + setuptools_file = 'setuptools-0.6c9-py%s.egg-info' % pyver + pkg_info = os.path.join(placeholder, setuptools_file) + if os.path.exists(pkg_info): + log.warn('%s already exists', pkg_info) + return + log.warn('Creating %s', pkg_info) + f = open(pkg_info, 'w') + try: + f.write(SETUPTOOLS_PKG_INFO) + finally: + f.close() + pth_file = os.path.join(placeholder, 'setuptools.pth') + log.warn('Creating %s', pth_file) + f = open(pth_file, 'w') + try: + f.write(os.path.join(os.curdir, setuptools_file)) + finally: + f.close() + + +def _patch_egg_dir(path): + # let's check if it's already patched + pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') + if os.path.exists(pkg_info): + if _same_content(pkg_info, SETUPTOOLS_PKG_INFO): + log.warn('%s already patched.', pkg_info) + return False + _rename_path(path) + os.mkdir(path) + os.mkdir(os.path.join(path, 'EGG-INFO')) + pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') + f = open(pkg_info, 'w') + try: + f.write(SETUPTOOLS_PKG_INFO) + finally: + f.close() + return True + + +def _before_install(): + log.warn('Before install bootstrap.') + _fake_setuptools() + + +def _under_prefix(location): + if 'install' not in sys.argv: + return True + args = sys.argv[sys.argv.index('install')+1:] + for index, arg in enumerate(args): + for option in ('--root', '--prefix'): + if arg.startswith('%s=' % option): + top_dir = arg.split('root=')[-1] + return location.startswith(top_dir) + elif arg == option: + if len(args) > index: + top_dir = args[index+1] + return location.startswith(top_dir) + elif option == '--user' and USER_SITE is not None: + return location.startswith(USER_SITE) + return True + + +def _fake_setuptools(): + log.warn('Scanning installed packages') + try: + import pkg_resources + except ImportError: + # we're cool + log.warn('Setuptools or Distribute does not seem to be installed.') + return + ws = pkg_resources.working_set + try: + setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools', + replacement=False)) + except TypeError: + # old distribute API + setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools')) + + if setuptools_dist is None: + log.warn('No setuptools distribution found') + return + # detecting if it was already faked + setuptools_location = setuptools_dist.location + log.warn('Setuptools installation detected at %s', setuptools_location) + + # if --root or --preix was provided, and if + # setuptools is not located in them, we don't patch it + if not _under_prefix(setuptools_location): + log.warn('Not patching, --root or --prefix is installing Distribute' + ' in another location') + return + + # let's see if its an egg + if not setuptools_location.endswith('.egg'): + log.warn('Non-egg installation') + res = _remove_flat_installation(setuptools_location) + if not res: + return + else: + log.warn('Egg installation') + pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO') + if (os.path.exists(pkg_info) and + _same_content(pkg_info, SETUPTOOLS_PKG_INFO)): + log.warn('Already patched.') + return + log.warn('Patching...') + # let's create a fake egg replacing setuptools one + res = _patch_egg_dir(setuptools_location) + if not res: + return + log.warn('Patched done.') + _relaunch() + + +def _relaunch(): + log.warn('Relaunching...') + # we have to relaunch the process + args = [sys.executable] + sys.argv + sys.exit(subprocess.call(args)) + + +def _extractall(self, path=".", members=None): + """Extract all members from the archive to the current working + directory and set owner, modification time and permissions on + directories afterwards. `path' specifies a different directory + to extract to. `members' is optional and must be a subset of the + list returned by getmembers(). + """ + import copy + import operator + from tarfile import ExtractError + directories = [] + + if members is None: + members = self + + for tarinfo in members: + if tarinfo.isdir(): + # Extract directories with a safe mode. + directories.append(tarinfo) + tarinfo = copy.copy(tarinfo) + tarinfo.mode = 448 # decimal for oct 0700 + self.extract(tarinfo, path) + + # Reverse sort directories. + if sys.version_info < (2, 4): + def sorter(dir1, dir2): + return cmp(dir1.name, dir2.name) + directories.sort(sorter) + directories.reverse() + else: + directories.sort(key=operator.attrgetter('name'), reverse=True) + + # Set correct owner, mtime and filemode on directories. + for tarinfo in directories: + dirpath = os.path.join(path, tarinfo.name) + try: + self.chown(tarinfo, dirpath) + self.utime(tarinfo, dirpath) + self.chmod(tarinfo, dirpath) + except ExtractError: + e = sys.exc_info()[1] + if self.errorlevel > 1: + raise + else: + self._dbg(1, "tarfile: %s" % e) + + +def main(argv, version=DEFAULT_VERSION): + """Install or upgrade setuptools and EasyInstall""" + tarball = download_setuptools() + _install(tarball) + + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/scripts/coverage b/scripts/coverage deleted file mode 100644 index e546cb7e..00000000 --- a/scripts/coverage +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/python -""" Coverage.py code coverage measurement. - http://nedbatchelder.com/code/coverage - - Copyright 2004-2009, Ned Batchelder. -""" - -import sys -from coverage import main # pylint: disable-msg=W0406 -sys.exit(main()) diff --git a/setup.py b/setup.py index 4a5aba1c..dfb4aedf 100644 --- a/setup.py +++ b/setup.py @@ -29,34 +29,18 @@ Topic :: Software Development :: Testing # Pull in the tools we need. import sys -if sys.hexversion < 0x03000000: - # In Py 2.x, use setuptools. - from ez_setup import use_setuptools - use_setuptools() - - from setuptools import setup - from distutils.core import Extension - - more_setup_args = dict( - entry_points = { - 'console_scripts': [ - 'coverage = coverage:main', - ] - }, - - # We need to get HTML assets from our htmlfiles dir. - zip_safe = False, - ) +# Distribute is a new fork of setuptools. It's supported on Py3.x, so we use +# it there, but stick with classic setuptools on Py2.x until Distribute becomes +# more accepted. +if sys.hexversion > 0x03000000: + from distribute_setup import use_setuptools else: - # No setuptools yet for Py 3.x, so do without. - from distutils.core import setup, Extension + from ez_setup import use_setuptools - more_setup_args = dict( - scripts = [ - 'scripts/coverage', - ], - ) +use_setuptools() +from setuptools import setup +from distutils.core import Extension # Get or massage our metadata. @@ -94,6 +78,15 @@ setup( Extension("coverage.tracer", sources=["coverage/tracer.c"]) ], + entry_points = { + 'console_scripts': [ + 'coverage = coverage:main', + ] + }, + + # We need to get HTML assets from our htmlfiles dir. + zip_safe = False, + author = 'Ned Batchelder', author_email = 'ned@nedbatchelder.com', description = doclines[0], @@ -102,6 +95,4 @@ setup( license = 'BSD', classifiers = classifier_list, url = __url__, - - **more_setup_args ) -- cgit v1.2.1 From 2f004409c3e1e7eecb1a3d1acb0d13dca323c082 Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Mon, 30 Nov 2009 08:00:41 -0500 Subject: The testing setup is involved: document it some. --HG-- rename : release.txt => howto.txt --- howto.txt | 39 +++++++++++++++++++++++++++++++++++++++ release.txt | 39 --------------------------------------- 2 files changed, 39 insertions(+), 39 deletions(-) create mode 100644 howto.txt delete mode 100644 release.txt diff --git a/howto.txt b/howto.txt new file mode 100644 index 00000000..36beef1e --- /dev/null +++ b/howto.txt @@ -0,0 +1,39 @@ +* Release checklist + +- Test on: + - Windows + - Ubuntu + - Mac + - Pythons 2.3, 2.4, 2.5, 2.6, 3.1 +- Version number in coverage/__init__.py + - 3.1a1, 3.1b1, 3.1c1, 3.1 +- Update CHANGES, including release date. +- Update docstring in setup.py, including "New in x.y:" +- Update docs + - Version, date, and changes in doc/changes.rst + - Version and date in doc/index.rst + - Version and copyright date in doc/conf.py + - Generate new sample_html to get the latest, incl footer version number: + cd C:\ned\cog\trunk + rmdir/s/q htmlcov + coverage run cogapp\test_cogapp.py CogTestsInMemory + coverage html -i -d htmlcov + copy htmlcov\*.* C:\ned\coverage\trunk\doc\sample_html + - Build and publish docs: + $ make px publish +- Kits: + - source .tgz and windows .exe for each Python + - $ allkits.cmd +- Update PyPi: + - $ make pypi + - Visit http://pypi.python.org/pypi?%3Aaction=pkg_edit&name=coverage : + - Upload kits + - Label the source kit with "Use this for either Python 2.x or 3.x" + - show/hide the proper versions. +- Tag the tree + - hg tag -m "Coverage 3.0.1" coverage-3.0.1 +- Update nedbatchelder.com + - Blog post? +- Update bitbucket: + - Issue tracker should get new version number in picker. +- Announce on TIP. diff --git a/release.txt b/release.txt deleted file mode 100644 index 36beef1e..00000000 --- a/release.txt +++ /dev/null @@ -1,39 +0,0 @@ -* Release checklist - -- Test on: - - Windows - - Ubuntu - - Mac - - Pythons 2.3, 2.4, 2.5, 2.6, 3.1 -- Version number in coverage/__init__.py - - 3.1a1, 3.1b1, 3.1c1, 3.1 -- Update CHANGES, including release date. -- Update docstring in setup.py, including "New in x.y:" -- Update docs - - Version, date, and changes in doc/changes.rst - - Version and date in doc/index.rst - - Version and copyright date in doc/conf.py - - Generate new sample_html to get the latest, incl footer version number: - cd C:\ned\cog\trunk - rmdir/s/q htmlcov - coverage run cogapp\test_cogapp.py CogTestsInMemory - coverage html -i -d htmlcov - copy htmlcov\*.* C:\ned\coverage\trunk\doc\sample_html - - Build and publish docs: - $ make px publish -- Kits: - - source .tgz and windows .exe for each Python - - $ allkits.cmd -- Update PyPi: - - $ make pypi - - Visit http://pypi.python.org/pypi?%3Aaction=pkg_edit&name=coverage : - - Upload kits - - Label the source kit with "Use this for either Python 2.x or 3.x" - - show/hide the proper versions. -- Tag the tree - - hg tag -m "Coverage 3.0.1" coverage-3.0.1 -- Update nedbatchelder.com - - Blog post? -- Update bitbucket: - - Issue tracker should get new version number in picker. -- Announce on TIP. -- cgit v1.2.1 From bf87b6346d32e4bd66e0282020304f97977a49bc Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Mon, 30 Nov 2009 08:02:40 -0500 Subject: The testing setup is involved: document it some. --- howto.txt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/howto.txt b/howto.txt index 36beef1e..316a8996 100644 --- a/howto.txt +++ b/howto.txt @@ -37,3 +37,18 @@ - Update bitbucket: - Issue tracker should get new version number in picker. - Announce on TIP. + + + +* Testing + +(automate these someday) + +- On Py 2.x: need setuptools installed +- On Py 3.x: need Distribute installed +- In each Python installation to be used, create a "coverage_test_egg.pth" + containing:: + + c:\ned\coverage\trunk\test\eggsrc\dist\covtestegg1-0.0.0-py2.5.egg + + (or equivalent). -- cgit v1.2.1 From 03898850c1646d639caaac94587d4284163c32bf Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Mon, 30 Nov 2009 08:16:52 -0500 Subject: Adapt the all-Python scripts to the new 3.1 Distribute scheme. allcoverage.cmd still doesn't save 3.1 results for some reason... --- allcoverage.cmd | 4 ++-- alltests.cmd | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/allcoverage.cmd b/allcoverage.cmd index 5da7e15f..2545427b 100644 --- a/allcoverage.cmd +++ b/allcoverage.cmd @@ -34,10 +34,10 @@ set COVERAGE_TEST_TRACER=py python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 call \ned\bin\switchpy 31 -python setup.py -q install +python setup.py -q develop set COVERAGE_TEST_TRACER=c python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 -del \python31\lib\site-packages\coverage\tracer.pyd +del coverage\tracer.pyd set COVERAGE_TEST_TRACER=py python test\coverage_coverage.py run %1 %2 %3 %4 %5 %6 %7 %8 %9 diff --git a/alltests.cmd b/alltests.cmd index 7b26ab81..5aee1e42 100644 --- a/alltests.cmd +++ b/alltests.cmd @@ -34,10 +34,10 @@ set COVERAGE_TEST_TRACER=py nosetests %1 %2 %3 %4 %5 %6 %7 %8 %9 call \ned\bin\switchpy 31 -python setup.py -q install +python setup.py -q develop set COVERAGE_TEST_TRACER=c python \python31\Scripts\nosetests3 %1 %2 %3 %4 %5 %6 %7 %8 %9 -del \python31\lib\site-packages\coverage\tracer.pyd +del coverage\tracer.pyd set COVERAGE_TEST_TRACER=py python \python31\Scripts\nosetests3 %1 %2 %3 %4 %5 %6 %7 %8 %9 -- cgit v1.2.1 From 62cd957d5ff36fa745affac27d23be7d7928b40b Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Mon, 30 Nov 2009 21:33:29 -0500 Subject: Mark some code as not covered. --- coverage/parser.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/coverage/parser.py b/coverage/parser.py index 505ce1cf..a1a24dd6 100644 --- a/coverage/parser.py +++ b/coverage/parser.py @@ -88,7 +88,7 @@ class CodeParser(object): tokgen = tokenize.generate_tokens(StringIO(self.text).readline) for toktype, ttext, (slineno, _), (elineno, _), ltext in tokgen: - if self.show_tokens: + if self.show_tokens: # pragma: no cover print("%10s %5s %-20r %r" % ( tokenize.tok_name.get(toktype, toktype), nice_pair((slineno, elineno)), ttext, ltext @@ -359,7 +359,7 @@ class ByteParser(object): stmts.add(l) return stmts - def _disassemble(self): + def _disassemble(self): # pragma: no cover """Disassemble code, for ad-hoc experimenting.""" import dis @@ -603,7 +603,7 @@ class Chunk(object): ) -class AdHocMain(object): +class AdHocMain(object): # pragma: no cover """An ad-hoc main for code parsing experiments.""" def main(self, args): -- cgit v1.2.1 From 9d2b8a09154727bee8c2296ea5852574c22a16cb Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Mon, 30 Nov 2009 21:35:27 -0500 Subject: A little explanation of the partial branch annotations in the HTML report. --- coverage/html.py | 12 ++++++--- coverage/htmlfiles/pyfile.html | 2 +- test/farm/html/gold_b_branch/b.html | 52 +++++++++++++++++++++++++++---------- test/farm/html/run_b_branch.py | 9 ++++--- test/farm/html/src/b.py | 14 +++++++++- 5 files changed, 66 insertions(+), 23 deletions(-) diff --git a/coverage/html.py b/coverage/html.py index 6df84a57..3671f036 100644 --- a/coverage/html.py +++ b/coverage/html.py @@ -80,7 +80,8 @@ class HtmlReporter(Reporter): lineno += 1 # 1-based line numbers. # Figure out how to mark this line. line_class = "" - annotate = "" + annotate_html = "" + annotate_title = "" if lineno in analysis.statements: line_class += " stm" if lineno in analysis.excluded: @@ -96,7 +97,11 @@ class HtmlReporter(Reporter): annlines.append("exit") else: annlines.append(str(b)) - annotate = " ".join(annlines) + 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 += c_run @@ -113,7 +118,8 @@ class HtmlReporter(Reporter): 'html': html, 'number': lineno, 'class': line_class.strip() or "pln", - 'annotate': annotate, + 'annotate': annotate_html, + 'annotate_title': annotate_title, }) # Write the HTML page for this file. diff --git a/coverage/htmlfiles/pyfile.html b/coverage/htmlfiles/pyfile.html index 566244f2..62518ba0 100644 --- a/coverage/htmlfiles/pyfile.html +++ b/coverage/htmlfiles/pyfile.html @@ -48,7 +48,7 @@ function toggle_lines(btn, cls) { {% for line in lines %} -

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

+

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

{% endfor %} diff --git a/test/farm/html/gold_b_branch/b.html b/test/farm/html/gold_b_branch/b.html index 270d596e..fed24838 100644 --- a/test/farm/html/gold_b_branch/b.html +++ b/test/farm/html/gold_b_branch/b.html @@ -24,15 +24,15 @@ function toggle_lines(btn, cls) {