[Checkins] SVN: z3c.coverage/trunk/ Dropped Python 2.4 and 2.5 support. Added Python 3.3 and PyPy 1.9 support.

Stephen Richter cvs-admin at zope.org
Wed Feb 20 05:29:42 UTC 2013


Log message for revision 129516:
  Dropped Python 2.4 and 2.5 support. Added Python 3.3 and PyPy 1.9 support.
  

Changed:
  _U  z3c.coverage/trunk/
  U   z3c.coverage/trunk/CHANGES.txt
  A   z3c.coverage/trunk/MANIFEST.in
  U   z3c.coverage/trunk/bootstrap.py
  U   z3c.coverage/trunk/setup.py
  U   z3c.coverage/trunk/src/z3c/coverage/README.txt
  U   z3c.coverage/trunk/src/z3c/coverage/coveragediff.py
  U   z3c.coverage/trunk/src/z3c/coverage/coveragediff.txt
  U   z3c.coverage/trunk/src/z3c/coverage/coveragereport.py
  U   z3c.coverage/trunk/src/z3c/coverage/tests.py
  U   z3c.coverage/trunk/tox.ini

-=-

Property changes on: z3c.coverage/trunk
___________________________________________________________________
Modified: svn:ignore
   - .installed.cfg
bin
build
coverage
develop-eggs
dist
eggs
parts

   + .installed.cfg
.tox
bin
build
coverage
develop-eggs
dist
eggs
parts


Modified: z3c.coverage/trunk/CHANGES.txt
===================================================================
--- z3c.coverage/trunk/CHANGES.txt	2013-02-20 04:38:27 UTC (rev 129515)
+++ z3c.coverage/trunk/CHANGES.txt	2013-02-20 05:29:42 UTC (rev 129516)
@@ -1,12 +1,14 @@
 Changes
 =======
 
-1.3.2 (unreleased)
+2.0.0 (unreleased)
 ------------------
 
-- Nothing changed yet.
+- Added Python 3.3 and PyPy 1.9 support.
 
+- Dropped Python 2.4 and 2.5 support.
 
+
 1.3.1 (2012-10-24)
 ------------------
 

Added: z3c.coverage/trunk/MANIFEST.in
===================================================================
--- z3c.coverage/trunk/MANIFEST.in	                        (rev 0)
+++ z3c.coverage/trunk/MANIFEST.in	2013-02-20 05:29:42 UTC (rev 129516)
@@ -0,0 +1,9 @@
+include *.rst
+include *.txt
+include *.py
+include buildout.cfg
+include tox.ini
+
+recursive-include src *
+
+global-exclude *.pyc

