[Checkins] SVN: zope.error/trunk/ Adding support for python-3.3

Andrey Lebedev cvs-admin at zope.org
Thu Feb 21 17:19:18 UTC 2013


Log message for revision 129583:
  Adding support for python-3.3
  
  

Changed:
  U   zope.error/trunk/bootstrap.py
  U   zope.error/trunk/setup.py
  A   zope.error/trunk/src/zope/error/_compat.py
  U   zope.error/trunk/src/zope/error/error.py
  U   zope.error/trunk/src/zope/error/tests.py
  U   zope.error/trunk/tox.ini

-=-
Modified: zope.error/trunk/bootstrap.py
===================================================================
--- zope.error/trunk/bootstrap.py	2013-02-21 16:45:28 UTC (rev 129582)
+++ zope.error/trunk/bootstrap.py	2013-02-21 17:19:18 UTC (rev 129583)
@@ -18,80 +18,11 @@
 use the -c option to specify an alternate configuration file.
 """
 
-import os, shutil, sys, tempfile, textwrap
-try:
-    import urllib.request as urllib2
-except ImportError:
-    import urllib2
-import 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, '-S', '-c',
-     'try:\n'
-     '    import pickle\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 = list(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
-sys.path[:] = clean_path
-for k, v in list(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')
-
-setup_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' % (
-                urllib2.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]
 
@@ -105,73 +36,49 @@
 '''
 
 parser = OptionParser(usage=usage)
-parser.add_option("-v", "--version", dest="version",
-                          help="use a specific zc.buildout version")
-parser.add_option("--setup-version", dest="setup_version",
-                  help="The version of distribute to use.")
-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 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=sys.version_info[0] > 2,
+                  action="store_true", default=False,
                   help=("Normally, if you do not specify a --version, the "
                         "bootstrap script and buildout gets the newest "
                         "*final* versions of zc.buildout and its recipes and "
                         "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.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(
-        setup_source).read().replace('\r\n'.encode(), '\n'.encode())
     ez = {}
-    exec(ez_code, ez)
-    setup_args = dict(to_dir=eggs_dir, download_delay=0)
-    if options.download_base:
-        setup_args['download_base'] = options.download_base
-    if options.setup_version:
-        setup_args['version'] = options.setup_version
-    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:
-        if sys.version_info[0] >= 3:
-            import imp
-            reload_ = imp.reload
-        else:
-            reload_ = reload
 
-        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.
@@ -179,28 +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])
 
-setup_requirement = 'distribute'
-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
@@ -214,7 +119,7 @@
                 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)
@@ -236,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: zope.error/trunk/setup.py
===================================================================
--- zope.error/trunk/setup.py	2013-02-21 16:45:28 UTC (rev 129582)
+++ zope.error/trunk/setup.py	2013-02-21 17:19:18 UTC (rev 129583)
@@ -60,6 +60,7 @@
                       'zope.interface',
                       'zope.location',
                       'persistent', # error.py imports from persistent
+                      'six'
                       ],
     extras_require=dict(
           test=[

Added: zope.error/trunk/src/zope/error/_compat.py
===================================================================
--- zope.error/trunk/src/zope/error/_compat.py	                        (rev 0)
+++ zope.error/trunk/src/zope/error/_compat.py	2013-02-21 17:19:18 UTC (rev 129583)
@@ -0,0 +1,26 @@
+##############################################################################
+#
+# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Python2/3 compatibility utilities
+"""
+import sys
+
+PYTHON2 = sys.version_info[0] == 2
+PYTHON3 = sys.version_info[0] == 3
+
+if PYTHON2:
+    _u = _u_type = unicode
+    _basestring = basestring
+else:
+    _u = _u_type = str
+    _basestring = (str, bytes)

Modified: zope.error/trunk/src/zope/error/error.py
===================================================================
--- zope.error/trunk/src/zope/error/error.py	2013-02-21 16:45:28 UTC (rev 129582)
+++ zope.error/trunk/src/zope/error/error.py	2013-02-21 17:19:18 UTC (rev 129583)
@@ -25,6 +25,8 @@
 from random import random
 from threading import Lock
 
+import six
+
 from zope.exceptions.exceptionformatter import format_exception
 from zope.interface import implementer
 
@@ -33,6 +35,8 @@
 
 import zope.location.interfaces
 
+from zope.error._compat import _u, _u_type, _basestring
+
 #Restrict the rate at which errors are sent to the Event Log
 _rate_restrict_pool = {}
 
