From 8e606da0d09f7e99baa08b91fe97dba4b5b5d4b2 Mon Sep 17 00:00:00 2001 From: Chris McDonough Date: Fri, 23 Sep 2011 06:28:50 -0400 Subject: more rusty knife in the eye changes --- pyramid/authentication.py | 26 +++---- pyramid/compat.py | 10 +++ pyramid/config/tweens.py | 3 +- pyramid/config/util.py | 12 ++- pyramid/config/views.py | 6 +- pyramid/encode.py | 18 +++-- pyramid/exceptions.py | 5 +- pyramid/httpexceptions.py | 13 +++- pyramid/i18n.py | 2 +- pyramid/mako_templating.py | 14 ++-- pyramid/paster.py | 27 ++++--- pyramid/renderers.py | 3 +- pyramid/request.py | 14 ++-- pyramid/scaffolds/__init__.py | 4 +- pyramid/session.py | 3 +- pyramid/settings.py | 5 +- pyramid/static.py | 2 + pyramid/tests/test_authentication.py | 13 +--- pyramid/tests/test_chameleon_text.py | 2 +- pyramid/tests/test_chameleon_zpt.py | 7 +- pyramid/tests/test_config/test_init.py | 10 +-- pyramid/tests/test_config/test_views.py | 20 ++--- pyramid/tests/test_encode.py | 7 +- pyramid/tests/test_httpexceptions.py | 38 +++++----- pyramid/tests/test_integration.py | 126 ++++++++++++++++---------------- pyramid/tests/test_mako_templating.py | 9 ++- pyramid/tests/test_renderers.py | 27 +++---- pyramid/tests/test_request.py | 8 +- pyramid/tests/test_router.py | 8 +- pyramid/tests/test_settings.py | 2 +- pyramid/tests/test_static.py | 28 +++---- pyramid/tests/test_testing.py | 6 +- pyramid/tests/test_traversal.py | 17 +++-- pyramid/tests/test_url.py | 10 +-- pyramid/tests/test_util.py | 8 +- pyramid/traversal.py | 23 +++--- pyramid/url.py | 10 ++- pyramid/urldispatch.py | 9 ++- 38 files changed, 299 insertions(+), 256 deletions(-) diff --git a/pyramid/authentication.py b/pyramid/authentication.py index d75549d36..a84983447 100644 --- a/pyramid/authentication.py +++ b/pyramid/authentication.py @@ -1,15 +1,18 @@ from codecs import utf_8_decode from codecs import utf_8_encode from hashlib import md5 +import base64 import datetime import re import time as time_mod -import urllib from zope.interface import implementer from pyramid.compat import long from pyramid.compat import text_type +from pyramid.compat import url_unquote +from pyramid.compat import url_quote +from pyramid.compat import bytes_ from pyramid.interfaces import IAuthenticationPolicy from pyramid.interfaces import IDebugLogger @@ -386,10 +389,10 @@ class AuthTktAuthenticationPolicy(CallbackAuthenticationPolicy): return self.cookie.forget(request) def b64encode(v): - return v.encode('base64').strip().replace('\n', '') + return base64.b64encode(v).strip().replace('\n', '') def b64decode(v): - return v.decode('base64') + return base64.b64decode(v) # this class licensed under the MIT license (stolen from Paste) class AuthTicket(object): @@ -443,7 +446,7 @@ class AuthTicket(object): def cookie_value(self): v = '%s%08x%s!' % (self.digest(), int(self.time), - urllib.quote(self.userid)) + url_quote(self.userid)) if self.tokens: v += self.tokens + '!' v += self.user_data @@ -478,7 +481,7 @@ def parse_ticket(secret, ticket, ip): userid, data = ticket[40:].split('!', 1) except ValueError: raise BadTicket('userid is not followed by !') - userid = urllib.unquote(userid) + userid = url_unquote(userid) if '!' in data: tokens, user_data = data.split('!', 1) else: # pragma: no cover (never generated) @@ -499,10 +502,10 @@ def parse_ticket(secret, ticket, ip): # this function licensed under the MIT license (stolen from Paste) def calculate_digest(ip, timestamp, secret, userid, tokens, user_data): - secret = maybe_encode(secret) - userid = maybe_encode(userid) - tokens = maybe_encode(tokens) - user_data = maybe_encode(user_data) + secret = bytes_(secret, 'utf-8') + userid = bytes_(userid, 'utf-8') + tokens = bytes_(tokens, 'utf-8') + user_data = bytes_(user_data, 'utf-8') digest0 = md5( encode_ip_timestamp(ip, timestamp) + secret + userid + '\0' + tokens + '\0' + user_data).hexdigest() @@ -520,11 +523,6 @@ def encode_ip_timestamp(ip, timestamp): ts_chars = ''.join(map(chr, ts)) return ip_chars + ts_chars -def maybe_encode(s, encoding='utf8'): - if isinstance(s, unicode): - s = s.encode(encoding) - return s - EXPIRE = object() class AuthTktCookieHelper(object): diff --git a/pyramid/compat.py b/pyramid/compat.py index 64648911e..a6f7f025e 100644 --- a/pyramid/compat.py +++ b/pyramid/compat.py @@ -169,11 +169,15 @@ if PY3: # pragma: no cover return d.items() def itervalues_(d): return d.values() + def iterkeys_(d): + return d.keys() else: def iteritems_(d): return d.iteritems() def itervalues_(d): return d.itervalues() + def iterkeys_(d): + return d.iterkeys() if PY3: @@ -200,3 +204,9 @@ if PY3: # pragma: no cover im_func = '__func__' else: im_func = 'im_func' + +try: + import configparser +except ImportError: + import ConfigParser + configparser = ConfigParser diff --git a/pyramid/config/tweens.py b/pyramid/config/tweens.py index c7d50248f..3c7ee384f 100644 --- a/pyramid/config/tweens.py +++ b/pyramid/config/tweens.py @@ -4,6 +4,7 @@ from pyramid.interfaces import ITweens from pyramid.compat import string_types from pyramid.compat import is_nonstr_iter +from pyramid.compat import string_types from pyramid.exceptions import ConfigurationError from pyramid.tweens import excview_tween_factory from pyramid.tweens import MAIN, INGRESS, EXCVIEW @@ -98,7 +99,7 @@ class TweensConfiguratorMixin(object): @action_method def _add_tween(self, tween_factory, under=None, over=None, explicit=False): - if not isinstance(tween_factory, basestring): + if not isinstance(tween_factory, string_types): raise ConfigurationError( 'The "tween_factory" argument to add_tween must be a ' 'dotted name to a globally importable object, not %r' % diff --git a/pyramid/config/util.py b/pyramid/config/util.py index 53a390c7e..7980a78e3 100644 --- a/pyramid/config/util.py +++ b/pyramid/config/util.py @@ -1,6 +1,8 @@ import re import traceback +from pyramid.compat import string_types +from pyramid.compat import bytes_ from pyramid.exceptions import ConfigurationError from pyramid.traversal import find_interface from pyramid.traversal import traversal_path @@ -177,7 +179,7 @@ def make_predicates(xhr=None, request_method=None, path_info=None, containment_predicate.__text__ = "containment = %s" % containment weights.append(1 << 7) predicates.append(containment_predicate) - h.update('containment:%r' % hash(containment)) + h.update('containment:%r' % hash_(containment)) if request_type is not None: def request_type_predicate(context, request): @@ -186,10 +188,10 @@ def make_predicates(xhr=None, request_method=None, path_info=None, request_type_predicate.__text__ = text % request_type weights.append(1 << 8) predicates.append(request_type_predicate) - h.update('request_type:%r' % hash(request_type)) + h.update('request_type:%r' % hash_(request_type)) if match_param is not None: - if isinstance(match_param, basestring): + if isinstance(match_param, string_types): match_param, match_param_val = match_param.split('=', 1) match_param = {match_param: match_param_val} text = "match_param %s" % match_param @@ -222,7 +224,7 @@ def make_predicates(xhr=None, request_method=None, path_info=None, # functions for custom predicates, so that the hash output # of predicate instances which are "logically the same" # may compare equal. - h.update('custom%s:%r' % (num, hash(predicate))) + h.update('custom%s:%r' % (num, hash_(predicate))) weights.append(1 << 10) if traverse is not None: @@ -259,3 +261,5 @@ def as_sorted_tuple(val): val = tuple(sorted(val)) return val +def hash_(v): + return bytes_(hash(v)) diff --git a/pyramid/config/views.py b/pyramid/config/views.py index e186d2430..326aa801e 100644 --- a/pyramid/config/views.py +++ b/pyramid/config/views.py @@ -1153,7 +1153,7 @@ class ViewsConfiguratorMixin(object): mapper=None, http_cache=None): view = self.maybe_dotted(view) mapper = self.maybe_dotted(mapper) - if isinstance(renderer, basestring): + if isinstance(renderer, string_types): renderer = renderers.RendererHelper( name=renderer, package=self.package, registry = self.registry) @@ -1211,7 +1211,7 @@ class ViewsConfiguratorMixin(object): The ``wrapper`` argument should be the name of another view which will wrap this view when rendered (see the ``add_view`` method's ``wrapper`` argument for a description).""" - if isinstance(renderer, basestring): + if isinstance(renderer, string_types): renderer = renderers.RendererHelper( name=renderer, package=self.package, registry = self.registry) @@ -1253,7 +1253,7 @@ class ViewsConfiguratorMixin(object): which will wrap this view when rendered (see the ``add_view`` method's ``wrapper`` argument for a description). """ - if isinstance(renderer, basestring): + if isinstance(renderer, string_types): renderer = renderers.RendererHelper( name=renderer, package=self.package, registry=self.registry) diff --git a/pyramid/encode.py b/pyramid/encode.py index 826e6a662..ee574a0eb 100644 --- a/pyramid/encode.py +++ b/pyramid/encode.py @@ -1,5 +1,9 @@ import re +from pyramid.compat import text_type +from pyramid.compat import native_ +from pyramid.compat import is_nonstr_iter + always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' '0123456789' '_.-') @@ -88,19 +92,19 @@ def urlencode(query, doseq=True): prefix = '' for (k, v) in query: - if k.__class__ is unicode: - k = k.encode('utf-8') + if k.__class__ is text_type: + k = native_(k, 'utf-8') k = quote_plus(str(k)) - if hasattr(v, '__iter__'): + if is_nonstr_iter(v): for x in v: - if x.__class__ is unicode: - x = x.encode('utf-8') + if x.__class__ is text_type: + x = native_(x, 'utf-8') x = quote_plus(str(x)) result += '%s%s=%s' % (prefix, k, x) prefix = '&' else: - if v.__class__ is unicode: - v = v.encode('utf-8') + if v.__class__ is text_type: + v = native_(v, 'utf-8') v = quote_plus(str(v)) result += '%s%s=%s' % (prefix, k, v) prefix = '&' diff --git a/pyramid/exceptions.py b/pyramid/exceptions.py index cd234adca..ff598fe2d 100644 --- a/pyramid/exceptions.py +++ b/pyramid/exceptions.py @@ -39,12 +39,11 @@ class ConfigurationConflictError(ConfigurationError): def __str__(self): r = ["Conflicting configuration actions"] - items = self._conflicts.items() - items.sort() + items = sorted(self._conflicts.items()) for discriminator, infos in items: r.append(" For: %s" % (discriminator, )) for info in infos: - for line in unicode(info).rstrip().split(CR): + for line in str(info).rstrip().split(CR): r.append(" "+line) return CR.join(r) diff --git a/pyramid/httpexceptions.py b/pyramid/httpexceptions.py index 46bc1890c..4dbca7021 100644 --- a/pyramid/httpexceptions.py +++ b/pyramid/httpexceptions.py @@ -131,15 +131,20 @@ from webob import html_escape as _html_escape from pyramid.interfaces import IExceptionResponse from pyramid.response import Response from pyramid.compat import class_types +from pyramid.compat import text_type +from pyramid.compat import binary_type +from pyramid.compat import text_ def _no_escape(value): if value is None: return '' - if not isinstance(value, basestring): + if not isinstance(value, text_type): if hasattr(value, '__unicode__'): - value = unicode(value) + value = value.__unicode__() + if isinstance(value, binary_type): + value = text_(value, 'utf-8') else: - value = str(value) + value = text_type(value) return value class HTTPException(Exception): # bw compat @@ -259,7 +264,7 @@ ${body}''') args[k.lower()] = escape(v) body = body_tmpl.substitute(args) page = page_template.substitute(status=self.status, body=body) - if isinstance(page, unicode): + if isinstance(page, text_type): page = page.encode(self.charset) self.app_iter = [page] self.body = page diff --git a/pyramid/i18n.py b/pyramid/i18n.py index f16aeb378..040e581b5 100644 --- a/pyramid/i18n.py +++ b/pyramid/i18n.py @@ -231,7 +231,7 @@ class Translations(gettext.GNUTranslations, object): # this domain; see https://github.com/Pylons/pyramid/issues/235 self.plural = lambda n: int(n != 1) gettext.GNUTranslations.__init__(self, fp=fileobj) - self.files = filter(None, [getattr(fileobj, 'name', None)]) + self.files = list(filter(None, [getattr(fileobj, 'name', None)])) self.domain = domain self._domains = {} diff --git a/pyramid/mako_templating.py b/pyramid/mako_templating.py index a12e72b86..29be339f2 100644 --- a/pyramid/mako_templating.py +++ b/pyramid/mako_templating.py @@ -7,6 +7,7 @@ from zope.interface import Interface from pyramid.asset import resolve_asset_spec from pyramid.asset import abspath_from_asset_spec +from pyramid.compat import is_nonstr_iter from pyramid.exceptions import ConfigurationError from pyramid.interfaces import ITemplateRenderer from pyramid.settings import asbool @@ -74,8 +75,8 @@ def renderer_factory(info): if directories is None: raise ConfigurationError( 'Mako template used without a ``mako.directories`` setting') - if not hasattr(directories, '__iter__'): - directories = filter(None, directories.splitlines()) + if not is_nonstr_iter(directories): + directories = list(filter(None, directories.splitlines())) directories = [ abspath_from_asset_spec(d) for d in directories ] if module_directory is not None: module_directory = abspath_from_asset_spec(module_directory) @@ -83,11 +84,12 @@ def renderer_factory(info): dotted = DottedNameResolver(info.package) error_handler = dotted.maybe_resolve(error_handler) if default_filters is not None: - if not hasattr(default_filters, '__iter__'): - default_filters = filter(None, default_filters.splitlines()) + if not is_nonstr_iter(default_filters): + default_filters = list(filter( + None, default_filters.splitlines())) if imports is not None: - if not hasattr(imports, '__iter__'): - imports = filter(None, imports.splitlines()) + if not is_nonstr_iter(imports): + imports = list(filter(None, imports.splitlines())) strict_undefined = asbool(strict_undefined) if preprocessor is not None: dotted = DottedNameResolver(info.package) diff --git a/pyramid/paster.py b/pyramid/paster.py index 4fc1812ca..0085c279e 100644 --- a/pyramid/paster.py +++ b/pyramid/paster.py @@ -1,19 +1,28 @@ -import ConfigParser import os import sys from code import interact import zope.deprecation -from paste.deploy import loadapp -from paste.script.command import Command +try: + from paste.deploy import loadapp +except ImportError: # pragma: no cover + def loadapp(*arg, **kw): + raise NotImplementedError + +try: + from paste.script.command import Command +except ImportError: + class Command: + pass from pyramid.interfaces import IMultiView from pyramid.interfaces import ITweens +from pyramid.compat import print_ +from pyramid.compat import configparser from pyramid.scripting import prepare from pyramid.util import DottedNameResolver - from pyramid.tweens import MAIN from pyramid.tweens import INGRESS @@ -136,7 +145,7 @@ class PShellCommand(PCommand): "option will override the 'setup' key in the " "[pshell] ini section.")) - ConfigParser = ConfigParser.ConfigParser # testing + ConfigParser = configparser.ConfigParser # testing loaded_objects = {} object_help = {} @@ -147,7 +156,7 @@ class PShellCommand(PCommand): config.read(filename) try: items = config.items('pshell') - except ConfigParser.NoSectionError: + except configparser.NoSectionError: return resolver = DottedNameResolver(None) @@ -299,7 +308,7 @@ class PRoutesCommand(PCommand): return config.get_routes_mapper() def out(self, msg): # pragma: no cover - print msg + print_(msg) def command(self): from pyramid.interfaces import IRouteRequest @@ -358,7 +367,7 @@ class PViewsCommand(PCommand): parser = Command.standard_parser(simulate=True) def out(self, msg): # pragma: no cover - print msg + print_(msg) def _find_multi_routes(self, mapper, request): infos = [] @@ -604,7 +613,7 @@ class PTweensCommand(PCommand): return config.registry.queryUtility(ITweens) def out(self, msg): # pragma: no cover - print msg + print_(msg) def show_chain(self, chain): fmt = '%-10s %-65s' diff --git a/pyramid/renderers.py b/pyramid/renderers.py index 04208fcdc..2d420f67a 100644 --- a/pyramid/renderers.py +++ b/pyramid/renderers.py @@ -16,6 +16,7 @@ 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 text_type from pyramid.compat import native_ from pyramid.decorator import reify from pyramid.events import BeforeRender @@ -439,7 +440,7 @@ class RendererHelper(object): if result is None: result = '' - if isinstance(result, unicode): + if isinstance(result, text_type): response.unicode_body = result else: response.body = result diff --git a/pyramid/request.py b/pyramid/request.py index 8188eecf1..fda233388 100644 --- a/pyramid/request.py +++ b/pyramid/request.py @@ -11,6 +11,8 @@ from pyramid.interfaces import ISessionFactory from pyramid.interfaces import IResponseFactory from pyramid.compat import json +from pyramid.compat import native_ +from pyramid.compat import iterkeys_, itervalues_, iteritems_ from pyramid.exceptions import ConfigurationError from pyramid.decorator import reify from pyramid.response import Response @@ -64,15 +66,15 @@ class DeprecatedRequestMethodsMixin(object): @deprecate(dictlike) def iteritems(self): - return self.environ.iteritems() + return iteritems_(self.environ) @deprecate(dictlike) def iterkeys(self): - return self.environ.iterkeys() + return iterkeys_(self.environ) @deprecate(dictlike) def itervalues(self): - return self.environ.itervalues() + return itervalues_(self.environ) @deprecate(dictlike) def keys(self): @@ -399,12 +401,12 @@ def call_app_with_subpath_as_path_info(request, app): environ = request.environ script_name = environ.get('SCRIPT_NAME', '') path_info = environ.get('PATH_INFO', '/') - subpath = list(getattr(request, 'subpath', ())) + subpath = getattr(request, 'subpath', ()) new_script_name = '' # compute new_path_info - new_path_info = '/' + '/'.join([x.encode('utf-8') for x in subpath]) + new_path_info = '/' + '/'.join([native_(x, 'utf-8') for x in subpath]) if new_path_info != '/': # don't want a sole double-slash if path_info != '/': # if orig path_info is '/', we're already done @@ -422,7 +424,7 @@ def call_app_with_subpath_as_path_info(request, app): break el = workback.pop() if el: - tmp.insert(0, el.decode('utf-8')) + tmp.insert(0, native_(el, 'utf-8')) # strip all trailing slashes from workback to avoid appending undue slashes # to end of script_name diff --git a/pyramid/scaffolds/__init__.py b/pyramid/scaffolds/__init__.py index ef93a53c7..e00a9f83b 100644 --- a/pyramid/scaffolds/__init__.py +++ b/pyramid/scaffolds/__init__.py @@ -3,13 +3,13 @@ import os try: from paste.script.templates import Template except ImportError: - class Template(object): + class Template: pass try: from paste.util.template import paste_script_template_renderer except ImportError: - def paste_script_template_renderer(self): + def paste_script_template_renderer(): pass class PyramidTemplate(Template): diff --git a/pyramid/session.py b/pyramid/session.py index 3a179e2fd..cd685e51c 100644 --- a/pyramid/session.py +++ b/pyramid/session.py @@ -9,6 +9,7 @@ from zope.interface import implementer from pyramid.compat import pickle from pyramid.compat import PY3 +from pyramid.compat import text_ from pyramid.interfaces import ISession def manage_accessed(wrapped): @@ -181,7 +182,7 @@ def UnencryptedCookieSessionFactoryConfig( # CSRF API methods @manage_accessed def new_csrf_token(self): - token = os.urandom(20).encode('hex') + token = text_(binascii.hexlify(os.urandom(20))) self['_csrft_'] = token return token diff --git a/pyramid/settings.py b/pyramid/settings.py index 3c376c4a9..de91042eb 100644 --- a/pyramid/settings.py +++ b/pyramid/settings.py @@ -1,6 +1,7 @@ from zope.deprecation import deprecated from pyramid.threadlocal import get_current_registry +from pyramid.compat import string_types def get_settings(): """ @@ -39,9 +40,9 @@ def asbool(s): return s.lower() in ('t', 'true', 'y', 'yes', 'on', '1') def aslist_cronly(value): - if isinstance(value, basestring): + if isinstance(value, string_types): value = filter(None, [x.strip() for x in value.splitlines()]) - return value + return list(value) def aslist(value): values = aslist_cronly(value) diff --git a/pyramid/static.py b/pyramid/static.py index 0ab4a0c79..edb20b54f 100644 --- a/pyramid/static.py +++ b/pyramid/static.py @@ -75,6 +75,8 @@ class _FileIter(object): raise StopIteration return data + __next__ = next # py3 + def close(self): self.file.close() diff --git a/pyramid/tests/test_authentication.py b/pyramid/tests/test_authentication.py index 37c179caf..7f64af705 100644 --- a/pyramid/tests/test_authentication.py +++ b/pyramid/tests/test_authentication.py @@ -586,7 +586,7 @@ class TestAuthTktCookieHelper(unittest.TestCase): result = helper.identify(request) self.assertEqual(len(result), 4) self.assertEqual(result['tokens'], ()) - self.assertEqual(result['userid'], unicode('\xc3\xa9ncoded', 'utf-8')) + self.assertEqual(result['userid'], text_('\xc3\xa9ncoded', 'utf-8')) self.assertEqual(result['userdata'], 'userid_type:b64unicode') self.assertEqual(result['timestamp'], 0) environ = request.environ @@ -856,7 +856,7 @@ class TestAuthTktCookieHelper(unittest.TestCase): def test_remember_unicode_userid(self): helper = self._makeOne('secret') request = self._makeRequest() - userid = unicode('\xc2\xa9', 'utf-8') + userid = text_('\xc2\xa9', 'utf-8') result = helper.remember(request, userid) values = self._parseHeaders(result) self.assertEqual(len(result), 3) @@ -1087,15 +1087,6 @@ class TestSessionAuthenticationPolicy(unittest.TestCase): self.assertEqual(request.session.get('userid'), None) self.assertEqual(result, []) -class Test_maybe_encode(unittest.TestCase): - def _callFUT(self, s, encoding='utf-8'): - from pyramid.authentication import maybe_encode - return maybe_encode(s, encoding) - - def test_unicode(self): - result = self._callFUT(text_('abc')) - self.assertEqual(result, text_('abc')) - class DummyContext: pass diff --git a/pyramid/tests/test_chameleon_text.py b/pyramid/tests/test_chameleon_text.py index 213f25f51..cae52c2f4 100644 --- a/pyramid/tests/test_chameleon_text.py +++ b/pyramid/tests/test_chameleon_text.py @@ -149,7 +149,7 @@ class RenderTemplateToResponseTests(Base, unittest.TestCase): result = self._callFUT(minimal) from webob import Response self.assertTrue(isinstance(result, Response)) - self.assertEqual(result.app_iter, ['Hello.\n']) + self.assertEqual(result.app_iter, [b'Hello.\n']) self.assertEqual(result.status, '200 OK') self.assertEqual(len(result.headerlist), 2) diff --git a/pyramid/tests/test_chameleon_zpt.py b/pyramid/tests/test_chameleon_zpt.py index 84eaedcf4..6a38bd329 100644 --- a/pyramid/tests/test_chameleon_zpt.py +++ b/pyramid/tests/test_chameleon_zpt.py @@ -2,6 +2,7 @@ import unittest from pyramid.testing import skip_on from pyramid import testing +from pyramid.compat import text_type class Base(object): def setUp(self): @@ -51,7 +52,7 @@ class ZPTTemplateRendererTests(Base, unittest.TestCase): lookup = DummyLookup() instance = self._makeOne(minimal, lookup) result = instance({}, {}) - self.assertTrue(isinstance(result, unicode)) + self.assertTrue(isinstance(result, text_type)) self.assertEqual(result.rstrip('\n'), '
\n
') @@ -126,7 +127,7 @@ class ZPTTemplateRendererTests(Base, unittest.TestCase): lookup = DummyLookup() instance = self._makeOne(minimal, lookup) result = instance.implementation()() - self.assertTrue(isinstance(result, unicode)) + self.assertTrue(isinstance(result, text_type)) self.assertEqual(result.rstrip('\n'), '
\n
') @@ -140,7 +141,7 @@ class RenderTemplateTests(Base, unittest.TestCase): def test_it(self): minimal = self._getTemplatePath('minimal.pt') result = self._callFUT(minimal) - self.assertTrue(isinstance(result, unicode)) + self.assertTrue(isinstance(result, text_type)) self.assertEqual(result.rstrip('\n'), '
\n
') diff --git a/pyramid/tests/test_config/test_init.py b/pyramid/tests/test_config/test_init.py index 6b5ea06b3..0decd28ad 100644 --- a/pyramid/tests/test_config/test_init.py +++ b/pyramid/tests/test_config/test_init.py @@ -915,7 +915,7 @@ pyramid.tests.test_config.dummy_include2""", c.scan(selfscan) try: c.commit() - except ConfigurationConflictError, why: + except ConfigurationConflictError as why: def scanconflicts(e): conflicts = e._conflicts.values() for conflict in conflicts: @@ -985,7 +985,7 @@ pyramid.tests.test_config.dummy_include2""", config.include(includeme2) try: config.commit() - except ConfigurationConflictError, why: + except ConfigurationConflictError as why: c1, c2 = _conflictFunctions(why) self.assertEqual(c1, 'includeme1') self.assertEqual(c2, 'includeme2') @@ -1029,7 +1029,7 @@ pyramid.tests.test_config.dummy_include2""", config.set_notfound_view(view2) try: config.commit() - except ConfigurationConflictError, why: + except ConfigurationConflictError as why: c1, c2 = _conflictFunctions(why) self.assertEqual(c1, 'test_conflict_set_notfound_view') self.assertEqual(c2, 'test_conflict_set_notfound_view') @@ -1044,7 +1044,7 @@ pyramid.tests.test_config.dummy_include2""", config.set_forbidden_view(view2) try: config.commit() - except ConfigurationConflictError, why: + except ConfigurationConflictError as why: c1, c2 = _conflictFunctions(why) self.assertEqual(c1, 'test_conflict_set_forbidden_view') self.assertEqual(c2, 'test_conflict_set_forbidden_view') @@ -1284,7 +1284,7 @@ class TestConfiguratorDeprecatedFeatures(unittest.TestCase): config.add_route('a', '/a', view=view2) try: config.commit() - except ConfigurationConflictError, why: + except ConfigurationConflictError as why: c1, c2, c3, c4, c5, c6 = _conflictFunctions(why) self.assertEqual(c1, 'test_conflict_route_with_view') self.assertEqual(c2, 'test_conflict_route_with_view') diff --git a/pyramid/tests/test_config/test_views.py b/pyramid/tests/test_config/test_views.py index 0ea9d6cd0..eceea94d5 100644 --- a/pyramid/tests/test_config/test_views.py +++ b/pyramid/tests/test_config/test_views.py @@ -103,7 +103,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): self._registerRenderer(config, name='dummy') config.add_view(renderer='dummy') view = self._getViewCallable(config) - self.assertTrue('Hello!' in view(None, None).body) + self.assertTrue(b'Hello!' in view(None, None).body) def test_add_view_wrapped_view_is_decorated(self): def view(request): # request-only wrapper @@ -891,7 +891,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): wrapper = self._getViewCallable(config) request = self._makeRequest(config) result = wrapper(None, request) - self.assertEqual(result.body, 'Hello!') + self.assertEqual(result.body, b'Hello!') settings = config.registry.queryUtility(ISettings) result = renderer.info self.assertEqual(result.registry, config.registry) @@ -919,7 +919,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): wrapper = self._getViewCallable(config) request = self._makeRequest(config) result = wrapper(None, request) - self.assertEqual(result.body, 'moo') + self.assertEqual(result.body, b'moo') def test_add_view_with_template_renderer_no_callable(self): from pyramid.tests import test_config @@ -931,7 +931,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): wrapper = self._getViewCallable(config) request = self._makeRequest(config) result = wrapper(None, request) - self.assertEqual(result.body, 'Hello!') + self.assertEqual(result.body, b'Hello!') settings = config.registry.queryUtility(ISettings) result = renderer.info self.assertEqual(result.registry, config.registry) @@ -1392,7 +1392,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): return 'OK' result = config.derive_view(view) self.assertFalse(result is view) - self.assertEqual(result(None, None).body, 'moo') + self.assertEqual(result(None, None).body, b'moo') def test_derive_view_with_default_renderer_with_explicit_renderer(self): class moo(object): pass @@ -1410,7 +1410,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): result = config.derive_view(view, renderer='foo') self.assertFalse(result is view) request = self._makeRequest(config) - self.assertEqual(result(None, request).body, 'foo') + self.assertEqual(result(None, request).body, b'foo') def test_add_static_view_here_no_utility_registered(self): from pyramid.renderers import null_renderer @@ -1545,7 +1545,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): result = view(None, request) finally: config.end() - self.assertTrue('div' in result.body) + self.assertTrue(b'div' in result.body) @testing.skip_on('java') def test_set_forbidden_view_with_renderer(self): @@ -1566,7 +1566,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): result = view(None, request) finally: config.end() - self.assertTrue('div' in result.body) + self.assertTrue(b'div' in result.body) def test_set_view_mapper(self): from pyramid.interfaces import IViewMapperFactory @@ -2110,7 +2110,7 @@ class TestViewDeriver(unittest.TestCase): request = self._makeRequest() request.override_renderer = 'moo' context = testing.DummyResource() - self.assertEqual(result(context, request).body, 'moo') + self.assertEqual(result(context, request).body, b'moo') def test_requestonly_function_with_renderer_request_has_view(self): response = DummyResponse() @@ -2666,7 +2666,7 @@ class TestViewDeriver(unittest.TestCase): self.assertEqual(inner_view.__doc__, result.__doc__) request = self._makeRequest() response = result(None, request) - self.assertEqual(response.body, 'outer OK') + self.assertEqual(response.body, b'outer OK') def test_with_wrapper_viewname_notfound(self): from pyramid.response import Response diff --git a/pyramid/tests/test_encode.py b/pyramid/tests/test_encode.py index 741a24393..738efeea2 100644 --- a/pyramid/tests/test_encode.py +++ b/pyramid/tests/test_encode.py @@ -1,4 +1,5 @@ import unittest +from pyramid.compat import text_ class UrlEncodeTests(unittest.TestCase): def _callFUT(self, query, doseq=False): @@ -10,17 +11,17 @@ class UrlEncodeTests(unittest.TestCase): self.assertEqual(result, 'a=1&b=2') def test_unicode_key(self): - la = unicode('LaPe\xc3\xb1a', 'utf-8') + la = text_('LaPe\xc3\xb1a', 'utf-8') result = self._callFUT([(la, 1), ('b',2)]) self.assertEqual(result, 'LaPe%C3%B1a=1&b=2') def test_unicode_val_single(self): - la = unicode('LaPe\xc3\xb1a', 'utf-8') + la = text_('LaPe\xc3\xb1a', 'utf-8') result = self._callFUT([('a', la), ('b',2)]) self.assertEqual(result, 'a=LaPe%C3%B1a&b=2') def test_unicode_val_multiple(self): - la = [unicode('LaPe\xc3\xb1a', 'utf-8')] * 2 + la = [text_('LaPe\xc3\xb1a', 'utf-8')] * 2 result = self._callFUT([('a', la), ('b',2)], doseq=True) self.assertEqual(result, 'a=LaPe%C3%B1a&a=LaPe%C3%B1a&b=2') diff --git a/pyramid/tests/test_httpexceptions.py b/pyramid/tests/test_httpexceptions.py index 6a3ea7367..60c97b5b4 100644 --- a/pyramid/tests/test_httpexceptions.py +++ b/pyramid/tests/test_httpexceptions.py @@ -125,7 +125,7 @@ class TestWSGIHTTPException(unittest.TestCase): self.assertEqual(exc.content_length, None) def test_ctor_with_body_doesnt_set_default_app_iter(self): - exc = self._makeOne(body='123') + exc = self._makeOne(body=b'123') self.assertEqual(exc.app_iter, [b'123']) def test_ctor_with_unicode_body_doesnt_set_default_app_iter(self): @@ -143,10 +143,10 @@ class TestWSGIHTTPException(unittest.TestCase): environ['HTTP_ACCEPT'] = 'text/html' start_response = DummyStartResponse() body = list(exc(environ, start_response))[0] - self.assertTrue(body.startswith('' in body) + self.assertTrue(b'' in body) def test__default_app_iter_with_comment_html2(self): cls = self._getTargetSubclass() @@ -233,7 +233,7 @@ class TestWSGIHTTPException(unittest.TestCase): environ['HTTP_ACCEPT'] = 'text/html' start_response = DummyStartResponse() body = list(exc(environ, start_response))[0] - self.assertTrue('' in body) + self.assertTrue(b'' in body) def test_custom_body_template(self): cls = self._getTargetSubclass() @@ -241,7 +241,7 @@ class TestWSGIHTTPException(unittest.TestCase): environ = _makeEnviron() start_response = DummyStartResponse() body = list(exc(environ, start_response))[0] - self.assertEqual(body, '200 OK\n\nGET') + self.assertEqual(body, b'200 OK\n\nGET') def test_custom_body_template_with_custom_variable_doesnt_choke(self): cls = self._getTargetSubclass() @@ -252,16 +252,16 @@ class TestWSGIHTTPException(unittest.TestCase): environ['gardentheory.user'] = Choke() start_response = DummyStartResponse() body = list(exc(environ, start_response))[0] - self.assertEqual(body, '200 OK\n\nGET') + self.assertEqual(body, b'200 OK\n\nGET') def test_body_template_unicode(self): cls = self._getTargetSubclass() - la = unicode('/La Pe\xc3\xb1a', 'utf-8') + la = text_('/La Pe\xc3\xb1a', 'utf-8') environ = _makeEnviron(unicodeval=la) exc = cls(body_template='${unicodeval}') start_response = DummyStartResponse() body = list(exc(environ, start_response))[0] - self.assertEqual(body, '200 OK\n\n/La Pe\xc3\xb1a') + self.assertEqual(body, b'200 OK\n\n/La Pe\xc3\xb1a') class TestRenderAllExceptionsWithoutArguments(unittest.TestCase): def _doit(self, content_type): @@ -310,8 +310,8 @@ class Test_HTTPMove(unittest.TestCase): start_response = DummyStartResponse() app_iter = exc(environ, start_response) self.assertEqual(app_iter[0], - ('None None\n\nThe resource has been moved to foo; ' - 'you should be redirected automatically.\n\n')) + (b'None None\n\nThe resource has been moved to foo; ' + b'you should be redirected automatically.\n\n')) class TestHTTPForbidden(unittest.TestCase): def _makeOne(self, *arg, **kw): @@ -337,8 +337,8 @@ class TestHTTPMethodNotAllowed(unittest.TestCase): start_response = DummyStartResponse() app_iter = exc(environ, start_response) self.assertEqual(app_iter[0], - ('405 Method Not Allowed\n\nThe method GET is not ' - 'allowed for this resource. \n\n\n')) + (b'405 Method Not Allowed\n\nThe method GET is not ' + b'allowed for this resource. \n\n\n')) class DummyRequest(object): diff --git a/pyramid/tests/test_integration.py b/pyramid/tests/test_integration.py index 40f1adf14..9db03c28b 100644 --- a/pyramid/tests/test_integration.py +++ b/pyramid/tests/test_integration.py @@ -66,7 +66,7 @@ class TestStaticAppBase(IntegrationBase): def _assertBody(self, body, filename): self.assertEqual( body.replace('\r', ''), - open(filename, 'r').read() + open(filename, 'rb').read() ) def test_basic(self): @@ -100,7 +100,7 @@ class TestStaticAppBase(IntegrationBase): self.testapp.extra_environ = { 'HTTP_IF_MODIFIED_SINCE':httpdate(pow(2, 32)-1)} res = self.testapp.get('/minimal.pt', status=304) - self.assertEqual(res.body, '') + self.assertEqual(res.body, b'') def test_file_in_subdir(self): fn = os.path.join(here, 'fixtures/static/index.html') @@ -130,12 +130,12 @@ class TestStaticAppBase(IntegrationBase): def test_range_inclusive(self): self.testapp.extra_environ = {'HTTP_RANGE':'bytes=1-2'} res = self.testapp.get('/static/index.html', status=206) - self.assertEqual(res.body, 'ht') + self.assertEqual(res.body, b'ht') def test_range_tilend(self): self.testapp.extra_environ = {'HTTP_RANGE':'bytes=-5'} res = self.testapp.get('/static/index.html', status=206) - self.assertEqual(res.body, 'tml>\n') + self.assertEqual(res.body, b'tml>\n') def test_range_notbytes(self): self.testapp.extra_environ = {'HTTP_RANGE':'kHz=-5'} @@ -176,7 +176,7 @@ class TestStaticAppNoSubpath(unittest.TestCase): staticapp = static_view(os.path.join(here, 'fixtures'), use_subpath=False) def _makeRequest(self, extra): from pyramid.request import Request - from StringIO import StringIO + from io import BytesIO kw = {'PATH_INFO':'', 'SCRIPT_NAME':'', 'SERVER_NAME':'localhost', @@ -184,7 +184,7 @@ class TestStaticAppNoSubpath(unittest.TestCase): 'REQUEST_METHOD':'GET', 'wsgi.version':(1,0), 'wsgi.url_scheme':'http', - 'wsgi.input':StringIO()} + 'wsgi.input':BytesIO()} kw.update(extra) request = Request(kw) return request @@ -192,7 +192,7 @@ class TestStaticAppNoSubpath(unittest.TestCase): def _assertBody(self, body, filename): self.assertEqual( body.replace('\r', ''), - open(filename, 'r').read() + open(filename, 'rb').read() ) def test_basic(self): @@ -207,7 +207,7 @@ class TestStaticAppWithRoutePrefix(IntegrationBase, unittest.TestCase): def _assertBody(self, body, filename): self.assertEqual( body.replace('\r', ''), - open(filename, 'r').read() + open(filename, 'rb').read() ) def test_includelevel1(self): @@ -225,18 +225,18 @@ class TestFixtureApp(IntegrationBase, unittest.TestCase): package = 'pyramid.tests.pkgs.fixtureapp' def test_another(self): res = self.testapp.get('/another.html', status=200) - self.assertEqual(res.body, 'fixture') + self.assertEqual(res.body, b'fixture') def test_root(self): res = self.testapp.get('/', status=200) - self.assertEqual(res.body, 'fixture') + self.assertEqual(res.body, b'fixture') def test_dummyskin(self): self.testapp.get('/dummyskin.html', status=404) def test_error(self): res = self.testapp.get('/error.html', status=200) - self.assertEqual(res.body, 'supressed') + self.assertEqual(res.body, b'supressed') def test_protected(self): self.testapp.get('/protected.html', status=403) @@ -247,8 +247,8 @@ class TestStaticPermApp(IntegrationBase, unittest.TestCase): def test_allowed(self): result = self.testapp.get('/allowed/index.html', status=200) self.assertEqual( - result.body.replace('\r', ''), - open(os.path.join(here, 'fixtures/static/index.html'), 'r').read()) + result.body.replace(b'\r', b''), + open(os.path.join(here, 'fixtures/static/index.html'), 'rb').read()) def test_denied_via_acl_global_root_factory(self): self.testapp.extra_environ = {'REMOTE_USER':'bob'} @@ -258,8 +258,8 @@ class TestStaticPermApp(IntegrationBase, unittest.TestCase): self.testapp.extra_environ = {'REMOTE_USER':'fred'} result = self.testapp.get('/protected/index.html', status=200) self.assertEqual( - result.body.replace('\r', ''), - open(os.path.join(here, 'fixtures/static/index.html'), 'r').read()) + result.body.replace(b'\r', b''), + open(os.path.join(here, 'fixtures/static/index.html'), 'rb').read()) def test_denied_via_acl_local_root_factory(self): self.testapp.extra_environ = {'REMOTE_USER':'fred'} @@ -269,8 +269,8 @@ class TestStaticPermApp(IntegrationBase, unittest.TestCase): self.testapp.extra_environ = {'REMOTE_USER':'bob'} result = self.testapp.get('/factory_protected/index.html', status=200) self.assertEqual( - result.body.replace('\r', ''), - open(os.path.join(here, 'fixtures/static/index.html'), 'r').read()) + result.body.replace(b'\r', b''), + open(os.path.join(here, 'fixtures/static/index.html'), 'rb').read()) class TestCCBug(IntegrationBase, unittest.TestCase): # "unordered" as reported in IRC by author of @@ -278,11 +278,11 @@ class TestCCBug(IntegrationBase, unittest.TestCase): package = 'pyramid.tests.pkgs.ccbugapp' def test_rdf(self): res = self.testapp.get('/licenses/1/v1/rdf', status=200) - self.assertEqual(res.body, 'rdf') + self.assertEqual(res.body, b'rdf') def test_juri(self): res = self.testapp.get('/licenses/1/v1/juri', status=200) - self.assertEqual(res.body, 'juri') + self.assertEqual(res.body, b'juri') class TestHybridApp(IntegrationBase, unittest.TestCase): # make sure views registered for a route "win" over views registered @@ -291,19 +291,19 @@ class TestHybridApp(IntegrationBase, unittest.TestCase): package = 'pyramid.tests.pkgs.hybridapp' def test_root(self): res = self.testapp.get('/', status=200) - self.assertEqual(res.body, 'global') + self.assertEqual(res.body, b'global') def test_abc(self): res = self.testapp.get('/abc', status=200) - self.assertEqual(res.body, 'route') + self.assertEqual(res.body, b'route') def test_def(self): res = self.testapp.get('/def', status=200) - self.assertEqual(res.body, 'route2') + self.assertEqual(res.body, b'route2') def test_ghi(self): res = self.testapp.get('/ghi', status=200) - self.assertEqual(res.body, 'global') + self.assertEqual(res.body, b'global') def test_jkl(self): self.testapp.get('/jkl', status=404) @@ -313,41 +313,41 @@ class TestHybridApp(IntegrationBase, unittest.TestCase): def test_pqr_global2(self): res = self.testapp.get('/pqr/global2', status=200) - self.assertEqual(res.body, 'global2') + self.assertEqual(res.body, b'global2') def test_error(self): res = self.testapp.get('/error', status=200) - self.assertEqual(res.body, 'supressed') + self.assertEqual(res.body, b'supressed') def test_error2(self): res = self.testapp.get('/error2', status=200) - self.assertEqual(res.body, 'supressed2') + self.assertEqual(res.body, b'supressed2') def test_error_sub(self): res = self.testapp.get('/error_sub', status=200) - self.assertEqual(res.body, 'supressed2') + self.assertEqual(res.body, b'supressed2') class TestRestBugApp(IntegrationBase, unittest.TestCase): # test bug reported by delijati 2010/2/3 (http://pastebin.com/d4cc15515) package = 'pyramid.tests.pkgs.restbugapp' def test_it(self): res = self.testapp.get('/pet', status=200) - self.assertEqual(res.body, 'gotten') + self.assertEqual(res.body, b'gotten') class TestForbiddenAppHasResult(IntegrationBase, unittest.TestCase): # test that forbidden exception has ACLDenied result attached package = 'pyramid.tests.pkgs.forbiddenapp' def test_it(self): res = self.testapp.get('/x', status=403) - message, result = [x.strip() for x in res.body.split('\n')] - self.assertTrue(message.endswith('failed permission check')) + message, result = [x.strip() for x in res.body.split(b'\n')] + self.assertTrue(message.endswith(b'failed permission check')) self.assertTrue( - result.startswith("ACLDenied permission 'private' via ACE " - "'' in ACL " - "'' on context")) + result.startswith(b"ACLDenied permission 'private' via ACE " + b"'' in ACL " + b"'' on context")) self.assertTrue( - result.endswith("for principals ['system.Everyone']")) + result.endswith(b"for principals ['system.Everyone']")) class TestViewDecoratorApp(IntegrationBase, unittest.TestCase): package = 'pyramid.tests.pkgs.viewdecoratorapp' @@ -362,20 +362,20 @@ class TestViewDecoratorApp(IntegrationBase, unittest.TestCase): # we use mako here instead of chameleon because it works on Jython self._configure_mako() res = self.testapp.get('/first', status=200) - self.assertTrue('OK' in res.body) + self.assertTrue(b'OK' in res.body) def test_second(self): # we use mako here instead of chameleon because it works on Jython self._configure_mako() res = self.testapp.get('/second', status=200) - self.assertTrue('OK2' in res.body) + self.assertTrue(b'OK2' in res.body) class TestViewPermissionBug(IntegrationBase, unittest.TestCase): # view_execution_permitted bug as reported by Shane at http://lists.repoze.org/pipermail/repoze-dev/2010-October/003603.html package = 'pyramid.tests.pkgs.permbugapp' def test_test(self): res = self.testapp.get('/test', status=200) - self.assertTrue('ACLDenied' in res.body) + self.assertTrue(b'ACLDenied' in res.body) def test_x(self): self.testapp.get('/x', status=403) @@ -385,15 +385,15 @@ class TestDefaultViewPermissionBug(IntegrationBase, unittest.TestCase): package = 'pyramid.tests.pkgs.defpermbugapp' def test_x(self): res = self.testapp.get('/x', status=403) - self.assertTrue('failed permission check' in res.body) + self.assertTrue(b'failed permission check' in res.body) def test_y(self): res = self.testapp.get('/y', status=403) - self.assertTrue('failed permission check' in res.body) + self.assertTrue(b'failed permission check' in res.body) def test_z(self): res = self.testapp.get('/z', status=200) - self.assertTrue('public' in res.body) + self.assertTrue(b'public' in res.body) from pyramid.tests.pkgs.exceptionviewapp.models import \ AnException, NotAnException @@ -405,31 +405,31 @@ class TestExceptionViewsApp(IntegrationBase, unittest.TestCase): root_factory = lambda *arg: excroot def test_root(self): res = self.testapp.get('/', status=200) - self.assertTrue('maybe' in res.body) + self.assertTrue(b'maybe' in res.body) def test_notanexception(self): res = self.testapp.get('/notanexception', status=200) - self.assertTrue('no' in res.body) + self.assertTrue(b'no' in res.body) def test_anexception(self): res = self.testapp.get('/anexception', status=200) - self.assertTrue('yes' in res.body) + self.assertTrue(b'yes' in res.body) def test_route_raise_exception(self): res = self.testapp.get('/route_raise_exception', status=200) - self.assertTrue('yes' in res.body) + self.assertTrue(b'yes' in res.body) def test_route_raise_exception2(self): res = self.testapp.get('/route_raise_exception2', status=200) - self.assertTrue('yes' in res.body) + self.assertTrue(b'yes' in res.body) def test_route_raise_exception3(self): res = self.testapp.get('/route_raise_exception3', status=200) - self.assertTrue('whoa' in res.body) + self.assertTrue(b'whoa' in res.body) def test_route_raise_exception4(self): res = self.testapp.get('/route_raise_exception4', status=200) - self.assertTrue('whoa' in res.body) + self.assertTrue(b'whoa' in res.body) class TestConflictApp(unittest.TestCase): package = 'pyramid.tests.pkgs.conflictapp' @@ -445,9 +445,9 @@ class TestConflictApp(unittest.TestCase): from webtest import TestApp self.testapp = TestApp(app) res = self.testapp.get('/') - self.assertTrue('a view' in res.body) + self.assertTrue(b'a view' in res.body) res = self.testapp.get('/route') - self.assertTrue('route view' in res.body) + self.assertTrue(b'route view' in res.body) def test_overridden_autoresolved_view(self): from pyramid.response import Response @@ -460,7 +460,7 @@ class TestConflictApp(unittest.TestCase): from webtest import TestApp self.testapp = TestApp(app) res = self.testapp.get('/') - self.assertTrue('this view' in res.body) + self.assertTrue(b'this view' in res.body) def test_overridden_route_view(self): from pyramid.response import Response @@ -473,7 +473,7 @@ class TestConflictApp(unittest.TestCase): from webtest import TestApp self.testapp = TestApp(app) res = self.testapp.get('/route') - self.assertTrue('this view' in res.body) + self.assertTrue(b'this view' in res.body) def test_nonoverridden_authorization_policy(self): config = self._makeConfig() @@ -482,7 +482,7 @@ class TestConflictApp(unittest.TestCase): from webtest import TestApp self.testapp = TestApp(app) res = self.testapp.get('/protected', status=403) - self.assertTrue('403 Forbidden' in res) + self.assertTrue(b'403 Forbidden' in res.body) def test_overridden_authorization_policy(self): config = self._makeConfig() @@ -512,15 +512,15 @@ class ImperativeIncludeConfigurationTest(unittest.TestCase): def test_root(self): res = self.testapp.get('/', status=200) - self.assertTrue('root' in res.body) + self.assertTrue(b'root' in res.body) def test_two(self): res = self.testapp.get('/two', status=200) - self.assertTrue('two' in res.body) + self.assertTrue(b'two' in res.body) def test_three(self): res = self.testapp.get('/three', status=200) - self.assertTrue('three' in res.body) + self.assertTrue(b'three' in res.body) class SelfScanAppTest(unittest.TestCase): def setUp(self): @@ -536,11 +536,11 @@ class SelfScanAppTest(unittest.TestCase): def test_root(self): res = self.testapp.get('/', status=200) - self.assertTrue('root' in res.body) + self.assertTrue(b'root' in res.body) def test_two(self): res = self.testapp.get('/two', status=200) - self.assertTrue('two' in res.body) + self.assertTrue(b'two' in res.body) class WSGIApp2AppTest(unittest.TestCase): def setUp(self): @@ -556,18 +556,18 @@ class WSGIApp2AppTest(unittest.TestCase): def test_hello(self): res = self.testapp.get('/hello', status=200) - self.assertTrue('Hello' in res.body) + self.assertTrue(b'Hello' in res.body) if os.name != 'java': # uses chameleon class RendererScanAppTest(IntegrationBase, unittest.TestCase): package = 'pyramid.tests.pkgs.rendererscanapp' def test_root(self): res = self.testapp.get('/one', status=200) - self.assertTrue('One!' in res.body) + self.assertTrue(b'One!' in res.body) def test_two(self): res = self.testapp.get('/two', status=200) - self.assertTrue('Two!' in res.body) + self.assertTrue(b'Two!' in res.body) def test_rescan(self): self.config.scan('pyramid.tests.pkgs.rendererscanapp') @@ -575,9 +575,9 @@ if os.name != 'java': # uses chameleon from webtest import TestApp testapp = TestApp(app) res = testapp.get('/one', status=200) - self.assertTrue('One!' in res.body) + self.assertTrue(b'One!' in res.body) res = testapp.get('/two', status=200) - self.assertTrue('Two!' in res.body) + self.assertTrue(b'Two!' in res.body) class DummyContext(object): pass diff --git a/pyramid/tests/test_mako_templating.py b/pyramid/tests/test_mako_templating.py index 9948c713c..074d28b85 100644 --- a/pyramid/tests/test_mako_templating.py +++ b/pyramid/tests/test_mako_templating.py @@ -3,6 +3,7 @@ import unittest from pyramid import testing from pyramid.compat import text_ +from pyramid.compat import text_type class Base(object): def setUp(self): @@ -276,7 +277,7 @@ class MakoLookupTemplateRendererTests(Base, unittest.TestCase): lookup = DummyLookup() instance = self._makeOne('path', lookup) result = instance({}, {'system':1}) - self.assertTrue(isinstance(result, unicode)) + self.assertTrue(isinstance(result, text_type)) self.assertEqual(result, text_('result')) def test_call_with_system_context(self): @@ -284,7 +285,7 @@ class MakoLookupTemplateRendererTests(Base, unittest.TestCase): lookup = DummyLookup() instance = self._makeOne('path', lookup) result = instance({}, {'context':1}) - self.assertTrue(isinstance(result, unicode)) + self.assertTrue(isinstance(result, text_type)) self.assertEqual(result, text_('result')) self.assertEqual(lookup.values, {'_context':1}) @@ -307,7 +308,7 @@ class MakoLookupTemplateRendererTests(Base, unittest.TestCase): instance = self._makeOne('path', lookup) try: instance({}, {}) - except MakoRenderingException, e: + except MakoRenderingException as e: self.assertTrue('NotImplementedError' in e.text) else: # pragma: no cover raise AssertionError @@ -316,7 +317,7 @@ class MakoLookupTemplateRendererTests(Base, unittest.TestCase): lookup = DummyLookup() instance = self._makeOne('path', lookup) result = instance.implementation().render_unicode() - self.assertTrue(isinstance(result, unicode)) + self.assertTrue(isinstance(result, text_type)) self.assertEqual(result, text_('result')) class TestIntegration(unittest.TestCase): diff --git a/pyramid/tests/test_renderers.py b/pyramid/tests/test_renderers.py index 48b1bed65..758331788 100644 --- a/pyramid/tests/test_renderers.py +++ b/pyramid/tests/test_renderers.py @@ -2,6 +2,7 @@ import unittest from pyramid.testing import cleanUp from pyramid import testing +from pyramid.compat import text_ class TestTemplateRendererFactory(unittest.TestCase): def setUp(self): @@ -433,7 +434,7 @@ class Test_string_renderer_factory(unittest.TestCase): def test_it_unicode(self): renderer = self._callFUT(None) - value = unicode('La Pe\xc3\xb1a', 'utf-8') + value = text_('La Pe\xc3\xb1a', 'utf-8') result = renderer(value, {}) self.assertEqual(result, value) @@ -593,7 +594,7 @@ class TestRendererHelper(unittest.TestCase): request = None helper = self._makeOne('loo.foo') response = helper._make_response('abc', request) - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') def test__make_response_request_is_None_response_factory_exists(self): self._registerResponseFactory() @@ -601,14 +602,14 @@ class TestRendererHelper(unittest.TestCase): helper = self._makeOne('loo.foo') response = helper._make_response('abc', request) self.assertEqual(response.__class__.__name__, 'ResponseFactory') - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') def test__make_response_result_is_unicode(self): from pyramid.response import Response request = testing.DummyRequest() request.response = Response() helper = self._makeOne('loo.foo') - la = unicode('/La Pe\xc3\xb1a', 'utf-8') + la = text_('/La Pe\xc3\xb1a', 'utf-8') response = helper._make_response(la, request) self.assertEqual(response.body, la.encode('utf-8')) @@ -617,7 +618,7 @@ class TestRendererHelper(unittest.TestCase): request = testing.DummyRequest() request.response = Response() helper = self._makeOne('loo.foo') - la = unicode('/La Pe\xc3\xb1a', 'utf-8') + la = text_('/La Pe\xc3\xb1a', 'utf-8') response = helper._make_response(la.encode('utf-8'), request) self.assertEqual(response.body, la.encode('utf-8')) @@ -630,7 +631,7 @@ class TestRendererHelper(unittest.TestCase): helper = self._makeOne('loo.foo') response = helper._make_response('abc', request) self.assertEqual(response.content_type, 'text/nonsense') - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') def test__make_response_with_headerlist(self): from pyramid.response import Response @@ -645,7 +646,7 @@ class TestRendererHelper(unittest.TestCase): ('Content-Length', '3'), ('a', '1'), ('b', '2')]) - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') def test__make_response_with_status(self): from pyramid.response import Response @@ -656,7 +657,7 @@ class TestRendererHelper(unittest.TestCase): helper = self._makeOne('loo.foo') response = helper._make_response('abc', request) self.assertEqual(response.status, '406 You Lose') - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') def test__make_response_with_charset(self): from pyramid.response import Response @@ -688,7 +689,7 @@ class TestRendererHelper(unittest.TestCase): helper = self._makeOne('loo.foo') response = helper._make_response('abc', request) self.assertEqual(response.__class__, ResponseFactory) - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') def test__make_response_with_real_request(self): # functional @@ -699,7 +700,7 @@ class TestRendererHelper(unittest.TestCase): helper = self._makeOne('loo.foo') response = helper._make_response('abc', request) self.assertEqual(response.status, '406 You Lose') - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') def test_clone_noargs(self): helper = self._makeOne('name', 'package', 'registry') @@ -811,7 +812,7 @@ class Test_render_to_response(unittest.TestCase): 'pyramid.tests:abc/def.pt') renderer.string_response = 'abc' response = self._callFUT('abc/def.pt', dict(a=1)) - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') renderer.assert_(a=1) renderer.assert_(request=None) @@ -822,7 +823,7 @@ class Test_render_to_response(unittest.TestCase): request = testing.DummyRequest() response = self._callFUT('abc/def.pt', dict(a=1), request=request) - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') renderer.assert_(a=1) renderer.assert_(request=request) @@ -834,7 +835,7 @@ class Test_render_to_response(unittest.TestCase): request = testing.DummyRequest() response = self._callFUT('abc/def.pt', dict(a=1), request=request, package=pyramid.tests) - self.assertEqual(response.body, 'abc') + self.assertEqual(response.body, b'abc') renderer.assert_(a=1) renderer.assert_(request=request) diff --git a/pyramid/tests/test_request.py b/pyramid/tests/test_request.py index f1338e331..2dadb7d52 100644 --- a/pyramid/tests/test_request.py +++ b/pyramid/tests/test_request.py @@ -237,19 +237,19 @@ class TestRequest(unittest.TestCase): def test_json_body_invalid_json(self): request = self._makeOne({'REQUEST_METHOD':'POST'}) - request.body = '{' + request.body = b'{' self.assertRaises(ValueError, getattr, request, 'json_body') def test_json_body_valid_json(self): request = self._makeOne({'REQUEST_METHOD':'POST'}) - request.body = '{"a":1}' + request.body = b'{"a":1}' self.assertEqual(request.json_body, {'a':1}) def test_json_body_alternate_charset(self): from pyramid.compat import json request = self._makeOne({'REQUEST_METHOD':'POST'}) request.charset = 'latin-1' - la = unicode('La Pe\xc3\xb1a', 'utf-8') + la = text_('La Pe\xc3\xb1a', 'utf-8') body = json.dumps({'a':la}, encoding='latin-1') request.body = body self.assertEqual(request.json_body, {'a':la}) @@ -501,7 +501,7 @@ class Test_call_app_with_subpath_as_path_info(unittest.TestCase): def test_subpath_path_info_and_script_name_have_utf8(self): la = 'La Pe\xc3\xb1a' request = DummyRequest({'PATH_INFO':'/'+la, 'SCRIPT_NAME':'/'+la}) - request.subpath = (unicode(la, 'utf-8'), ) + request.subpath = (text_(la, 'utf-8'), ) response = self._callFUT(request, 'app') self.assertTrue(request.copied) self.assertEqual(response, 'app') diff --git a/pyramid/tests/test_router.py b/pyramid/tests/test_router.py index 1bee26e6a..1e3261b77 100644 --- a/pyramid/tests/test_router.py +++ b/pyramid/tests/test_router.py @@ -177,7 +177,7 @@ class TestRouter(unittest.TestCase): return Response(s) router.registry.registerAdapter(make_response, (str,), IResponse) app_iter = router(environ, start_response) - self.assertEqual(app_iter, ['abc']) + self.assertEqual(app_iter, [b'abc']) self.assertEqual(start_response.status, '200 OK') self.assertEqual(environ['handled'], ['two', 'one']) @@ -310,7 +310,7 @@ class TestRouter(unittest.TestCase): return Response(s) router.registry.registerAdapter(make_response, (str,), IResponse) app_iter = router(environ, start_response) - self.assertEqual(app_iter, ['abc']) + self.assertEqual(app_iter, [b'abc']) self.assertEqual(start_response.status, '200 OK') def test_call_view_registered_nonspecific_default_path(self): @@ -466,7 +466,7 @@ class TestRouter(unittest.TestCase): raise KeyError def exc_view(context, request): self.assertFalse(hasattr(request.response, 'a')) - request.response.body = 'OK' + request.response.body = b'OK' return request.response environ = self._makeEnviron() self._registerView(view, '', IViewClassifier, IRequest, IContext) @@ -475,7 +475,7 @@ class TestRouter(unittest.TestCase): router = self._makeOne() start_response = DummyStartResponse() itera = router(environ, start_response) - self.assertEqual(itera, ['OK']) + self.assertEqual(itera, [b'OK']) def test_call_request_has_response_callbacks(self): from zope.interface import Interface diff --git a/pyramid/tests/test_settings.py b/pyramid/tests/test_settings.py index 5cc4ce561..d02b3cd3e 100644 --- a/pyramid/tests/test_settings.py +++ b/pyramid/tests/test_settings.py @@ -87,7 +87,7 @@ class Test_aslist(unittest.TestCase): def test_with_list(self): result = self._callFUT(['abc', 'def']) - self.assertEqual(result, ['abc', 'def']) + self.assertEqual(list(result), ['abc', 'def']) def test_with_string(self): result = self._callFUT('abc def') diff --git a/pyramid/tests/test_static.py b/pyramid/tests/test_static.py index 6dc38fc57..427b03c80 100644 --- a/pyramid/tests/test_static.py +++ b/pyramid/tests/test_static.py @@ -37,14 +37,14 @@ class Test_static_view_use_subpath_False(unittest.TestCase): response = inst(context, request) response.prepare(request.environ) self.assertEqual(response.status, '301 Moved Permanently') - self.assertTrue('http://example.com:6543/' in response.body) + self.assertTrue(b'http://example.com:6543/' in response.body) def test_path_info_slash_means_index_html(self): inst = self._makeOne('pyramid.tests:fixtures/static') request = self._makeRequest() context = DummyContext() response = inst(context, request) - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) def test_oob_singledot(self): inst = self._makeOne('pyramid.tests:fixtures/static') @@ -52,7 +52,7 @@ class Test_static_view_use_subpath_False(unittest.TestCase): context = DummyContext() response = inst(context, request) self.assertEqual(response.status, '200 OK') - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) def test_oob_emptyelement(self): inst = self._makeOne('pyramid.tests:fixtures/static') @@ -60,7 +60,7 @@ class Test_static_view_use_subpath_False(unittest.TestCase): context = DummyContext() response = inst(context, request) self.assertEqual(response.status, '200 OK') - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) def test_oob_dotdotslash(self): inst = self._makeOne('pyramid.tests:fixtures/static') @@ -99,21 +99,21 @@ class Test_static_view_use_subpath_False(unittest.TestCase): request = self._makeRequest({'PATH_INFO':'/subdir/'}) context = DummyContext() response = inst(context, request) - self.assertTrue('subdir' in response.body) + self.assertTrue(b'subdir' in response.body) def test_resource_is_file(self): inst = self._makeOne('pyramid.tests:fixtures/static') request = self._makeRequest({'PATH_INFO':'/index.html'}) context = DummyContext() response = inst(context, request) - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) def test_resource_is_file_with_cache_max_age(self): inst = self._makeOne('pyramid.tests:fixtures/static', cache_max_age=600) request = self._makeRequest({'PATH_INFO':'/index.html'}) context = DummyContext() response = inst(context, request) - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) self.assertEqual(len(response.headerlist), 5) header_names = [ x[0] for x in response.headerlist ] header_names.sort() @@ -127,7 +127,7 @@ class Test_static_view_use_subpath_False(unittest.TestCase): request = self._makeRequest({'PATH_INFO':'/index.html'}) context = DummyContext() response = inst(context, request) - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) self.assertEqual(len(response.headerlist), 3) header_names = [ x[0] for x in response.headerlist ] header_names.sort() @@ -192,7 +192,7 @@ class Test_static_view_use_subpath_True(unittest.TestCase): response = inst(context, request) response.prepare(request.environ) self.assertEqual(response.status, '301 Moved Permanently') - self.assertTrue('http://example.com:6543/' in response.body) + self.assertTrue(b'http://example.com:6543/' in response.body) def test_path_info_slash_means_index_html(self): inst = self._makeOne('pyramid.tests:fixtures/static') @@ -200,7 +200,7 @@ class Test_static_view_use_subpath_True(unittest.TestCase): request.subpath = () context = DummyContext() response = inst(context, request) - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) def test_oob_singledot(self): inst = self._makeOne('pyramid.tests:fixtures/static') @@ -258,7 +258,7 @@ class Test_static_view_use_subpath_True(unittest.TestCase): request.subpath = ('subdir',) context = DummyContext() response = inst(context, request) - self.assertTrue('subdir' in response.body) + self.assertTrue(b'subdir' in response.body) def test_resource_is_file(self): inst = self._makeOne('pyramid.tests:fixtures/static') @@ -266,7 +266,7 @@ class Test_static_view_use_subpath_True(unittest.TestCase): request.subpath = ('index.html',) context = DummyContext() response = inst(context, request) - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) def test_resource_is_file_with_cache_max_age(self): inst = self._makeOne('pyramid.tests:fixtures/static', cache_max_age=600) @@ -274,7 +274,7 @@ class Test_static_view_use_subpath_True(unittest.TestCase): request.subpath = ('index.html',) context = DummyContext() response = inst(context, request) - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) self.assertEqual(len(response.headerlist), 5) header_names = [ x[0] for x in response.headerlist ] header_names.sort() @@ -289,7 +289,7 @@ class Test_static_view_use_subpath_True(unittest.TestCase): request.subpath = ('index.html',) context = DummyContext() response = inst(context, request) - self.assertTrue('static' in response.body) + self.assertTrue(b'static' in response.body) self.assertEqual(len(response.headerlist), 3) header_names = [ x[0] for x in response.headerlist ] header_names.sort() diff --git a/pyramid/tests/test_testing.py b/pyramid/tests/test_testing.py index f428fa40a..4768daa9e 100644 --- a/pyramid/tests/test_testing.py +++ b/pyramid/tests/test_testing.py @@ -35,8 +35,10 @@ class Test_registerDummySecurityPolicy(TestBase): class Test_registerResources(TestBase): def test_it(self): - ob1 = object() - ob2 = object() + class Dummy: + pass + ob1 = Dummy() + ob2 = Dummy() resources = {'/ob1':ob1, '/ob2':ob2} from pyramid import testing testing.registerResources(resources) diff --git a/pyramid/tests/test_traversal.py b/pyramid/tests/test_traversal.py index 6abaf403d..837b2afc8 100644 --- a/pyramid/tests/test_traversal.py +++ b/pyramid/tests/test_traversal.py @@ -2,6 +2,7 @@ import unittest from pyramid.testing import cleanUp from pyramid.compat import text_ +from pyramid.compat import text_type class TraversalPathTests(unittest.TestCase): def _callFUT(self, path): @@ -30,8 +31,8 @@ class TraversalPathTests(unittest.TestCase): def test_segments_are_unicode(self): result = self._callFUT('/foo/bar') - self.assertEqual(type(result[0]), unicode) - self.assertEqual(type(result[1]), unicode) + self.assertEqual(type(result[0]), text_type) + self.assertEqual(type(result[1]), text_type) def test_same_value_returned_if_cached(self): result1 = self._callFUT('/foo/bar') @@ -43,14 +44,14 @@ class TraversalPathTests(unittest.TestCase): import urllib la = 'La Pe\xc3\xb1a' encoded = urllib.quote(la) - decoded = unicode(la, 'utf-8') + decoded = text_(la, 'utf-8') path = '/'.join([encoded, encoded]) self.assertEqual(self._callFUT(path), (decoded, decoded)) def test_utf16(self): from pyramid.exceptions import URLDecodeError import urllib - la = unicode('La Pe\xc3\xb1a', 'utf-8').encode('utf-16') + la = text_('La Pe\xc3\xb1a', 'utf-8').encode('utf-16') encoded = urllib.quote(la) path = '/'.join([encoded, encoded]) self.assertRaises(URLDecodeError, self._callFUT, path) @@ -280,7 +281,7 @@ class ResourceTreeTraverserTests(unittest.TestCase): foo = DummyContext() root = DummyContext(foo) policy = self._makeOne(root) - segment = unicode('LaPe\xc3\xb1a', 'utf-8').encode('utf-16') + segment = text_('LaPe\xc3\xb1a', 'utf-8').encode('utf-16') environ = self._getEnviron(PATH_INFO='/%s' % segment) request = DummyRequest(environ) from pyramid.exceptions import URLDecodeError @@ -290,7 +291,7 @@ class ResourceTreeTraverserTests(unittest.TestCase): foo = DummyContext() root = DummyContext(foo) policy = self._makeOne(root) - segment = unicode('LaPe\xc3\xb1a', 'utf-8').encode('utf-16') + segment = text_('LaPe\xc3\xb1a', 'utf-8').encode('utf-16') environ = self._getEnviron(PATH_INFO='/%s' % segment) request = DummyRequest(environ) from pyramid.exceptions import URLDecodeError @@ -755,7 +756,7 @@ class QuotePathSegmentTests(unittest.TestCase): return quote_path_segment(s) def test_unicode(self): - la = unicode('/La Pe\xc3\xb1a', 'utf-8') + la = text_('/La Pe\xc3\xb1a', 'utf-8') result = self._callFUT(la) self.assertEqual(result, '%2FLa%20Pe%C3%B1a') @@ -845,7 +846,7 @@ class TraversalContextURLTests(unittest.TestCase): root.__name__ = None one = DummyContext() one.__parent__ = root - one.__name__ = unicode('La Pe\xc3\xb1a', 'utf-8') + one.__name__ = text_('La Pe\xc3\xb1a', 'utf-8') two = DummyContext() two.__parent__ = one two.__name__ = 'La Pe\xc3\xb1a' diff --git a/pyramid/tests/test_url.py b/pyramid/tests/test_url.py index 452debd42..22eacd758 100644 --- a/pyramid/tests/test_url.py +++ b/pyramid/tests/test_url.py @@ -49,7 +49,7 @@ class TestURLMethodsMixin(unittest.TestCase): def test_resource_url_unicode_in_element_names(self): request = self._makeOne() self._registerContextURL(request.registry) - uc = unicode('La Pe\xc3\xb1a', 'utf-8') + uc = text_('La Pe\xc3\xb1a', 'utf-8') context = DummyContext() result = request.resource_url(context, uc) self.assertEqual(result, @@ -74,7 +74,7 @@ class TestURLMethodsMixin(unittest.TestCase): request = self._makeOne() self._registerContextURL(request.registry) context = DummyContext() - uc = unicode('La Pe\xc3\xb1a', 'utf-8') + uc = text_('La Pe\xc3\xb1a', 'utf-8') result = request.resource_url(context, 'a', query={'a':uc}) self.assertEqual(result, 'http://example.com/context/a?a=La+Pe%C3%B1a') @@ -83,7 +83,7 @@ class TestURLMethodsMixin(unittest.TestCase): request = self._makeOne() self._registerContextURL(request.registry) context = DummyContext() - uc = unicode('La Pe\xc3\xb1a', 'utf-8') + uc = text_('La Pe\xc3\xb1a', 'utf-8') result = request.resource_url(context, 'a', query=[('a', 'hi there'), ('b', uc)]) self.assertEqual(result, @@ -118,7 +118,7 @@ class TestURLMethodsMixin(unittest.TestCase): request = self._makeOne() self._registerContextURL(request.registry) context = DummyContext() - uc = unicode('La Pe\xc3\xb1a', 'utf-8') + uc = text_('La Pe\xc3\xb1a', 'utf-8') result = request.resource_url(context, anchor=uc) self.assertEqual(result, 'http://example.com/context/#La Pe\xc3\xb1a') @@ -191,7 +191,7 @@ class TestURLMethodsMixin(unittest.TestCase): request = self._makeOne() mapper = DummyRoutesMapper(route=DummyRoute('/1/2/3')) request.registry.registerUtility(mapper, IRoutesMapper) - anchor = unicode('La Pe\xc3\xb1a', 'utf-8') + anchor = text_('La Pe\xc3\xb1a', 'utf-8') result = request.route_url('flub', _anchor=anchor) self.assertEqual(result, 'http://example.com:5432/1/2/3#La Pe\xc3\xb1a') diff --git a/pyramid/tests/test_util.py b/pyramid/tests/test_util.py index eb165ef69..2883a968c 100644 --- a/pyramid/tests/test_util.py +++ b/pyramid/tests/test_util.py @@ -190,7 +190,7 @@ class Test_WeakOrderedSet(unittest.TestCase): reg = Dummy() wos.add(reg) self.assertEqual(list(wos), [reg]) - self.assert_(reg in wos) + self.assertTrue(reg in wos) self.assertEqual(wos.last, reg) def test_add_multiple_items(self): @@ -201,8 +201,8 @@ class Test_WeakOrderedSet(unittest.TestCase): wos.add(reg2) self.assertEqual(len(wos), 2) self.assertEqual(list(wos), [reg1, reg2]) - self.assert_(reg1 in wos) - self.assert_(reg2 in wos) + self.assertTrue(reg1 in wos) + self.assertTrue(reg2 in wos) self.assertEqual(wos.last, reg2) def test_add_duplicate_items(self): @@ -212,7 +212,7 @@ class Test_WeakOrderedSet(unittest.TestCase): wos.add(reg) self.assertEqual(len(wos), 1) self.assertEqual(list(wos), [reg]) - self.assert_(reg in wos) + self.assertTrue(reg in wos) self.assertEqual(wos.last, reg) def test_weakref_removal(self): diff --git a/pyramid/traversal.py b/pyramid/traversal.py index d586c30d9..897e01751 100644 --- a/pyramid/traversal.py +++ b/pyramid/traversal.py @@ -1,4 +1,3 @@ -import urllib import warnings from zope.interface import implementer @@ -14,6 +13,8 @@ from pyramid.interfaces import VH_ROOT_KEY from pyramid.compat import native_ from pyramid.compat import text_ from pyramid.compat import text_type +from pyramid.compat import url_unquote +from pyramid.compat import is_nonstr_iter from pyramid.encode import url_quote from pyramid.exceptions import URLDecodeError from pyramid.location import lineage @@ -278,7 +279,7 @@ def traverse(resource, path): and will be URL-decoded. """ - if hasattr(path, '__iter__'): + if is_nonstr_iter(path): # the traverser factory expects PATH_INFO to be a string, not # unicode and it expects path segments to be utf-8 and # urlencoded (it's the same traverser which accepts PATH_INFO @@ -296,8 +297,8 @@ def traverse(resource, path): # step rather than later down the line as the result of calling # ``traversal_path``). - if isinstance(path, unicode): - path = path.encode('ascii') + if isinstance(path, text_type): + path = native_(path, 'ascii') if path and path[0] == '/': resource = find_root(resource) @@ -475,14 +476,14 @@ def traversal_path(path): their own traversal machinery, as opposed to users writing applications in :app:`Pyramid`. """ - if isinstance(path, unicode): - path = path.encode('ascii') + if isinstance(path, text_type): + path = native_(path, 'ascii') path = path.strip('/') clean = [] for segment in path.split('/'): - segment = urllib.unquote(segment) + segment = url_unquote(segment) try: - segment = segment.decode('utf-8') + segment = native_(segment, 'utf-8') except UnicodeDecodeError as e: raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason) if not segment or segment == '.': @@ -530,7 +531,7 @@ def quote_path_segment(segment, safe=''): return _segment_cache[(segment, safe)] except KeyError: if segment.__class__ is text_type: # isinstance slighly slower (~15%) - result = url_quote(segment.encode('utf-8'), safe) + result = url_quote(native_(segment, 'utf-8'), safe) else: result = url_quote(native_(segment), safe) # we don't need a lock to mutate _segment_cache, as the below @@ -568,12 +569,12 @@ class ResourceTreeTraverser(object): matchdict = environ['bfg.routes.matchdict'] path = matchdict.get('traverse', '/') or '/' - if hasattr(path, '__iter__'): + if is_nonstr_iter(path): # this is a *traverse stararg (not a {traverse}) path = '/'.join([quote_path_segment(x) for x in path]) or '/' subpath = matchdict.get('subpath', ()) - if not hasattr(subpath, '__iter__'): + if not is_nonstr_iter(subpath): # this is not a *subpath stararg (just a {subpath}) subpath = traversal_path(subpath) diff --git a/pyramid/url.py b/pyramid/url.py index a28228290..c0c623aeb 100644 --- a/pyramid/url.py +++ b/pyramid/url.py @@ -8,6 +8,8 @@ from pyramid.interfaces import IContextURL from pyramid.interfaces import IRoutesMapper from pyramid.interfaces import IStaticURLInfo +from pyramid.compat import native_ +from pyramid.compat import text_type from pyramid.encode import urlencode from pyramid.path import caller_package from pyramid.threadlocal import get_current_registry @@ -135,8 +137,8 @@ class URLMethodsMixin(object): if '_anchor' in kw: anchor = kw.pop('_anchor') - if isinstance(anchor, unicode): - anchor = anchor.encode('utf-8') + if isinstance(anchor, text_type): + anchor = native_(anchor, 'utf-8') anchor = '#' + anchor if '_app_url' in kw: @@ -300,8 +302,8 @@ class URLMethodsMixin(object): if 'anchor' in kw: anchor = kw['anchor'] - if isinstance(anchor, unicode): - anchor = anchor.encode('utf-8') + if isinstance(anchor, text_type): + anchor = native_(anchor, 'utf-8') anchor = '#' + anchor if elements: diff --git a/pyramid/urldispatch.py b/pyramid/urldispatch.py index 8484fa549..a25bd58a9 100644 --- a/pyramid/urldispatch.py +++ b/pyramid/urldispatch.py @@ -5,6 +5,9 @@ from pyramid.interfaces import IRoutesMapper from pyramid.interfaces import IRoute from pyramid.compat import url_unquote +from pyramid.compat import native_ +from pyramid.compat import text_type +from pyramid.compat import text_ from pyramid.encode import url_quote from pyramid.exceptions import URLDecodeError from pyramid.traversal import traversal_path @@ -139,7 +142,7 @@ def _compile_route(route): else: encoded = url_unquote(v) try: - d[k] = encoded.decode('utf-8') + d[k] = text_(encoded, 'utf-8') except UnicodeDecodeError as e: raise URLDecodeError( e.encoding, e.object, e.start, e.end, e.reason @@ -153,8 +156,8 @@ def _compile_route(route): def generator(dict): newdict = {} for k, v in dict.items(): - if isinstance(v, unicode): - v = v.encode('utf-8') + if isinstance(v, text_type): + v = native_(v, 'utf-8') if k == star and hasattr(v, '__iter__'): v = '/'.join([quote_path_segment(x) for x in v]) elif k != star: -- cgit v1.2.3