Modified: z3c.coverage/trunk/bootstrap.py
===================================================================
--- z3c.coverage/trunk/bootstrap.py	2013-02-20 04:38:27 UTC (rev 129515)
+++ z3c.coverage/trunk/bootstrap.py	2013-02-20 05:29:42 UTC (rev 129516)
@@ -18,76 +18,11 @@
 use the -c option to specify an alternate configuration file.
 """
 
-import os, shutil, sys, tempfile, urllib, urllib2, subprocess
+import os, shutil, sys, tempfile
 from optparse import OptionParser
 
-if sys.platform == 'win32':
-    def quote(c):
-        if ' ' in c:
-            return '"%s"' % c  # work around spawn lamosity on windows
-        else:
-            return c
-else:
-    quote = str
+tmpeggs = tempfile.mkdtemp()
 
-# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
-stdout, stderr = subprocess.Popen(
-    [sys.executable, '-Sc',
-     'try:\n'
-     '    import ConfigParser\n'
-     'except ImportError:\n'
-     '    print 1\n'
-     'else:\n'
-     '    print 0\n'],
-    stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
-has_broken_dash_S = bool(int(stdout.strip()))
-
-# In order to be more robust in the face of system Pythons, we want to
-# run without site-packages loaded.  This is somewhat tricky, in
-# particular because Python 2.6's distutils imports site, so starting
-# with the -S flag is not sufficient.  However, we'll start with that:
-if not has_broken_dash_S and 'site' in sys.modules:
-    # We will restart with python -S.
-    args = sys.argv[:]
-    args[0:0] = [sys.executable, '-S']
-    args = map(quote, args)
-    os.execv(sys.executable, args)
-# Now we are running with -S.  We'll get the clean sys.path, import site
-# because distutils will do it later, and then reset the path and clean
-# out any namespace packages from site-packages that might have been
-# loaded by .pth files.
-clean_path = sys.path[:]
-import site  # imported because of its side effects
-sys.path[:] = clean_path
-for k, v in sys.modules.items():
-    if k in ('setuptools', 'pkg_resources') or (
-        hasattr(v, '__path__') and
-        len(v.__path__) == 1 and
-        not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))):
-        # This is a namespace package.  Remove it.
-        sys.modules.pop(k)
-
-is_jython = sys.platform.startswith('java')
-
-setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
-distribute_source = 'http://python-distribute.org/distribute_setup.py'
-
-
-# parsing arguments
-def normalize_to_url(option, opt_str, value, parser):
-    if value:
-        if '://' not in value:  # It doesn't smell like a URL.
-            value = 'file://%s' % (
-                urllib.pathname2url(
-                    os.path.abspath(os.path.expanduser(value))),)
-        if opt_str == '--download-base' and not value.endswith('/'):
-            # Download base needs a trailing slash to make the world happy.
-            value += '/'
-    else:
-        value = None
-    name = opt_str[2:].replace('-', '_')
-    setattr(parser.values, name, value)
-
 usage = '''\
 [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
 
@@ -101,26 +36,8 @@
 '''
 
 parser = OptionParser(usage=usage)
-parser.add_option("-v", "--version", dest="version",
-                          help="use a specific zc.buildout version")
-parser.add_option("-d", "--distribute",
-                   action="store_true", dest="use_distribute", default=False,
-                   help="Use Distribute rather than Setuptools.")
-parser.add_option("--setup-source", action="callback", dest="setup_source",
-                  callback=normalize_to_url, nargs=1, type="string",
-                  help=("Specify a URL or file location for the setup file. "
-                        "If you use Setuptools, this will default to " +
-                        setuptools_source + "; if you use Distribute, this "
-                        "will default to " + distribute_source + "."))
-parser.add_option("--download-base", action="callback", dest="download_base",
-                  callback=normalize_to_url, nargs=1, type="string",
-                  help=("Specify a URL or directory for downloading "
-                        "zc.buildout and either Setuptools or Distribute. "
-                        "Defaults to PyPI."))
-parser.add_option("--eggs",
-                  help=("Specify a directory for storing eggs.  Defaults to "
-                        "a temporary directory that is deleted when the "
-                        "bootstrap script completes."))
+parser.add_option("-v", "--version", help="use a specific zc.buildout version")
+
 parser.add_option("-t", "--accept-buildout-test-releases",
                   dest='accept_buildout_test_releases',
                   action="store_true", default=False,
@@ -130,49 +47,38 @@
                         "extensions for you.  If you use this flag, "
                         "bootstrap and buildout will get the newest releases "
                         "even if they are alphas or betas."))
-parser.add_option("-c", None, action="store", dest="config_file",
+parser.add_option("-c", "--config-file",
                    help=("Specify the path to the buildout configuration "
                          "file to be used."))
+parser.add_option("-f", "--find-links",
+                   help=("Specify a URL to search for buildout releases"))
 
+
 options, args = parser.parse_args()
 
-# if -c was provided, we push it back into args for buildout's main function
-if options.config_file is not None:
-    args += ['-c', options.config_file]
+######################################################################
+# load/install distribute
 
-if options.eggs:
-    eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
-else:
-    eggs_dir = tempfile.mkdtemp()
-
-if options.setup_source is None:
-    if options.use_distribute:
-        options.setup_source = distribute_source
-    else:
-        options.setup_source = setuptools_source
-
-if options.accept_buildout_test_releases:
-    args.append('buildout:accept-buildout-test-releases=true')
-args.append('bootstrap')
-
+to_reload = False
 try:
-    import pkg_resources
-    import setuptools  # A flag.  Sometimes pkg_resources is installed alone.
+    import pkg_resources, setuptools
     if not hasattr(pkg_resources, '_distribute'):
+        to_reload = True
         raise ImportError
 except ImportError:
-    ez_code = urllib2.urlopen(
-        options.setup_source).read().replace('\r\n', '\n')
     ez = {}
-    exec ez_code in ez
-    setup_args = dict(to_dir=eggs_dir, download_delay=0)
-    if options.download_base:
-        setup_args['download_base'] = options.download_base
-    if options.use_distribute:
-        setup_args['no_fake'] = True
+
+    try:
+        from urllib.request import urlopen
+    except ImportError:
+        from urllib2 import urlopen
+
+    exec(urlopen('http://python-distribute.org/distribute_setup.py').read(), ez)
+    setup_args = dict(to_dir=tmpeggs, download_delay=0, no_fake=True)
     ez['use_setuptools'](**setup_args)
-    if 'pkg_resources' in sys.modules:
-        reload(sys.modules['pkg_resources'])
+
+    if to_reload:
+        reload(pkg_resources)
     import pkg_resources
     # This does not (always?) update the default working set.  We will
     # do it.
@@ -180,31 +86,26 @@
         if path not in pkg_resources.working_set.entries:
             pkg_resources.working_set.add_entry(path)
 
-cmd = [quote(sys.executable),
-       '-c',
-       quote('from setuptools.command.easy_install import main; main()'),
-       '-mqNxd',
-       quote(eggs_dir)]
+######################################################################
+# Install buildout
 
-if not has_broken_dash_S:
-    cmd.insert(1, '-S')
+ws  = pkg_resources.working_set
 
-find_links = options.download_base
-if not find_links:
-    find_links = os.environ.get('bootstrap-testing-find-links')
+cmd = [sys.executable, '-c',
+       'from setuptools.command.easy_install import main; main()',
+       '-mZqNxd', tmpeggs]
+
+find_links = os.environ.get(
+    'bootstrap-testing-find-links',
+    options.find_links or
+    ('http://downloads.buildout.org/'
+     if options.accept_buildout_test_releases else None)
+    )
 if find_links:
-    cmd.extend(['-f', quote(find_links)])
+    cmd.extend(['-f', find_links])
 
-if options.use_distribute:
-    setup_requirement = 'distribute'
-else:
-    setup_requirement = 'setuptools'
-ws = pkg_resources.working_set
-setup_requirement_path = ws.find(
-    pkg_resources.Requirement.parse(setup_requirement)).location
-env = dict(
-    os.environ,
-    PYTHONPATH=setup_requirement_path)
+distribute_path = ws.find(
+    pkg_resources.Requirement.parse('distribute')).location
 
 requirement = 'zc.buildout'
 version = options.version
@@ -212,14 +113,13 @@
     # Figure out the most recent final version of zc.buildout.
     import setuptools.package_index
     _final_parts = '*final-', '*final'
-
     def _final_version(parsed_version):
         for part in parsed_version:
             if (part[:1] == '*') and (part not in _final_parts):
                 return False
         return True
     index = setuptools.package_index.PackageIndex(
-        search_path=[setup_requirement_path])
+        search_path=[distribute_path])
     if find_links:
         index.add_find_links((find_links,))
     req = pkg_resources.Requirement.parse(requirement)
@@ -241,22 +141,25 @@
     requirement = '=='.join((requirement, version))
 cmd.append(requirement)
 
-if is_jython:
-    import subprocess
-    exitcode = subprocess.Popen(cmd, env=env).wait()
-else:  # Windows prefers this, apparently; otherwise we would prefer subprocess
-    exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
-if exitcode != 0:
-    sys.stdout.flush()
-    sys.stderr.flush()
-    print ("An error occurred when trying to install zc.buildout. "
-           "Look above this message for any errors that "
-           "were output by easy_install.")
-    sys.exit(exitcode)
+import subprocess
+if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=distribute_path)) != 0:
+    raise Exception(
+        "Failed to execute command:\n%s",
+        repr(cmd)[1:-1])
 
-ws.add_entry(eggs_dir)
+######################################################################
+# Import and run buildout
+
+ws.add_entry(tmpeggs)
 ws.require(requirement)
 import zc.buildout.buildout
+
+if not [a for a in args if '=' not in a]:
+    args.append('bootstrap')
+
+# if -c was provided, we push it back into args for buildout' main function
+if options.config_file is not None:
+    args[0:0] = ['-c', options.config_file]
+
 zc.buildout.buildout.main(args)
-if not options.eggs:  # clean up temporary egg directory
-    shutil.rmtree(eggs_dir)
+shutil.rmtree(tmpeggs)

Modified: z3c.coverage/trunk/setup.py
===================================================================
--- z3c.coverage/trunk/setup.py	2013-02-20 04:38:27 UTC (rev 129515)
+++ z3c.coverage/trunk/setup.py	2013-02-20 05:29:42 UTC (rev 129516)
@@ -41,10 +41,10 @@
         'License :: OSI Approved :: Zope Public License',
         'Programming Language :: Python',
         'Programming Language :: Python :: 2',
-        'Programming Language :: Python :: 2.4',
-        'Programming Language :: Python :: 2.5',
         'Programming Language :: Python :: 2.6',
         'Programming Language :: Python :: 2.7',
+        'Programming Language :: Python :: 3',
+        'Programming Language :: Python :: 3.3',
         'Natural Language :: English',
         'Operating System :: OS Independent',
         'Topic :: Internet :: WWW/HTTP',
@@ -56,7 +56,7 @@
     package_dir={'': 'src'},
     namespace_packages=['z3c'],
     extras_require=dict(
-        test=['zope.testing'],
+        test=['six', 'zope.testing'],
         ),
     install_requires=[
         'setuptools',

Modified: z3c.coverage/trunk/src/z3c/coverage/README.txt
===================================================================
--- z3c.coverage/trunk/src/z3c/coverage/README.txt	2013-02-20 04:38:27 UTC (rev 129515)
+++ z3c.coverage/trunk/src/z3c/coverage/README.txt	2013-02-20 05:29:42 UTC (rev 129516)
@@ -29,7 +29,7 @@
 
 Looking at the output directory, we now see several files:
 
-    >>> print '\n'.join(sorted(os.listdir(outputDir)))
+    >>> print('\n'.join(sorted(os.listdir(outputDir))))
     all.html
     z3c.coverage.__init__.html
     z3c.coverage.coveragediff.html
@@ -59,7 +59,7 @@
     ...         % os.path.dirname(os.path.dirname(
     ...             os.path.dirname(z3c.coverage.__file__))),
     ... ])
-    >>> print '\n'.join(sorted(os.listdir(outputDir)))
+    >>> print('\n'.join(sorted(os.listdir(outputDir))))
     all.html
     z3c.coverage.__init__.html
     z3c.coverage.coveragediff.html
@@ -80,7 +80,9 @@
   >>> script_file = os.path.join(
   ...     z3c.coverage.__path__[0], 'coveragereport.py')
 
-  >>> execfile(script_file, dict(__name__='__main__'))
+  >>> with open(script_file) as f:
+  ...     code = compile(f.read(), script_file, 'exec')
+  ...     exec(code, dict(__name__='__main__'))
 
 Let's clean up
 

Modified: z3c.coverage/trunk/src/z3c/coverage/coveragediff.py
===================================================================
--- z3c.coverage/trunk/src/z3c/coverage/coveragediff.py	2013-02-20 04:38:27 UTC (rev 129515)
+++ z3c.coverage/trunk/src/z3c/coverage/coveragediff.py	2013-02-20 05:29:42 UTC (rev 129516)
@@ -22,35 +22,19 @@
 The directories are expected to contain files named '<package>.<module>.cover'
 with the format that Python's trace.py produces.
 """