@@ -53,15 +57,15 @@
 logger = logging.getLogger('SiteError')
 
 def printedreplace(error):
-    symbols = (ur"\x%02x" % ord(s)
+    symbols = (u"\\x%02x" % (s if isinstance(s, int) else ord(s))
         for s in error.object[error.start:error.end])
     return u"".join(symbols), error.end
 
 codecs.register_error("zope.error.printedreplace", printedreplace)
 
 def getPrintable(value, as_html=False):
-    if not isinstance(value, unicode):
-        if not isinstance(value, str):
+    if not isinstance(value, _u_type):
+        if not isinstance(value, bytes):
             # A call to str(obj) could raise anything at all.
             # We'll ignore these errors, and print something
             # useful instead, but also log the error.
@@ -73,7 +77,8 @@
                     " representation of an object")
                 return u"<unprintable %s object>" % (
                     xml_escape(type(value).__name__))
-        value = unicode(value, errors="zope.error.printedreplace")
+        if isinstance(value, bytes):
+            value = _u(value, errors="zope.error.printedreplace")
     if as_html:
         return value
     else:
@@ -164,13 +169,13 @@
         """
         now = time.time()
         try:
-            strtype = unicode(getattr(info[0], '__name__', info[0]))
+            strtype = _u(getattr(info[0], '__name__', info[0]))
             if strtype in self._ignored_exceptions:
                 return
 
             tb_text = None
             tb_html = None
-            if not isinstance(info[2], basestring):
+            if not isinstance(info[2], _basestring):
                 tb_text = getFormattedException(info)
                 tb_html = getFormattedException(info, True)
             else:
@@ -225,7 +230,7 @@
             next_when += _rate_restrict_period
             _rate_restrict_pool[strtype] = next_when
             try:
-                raise info[0], info[1], info[2]
+                six.reraise(info[0], info[1], info[2])
             except:
                 logger.exception(str(url))
 
@@ -243,7 +248,7 @@
         self.keep_entries = int(keep_entries)
         self.copy_to_zlog = bool(copy_to_zlog)
         self._ignored_exceptions = tuple(
-                [unicode(e) for e in ignored_exceptions if e]
+                [_u(e) for e in ignored_exceptions if e]
                 )
 
     def getLogEntries(self):

Modified: zope.error/trunk/src/zope/error/tests.py
===================================================================
--- zope.error/trunk/src/zope/error/tests.py	2013-02-21 16:45:28 UTC (rev 129582)
+++ zope.error/trunk/src/zope/error/tests.py	2013-02-21 17:19:18 UTC (rev 129583)
@@ -15,13 +15,18 @@
 """
 import sys
 import unittest
-import doctest
+import logging
 
 from zope.exceptions.exceptionformatter import format_exception
 from zope.testing import cleanup
 
 from zope.error.error import ErrorReportingUtility, getFormattedException
+from zope.error._compat import _u_type, PYTHON2
 
+if PYTHON2:
+    from cStringIO import StringIO
+else:
+    from io import StringIO
 
 class Error(Exception):
 
@@ -79,12 +84,12 @@
         exc_info = getAnErrorInfo()
         errUtility.raising(exc_info)
         getErrLog = errUtility.getLogEntries()
-        self.assertEquals(1, len(getErrLog))
+        self.assertEqual(1, len(getErrLog))
 
         tb_text = ''.join(format_exception(as_html=0, *exc_info))
 
         err_id = getErrLog[0]['id']
