diff options
| author | Chris McDonough <chrism@plope.com> | 2011-09-22 17:13:45 -0400 |
|---|---|---|
| committer | Chris McDonough <chrism@plope.com> | 2011-09-22 17:13:45 -0400 |
| commit | e6c2d2eb7a9608658823fc2854104c2a61284942 (patch) | |
| tree | 4ce76f4468b18280125a5e3bca15be3dce849214 | |
| parent | 03ce311ef998239bb76c04baa3cdbe76cc3b3fcf (diff) | |
| download | pyramid-e6c2d2eb7a9608658823fc2854104c2a61284942.tar.gz pyramid-e6c2d2eb7a9608658823fc2854104c2a61284942.tar.bz2 pyramid-e6c2d2eb7a9608658823fc2854104c2a61284942.zip | |
anger release commit
41 files changed, 408 insertions, 140 deletions
diff --git a/pyramid/asset.py b/pyramid/asset.py index 730969a4a..4bf0d7bf4 100644 --- a/pyramid/asset.py +++ b/pyramid/asset.py @@ -1,11 +1,13 @@ import os import pkg_resources +from pyramid.compat import string_types + from pyramid.path import package_path from pyramid.path import package_name def resolve_asset_spec(spec, pname='__main__'): - if pname and not isinstance(pname, basestring): + if pname and not isinstance(pname, string_types): pname = pname.__name__ # as package if os.path.isabs(spec): return None, spec diff --git a/pyramid/authentication.py b/pyramid/authentication.py index e2014b9a1..d3d5a1ecd 100644 --- a/pyramid/authentication.py +++ b/pyramid/authentication.py @@ -3,11 +3,14 @@ from codecs import utf_8_encode from hashlib import md5 import datetime import re +import sys import time as time_mod import urllib from zope.interface import implements +from pyramid.compat import long + from pyramid.interfaces import IAuthenticationPolicy from pyramid.interfaces import IDebugLogger @@ -469,7 +472,8 @@ def parse_ticket(secret, ticket, ip): digest = ticket[:32] try: timestamp = int(ticket[32:40], 16) - except ValueError, e: + except ValueError: + e = sys.exc_info()[1] raise BadTicket('Timestamp is not a hex integer: %s' % e) try: userid, data = ticket[40:].split('!', 1) diff --git a/pyramid/chameleon_text.py b/pyramid/chameleon_text.py index b687ecda9..bb6531976 100644 --- a/pyramid/chameleon_text.py +++ b/pyramid/chameleon_text.py @@ -3,6 +3,8 @@ import sys from zope.deprecation import deprecated from zope.interface import implements +from pyramid.compat import reraise + try: from chameleon.zpt.template import PageTextTemplateFile # prevent pyflakes complaining about a redefinition below @@ -12,7 +14,7 @@ except ImportError: # pragma: no cover # Chameleon doesn't work on non-CPython platforms class PageTextTemplateFile(object): def __init__(self, *arg, **kw): - raise ImportError, exc, tb + reraise(ImportError, exc, tb) from pyramid.interfaces import ITemplateRenderer diff --git a/pyramid/chameleon_zpt.py b/pyramid/chameleon_zpt.py index cfa37a65f..495835c3d 100644 --- a/pyramid/chameleon_zpt.py +++ b/pyramid/chameleon_zpt.py @@ -3,6 +3,8 @@ import sys from zope.deprecation import deprecated from zope.interface import implements +from pyramid.compat import reraise + try: from chameleon.zpt.template import PageTemplateFile PageTemplateFile # prevent pyflakes complaining about a redefinition below @@ -11,7 +13,7 @@ except ImportError: # pragma: no cover # Chameleon doesn't work on non-CPython platforms class PageTemplateFile(object): def __init__(self, *arg, **kw): - raise ImportError, exc, tb + reraise(ImportError, exc, tb) from pyramid.interfaces import ITemplateRenderer diff --git a/pyramid/compat.py b/pyramid/compat.py index 7d723715e..5ef3c4e6d 100644 --- a/pyramid/compat.py +++ b/pyramid/compat.py @@ -1,3 +1,11 @@ +import sys +import types + +try: + import cPickle as pickle +except ImportError: # pragma: no cover + import pickle + try: import json except ImportError: # pragma: no cover @@ -6,3 +14,170 @@ except ImportError: # pragma: no cover except NotImplementedError: from django.utils import simplejson as json # GAE +# True if we are running on Python 3. +PY3 = sys.version_info[0] == 3 + +if PY3: # pragma: no cover + string_types = str, + integer_types = int, + class_types = type, + text_type = str + binary_type = bytes + long = int + def ords_(b): + return b +else: + string_types = basestring, + integer_types = (int, long) + class_types = (type, types.ClassType) + text_type = unicode + binary_type = str + def ords_(s): + return [ord(x) for x in s] + +def text_(s, encoding='latin-1', errors='strict'): + if isinstance(s, binary_type): + return s.decode(encoding, errors) + return s + +def bytes_(s, encoding='latin-1', errors='strict'): + if isinstance(s, text_type): + return s.encode(encoding, errors) + return s + +if PY3: # pragma: no cover + def native_(s, encoding='latin-1', errors='strict'): + if isinstance(s, text_type): + return s + return str(s, encoding, errors) +else: + def native_(s, encoding='latin-1', errors='strict'): + if isinstance(s, text_type): + return s.encode(encoding, errors) + return str(s) + +if PY3: # pragma: no cover + fsenc = sys.getfilesystemencoding() + def text_to_wsgi(u): + # On Python 3, convert an environment variable to a WSGI + # "bytes-as-unicode" string + return u.encode(fsenc, 'surrogateescape').decode('latin-1') +else: + def text_to_wsgi(u): + return u.encode('latin-1', 'surrogateescape') + +try: + from queue import Queue, Empty +except ImportError: + from Queue import Queue, Empty + +try: # pragma: no cover + from urllib import parse + urlparse = parse + from urllib.parse import quote as url_quote + from urllib.parse import unquote as url_unquote + from urllib.parse import urlencode as url_encode + from urllib.request import urlopen as url_open +except ImportError: + import urlparse + from urllib import quote as url_quote + from urllib import unquote as url_unquote + from urllib import urlencode as url_encode + from urllib2 import urlopen as url_open + +if PY3: # pragma: no cover + import builtins + exec_ = getattr(builtins, "exec") + + + def reraise(tp, value, tb=None): + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + + + print_ = getattr(builtins, "print") + del builtins + +else: # pragma: no cover + def exec_(code, globs=None, locs=None): + """Execute code in a namespace.""" + if globs is None: + frame = sys._getframe(1) + globs = frame.f_globals + if locs is None: + locs = frame.f_locals + del frame + elif locs is None: + locs = globs + exec("""exec code in globs, locs""") + + + exec_("""def reraise(tp, value, tb=None): + raise tp, value, tb +""") + + + def print_(*args, **kwargs): + """The new-style print function.""" + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + def write(data): + if not isinstance(data, basestring): + data = str(data) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) + +if PY3: # pragma: no cover + def iteritems_(d): + return d.items() + def itervalues_(d): + return d.values() +else: + def iteritems_(d): + return d.iteritems() + def itervalues_(d): + return d.itervalues() + + +if PY3: + def map_(*arg): + return list(map(*arg)) +else: + map_ = map + diff --git a/pyramid/config/__init__.py b/pyramid/config/__init__.py index a2014b1b5..527745ecf 100644 --- a/pyramid/config/__init__.py +++ b/pyramid/config/__init__.py @@ -13,6 +13,9 @@ from pyramid.interfaces import IExceptionResponse from pyramid.asset import resolve_asset_spec from pyramid.authorization import ACLAuthorizationPolicy +from pyramid.compat import text_ +from pyramid.compat import reraise +from pyramid.compat import string_types from pyramid.events import ApplicationCreated from pyramid.exceptions import ConfigurationConflictError from pyramid.exceptions import ConfigurationError @@ -42,6 +45,8 @@ from pyramid.config.util import action_method from pyramid.config.views import ViewsConfiguratorMixin from pyramid.config.zca import ZCAConfiguratorMixin +empty = text_('') + ConfigurationError = ConfigurationError # pyflakes class Configurator( @@ -283,7 +288,7 @@ class Configurator( self._set_settings(settings) self._register_response_adapters() - if isinstance(debug_logger, basestring): + if isinstance(debug_logger, string_types): debug_logger = logging.getLogger(debug_logger) if debug_logger is None: @@ -401,7 +406,7 @@ class Configurator( if not hasattr(_registry, 'registerSelfAdapter'): def registerSelfAdapter(required=None, provided=None, - name=u'', info=u'', event=True): + name=empty, info=empty, event=True): return _registry.registerAdapter(lambda x: x, required=required, provided=provided, name=name, @@ -709,7 +714,7 @@ class Configurator( when generating an absolute asset specification. If the provided ``relative_spec`` argument is already absolute, or if the ``relative_spec`` is not a string, it is simply returned.""" - if not isinstance(relative_spec, basestring): + if not isinstance(relative_spec, string_types): return relative_spec return self._make_spec(relative_spec) @@ -907,7 +912,8 @@ class ActionState(object): except: t, v, tb = sys.exc_info() try: - raise ConfigurationExecutionError(t, v, info), None, tb + reraise( + ConfigurationExecutionError(t, v, info), None, tb) finally: del t, v, tb finally: diff --git a/pyramid/config/tweens.py b/pyramid/config/tweens.py index 2704b89c1..6feb1bfe6 100644 --- a/pyramid/config/tweens.py +++ b/pyramid/config/tweens.py @@ -197,7 +197,7 @@ class Tweens(object): order.append((a, b)) def add_node(node): - if not graph.has_key(node): + if not node in graph: roots.append(node) graph[node] = [0] # 0 = number of arcs coming into this node diff --git a/pyramid/config/util.py b/pyramid/config/util.py index 7ce9adc4f..f549b1977 100644 --- a/pyramid/config/util.py +++ b/pyramid/config/util.py @@ -1,4 +1,5 @@ import re +import sys import traceback from pyramid.exceptions import ConfigurationError @@ -111,7 +112,8 @@ def make_predicates(xhr=None, request_method=None, path_info=None, if path_info is not None: try: path_info_val = re.compile(path_info) - except re.error, why: + except re.error: + why = sys.exc_info()[1] raise ConfigurationError(why[0]) def path_info_predicate(context, request): return path_info_val.match(request.path_info) is not None @@ -145,7 +147,8 @@ def make_predicates(xhr=None, request_method=None, path_info=None, header_name, header_val = header.split(':', 1) try: header_val = re.compile(header_val) - except re.error, why: + except re.error: + why = sys.exc_info()[1] raise ConfigurationError(why[0]) if header_val is None: text = "header %s" % header_name diff --git a/pyramid/config/views.py b/pyramid/config/views.py index 703e3cca5..f1370a4b9 100644 --- a/pyramid/config/views.py +++ b/pyramid/config/views.py @@ -1,6 +1,4 @@ import inspect -from urlparse import urljoin -from urlparse import urlparse from zope.interface import Interface from zope.interface import classProvides @@ -28,6 +26,7 @@ from pyramid.interfaces import IViewMapperFactory from pyramid.interfaces import PHASE1_CONFIG from pyramid import renderers +from pyramid.compat import urlparse from pyramid.exceptions import ConfigurationError from pyramid.exceptions import PredicateMismatch from pyramid.httpexceptions import HTTPForbidden @@ -43,6 +42,8 @@ from pyramid.config.util import action_method from pyramid.config.util import as_sorted_tuple from pyramid.config.util import make_predicates +urljoin = urlparse.urljoin + def wraps_view(wrapper): def inner(self, view): wrapper_view = wrapper(self, view) diff --git a/pyramid/exceptions.py b/pyramid/exceptions.py index cafdb93f0..cd234adca 100644 --- a/pyramid/exceptions.py +++ b/pyramid/exceptions.py @@ -4,6 +4,8 @@ from pyramid.httpexceptions import HTTPForbidden NotFound = HTTPNotFound # bw compat Forbidden = HTTPForbidden # bw compat +CR = '\n' + class PredicateMismatch(HTTPNotFound): """ Internal exception (not an API) raised by multiviews when no @@ -42,10 +44,10 @@ class ConfigurationConflictError(ConfigurationError): for discriminator, infos in items: r.append(" For: %s" % (discriminator, )) for info in infos: - for line in unicode(info).rstrip().split(u'\n'): - r.append(u" "+line) + for line in unicode(info).rstrip().split(CR): + r.append(" "+line) - return "\n".join(r) + return CR.join(r) class ConfigurationExecutionError(ConfigurationError): diff --git a/pyramid/httpexceptions.py b/pyramid/httpexceptions.py index 0887b0eec..7cebfdc48 100644 --- a/pyramid/httpexceptions.py +++ b/pyramid/httpexceptions.py @@ -122,7 +122,6 @@ field. Reflecting this, these subclasses have one additional keyword argument: ``location``, which indicates the location to which to redirect. """ -import types from string import Template from zope.interface import implements @@ -131,6 +130,7 @@ from webob import html_escape as _html_escape from pyramid.interfaces import IExceptionResponse from pyramid.response import Response +from pyramid.compat import class_types def _no_escape(value): if value is None: @@ -1016,8 +1016,8 @@ def default_exceptionresponse_view(context, request): status_map={} code = None -for name, value in globals().items(): - if (isinstance(value, (type, types.ClassType)) and +for name, value in list(globals().items()): + if (isinstance(value, class_types) and issubclass(value, HTTPException) and not name.startswith('_')): code = getattr(value, 'code', None) diff --git a/pyramid/interfaces.py b/pyramid/interfaces.py index a0f27dd7a..a2b7990aa 100644 --- a/pyramid/interfaces.py +++ b/pyramid/interfaces.py @@ -42,7 +42,7 @@ class IApplicationCreated(Interface): versions before 1.0, this interface can also be imported as :class:`pyramid.interfaces.IWSGIApplicationCreatedEvent`. """ - app = Attribute(u"Created application") + app = Attribute("Created application") IWSGIApplicationCreatedEvent = IApplicationCreated # b /c diff --git a/pyramid/registry.py b/pyramid/registry.py index b88aabaff..ac706595e 100644 --- a/pyramid/registry.py +++ b/pyramid/registry.py @@ -1,7 +1,10 @@ from zope.interface.registry import Components +from pyramid.compat import text_ from pyramid.interfaces import ISettings +empty = text_('') + class Registry(Components, dict): """ A registry object is an :term:`application registry`. It is used by the framework itself to perform mappings of URLs to view callables, as @@ -34,8 +37,8 @@ class Registry(Components, dict): self.has_listeners = True return result - def registerSelfAdapter(self, required=None, provided=None, name=u'', - info=u'', event=True): + def registerSelfAdapter(self, required=None, provided=None, name=empty, + info=empty, event=True): # registerAdapter analogue which always returns the object itself # when required is matched return self.registerAdapter(lambda x: x, required=required, diff --git a/pyramid/renderers.py b/pyramid/renderers.py index 2efe0f123..93e97de8f 100644 --- a/pyramid/renderers.py +++ b/pyramid/renderers.py @@ -15,6 +15,8 @@ from pyramid.interfaces import IRendererInfo from pyramid.asset import asset_spec_from_abspath from pyramid.compat import json +from pyramid.compat import string_types +from pyramid.compat import native_ from pyramid.decorator import reify from pyramid.events import BeforeRender from pyramid.path import caller_package @@ -145,8 +147,8 @@ def json_renderer_factory(info): def string_renderer_factory(info): def _render(value, system): - if not isinstance(value, basestring): - value = str(value) + if not isinstance(value, string_types): + value = native_(value, 'utf-8') request = system.get('request') if request is not None: response = request.response diff --git a/pyramid/resource.py b/pyramid/resource.py index 5e8f3c968..986c75e37 100644 --- a/pyramid/resource.py +++ b/pyramid/resource.py @@ -1,5 +1,5 @@ """ Backwards compatibility shim module (forever). """ -from asset import * # b/w compat +from pyramid.asset import * # b/w compat resolve_resource_spec = resolve_asset_spec resource_spec_from_abspath = asset_spec_from_abspath abspath_from_resource_spec = abspath_from_asset_spec diff --git a/pyramid/session.py b/pyramid/session.py index bfa80ff10..633620716 100644 --- a/pyramid/session.py +++ b/pyramid/session.py @@ -1,18 +1,14 @@ - -try: - import cPickle as pickle -except ImportError: # pragma: no cover - import pickle - from hashlib import sha1 import base64 import binascii import hmac +import sys import time import os from zope.interface import implements +from pyramid.compat import pickle from pyramid.interfaces import ISession def manage_accessed(wrapped): @@ -255,8 +251,9 @@ def signed_deserialize(serialized, secret, hmac=hmac): try: input_sig, pickled = (serialized[:40], base64.standard_b64decode(serialized[40:])) - except (binascii.Error, TypeError), e: + except (binascii.Error, TypeError): # Badly formed data can make base64 die + e = sys.exc_info()[1] raise ValueError('Badly formed base64 data: %s' % e) sig = hmac.new(secret, pickled, sha1).hexdigest() diff --git a/pyramid/static.py b/pyramid/static.py index eeb88bf5c..0ab4a0c79 100644 --- a/pyramid/static.py +++ b/pyramid/static.py @@ -15,12 +15,15 @@ from pkg_resources import resource_isdir from repoze.lru import lru_cache from pyramid.asset import resolve_asset_spec +from pyramid.compat import text_ from pyramid.httpexceptions import HTTPNotFound from pyramid.httpexceptions import HTTPMovedPermanently from pyramid.path import caller_package from pyramid.response import Response from pyramid.traversal import traversal_path +slash = text_('/') + def init_mimetypes(mimetypes): # this is a function so it can be unittested if hasattr(mimetypes, 'init'): @@ -192,6 +195,6 @@ def _secure_path(path_tuple): return None if any([_contains_slash(item) for item in path_tuple]): return None - encoded = u'/'.join(path_tuple) # will be unicode + encoded = slash.join(path_tuple) # will be unicode return encoded diff --git a/pyramid/testing.py b/pyramid/testing.py index 07f523868..862b9d6b1 100644 --- a/pyramid/testing.py +++ b/pyramid/testing.py @@ -28,6 +28,13 @@ from pyramid.request import DeprecatedRequestMethodsMixin from pyramid.request import CallbackMethodsMixin from pyramid.url import URLMethodsMixin +try: + import zope.component + zope.component + have_zca = True +except ImportError: + have_zca = False + _marker = object() def registerDummySecurityPolicy(userid=None, groupids=(), permissive=True): @@ -801,7 +808,7 @@ def setUp(registry=None, request=None, hook_zca=True, autocommit=True, # any existing renderer factory lookup system. config.add_renderer(name, renderer) config.commit() - hook_zca and config.hook_zca() + have_zca and hook_zca and config.hook_zca() config.begin(request=request) return config diff --git a/pyramid/tests/test_authentication.py b/pyramid/tests/test_authentication.py index ff96ae471..37c179caf 100644 --- a/pyramid/tests/test_authentication.py +++ b/pyramid/tests/test_authentication.py @@ -1,5 +1,6 @@ import unittest from pyramid import testing +from pyramid.compat import text_ class TestCallbackAuthenticationPolicyDebugging(unittest.TestCase): def setUp(self): @@ -903,7 +904,7 @@ class TestAuthTktCookieHelper(unittest.TestCase): helper = self._makeOne('secret') request = self._makeRequest() self.assertRaises(ValueError, helper.remember, request, 'other', - tokens=(u'foo',)) + tokens=(text_('foo'),)) def test_remember_invalid_token_format(self): helper = self._makeOne('secret') @@ -1092,8 +1093,8 @@ class Test_maybe_encode(unittest.TestCase): return maybe_encode(s, encoding) def test_unicode(self): - result = self._callFUT(u'abc') - self.assertEqual(result, 'abc') + result = self._callFUT(text_('abc')) + self.assertEqual(result, text_('abc')) class DummyContext: pass diff --git a/pyramid/tests/test_config/test_assets.py b/pyramid/tests/test_config/test_assets.py index 322c854f5..a07753118 100644 --- a/pyramid/tests/test_config/test_assets.py +++ b/pyramid/tests/test_config/test_assets.py @@ -581,7 +581,7 @@ class DummyPackage: class DummyUnderOverride: def __call__(self, package, path, override_package, override_prefix, - _info=u''): + _info=''): self.package = package self.path = path self.override_package = override_package diff --git a/pyramid/tests/test_config/test_i18n.py b/pyramid/tests/test_config/test_i18n.py index 03b410445..25cb88cc3 100644 --- a/pyramid/tests/test_config/test_i18n.py +++ b/pyramid/tests/test_config/test_i18n.py @@ -92,7 +92,7 @@ class TestI18NConfiguratorMixin(unittest.TestCase): try: config.add_translation_dirs('pyramid.tests.pkgs.localeapp:locale') translate = config.registry.getUtility(IChameleonTranslate) - self.assertEqual(translate('Approve'), u'Approve') + self.assertEqual(translate('Approve'), 'Approve') finally: manager.pop() diff --git a/pyramid/tests/test_config/test_init.py b/pyramid/tests/test_config/test_init.py index 1dccd00e1..750cdb94f 100644 --- a/pyramid/tests/test_config/test_init.py +++ b/pyramid/tests/test_config/test_init.py @@ -333,7 +333,7 @@ class ConfiguratorTests(unittest.TestCase): args, kw = reg.adapters[0] self.assertEqual(args[0]('abc'), 'abc') self.assertEqual(kw, - {'info': u'', 'provided': 'provided', + {'info': '', 'provided': 'provided', 'required': 'required', 'name': 'abc', 'event': True}) def test_setup_registry_calls_fix_registry(self): diff --git a/pyramid/tests/test_config/test_views.py b/pyramid/tests/test_config/test_views.py index be5143d45..84d53338e 100644 --- a/pyramid/tests/test_config/test_views.py +++ b/pyramid/tests/test_config/test_views.py @@ -1,4 +1,5 @@ import unittest +import sys from pyramid import testing from pyramid.tests.test_config import IDummy @@ -2530,7 +2531,8 @@ class TestViewDeriver(unittest.TestCase): request.url = 'url' try: result(None, request) - except HTTPForbidden, e: + except HTTPForbidden: + e = sys.exc_info()[1] self.assertEqual(e.message, 'Unauthorized: <lambda> failed permission check') else: # pragma: no cover @@ -2552,7 +2554,8 @@ class TestViewDeriver(unittest.TestCase): request.url = 'url' try: result(None, request) - except HTTPForbidden, e: + except HTTPForbidden: + e = sys.exc_info()[1] self.assertEqual(e.message, 'Unauthorized: myview failed permission check') else: # pragma: no cover @@ -2570,7 +2573,8 @@ class TestViewDeriver(unittest.TestCase): request.method = 'POST' try: result(None, None) - except PredicateMismatch, e: + except PredicateMismatch: + e = sys.exc_info()[1] self.assertEqual(e.detail, 'predicate mismatch for view <lambda>') else: # pragma: no cover raise AssertionError @@ -2586,7 +2590,8 @@ class TestViewDeriver(unittest.TestCase): request.method = 'POST' try: result(None, None) - except PredicateMismatch, e: + except PredicateMismatch: + e = sys.exc_info()[1] self.assertEqual(e.detail, 'predicate mismatch for view myview') else: # pragma: no cover raise AssertionError diff --git a/pyramid/tests/test_docs.py b/pyramid/tests/test_docs.py index bf06c7ca6..eba95b210 100644 --- a/pyramid/tests/test_docs.py +++ b/pyramid/tests/test_docs.py @@ -1,4 +1,5 @@ import unittest +from pyramid.compat import print_ if 0: # no released version of manuel actually works with :lineno: @@ -31,5 +32,5 @@ if 0: if filename.endswith('.rst'): docs.append(os.path.join(root, filename)) - print path + print_(path) return manuel.testing.TestSuite(m, *docs) diff --git a/pyramid/tests/test_httpexceptions.py b/pyramid/tests/test_httpexceptions.py index 9c7b38e27..fe3a79593 100644 --- a/pyramid/tests/test_httpexceptions.py +++ b/pyramid/tests/test_httpexceptions.py @@ -1,4 +1,5 @@ import unittest +from pyramid.compat import text_ class Test_exception_response(unittest.TestCase): def _callFUT(self, *arg, **kw): @@ -48,9 +49,9 @@ class Test__no_escape(unittest.TestCase): def test_unicode(self): class DummyUnicodeObject(object): def __unicode__(self): - return u'42' + return text_('42') duo = DummyUnicodeObject() - self.assertEqual(self._callFUT(duo), u'42') + self.assertEqual(self._callFUT(duo), text_('42')) class TestWSGIHTTPException(unittest.TestCase): def _getTargetClass(self): @@ -128,7 +129,7 @@ class TestWSGIHTTPException(unittest.TestCase): self.assertEqual(exc.app_iter, ['123']) def test_ctor_with_unicode_body_doesnt_set_default_app_iter(self): - exc = self._makeOne(unicode_body=u'123') + exc = self._makeOne(unicode_body=text_('123')) self.assertEqual(exc.app_iter, ['123']) def test_ctor_with_app_iter_doesnt_set_default_app_iter(self): diff --git a/pyramid/tests/test_integration.py b/pyramid/tests/test_integration.py index 1fa1cbbcf..40f1adf14 100644 --- a/pyramid/tests/test_integration.py +++ b/pyramid/tests/test_integration.py @@ -6,6 +6,7 @@ import unittest from pyramid.wsgi import wsgiapp from pyramid.view import view_config from pyramid.static import static_view +from pyramid.compat import text_ from zope.interface import Interface @@ -82,13 +83,17 @@ class TestStaticAppBase(IntegrationBase): def test_highchars_in_pathelement(self): res = self.testapp.get('/static/héhé/index.html', status=200) self._assertBody( - res.body, os.path.join(here, u'fixtures/static/héhé/index.html') + res.body, os.path.join( + here, + text_('fixtures/static/héhé/index.html', 'utf-8')) ) def test_highchars_in_filename(self): res = self.testapp.get('/static/héhé.html', status=200) self._assertBody( - res.body, os.path.join(here, u'fixtures/static/héhé.html') + res.body, os.path.join( + here, + text_('fixtures/static/héhé.html', 'utf-8')) ) def test_not_modified(self): diff --git a/pyramid/tests/test_mako_templating.py b/pyramid/tests/test_mako_templating.py index 162f774f5..9948c713c 100644 --- a/pyramid/tests/test_mako_templating.py +++ b/pyramid/tests/test_mako_templating.py @@ -2,6 +2,7 @@ import unittest from pyramid import testing +from pyramid.compat import text_ class Base(object): def setUp(self): @@ -276,7 +277,7 @@ class MakoLookupTemplateRendererTests(Base, unittest.TestCase): instance = self._makeOne('path', lookup) result = instance({}, {'system':1}) self.assertTrue(isinstance(result, unicode)) - self.assertEqual(result, u'result') + self.assertEqual(result, text_('result')) def test_call_with_system_context(self): # lame @@ -284,7 +285,7 @@ class MakoLookupTemplateRendererTests(Base, unittest.TestCase): instance = self._makeOne('path', lookup) result = instance({}, {'context':1}) self.assertTrue(isinstance(result, unicode)) - self.assertEqual(result, u'result') + self.assertEqual(result, text_('result')) self.assertEqual(lookup.values, {'_context':1}) def test_call_with_tuple_value(self): @@ -292,7 +293,7 @@ class MakoLookupTemplateRendererTests(Base, unittest.TestCase): instance = self._makeOne('path', lookup) result = instance(('fub', {}), {'context':1}) self.assertEqual(lookup.deffed, 'fub') - self.assertEqual(result, u'result') + self.assertEqual(result, text_('result')) self.assertEqual(lookup.values, {'_context':1}) def test_call_with_nondict_value(self): @@ -316,7 +317,7 @@ class MakoLookupTemplateRendererTests(Base, unittest.TestCase): instance = self._makeOne('path', lookup) result = instance.implementation().render_unicode() self.assertTrue(isinstance(result, unicode)) - self.assertEqual(result, u'result') + self.assertEqual(result, text_('result')) class TestIntegration(unittest.TestCase): def setUp(self): @@ -333,45 +334,48 @@ class TestIntegration(unittest.TestCase): def test_render(self): from pyramid.renderers import render result = render('helloworld.mak', {'a':1}).replace('\r','') - self.assertEqual(result, u'\nHello föö\n') + self.assertEqual(result, text_('\nHello föö\n', 'utf-8')) def test_render_from_fs(self): from pyramid.renderers import render self.config.add_settings({'reload_templates': True}) result = render('helloworld.mak', {'a':1}).replace('\r','') - self.assertEqual(result, u'\nHello föö\n') + self.assertEqual(result, text_('\nHello föö\n', 'utf-8')) def test_render_inheritance(self): from pyramid.renderers import render result = render('helloinherit.mak', {}).replace('\r','') - self.assertEqual(result, u'Layout\nHello World!\n') + self.assertEqual(result, text_('Layout\nHello World!\n')) def test_render_inheritance_pkg_spec(self): from pyramid.renderers import render result = render('hello_inherit_pkg.mak', {}).replace('\r','') - self.assertEqual(result, u'Layout\nHello World!\n') + self.assertEqual(result, text_('Layout\nHello World!\n')) def test_render_to_response(self): from pyramid.renderers import render_to_response result = render_to_response('helloworld.mak', {'a':1}) - self.assertEqual(result.ubody.replace('\r',''), u'\nHello föö\n') + self.assertEqual(result.ubody.replace('\r',''), + text_('\nHello föö\n', 'utf-8')) def test_render_to_response_pkg_spec(self): from pyramid.renderers import render_to_response result = render_to_response('pyramid.tests:fixtures/helloworld.mak', {'a':1}) - self.assertEqual(result.ubody.replace('\r', ''), u'\nHello föö\n') + self.assertEqual(result.ubody.replace('\r', ''), + text_('\nHello föö\n', 'utf-8')) def test_render_with_abs_path(self): from pyramid.renderers import render result = render('/helloworld.mak', {'a':1}).replace('\r','') - self.assertEqual(result, u'\nHello föö\n') + self.assertEqual(result, text_('\nHello föö\n', 'utf-8')) def test_get_renderer(self): from pyramid.renderers import get_renderer result = get_renderer('helloworld.mak') - self.assertEqual(result.implementation().render_unicode().replace('\r',''), - u'\nHello föö\n') + self.assertEqual( + result.implementation().render_unicode().replace('\r',''), + text_('\nHello föö\n', 'utf-8')) def test_template_not_found(self): from pyramid.renderers import render @@ -381,8 +385,9 @@ class TestIntegration(unittest.TestCase): def test_template_default_escaping(self): from pyramid.renderers import render - result = render('nonminimal.mak', {'name':'<b>fred</b>'}).replace('\r','') - self.assertEqual(result, u'Hello, <b>fred</b>!\n') + result = render('nonminimal.mak', + {'name':'<b>fred</b>'}).replace('\r','') + self.assertEqual(result, text_('Hello, <b>fred</b>!\n')) class TestPkgResourceTemplateLookup(unittest.TestCase): def _makeOne(self, **kw): @@ -448,7 +453,7 @@ class DummyLookup(object): if self.exc: raise self.exc self.values = values - return u'result' + return text_('result') class DummyRendererInfo(object): def __init__(self, kw): diff --git a/pyramid/tests/test_paster.py b/pyramid/tests/test_paster.py index 995e05d46..cf551ed5c 100644 --- a/pyramid/tests/test_paster.py +++ b/pyramid/tests/test_paster.py @@ -1062,7 +1062,7 @@ class DummyConfigParser(object): self.section = section if self.result is None: from ConfigParser import NoSectionError - raise NoSectionError, section + raise NoSectionError(section) return self.result class DummyConfigParserFactory(object): diff --git a/pyramid/tests/test_request.py b/pyramid/tests/test_request.py index 066aa9207..d48cba58d 100644 --- a/pyramid/tests/test_request.py +++ b/pyramid/tests/test_request.py @@ -1,6 +1,8 @@ import unittest from pyramid import testing +from pyramid.compat import text_ + class TestRequest(unittest.TestCase): def setUp(self): self.config = testing.setUp() @@ -50,7 +52,7 @@ class TestRequest(unittest.TestCase): } request = self._makeOne(environ) request.charset = None - self.assertEqual(request.GET['la'], u'La Pe\xf1a') + self.assertEqual(request.GET['la'], text_('La Pe\xf1a', 'utf-8')) def test_class_implements(self): from pyramid.interfaces import IRequest @@ -166,7 +168,7 @@ class TestRequest(unittest.TestCase): self.config.registry.registerUtility(mapper, IRoutesMapper) result = inst.route_url('flub', 'extra1', 'extra2', a=1, b=2, c=3, _query={'a':1}, - _anchor=u"foo") + _anchor=text_("foo")) self.assertEqual(result, 'http://example.com:5432/1/2/3/extra1/extra2?a=1#foo') @@ -184,7 +186,7 @@ class TestRequest(unittest.TestCase): self.config.registry.registerUtility(mapper, IRoutesMapper) result = inst.route_path('flub', 'extra1', 'extra2', a=1, b=2, c=3, _query={'a':1}, - _anchor=u"foo") + _anchor=text_("foo")) self.assertEqual(result, '/1/2/3/extra1/extra2?a=1#foo') def test_static_url(self): diff --git a/pyramid/tests/test_router.py b/pyramid/tests/test_router.py index 35f2e4352..ebb76f941 100644 --- a/pyramid/tests/test_router.py +++ b/pyramid/tests/test_router.py @@ -1,3 +1,4 @@ +import sys import unittest from pyramid import testing @@ -1204,7 +1205,8 @@ class DummyLogger: def exc_raised(exc, func, *arg, **kw): try: func(*arg, **kw) - except exc, e: + except exc: + e = sys.exc_info()[1] return e else: raise AssertionError('%s not raised' % exc) # pragma: no cover diff --git a/pyramid/tests/test_testing.py b/pyramid/tests/test_testing.py index 41a4788ec..c131cc94b 100644 --- a/pyramid/tests/test_testing.py +++ b/pyramid/tests/test_testing.py @@ -1,5 +1,5 @@ - import unittest +from pyramid.compat import text_ class TestBase(unittest.TestCase): def setUp(self): @@ -46,14 +46,14 @@ class Test_registerResources(TestBase): self.assertEqual(result['context'], ob1) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) - self.assertEqual(result['traversed'], (u'ob1',)) + self.assertEqual(result['traversed'], (text_('ob1'),)) self.assertEqual(result['virtual_root'], ob1) self.assertEqual(result['virtual_root_path'], ()) result = adapter(DummyRequest({'PATH_INFO':'/ob2'})) self.assertEqual(result['context'], ob2) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) - self.assertEqual(result['traversed'], (u'ob2',)) + self.assertEqual(result['traversed'], (text_('ob2'),)) self.assertEqual(result['virtual_root'], ob2) self.assertEqual(result['virtual_root_path'], ()) self.assertRaises(KeyError, adapter, DummyRequest({'PATH_INFO':'/ob3'})) diff --git a/pyramid/tests/test_traversal.py b/pyramid/tests/test_traversal.py index 95caf21be..2f3a0017a 100644 --- a/pyramid/tests/test_traversal.py +++ b/pyramid/tests/test_traversal.py @@ -1,6 +1,7 @@ import unittest from pyramid.testing import cleanUp +from pyramid.compat import text_ class TraversalPathTests(unittest.TestCase): def _callFUT(self, path): @@ -8,23 +9,24 @@ class TraversalPathTests(unittest.TestCase): return traversal_path(path) def test_path_startswith_endswith(self): - self.assertEqual(self._callFUT('/foo/'), (u'foo',)) + self.assertEqual(self._callFUT('/foo/'), (text_('foo'),)) def test_empty_elements(self): - self.assertEqual(self._callFUT('foo///'), (u'foo',)) + self.assertEqual(self._callFUT('foo///'), (text_('foo'),)) def test_onedot(self): - self.assertEqual(self._callFUT('foo/./bar'), (u'foo', u'bar')) + self.assertEqual(self._callFUT('foo/./bar'), + (text_('foo'), text_('bar'))) def test_twodots(self): - self.assertEqual(self._callFUT('foo/../bar'), (u'bar',)) + self.assertEqual(self._callFUT('foo/../bar'), (text_('bar'),)) def test_twodots_at_start(self): - self.assertEqual(self._callFUT('../../bar'), (u'bar',)) + self.assertEqual(self._callFUT('../../bar'), (text_('bar'),)) def test_element_urllquoted(self): self.assertEqual(self._callFUT('/foo/space%20thing/bar'), - (u'foo', u'space thing', u'bar')) + (text_('foo'), text_('space thing'), text_('bar'))) def test_segments_are_unicode(self): result = self._callFUT('/foo/bar') @@ -34,8 +36,8 @@ class TraversalPathTests(unittest.TestCase): def test_same_value_returned_if_cached(self): result1 = self._callFUT('/foo/bar') result2 = self._callFUT('/foo/bar') - self.assertEqual(result1, (u'foo', u'bar')) - self.assertEqual(result2, (u'foo', u'bar')) + self.assertEqual(result1, (text_('foo'), text_('bar'))) + self.assertEqual(result2, (text_('foo'), text_('bar'))) def test_utf8(self): import urllib @@ -54,15 +56,16 @@ class TraversalPathTests(unittest.TestCase): self.assertRaises(URLDecodeError, self._callFUT, path) def test_unicode_highorder_chars(self): - path = u'/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF' - self.assertEqual(self._callFUT(path), (u'\u6d41\u884c\u8d8b\u52bf',)) + path = text_('/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF') + self.assertEqual(self._callFUT(path), + (text_('\u6d41\u884c\u8d8b\u52bf'),)) def test_unicode_simple(self): - path = u'/abc' - self.assertEqual(self._callFUT(path), (u'abc',)) + path = text_('/abc') + self.assertEqual(self._callFUT(path), (text_('abc'),)) def test_unicode_undecodeable_to_ascii(self): - path = unicode('/La Pe\xc3\xb1a', 'utf-8') + path = text_('/La Pe\xc3\xb1a', 'utf-8') self.assertRaises(UnicodeEncodeError, self._callFUT, path) class ResourceTreeTraverserTests(unittest.TestCase): @@ -146,7 +149,7 @@ class ResourceTreeTraverserTests(unittest.TestCase): self.assertEqual(result['context'], foo) self.assertEqual(result['view_name'], 'bar') self.assertEqual(result['subpath'], ()) - self.assertEqual(result['traversed'], (u'foo',)) + self.assertEqual(result['traversed'], (text_('foo'),)) self.assertEqual(result['root'], root) self.assertEqual(result['virtual_root'], root) self.assertEqual(result['virtual_root_path'], ()) @@ -161,7 +164,7 @@ class ResourceTreeTraverserTests(unittest.TestCase): self.assertEqual(result['context'], foo) self.assertEqual(result['view_name'], 'bar') self.assertEqual(result['subpath'], ('baz', 'buz')) - self.assertEqual(result['traversed'], (u'foo',)) + self.assertEqual(result['traversed'], (text_('foo'),)) self.assertEqual(result['root'], root) self.assertEqual(result['virtual_root'], root) self.assertEqual(result['virtual_root_path'], ()) @@ -194,10 +197,12 @@ class ResourceTreeTraverserTests(unittest.TestCase): self.assertEqual(result['context'], baz) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) - self.assertEqual(result['traversed'], (u'foo', u'bar', u'baz')) + self.assertEqual(result['traversed'], + (text_('foo'), text_('bar'), text_('baz'))) self.assertEqual(result['root'], root) self.assertEqual(result['virtual_root'], bar) - self.assertEqual(result['virtual_root_path'], (u'foo', u'bar')) + self.assertEqual(result['virtual_root_path'], + (text_('foo'), text_('bar'))) def test_call_with_vh_root2(self): environ = self._getEnviron(PATH_INFO='/bar/baz', @@ -212,10 +217,11 @@ class ResourceTreeTraverserTests(unittest.TestCase): self.assertEqual(result['context'], baz) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) - self.assertEqual(result['traversed'], (u'foo', u'bar', u'baz')) + self.assertEqual(result['traversed'], + (text_('foo'), text_('bar'), text_('baz'))) self.assertEqual(result['root'], root) self.assertEqual(result['virtual_root'], foo) - self.assertEqual(result['virtual_root_path'], (u'foo',)) + self.assertEqual(result['virtual_root_path'], (text_('foo'),)) def test_call_with_vh_root3(self): environ = self._getEnviron(PATH_INFO='/foo/bar/baz', @@ -230,7 +236,8 @@ class ResourceTreeTraverserTests(unittest.TestCase): self.assertEqual(result['context'], baz) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) - self.assertEqual(result['traversed'], (u'foo', u'bar', u'baz')) + self.assertEqual(result['traversed'], + (text_('foo'), text_('bar'), text_('baz'))) self.assertEqual(result['root'], root) self.assertEqual(result['virtual_root'], root) self.assertEqual(result['virtual_root_path'], ()) @@ -248,10 +255,12 @@ class ResourceTreeTraverserTests(unittest.TestCase): self.assertEqual(result['context'], baz) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) - self.assertEqual(result['traversed'], (u'foo', u'bar', u'baz')) + self.assertEqual(result['traversed'], + (text_('foo'), text_('bar'), text_('baz'))) self.assertEqual(result['root'], root) self.assertEqual(result['virtual_root'], baz) - self.assertEqual(result['virtual_root_path'], (u'foo', u'bar', u'baz')) + self.assertEqual(result['virtual_root_path'], + (text_('foo'), text_('bar'), text_('baz'))) def test_call_with_vh_root_path_root(self): policy = self._makeOne(None) @@ -592,13 +601,15 @@ class FindResourceTests(unittest.TestCase): unprintable = DummyContext() root = DummyContext(unprintable) unprintable.__parent__ = root - unprintable.__name__ = unicode( + unprintable.__name__ = text_( '/\xe6\xb5\x81\xe8\xa1\x8c\xe8\xb6\x8b\xe5\x8a\xbf', 'utf-8') root.__parent__ = None root.__name__ = None traverser = ResourceTreeTraverser self._registerTraverser(traverser) - result = self._callFUT(root, u'/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF') + result = self._callFUT( + root, + text_('/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF')) self.assertEqual(result, unprintable) class ResourcePathTests(unittest.TestCase): @@ -1168,7 +1179,7 @@ class DummyContext(object): def __getitem__(self, name): if self.next is None: - raise KeyError, name + raise KeyError(name) return self.next def __repr__(self): diff --git a/pyramid/tests/test_url.py b/pyramid/tests/test_url.py index 8b95374fb..452debd42 100644 --- a/pyramid/tests/test_url.py +++ b/pyramid/tests/test_url.py @@ -2,6 +2,7 @@ import unittest from pyramid.testing import setUp from pyramid.testing import tearDown +from pyramid.compat import text_ class TestURLMethodsMixin(unittest.TestCase): def setUp(self): @@ -172,7 +173,7 @@ class TestURLMethodsMixin(unittest.TestCase): mapper = DummyRoutesMapper(route=DummyRoute('/1/2/3')) request.registry.registerUtility(mapper, IRoutesMapper) result = request.route_url('flub', a=1, b=2, c=3, _query={'a':1}, - _anchor=u"foo") + _anchor=text_("foo")) self.assertEqual(result, 'http://example.com:5432/1/2/3?a=1#foo') @@ -281,7 +282,7 @@ class TestURLMethodsMixin(unittest.TestCase): request.matchdict = {} request.registry.registerUtility(mapper, IRoutesMapper) result = request.current_route_url('extra1', 'extra2', _query={'a':1}, - _anchor=u"foo") + _anchor=text_("foo")) self.assertEqual(result, 'http://example.com:5432/1/2/3/extra1/extra2?a=1#foo') @@ -294,7 +295,8 @@ class TestURLMethodsMixin(unittest.TestCase): request.matchdict = {} request.registry.registerUtility(mapper, IRoutesMapper) result = request.current_route_url('extra1', 'extra2', _query={'a':1}, - _anchor=u"foo", _route_name='bar') + _anchor=text_("foo"), + _route_name='bar') self.assertEqual(result, 'http://example.com:5432/1/2/3/extra1/extra2?a=1#foo') @@ -308,7 +310,7 @@ class TestURLMethodsMixin(unittest.TestCase): request.script_name = '/script_name' request.registry.registerUtility(mapper, IRoutesMapper) result = request.current_route_path('extra1', 'extra2', _query={'a':1}, - _anchor=u"foo") + _anchor=text_("foo")) self.assertEqual(result, '/script_name/1/2/3/extra1/extra2?a=1#foo') def test_route_path_with_elements(self): @@ -319,7 +321,7 @@ class TestURLMethodsMixin(unittest.TestCase): request.script_name = '' result = request.route_path('flub', 'extra1', 'extra2', a=1, b=2, c=3, _query={'a':1}, - _anchor=u"foo") + _anchor=text_("foo")) self.assertEqual(result, '/1/2/3/extra1/extra2?a=1#foo') def test_route_path_with_script_name(self): @@ -330,7 +332,7 @@ class TestURLMethodsMixin(unittest.TestCase): request.registry.registerUtility(mapper, IRoutesMapper) result = request.route_path('flub', 'extra1', 'extra2', a=1, b=2, c=3, _query={'a':1}, - _anchor=u"foo") + _anchor=text_("foo")) self.assertEqual(result, '/foo/1/2/3/extra1/extra2?a=1#foo') def test_static_url_staticurlinfo_notfound(self): diff --git a/pyramid/tests/test_urldispatch.py b/pyramid/tests/test_urldispatch.py index 3c92e87be..6cad71d90 100644 --- a/pyramid/tests/test_urldispatch.py +++ b/pyramid/tests/test_urldispatch.py @@ -1,5 +1,6 @@ import unittest from pyramid import testing +from pyramid.compat import text_ class TestRoute(unittest.TestCase): def _getTargetClass(self): @@ -146,7 +147,7 @@ class RoutesMapperTests(unittest.TestCase): def test___call__custom_predicate_gets_info(self): mapper = self._makeOne() def pred(info, request): - self.assertEqual(info['match'], {'action':u'action1'}) + self.assertEqual(info['match'], {'action':'action1'}) self.assertEqual(info['route'], mapper.routes['foo']) return True mapper.connect('foo', 'archives/:action/article1', predicates=[pred]) @@ -269,7 +270,7 @@ class TestCompileRoute(unittest.TestCase): 'traverse':('everything', 'else', 'here')}) self.assertEqual(matcher('foo/baz/biz/buz/bar'), None) self.assertEqual(generator( - {'baz':1, 'buz':2, 'traverse':u'/a/b'}), '/foo/1/biz/2/bar/a/b') + {'baz':1, 'buz':2, 'traverse':'/a/b'}), '/foo/1/biz/2/bar/a/b') def test_with_bracket_star(self): matcher, generator = self._callFUT( @@ -364,9 +365,10 @@ class TestCompileRouteFunctional(unittest.TestCase): {'x':'abc', 'traverse':('def', 'g')}) self.matches('*traverse', '/zzz/abc', {'traverse':('zzz', 'abc')}) self.matches('*traverse', '/zzz/%20abc', {'traverse':('zzz', ' abc')}) - self.matches('{x}', '/La%20Pe%C3%B1a', {'x':u'La Pe\xf1a'}) + self.matches('{x}', '/La%20Pe%C3%B1a', + {'x':text_('La Pe\xf1a', 'utf-8')}) self.matches('*traverse', '/La%20Pe%C3%B1a/x', - {'traverse':(u'La Pe\xf1a', 'x')}) + {'traverse':(text_('La Pe\xf1a', 'utf-8'), 'x')}) self.matches('/foo/{id}.html', '/foo/bar.html', {'id':'bar'}) self.matches('/{num:[0-9]+}/*traverse', '/555/abc/def', {'num':'555', 'traverse':('abc', 'def')}) @@ -387,9 +389,10 @@ class TestCompileRouteFunctional(unittest.TestCase): {'x':'abc', 'traverse':('def', 'g')}) self.matches('*traverse', '/zzz/abc', {'traverse':('zzz', 'abc')}) self.matches('*traverse', '/zzz/%20abc', {'traverse':('zzz', ' abc')}) - self.matches(':x', '/La%20Pe%C3%B1a', {'x':u'La Pe\xf1a'}) + self.matches(':x', '/La%20Pe%C3%B1a', + {'x':text_('La Pe\xf1a', 'utf-8')}) self.matches('*traverse', '/La%20Pe%C3%B1a/x', - {'traverse':(u'La Pe\xf1a', 'x')}) + {'traverse':(text_('La Pe\xf1a', 'utf-8'), 'x')}) self.matches('/foo/:id.html', '/foo/bar.html', {'id':'bar'}) self.matches('/foo/:id_html', '/foo/bar_html', {'id_html':'bar_html'}) self.matches('zzz/:_', '/zzz/abc', {'_':'abc'}) @@ -413,7 +416,8 @@ class TestCompileRouteFunctional(unittest.TestCase): self.generates('/{x}*y', {'x':unicode('/La Pe\xc3\xb1a', 'utf-8'), 'y':'/rest/of/path'}, '/%2FLa%20Pe%C3%B1a/rest/of/path') - self.generates('*traverse', {'traverse':('a', u'La Pe\xf1a')}, + self.generates('*traverse', {'traverse':('a', + text_('La Pe\xf1a', 'utf-8'))}, '/a/La%20Pe%C3%B1a') self.generates('/foo/{id}.html', {'id':'bar'}, '/foo/bar.html') self.generates('/foo/{_}', {'_':'20'}, '/foo/20') @@ -433,7 +437,8 @@ class TestCompileRouteFunctional(unittest.TestCase): self.generates('/:x*y', {'x':unicode('/La Pe\xc3\xb1a', 'utf-8'), 'y':'/rest/of/path'}, '/%2FLa%20Pe%C3%B1a/rest/of/path') - self.generates('*traverse', {'traverse':('a', u'La Pe\xf1a')}, + self.generates('*traverse', {'traverse':('a', + text_('La Pe\xf1a', 'utf-8'))}, '/a/La%20Pe%C3%B1a') self.generates('/foo/:id.html', {'id':'bar'}, '/foo/bar.html') self.generates('/foo/:_', {'_':'20'}, '/foo/20') diff --git a/pyramid/tests/test_util.py b/pyramid/tests/test_util.py index 247b61dad..2c38314f4 100644 --- a/pyramid/tests/test_util.py +++ b/pyramid/tests/test_util.py @@ -1,4 +1,5 @@ import unittest +import sys class TestDottedNameResolver(unittest.TestCase): def _makeOne(self, package=None): @@ -9,7 +10,8 @@ class TestDottedNameResolver(unittest.TestCase): from pyramid.exceptions import ConfigurationError try: func(*arg, **kw) - except ConfigurationError, e: + except ConfigurationError: + e = sys.exc_info()[1] return e else: raise AssertionError('Invalid not raised') # pragma: no cover diff --git a/pyramid/traversal.py b/pyramid/traversal.py index b871b8229..7fa80e6b3 100644 --- a/pyramid/traversal.py +++ b/pyramid/traversal.py @@ -1,3 +1,4 @@ +import sys import urllib import warnings @@ -11,11 +12,14 @@ from pyramid.interfaces import IRequestFactory from pyramid.interfaces import ITraverser from pyramid.interfaces import VH_ROOT_KEY +from pyramid.compat import text_ from pyramid.encode import url_quote from pyramid.exceptions import URLDecodeError from pyramid.location import lineage from pyramid.threadlocal import get_current_registry +empty = text_('') + def find_root(resource): """ Find the root node in the resource tree to which ``resource`` belongs. Note that ``resource`` should be :term:`location`-aware. @@ -478,7 +482,8 @@ def traversal_path(path): segment = urllib.unquote(segment) try: segment = segment.decode('utf-8') - except UnicodeDecodeError, e: + except UnicodeDecodeError: + e = sys.exc_info()[1] raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if not segment or segment == '.': continue @@ -639,7 +644,7 @@ class ResourceTreeTraverser(object): ob = next i += 1 - return {'context':ob, 'view_name':u'', 'subpath':subpath, + return {'context':ob, 'view_name':empty, 'subpath':subpath, 'traversed':vpath_tuple, 'virtual_root':vroot, 'virtual_root_path':vroot_tuple, 'root':root} diff --git a/pyramid/tweens.py b/pyramid/tweens.py index b15204e9d..e40f5102f 100644 --- a/pyramid/tweens.py +++ b/pyramid/tweens.py @@ -15,11 +15,11 @@ def excview_tween_factory(handler, registry): attrs = request.__dict__ try: response = handler(request) - except Exception, exc: + except Exception: # WARNING: do not assign the result of sys.exc_info() to a # local var here, doing so will cause a leak attrs['exc_info'] = sys.exc_info() - attrs['exception'] = exc + exc = attrs['exception'] = attrs['exc_info'][1] # clear old generated request.response, if any; it may # have been mutated by the view, and its state is not # sane (e.g. caching headers) diff --git a/pyramid/urldispatch.py b/pyramid/urldispatch.py index 73318193c..215f6a4a1 100644 --- a/pyramid/urldispatch.py +++ b/pyramid/urldispatch.py @@ -1,10 +1,11 @@ import re -from urllib import unquote +import sys from zope.interface import implements from pyramid.interfaces import IRoutesMapper from pyramid.interfaces import IRoute +from pyramid.compat import url_unquote from pyramid.encode import url_quote from pyramid.exceptions import URLDecodeError from pyramid.traversal import traversal_path @@ -133,14 +134,15 @@ def _compile_route(route): if m is None: return m d = {} - for k, v in m.groupdict().iteritems(): + for k, v in m.groupdict().items(): if k == star: d[k] = traversal_path(v) else: - encoded = unquote(v) + encoded = url_unquote(v) try: d[k] = encoded.decode('utf-8') - except UnicodeDecodeError, e: + except UnicodeDecodeError: + e = sys.exc_info()[1] raise URLDecodeError( e.encoding, e.object, e.start, e.end, e.reason ) diff --git a/pyramid/util.py b/pyramid/util.py index c0e7640c4..a43b50aef 100644 --- a/pyramid/util.py +++ b/pyramid/util.py @@ -2,6 +2,7 @@ import pkg_resources import sys import weakref +from pyramid.compat import string_types from pyramid.exceptions import ConfigurationError from pyramid.path import package_of @@ -69,7 +70,7 @@ class DottedNameResolver(object): self.package_name = None self.package = None else: - if isinstance(package, basestring): + if isinstance(package, string_types): try: __import__(package) except ImportError: @@ -132,12 +133,12 @@ class DottedNameResolver(object): return found def resolve(self, dotted): - if not isinstance(dotted, basestring): + if not isinstance(dotted, string_types): raise ConfigurationError('%r is not a string' % (dotted,)) return self.maybe_resolve(dotted) def maybe_resolve(self, dotted): - if isinstance(dotted, basestring): + if isinstance(dotted, string_types): if ':' in dotted: return self._pkg_resources_style(dotted) else: diff --git a/pyramid/view.py b/pyramid/view.py index 8b8ac58ce..f4d92b6ed 100644 --- a/pyramid/view.py +++ b/pyramid/view.py @@ -7,6 +7,7 @@ from pyramid.interfaces import IRoutesMapper from pyramid.interfaces import IView from pyramid.interfaces import IViewClassifier +from pyramid.compat import map_ from pyramid.httpexceptions import HTTPFound from pyramid.httpexceptions import default_exceptionresponse_view from pyramid.path import caller_package @@ -52,7 +53,7 @@ def render_view_to_response(context, request, name='', secure=True): disallowed. If ``secure`` is ``False``, no permission checking is done.""" - provides = [IViewClassifier] + map(providedBy, (request, context)) + provides = [IViewClassifier] + map_(providedBy, (request, context)) try: reg = request.registry except AttributeError: @@ -18,6 +18,9 @@ import sys from setuptools import setup, find_packages +PY3 = sys.version_info[0] == 3 +JYTHON = platform.system() != 'Java' + here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() @@ -28,9 +31,6 @@ except IOError: install_requires=[ 'Chameleon >= 1.2.3', 'Mako >= 0.3.6', # strict_undefined - 'Paste > 1.7', # temp version pin to prevent PyPi install failure :-( - 'PasteDeploy', - 'PasteScript >= 1.7.4', # "here" in logging fileConfig 'WebOb >= 1.0.2', # no "default_charset"; request.script_name doesnt error 'repoze.lru', 'setuptools', @@ -40,21 +40,29 @@ install_requires=[ 'translationstring', ] -if platform.system() == 'Java': - tests_require = install_requires + [ - 'WebTest', - 'virtualenv', - 'zope.component>=3.11.0', - ] -else: - tests_require= install_requires + [ +if not PY3: + install_requires.extend([ + 'Paste > 1.7', # temp version pin to prevent PyPi install failure :-( + 'PasteDeploy', + 'PasteScript >= 1.7.4', # "here" in logging fileConfig + ]) + +tests_require = install_requires + [ + 'WebTest', + 'virtualenv', + ] + +if not JYTHON: + tests_require.extend([ 'Sphinx', 'docutils', 'repoze.sphinx.autointerface', - 'WebTest', - 'virtualenv', + ]) + +if not PY3: + tests_require.extend([ 'zope.component>=3.11.0', - ] + ]) if sys.version_info[:2] < (2, 6): install_requires.append('simplejson') |