+from __future__ import print_function
 
 import os
 import re
 import smtplib
 import optparse
-from email.MIMEText import MIMEText
 
-
 try:
-    any
-except NameError:
-    # python 2.4 compatibility
-    def any(list):
-        """Return True if bool(x) is True for any x in the iterable.
+    from email.MIMEText import MIMEText
+except ImportError:
+    from email.mime.text import MIMEText
 
-            >>> any([1, 'yes', 0, None])
-            True
-            >>> any([0, None, ''])
-            False
-            >>> any([])
-            False
 
-        """
-        for item in list:
-            if item:
-                return True
-        return False
-
-
 def matches(string, list_of_regexes):
     """Check whether a string matches any of a list of regexes.
 
@@ -91,8 +75,8 @@
         include = ['.'] # include everything by default
     if not exclude:
         exclude = []    # exclude nothing by default
-    include = map(re.compile, include)
-    exclude = map(re.compile, exclude)
+    include = list(map(re.compile, include))
+    exclude = list(map(re.compile, exclude))
     return [fn for fn in files
             if matches(fn, include) and not matches(fn, exclude)]
 
@@ -128,7 +112,7 @@
 
     """
     module = strip(os.path.basename(filename), '.cover')
-    print '%s: %s' % (module, message)
+    print('%s: %s' % (module, message))
 
 
 def compare_dirs(olddir, newdir, include=(), exclude=(), warn=warn):