-        self.assertEquals(tb_text,
+        self.assertEqual(tb_text,
                           errUtility.getLogEntryById(err_id)['tb_text'])
 
     def test_ErrorLog_unicode(self):
@@ -103,16 +108,16 @@
         exc_info = getAnErrorInfo(u"Error (\u0441)")
         errUtility.raising(exc_info, request=request)
         getErrLog = errUtility.getLogEntries()
-        self.assertEquals(1, len(getErrLog))
+        self.assertEqual(1, len(getErrLog))
 
         tb_text = getFormattedException(exc_info)
 
         err_id = getErrLog[0]['id']
-        self.assertEquals(tb_text,
+        self.assertEqual(tb_text,
                           errUtility.getLogEntryById(err_id)['tb_text'])
 
         username = getErrLog[0]['username']
-        self.assertEquals(username, u'unauthenticated, \u0441, \u0441, \u0441')
+        self.assertEqual(username, u'unauthenticated, \u0441, \u0441, \u0441')
 
     def test_ErrorLog_nonascii(self):
         # Emulate a unicode url, it gets encoded to utf-8 before it's passed
@@ -121,27 +126,37 @@
         request = TestRequest(environ={'PATH_INFO': '/\xd1\x82',
                                        'SOME_NONASCII': '\xe1'})
         class PrincipalStub(object):
-            id = '\xe1'
-            title = '\xe1'
-            description = '\xe1'
+            id = b'\xe1'
+            title = b'\xe1'
+            description = b'\xe1'
         request.setPrincipal(PrincipalStub())
 
         errUtility = ErrorReportingUtility()
         exc_info = getAnErrorInfo("Error (\xe1)")
         errUtility.raising(exc_info, request=request)
         getErrLog = errUtility.getLogEntries()
-        self.assertEquals(1, len(getErrLog))
+        self.assertEqual(1, len(getErrLog))
 
         tb_text = getFormattedException(exc_info)
 
         err_id = getErrLog[0]['id']
-        self.assertEquals(tb_text,
+        self.assertEqual(tb_text,
                           errUtility.getLogEntryById(err_id)['tb_text'])
 
         username = getErrLog[0]['username']
-        self.assertEquals(username, r"unauthenticated, \xe1, \xe1, \xe1")
+        self.assertEqual(username, r"unauthenticated, \xe1, \xe1, \xe1")
 
+    def setUp(self):
+        super(ErrorReportingUtilityTests, self).setUp()
+        self.log_buffer = StringIO()
+        self.log_handler = logging.StreamHandler(self.log_buffer)
+        logging.getLogger().addHandler(self.log_handler)
 
+    def tearDown(self):
+        logging.getLogger().removeHandler(self.log_handler)
+        super(ErrorReportingUtilityTests, self).tearDown()
+
+
 class GetPrintableTests(unittest.TestCase):
     """Testing .error.getPrintable(value)"""
 
@@ -153,15 +168,15 @@
         self.assertEqual(u'&lt;script&gt;', self.getPrintable(u'<script>'))
 
     def test_str_values_get_converted_to_unicode(self):
-        self.assertEqual(u'\\u0441', self.getPrintable('\u0441'))
-        self.assertTrue(isinstance(self.getPrintable('\u0441'), unicode))
+        self.assertEqual(u'\\u0441', self.getPrintable(b'\u0441'))
+        self.assertTrue(isinstance(self.getPrintable('\u0441'), _u_type))
 
     def test_non_str_values_get_converted_using_a_str_call(self):
         class NonStr(object):
             def __str__(self):
                 return 'non-str'
         self.assertEqual(u'non-str', self.getPrintable(NonStr()))
-        self.assertTrue(isinstance(self.getPrintable(NonStr()), unicode))
+        self.assertTrue(isinstance(self.getPrintable(NonStr()), _u_type))
 
     def test_non_str_those_conversion_fails_are_returned_specially(self):
         class NonStr(object):
@@ -169,7 +184,7 @@
                 raise ValueError('non-str')
         self.assertEqual(
                 u'<unprintable NonStr object>', self.getPrintable(NonStr()))
-        self.assertTrue(isinstance(self.getPrintable(NonStr()), unicode))
+        self.assertTrue(isinstance(self.getPrintable(NonStr()), _u_type))
 
     def test_non_str_those_conversion_fails_are_returned_with_escaped_name(
             self):
@@ -206,6 +221,18 @@
         # the bugfix for that.
 
 
+    def setUp(self):
+        super(GetPrintableTests, self).setUp()
+        self.log_buffer = StringIO()
+        self.log_handler = logging.StreamHandler(self.log_buffer)
+        logging.getLogger().addHandler(self.log_handler)
+
+    def tearDown(self):
+        logging.getLogger().removeHandler(self.log_handler)
+        super(GetPrintableTests, self).tearDown()
+
+
+
 def test_suite():
     return unittest.TestSuite([
         unittest.defaultTestLoader.loadTestsFromName(__name__),

Modified: zope.error/trunk/tox.ini
===================================================================
--- zope.error/trunk/tox.ini	2013-02-21 16:45:28 UTC (rev 129582)
+++ zope.error/trunk/tox.ini	2013-02-21 17:19:18 UTC (rev 129583)
@@ -1,8 +1,9 @@
 [tox]
-envlist = py26,py27
+envlist = py26, py27, py33
 
 [testenv]
 commands =
     python setup.py test -q
 deps = 
     zope.testing
+    six



More information about the checkins mailing list