@@ -148,11 +132,12 @@
 def count_coverage(filename):
     """Count the number of covered and uncovered lines in a file."""
     covered = uncovered = 0
-    for line in file(filename):
-        if line.startswith('>>>>>>'):
-            uncovered += 1
-        elif len(line) >= 7 and not line.startswith(' '*7):
-            covered += 1
+    with open(filename) as file:
+        for line in file:
+            if line.startswith('>>>>>>'):
+                uncovered += 1
+            elif len(line) >= 7 and not line.startswith(' '*7):
+                covered += 1
     return covered, uncovered
 
 
@@ -255,11 +240,11 @@
     def warn(self, filename, message):
         """Warn about test coverage regression."""
         module = strip(os.path.basename(filename), '.cover')
-        print '%s: %s' % (module, message)
+        print('%s: %s' % (module, message))
         if self.web_url:
             url = urljoin(self.web_url, module + '.html')
-            print 'See ' + url
-            print
+            print('See ' + url)
+            print('')
 
 
 class ReportEmailer(object):

Modified: z3c.coverage/trunk/src/z3c/coverage/coveragediff.txt
===================================================================
--- z3c.coverage/trunk/src/z3c/coverage/coveragediff.txt	2013-02-20 04:38:27 UTC (rev 129515)
+++ z3c.coverage/trunk/src/z3c/coverage/coveragediff.txt	2013-02-20 05:29:42 UTC (rev 129516)
@@ -23,7 +23,7 @@
 
     >>> from z3c.coverage.coveragediff import find_coverage_files
     >>> for filename in sorted(find_coverage_files(sampleinput_dir)):
-    ...     print filename
+    ...     print(filename)
     z3c.coverage.__init__.cover
     z3c.coverage.coveragediff.cover
     z3c.coverage.coveragereport.cover
@@ -34,7 +34,7 @@
 
     >>> from z3c.coverage.coveragediff import filter_coverage_files
     >>> for filename in sorted(filter_coverage_files(sampleinput_dir)):
-    ...     print filename
+    ...     print(filename)
     z3c.coverage.__init__.cover
     z3c.coverage.coveragediff.cover
     z3c.coverage.coveragereport.cover
@@ -42,14 +42,14 @@
 
     >>> for filename in sorted(filter_coverage_files(sampleinput_dir,
     ...                                              include=['diff'])):
-    ...     print filename
+    ...     print(filename)
     z3c.coverage.coveragediff.cover
 
 The patterns are regular expressions
 
     >>> for filename in sorted(filter_coverage_files(sampleinput_dir,
     ...                                              exclude=['^z'])):
-    ...     print filename
+    ...     print(filename)
 
 
 Parsing coverage files
@@ -140,22 +140,23 @@
 send any real emails:
 
     >>> MailSender.connection_class = None
+    >>> import six
 
     >>> class FakeSMTP(object):
     ...     def __init__(self, host, port):
-    ...         print "Connecting to %s:%s" % (host, port)
+    ...         print("Connecting to %s:%s" % (host, port))
     ...     def sendmail(self, sender, recipients, body):
     ...         from smtplib import quoteaddr
-    ...         print "MAIL FROM:%s" % quoteaddr(sender)
-    ...         if isinstance(recipients, basestring):
+    ...         print("MAIL FROM:%s" % quoteaddr(sender))
+    ...         if isinstance(recipients, six.string_types):
     ...             recipients = [recipients]
     ...         for recipient in recipients:
-    ...             print "RCPT TO:%s" % quoteaddr(recipient)
-    ...         print "DATA"
-    ...         print body
-    ...         print "."
+    ...             print("RCPT TO:%s" % quoteaddr(recipient))
+    ...         print("DATA")
+    ...         print(body)
+    ...         print(".")
     ...     def quit(self):
-    ...         print "QUIT"
+    ...         print("QUIT")
     >>> mailer.connection_class = FakeSMTP
 
 Here's how you send an email:
@@ -250,11 +251,11 @@
 
     >>> class FakeMailSender(object):
     ...     def send_email(self, from_addr, to_addr, subject, body):
-    ...         print "From:", from_addr
-    ...         print "To:", to_addr
-    ...         print "Subject:", subject
-    ...         print "---"
-    ...         print body
+    ...         print("From:", from_addr)
+    ...         print("To:", to_addr)
+    ...         print("Subject:", subject)
+    ...         print("---")
+    ...         print(body)
     >>> emailer.mailer = FakeMailSender()
     >>> emailer.send()
     From: Some Bot <bot at example.com>
@@ -324,9 +325,9 @@
     ...             main()
     ...         finally:
     ...             sys.stderr = old_stderr
-    ...     except SystemExit, e:
+    ...     except SystemExit as e:
     ...         if e.code:
-    ...             print "(returned exit code %s)" % e.code
+    ...             print("(returned exit code %s)" % e.code)
 
 
 Help message
@@ -454,7 +455,8 @@
 
     >>> sys.argv = ['coveragediff', sampleinput_dir, another_dir]
     >>> script_file = os.path.join(z3c.coverage.__path__[0], 'coveragediff.py')
-    >>> execfile(script_file, dict(__name__='__main__'))
+    >>> with open(script_file) as f:
+    ...     code = compile(f.read(), script_file, 'exec')
+    ...     exec(code, dict(__name__='__main__'))
     z3c.coverage.coveragediff: 36 new lines of untested code
     z3c.coverage.fakenewmodule: new file with 3 lines of untested code (out of 13)
-

Modified: z3c.coverage/trunk/src/z3c/coverage/coveragereport.py
===================================================================
--- z3c.coverage/trunk/src/z3c/coverage/coveragereport.py	2013-02-20 04:38:27 UTC (rev 129515)
+++ z3c.coverage/trunk/src/z3c/coverage/coveragereport.py	2013-02-20 05:29:42 UTC (rev 129516)
@@ -40,6 +40,7 @@
 
 $Id$
 """
+from __future__ import print_function
 __docformat__ = "reStructuredText"
 
 import sys
@@ -82,11 +83,11 @@
 
     @Lazy
     def covered(self):
-        return sum(child.covered for child in self.itervalues())
+        return sum(child.covered for child in self.values())
 
     @Lazy
     def total(self):
-        return sum(child.total for child in self.itervalues())
+        return sum(child.total for child in self.values())
 
     @Lazy
     def uncovered(self):
@@ -141,12 +142,13 @@
         """Parse a plain-text coverage report and return (covered, total)."""
         covered = 0
         total = 0
-        for line in file(filename):
-            if line.startswith(' '*7) or len(line) < 7:
-                continue
-            total += 1
-            if not line.startswith('>>>>>>'):
-                covered += 1
+        with open(filename) as file:
+            for line in file:
+                if line.startswith(' '*7) or len(line) < 7:
+                    continue
+                total += 1
+                if not line.startswith('>>>>>>'):
+                    covered += 1
         return (covered, total)
 
     @Lazy
@@ -268,8 +270,9 @@
 def apply_path_aliases(cov, aliases):
     """Adjust filenames in coverage data."""
     # XXX: fragile: we're touching the internal data structures directly
-    aliases = aliases.items()
-    aliases.sort(key=lambda (k, v): len(k), reverse=True) # longest key first
+    # longest key first
+    aliases = sorted(
+        aliases.items(), key=lambda i: len(i[0]), reverse=True)
     def fixup_filename(filename):
         for alias, local in aliases:
             return local + filename[len(alias):]
@@ -351,12 +354,12 @@
         nice_name += '.py'
     else:
         nice_name += '/'
-    print >> html, '<tr><td><a href="%s">%s</a></td>' % \
-                   (index_to_url(file_index), nice_name),
-    print >> html, '<td style="background: %s">&nbsp;&nbsp;&nbsp;&nbsp;</td>' % \
-                   (percent_to_colour(node.percent)),
-    print >> html, '<td>covered %s%% (%s of %s uncovered)</td></tr>' % \
-                   (node.percent, node.uncovered, node.total)
+    print('<tr><td><a href="%s">%s</a></td>' % \
+              (index_to_url(file_index), nice_name), file=html)
+    print('<td style="background: %s">&nbsp;&nbsp;&nbsp;&nbsp;</td>' % \
+              (percent_to_colour(node.percent)), file=html)
+    print('<td>covered %s%% (%s of %s uncovered)</td></tr>' % \
+              (node.percent, node.uncovered, node.total), file=html)
 
 
 HEADER = """
@@ -398,18 +401,19 @@
     ``path`` is the directory name for the plain-text report files.
     """
     html = open(output_filename, 'w')
-    print >> html, HEADER % {'name': index_to_name(my_index)}
+    print(HEADER % {'name': index_to_name(my_index)}, file=html)
     info = [(tree.get_at(node_path), node_path) for node_path in info]
-    def key((node, node_path)):
+    def key(node_info):
+        (node, node_path) = node_info
         return (len(node_path), -node.uncovered, node_path and node_path[-1])
     info.sort(key=key)
     for node, file_index in info:
         if not file_index:
             continue # skip root node
         print_table_row(html, node, file_index)
-    print >> html, '</table><hr/>'
-    print >> html, tree.get_at(my_index).html_source
-    print >> html, FOOTER % footer
+    print('</table><hr/>', file=html)
+    print(tree.get_at(my_index).html_source, file=html)
+    print(FOOTER % footer, file=html)
     html.close()
 
 
@@ -425,8 +429,10 @@
     except OSError:
         # Failed to run enscript; maybe it is not installed?  Disable
         # syntax highlighting then.
-        text = cgi.escape(file(filename).read())
+        with open(filename, 'r') as file:
+            text = cgi.escape(file.read())
     else:
+        text = text.decode('ascii')
         text = text[text.find('<PRE>')+len('<PRE>'):]
         text = text[:text.find('</PRE>')]
     return text
@@ -476,15 +482,16 @@
 def generate_overall_html_from_tree(tree, output_filename, footer=""):
     """Generate an overall HTML file for all nodes in the tree."""
     html = open(output_filename, 'w')
-    print >> html, HEADER % {'name': ', '.join(sorted(tree.keys()))}
+    print(HEADER % {'name': ', '.join(sorted(tree.keys()))}, file=html)
     def print_node(node, file_index):
         if file_index: # skip root node
             print_table_row(html, node, file_index)
-    def sort_by((key, node)):
+    def sort_by(node_info):
+        (key, node) = node_info
         return (-node.uncovered, key)
     traverse_tree_in_order(tree, [], print_node, sort_by)
-    print >> html, '</table><hr/>'
-    print >> html, FOOTER % footer
+    print('</table><hr/>', file=html)
+    print(FOOTER % footer, file=html)
     html.close()
 
 
@@ -543,10 +550,10 @@
 def make_coverage_reports(path, report_path, opts):
     """Convert reports from ``path`` into HTML files in ``report_path``."""
     if opts.verbose:
-        print "Loading coverage reports from %s" % path
+        print("Loading coverage reports from %s" % path)
     tree = load_coverage(path, opts=opts)
     if opts.verbose:
-        print tree
+        print(tree)
     rev = get_svn_revision(os.path.join(path, os.path.pardir))
     timestamp = str(datetime.datetime.utcnow())+"Z"
     footer = "Generated for revision %s on %s" % (rev, timestamp)
@@ -555,7 +562,7 @@
     generate_overall_html_from_tree(
         tree, os.path.join(report_path, 'all.html'), footer)
     if opts.verbose:
-        print "Generated HTML files in %s" % report_path
+        print("Generated HTML files in %s" % report_path)
 
 
 def get_svn_revision(path):

Modified: z3c.coverage/trunk/src/z3c/coverage/tests.py
===================================================================
--- z3c.coverage/trunk/src/z3c/coverage/tests.py	2013-02-20 04:38:27 UTC (rev 129515)
+++ z3c.coverage/trunk/src/z3c/coverage/tests.py	2013-02-20 05:29:42 UTC (rev 129516)
@@ -2,6 +2,7 @@
 """
 Test suite for z3c.coverage
 """
+from __future__ import print_function
 
 import doctest
 import os
@@ -26,7 +27,7 @@
         >>> class MyClass(object):
         ...     @Lazy
         ...     def foo(self):
-        ...         print "computing foo"
+        ...         print("computing foo")
         ...         return 42
 
     This is basic lazy evaluation
@@ -121,7 +122,7 @@
 
     Finally, we also can get a nice output:
 
-        >>> print root['z3c']
+        >>> print(root['z3c'])
         64% covered (94 of 262 lines uncovered)
 
     """
@@ -180,8 +181,8 @@
 
         >>> tree = dict(a=dict(b={}, c={}, d={}), b=dict(x={}, y={}, z={}))
         >>> def pr_index(tree, index):
-        ...     print index
-        >>> traverse_tree_in_order(tree, [], pr_index, lambda (k, n): k)
+        ...     print(index)
+        >>> traverse_tree_in_order(tree, [], pr_index, lambda i: i[0])
         []
         ['a']
         ['a', 'b']
@@ -228,7 +229,7 @@
         ... <I><FONT COLOR="#B22222"># Make a package.
         ... </FONT></I>'''
 
-        >>> print output
+        >>> print(output)
         ... # this will fail if you don't have enscript in your $PATH
         <BLANKLINE>
         <I><FONT COLOR="#B22222"># Make a package.
@@ -248,7 +249,7 @@
         >>> filename = os.path.join(
         ...     os.path.dirname(z3c.coverage.__file__), '__init__.py')
 
-        >>> print syntax_highlight(filename)
+        >>> print(syntax_highlight(filename))
         # Make a package.
         <BLANKLINE>
 
@@ -262,8 +263,8 @@
     Defaults are chosen when no input and output dir is specified.
 
         >>> def make_coverage_reports_stub(path, report_path, **kw):
-        ...     print path
-        ...     print report_path
+        ...     print(path)
+        ...     print(report_path)
 
         >>> make_coverage_reports_orig = coveragereport.make_coverage_reports
         >>> coveragereport.make_coverage_reports = make_coverage_reports_stub
@@ -292,6 +293,8 @@
 
     """
 
+def setUp(test):
+    test.globs['print_function'] = print_function
 
 def test_suite():
     checker = renormalizing.RENormalizing([
@@ -304,11 +307,11 @@
     ])
     return unittest.TestSuite([
         doctest.DocFileSuite(
-            'README.txt', checker=checker,
+            'README.txt', setUp=setUp, checker=checker,
             optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,
             ),
         doctest.DocFileSuite(
-            'coveragediff.txt', checker=checker,
+            'coveragediff.txt', setUp=setUp, checker=checker,
             optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,
             ),
         doctest.DocTestSuite(checker=checker),

Modified: z3c.coverage/trunk/tox.ini
===================================================================
--- z3c.coverage/trunk/tox.ini	2013-02-20 04:38:27 UTC (rev 129515)
+++ z3c.coverage/trunk/tox.ini	2013-02-20 05:29:42 UTC (rev 129516)
@@ -1,17 +1,7 @@
 [tox]
-envlist = py24, py25, py26, py27
+envlist = py26,py27,py33,pypy
 
 [testenv]
 deps = zope.testrunner
        zope.testing
 commands = zope-testrunner --test-path=src
-
-[testenv:py25]
-deps = {[testenv]deps}
-       zope.interface < 4.0.0
-       zope.exceptions < 4.0.0
-
-[testenv:py24]
-deps = {[testenv]deps}
-       zope.interface < 4.0.0
-       zope.exceptions < 4.0.0



More information about the checkins mailing list