diff options
Diffstat (limited to 'tests')
29 files changed, 265 insertions, 290 deletions
diff --git a/tests/pkgs/forbiddenapp/__init__.py b/tests/pkgs/forbiddenapp/__init__.py index 9ebf62a9d..31ea4dd52 100644 --- a/tests/pkgs/forbiddenapp/__init__.py +++ b/tests/pkgs/forbiddenapp/__init__.py @@ -1,6 +1,6 @@ from webob import Response from pyramid.httpexceptions import HTTPForbidden -from pyramid.compat import bytes_ +from pyramid.util import bytes_ def x_view(request): # pragma: no cover diff --git a/tests/pkgs/permbugapp/__init__.py b/tests/pkgs/permbugapp/__init__.py index aedd405f8..72b5d9c17 100644 --- a/tests/pkgs/permbugapp/__init__.py +++ b/tests/pkgs/permbugapp/__init__.py @@ -1,4 +1,4 @@ -from pyramid.compat import escape +from html import escape from pyramid.security import view_execution_permitted from pyramid.response import Response diff --git a/tests/test_authentication.py b/tests/test_authentication.py index fc3e60587..8671eba05 100644 --- a/tests/test_authentication.py +++ b/tests/test_authentication.py @@ -1,7 +1,8 @@ +from http.cookies import SimpleCookie import unittest import warnings from pyramid import testing -from pyramid.compat import text_, bytes_ +from pyramid.util import text_, bytes_ class TestCallbackAuthenticationPolicyDebugging(unittest.TestCase): @@ -706,8 +707,6 @@ class TestAuthTktCookieHelper(unittest.TestCase): return cookie def _parseCookie(self, cookie): - from pyramid.compat import SimpleCookie - cookies = SimpleCookie() cookies.load(cookie) return cookies.get('auth_tkt') @@ -1272,18 +1271,6 @@ class TestAuthTktCookieHelper(unittest.TestCase): self.assertEqual(val['userid'], '1') self.assertEqual(val['user_data'], 'userid_type:int') - def test_remember_long_userid(self): - from pyramid.compat import long - - helper = self._makeOne('secret') - request = self._makeRequest() - result = helper.remember(request, long(1)) - values = self._parseHeaders(result) - self.assertEqual(len(result), 3) - val = self._cookieValue(values[0]) - self.assertEqual(val['userid'], '1') - self.assertEqual(val['user_data'], 'userid_type:int') - def test_remember_unicode_userid(self): import base64 diff --git a/tests/test_compat.py b/tests/test_compat.py deleted file mode 100644 index 4a14caedf..000000000 --- a/tests/test_compat.py +++ /dev/null @@ -1,32 +0,0 @@ -import unittest -from pyramid.compat import is_unbound_method - - -class TestUnboundMethods(unittest.TestCase): - def test_old_style_bound(self): - self.assertFalse(is_unbound_method(OldStyle().run)) - - def test_new_style_bound(self): - self.assertFalse(is_unbound_method(NewStyle().run)) - - def test_old_style_unbound(self): - self.assertTrue(is_unbound_method(OldStyle.run)) - - def test_new_style_unbound(self): - self.assertTrue(is_unbound_method(NewStyle.run)) - - def test_normal_func_unbound(self): - def func(): # pragma: no cover - return 'OK' - - self.assertFalse(is_unbound_method(func)) - - -class OldStyle: - def run(self): # pragma: no cover - return 'OK' - - -class NewStyle(object): - def run(self): # pragma: no cover - return 'OK' diff --git a/tests/test_config/test_adapters.py b/tests/test_config/test_adapters.py index d871e8825..60a4f3090 100644 --- a/tests/test_config/test_adapters.py +++ b/tests/test_config/test_adapters.py @@ -1,6 +1,5 @@ import unittest -from pyramid.compat import PY2 from . import IDummy @@ -270,10 +269,7 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase): from pyramid.interfaces import IResponse config = self._makeOne(autocommit=True) - if PY2: - str_name = '__builtin__.str' - else: - str_name = 'builtins.str' + str_name = 'builtins.str' config.add_response_adapter('pyramid.response.Response', str_name) result = config.registry.queryAdapter('foo', IResponse) self.assertTrue(result.body, b'foo') diff --git a/tests/test_config/test_factories.py b/tests/test_config/test_factories.py index c03d3f68b..bbc38b6cd 100644 --- a/tests/test_config/test_factories.py +++ b/tests/test_config/test_factories.py @@ -160,8 +160,7 @@ class TestFactoriesMixin(unittest.TestCase): config = self._makeOne(autocommit=True) self.assertRaises(AttributeError, config.add_request_method) - def test_add_request_method_with_text_type_name(self): - from pyramid.compat import text_, PY2 + def test_add_request_method_with_text_name(self): from pyramid.exceptions import ConfigurationError config = self._makeOne(autocommit=True) @@ -170,11 +169,7 @@ class TestFactoriesMixin(unittest.TestCase): pass def get_bad_name(): - if PY2: - name = text_(b'La Pe\xc3\xb1a', 'utf-8') - else: - name = b'La Pe\xc3\xb1a' - + name = b'La Pe\xc3\xb1a' config.add_request_method(boomshaka, name=name) self.assertRaises(ConfigurationError, get_bad_name) diff --git a/tests/test_config/test_init.py b/tests/test_config/test_init.py index 811672fb3..ce2b042ec 100644 --- a/tests/test_config/test_init.py +++ b/tests/test_config/test_init.py @@ -1,9 +1,6 @@ import os import unittest -from pyramid.compat import im_func -from pyramid.testing import skip_on - from . import dummy_tween_factory from . import dummy_include from . import dummy_extend @@ -1157,7 +1154,6 @@ test_config.dummy_include2""" "@view_config(name='two', renderer='string')" in which ) - @skip_on('py3') def test_hook_zca(self): from zope.component import getSiteManager @@ -1173,7 +1169,6 @@ test_config.dummy_include2""" finally: getSiteManager.reset() - @skip_on('py3') def test_unhook_zca(self): from zope.component import getSiteManager @@ -1208,7 +1203,7 @@ test_config.dummy_include2""" directives = {'foo': (foo, True)} config.registry._directives = directives foo_meth = config.foo - self.assertTrue(getattr(foo_meth, im_func).__docobj__ is foo) + self.assertTrue(getattr(foo_meth, '__func__').__docobj__ is foo) def test___getattr__matches_no_action_wrap(self): config = self._makeOne() @@ -1219,7 +1214,7 @@ test_config.dummy_include2""" directives = {'foo': (foo, False)} config.registry._directives = directives foo_meth = config.foo - self.assertTrue(getattr(foo_meth, im_func) is foo) + self.assertTrue(getattr(foo_meth, '__func__') is foo) class TestConfigurator_add_directive(unittest.TestCase): diff --git a/tests/test_config/test_predicates.py b/tests/test_config/test_predicates.py index 079652b39..c27b41639 100644 --- a/tests/test_config/test_predicates.py +++ b/tests/test_config/test_predicates.py @@ -1,6 +1,6 @@ import unittest -from pyramid.compat import text_ +from pyramid.util import text_ class TestPredicateList(unittest.TestCase): diff --git a/tests/test_config/test_routes.py b/tests/test_config/test_routes.py index 32a64b4bd..4ff67cf66 100644 --- a/tests/test_config/test_routes.py +++ b/tests/test_config/test_routes.py @@ -2,7 +2,7 @@ import unittest from . import dummyfactory from . import DummyContext -from pyramid.compat import text_ +from pyramid.util import text_ class RoutesConfiguratorMixinTests(unittest.TestCase): @@ -54,6 +54,30 @@ class RoutesConfiguratorMixinTests(unittest.TestCase): config.add_route('name', 'path') self._assertRoute(config, 'name', 'root/path') + def test_add_route_with_inherit_errors(self): + from pyramid.exceptions import ConfigurationError + + config = self._makeOne(autocommit=True) + self.assertRaises( + ConfigurationError, + config.add_route, + 'name', + '/', + inherit_slash=True, + ) + + def test_add_route_with_route_prefix_with_inherit_slash(self): + config = self._makeOne(autocommit=True) + config.route_prefix = 'root' + config.add_route('name', '', inherit_slash=True) + self._assertRoute(config, 'name', 'root') + + def test_add_route_with_root_slash_with_route_prefix(self): + config = self._makeOne(autocommit=True) + config.route_prefix = 'root' + config.add_route('name', '/') + self._assertRoute(config, 'name', 'root/') + def test_add_route_discriminator(self): config = self._makeOne() config.add_route('name', 'path') diff --git a/tests/test_config/test_testing.py b/tests/test_config/test_testing.py index ede31e1b6..0fb73d268 100644 --- a/tests/test_config/test_testing.py +++ b/tests/test_config/test_testing.py @@ -1,8 +1,8 @@ import unittest from zope.interface import implementer -from pyramid.compat import text_ from pyramid.security import AuthenticationAPIMixin, AuthorizationAPIMixin +from pyramid.util import text_ from . import IDummy @@ -69,23 +69,27 @@ class TestingConfiguratorMixinTests(unittest.TestCase): config = self._makeOne(autocommit=True) config.testing_resources(resources) adapter = config.registry.getAdapter(None, ITraverser) - result = adapter(DummyRequest({'PATH_INFO': '/ob1'})) + request = DummyRequest() + request.path_info = '/ob1' + result = adapter(request) self.assertEqual(result['context'], ob1) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) self.assertEqual(result['traversed'], (text_('ob1'),)) self.assertEqual(result['virtual_root'], ob1) self.assertEqual(result['virtual_root_path'], ()) - result = adapter(DummyRequest({'PATH_INFO': '/ob2'})) + request = DummyRequest() + request.path_info = '/ob2' + result = adapter(request) self.assertEqual(result['context'], ob2) self.assertEqual(result['view_name'], '') self.assertEqual(result['subpath'], ()) 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'}) - ) + request = DummyRequest() + request.path_info = '/ob3' + self.assertRaises(KeyError, adapter, request) try: config.begin() self.assertEqual(find_resource(None, '/ob1'), ob1) diff --git a/tests/test_config/test_views.py b/tests/test_config/test_views.py index b72b9b36a..685b81a0f 100644 --- a/tests/test_config/test_views.py +++ b/tests/test_config/test_views.py @@ -3,11 +3,11 @@ import unittest from zope.interface import implementer from pyramid import testing -from pyramid.compat import im_func, text_ from pyramid.exceptions import ConfigurationError from pyramid.exceptions import ConfigurationExecutionError from pyramid.exceptions import ConfigurationConflictError from pyramid.interfaces import IResponse, IRequest, IMultiView +from pyramid.util import text_ from . import IDummy from . import dummy_view @@ -1357,6 +1357,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): request_method='POST', ) request = self._makeRequest(config) + request.path_info = '/' request.method = 'POST' request.params = {} router = Router(config.registry) @@ -1412,6 +1413,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): request_method='POST', ) request = self._makeRequest(config) + request.path_info = '/' request.method = 'POST' request.params = {} router = Router(config.registry) @@ -2722,7 +2724,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): view, renderer=null_renderer, append_slash=True ) request = self._makeRequest(config) - request.environ['PATH_INFO'] = '/foo' + request.path_info = '/foo' request.query_string = 'a=1&b=2' request.path = '/scriptname/foo' view = self._getViewCallable( @@ -2751,7 +2753,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): view, renderer=null_renderer, append_slash=HTTPMovedPermanently ) request = self._makeRequest(config) - request.environ['PATH_INFO'] = '/foo' + request.path_info = '/foo' request.query_string = 'a=1&b=2' request.path = '/scriptname/foo' view = self._getViewCallable( @@ -2795,15 +2797,6 @@ class TestViewsConfigurationMixin(unittest.TestCase): request = self._makeRequest(config) self.assertRaises(PredicateMismatch, wrapper, context, request) - # Since Python 3 has to be all cool and fancy and different... - def _assertBody(self, response, value): - from pyramid.compat import text_type - - if isinstance(value, text_type): # pragma: no cover - self.assertEqual(response.text, value) - else: # pragma: no cover - self.assertEqual(response.body, value) - def test_add_notfound_view_with_renderer(self): from zope.interface import implementedBy from pyramid.interfaces import IRequest @@ -2820,7 +2813,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): request_iface=IRequest, ) result = view(None, request) - self._assertBody(result, '{}') + self.assertEqual(result.text, '{}') def test_add_forbidden_view_with_renderer(self): from zope.interface import implementedBy @@ -2838,7 +2831,7 @@ class TestViewsConfigurationMixin(unittest.TestCase): request_iface=IRequest, ) result = view(None, request) - self._assertBody(result, '{}') + self.assertEqual(result.text, '{}') def test_set_view_mapper(self): from pyramid.interfaces import IViewMapperFactory @@ -3732,16 +3725,16 @@ class Test_preserve_view_attrs(unittest.TestCase): self.assertTrue(view1.__module__ is view2.__module__) self.assertTrue(view1.__name__ is view2.__name__) self.assertTrue( - getattr(view1.__call_permissive__, im_func) - is getattr(view2.__call_permissive__, im_func) + getattr(view1.__call_permissive__, '__func__') + is getattr(view2.__call_permissive__, '__func__') ) self.assertTrue( - getattr(view1.__permitted__, im_func) - is getattr(view2.__permitted__, im_func) + getattr(view1.__permitted__, '__func__') + is getattr(view2.__permitted__, '__func__') ) self.assertTrue( - getattr(view1.__predicated__, im_func) - is getattr(view2.__predicated__, im_func) + getattr(view1.__predicated__, '__func__') + is getattr(view2.__predicated__, '__func__') ) diff --git a/tests/test_encode.py b/tests/test_encode.py index f70050cac..4df08d509 100644 --- a/tests/test_encode.py +++ b/tests/test_encode.py @@ -1,5 +1,5 @@ import unittest -from pyramid.compat import text_, native_ +from pyramid.util import text_ class UrlEncodeTests(unittest.TestCase): @@ -74,7 +74,7 @@ class URLQuoteTests(unittest.TestCase): self.assertEqual(result, 'La%2FPe%C3%B1a') def test_it_native(self): - la = native_(b'La/Pe\xc3\xb1a', 'utf-8') + la = text_(b'La/Pe\xc3\xb1a', 'utf-8') result = self._callFUT(la) self.assertEqual(result, 'La%2FPe%C3%B1a') diff --git a/tests/test_httpexceptions.py b/tests/test_httpexceptions.py index 4c13e096d..5decfc39c 100644 --- a/tests/test_httpexceptions.py +++ b/tests/test_httpexceptions.py @@ -1,6 +1,6 @@ import unittest -from pyramid.compat import bytes_, string_types, text_ +from pyramid.util import bytes_, text_ class Test_exception_response(unittest.TestCase): @@ -67,6 +67,12 @@ class Test__no_escape(unittest.TestCase): def test_not_basestring(self): self.assertEqual(self._callFUT(42), '42') + def test_bytes(self): + self.assertEqual( + self._callFUT(b'/La Pe\xc3\xb1a/{x}'), + b'/La Pe\xc3\xb1a/{x}'.decode('utf-8'), + ) + def test_unicode(self): class DummyUnicodeObject(object): def __unicode__(self): @@ -406,7 +412,7 @@ class TestHTTPException(unittest.TestCase): def test_allow_detail_non_str(self): exc = self._makeOne(detail={'error': 'This is a test'}) - self.assertIsInstance(exc.__str__(), string_types) + self.assertIsInstance(exc.__str__(), str) class TestRenderAllExceptionsWithoutArguments(unittest.TestCase): diff --git a/tests/test_integration.py b/tests/test_integration.py index d57a7cf6e..e6dccbb5b 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -4,14 +4,15 @@ import gc import locale import os import unittest +from urllib.parse import quote from webtest import TestApp from zope.interface import Interface -from pyramid.wsgi import wsgiapp -from pyramid.view import view_config from pyramid.static import static_view from pyramid.testing import skip_on -from pyramid.compat import text_, url_quote +from pyramid.util import text_ +from pyramid.view import view_config +from pyramid.wsgi import wsgiapp from .pkgs.exceptionviewapp.models import AnException, NotAnException @@ -108,7 +109,7 @@ class StaticAppBase(IntegrationBase): os.makedirs(pathdir) with open(path, 'wb') as fp: fp.write(body) - url = url_quote('/static/héhé/index.html') + url = quote('/static/héhé/index.html') res = self.testapp.get(url, status=200) self.assertEqual(res.body, body) finally: @@ -123,7 +124,7 @@ class StaticAppBase(IntegrationBase): with open(path, 'wb') as fp: fp.write(body) try: - url = url_quote('/static/héhé.html') + url = quote('/static/héhé.html') res = self.testapp.get(url, status=200) self.assertEqual(res.body, body) finally: @@ -725,8 +726,8 @@ class UnicodeInURLTest(unittest.TestCase): res = testapp.get(request_path, status=404) # Pyramid default 404 handler outputs: - # u'404 Not Found\n\nThe resource could not be found.\n\n\n' - # u'/avalia\xe7\xe3o_participante\n\n' + # '404 Not Found\n\nThe resource could not be found.\n\n\n' + # '/avalia\xe7\xe3o_participante\n\n' self.assertTrue(request_path_unicode in res.text) def test_unicode_in_url_200(self): diff --git a/tests/test_path.py b/tests/test_path.py index 626bb1139..da7cd64e1 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -1,6 +1,5 @@ import unittest import os -from pyramid.compat import PY2 here = os.path.abspath(os.path.dirname(__file__)) @@ -429,10 +428,7 @@ class TestDottedNameResolver(unittest.TestCase): def test_zope_dottedname_style_resolve_builtin(self): typ = self._makeOne() - if PY2: - result = typ._zope_dottedname_style('__builtin__.str', None) - else: - result = typ._zope_dottedname_style('builtins.str', None) + result = typ._zope_dottedname_style('builtins.str', None) self.assertEqual(result, str) def test_zope_dottedname_style_resolve_absolute(self): diff --git a/tests/test_predicates.py b/tests/test_predicates.py index c072b4229..a99651a8f 100644 --- a/tests/test_predicates.py +++ b/tests/test_predicates.py @@ -2,7 +2,7 @@ import unittest from pyramid import testing -from pyramid.compat import text_ +from pyramid.util import text_ class TestXHRPredicate(unittest.TestCase): diff --git a/tests/test_renderers.py b/tests/test_renderers.py index 0eacfa996..db8b3b4f2 100644 --- a/tests/test_renderers.py +++ b/tests/test_renderers.py @@ -1,8 +1,8 @@ import unittest -from pyramid.testing import cleanUp from pyramid import testing -from pyramid.compat import text_ +from pyramid.testing import cleanUp +from pyramid.util import text_ class TestJSON(unittest.TestCase): @@ -774,7 +774,7 @@ class DummyResponse: body = b'' # compat for renderer that will set unicode on py3 - def _set_text(self, val): # pragma: no cover + def _set_text(self, val): self.body = val.encode('utf8') text = property(fset=_set_text) diff --git a/tests/test_request.py b/tests/test_request.py index dcac501aa..484d86e01 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -1,8 +1,8 @@ import unittest from pyramid import testing -from pyramid.compat import PY2, text_, bytes_, native_ from pyramid.security import AuthenticationAPIMixin, AuthorizationAPIMixin +from pyramid.util import text_, bytes_ class TestRequest(unittest.TestCase): @@ -352,10 +352,7 @@ class TestRequest(unittest.TestCase): inp = text_( b'/\xe6\xb5\x81\xe8\xa1\x8c\xe8\xb6\x8b\xe5\x8a\xbf', 'utf-8' ) - if PY2: - body = json.dumps({'a': inp}).decode('utf-8').encode('utf-16') - else: - body = bytes(json.dumps({'a': inp}), 'utf-16') + body = bytes(json.dumps({'a': inp}), 'utf-16') request.body = body request.content_type = 'application/json; charset=utf-16' self.assertEqual(request.json_body, {'a': inp}) @@ -481,7 +478,7 @@ class Test_call_app_with_subpath_as_path_info(unittest.TestCase): self.assertEqual(request.environ['PATH_INFO'], '/hello/') def test_subpath_path_info_and_script_name_have_utf8(self): - encoded = native_(text_(b'La Pe\xc3\xb1a')) + encoded = text_(b'La Pe\xc3\xb1a') decoded = text_(bytes_(encoded), 'utf-8') request = DummyRequest( {'PATH_INFO': '/' + encoded, 'SCRIPT_NAME': '/' + encoded} diff --git a/tests/test_response.py b/tests/test_response.py index 5231e47f0..b63ccc6b1 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -73,9 +73,9 @@ class TestFileResponse(unittest.TestCase): # function returns Unicode for the content_type, unlike any previous # version of Python. See https://github.com/Pylons/pyramid/issues/1360 # for more information. - from pyramid.compat import text_ import mimetypes as old_mimetypes from pyramid import response + from pyramid.util import text_ class FakeMimetypesModule(object): def guess_type(self, *arg, **kw): @@ -120,31 +120,6 @@ class TestFileIter(unittest.TestCase): self.assertTrue(f.closed) -class Test_patch_mimetypes(unittest.TestCase): - def _callFUT(self, module): - from pyramid.response import init_mimetypes - - return init_mimetypes(module) - - def test_has_init(self): - class DummyMimetypes(object): - def init(self): - self.initted = True - - module = DummyMimetypes() - result = self._callFUT(module) - self.assertEqual(result, True) - self.assertEqual(module.initted, True) - - def test_missing_init(self): - class DummyMimetypes(object): - pass - - module = DummyMimetypes() - result = self._callFUT(module) - self.assertEqual(result, False) - - class TestResponseAdapter(unittest.TestCase): def setUp(self): registry = Dummy() diff --git a/tests/test_scripts/dummy.py b/tests/test_scripts/dummy.py index 8e340f645..bb3475d39 100644 --- a/tests/test_scripts/dummy.py +++ b/tests/test_scripts/dummy.py @@ -81,8 +81,11 @@ class DummyRoute(object): class DummyRequest: application_url = 'http://example.com:5432' script_name = '' + path_info = '/' - def __init__(self, environ): + def __init__(self, environ=None): + if environ is None: + environ = {} self.environ = environ self.matchdict = {} diff --git a/tests/test_scripts/test_prequest.py b/tests/test_scripts/test_prequest.py index 1521172bc..aadde719a 100644 --- a/tests/test_scripts/test_prequest.py +++ b/tests/test_scripts/test_prequest.py @@ -1,3 +1,4 @@ +from io import StringIO import unittest from . import dummy @@ -134,13 +135,11 @@ class TestPRequestCommand(unittest.TestCase): self.assertEqual(self._out, ['abc']) def test_command_method_post(self): - from pyramid.compat import NativeIO - command = self._makeOne( ['', '--method=POST', 'development.ini', '/'], [('Content-Type', 'text/html; charset=UTF-8')], ) - stdin = NativeIO() + stdin = StringIO() command.stdin = stdin command.run() self.assertEqual(self._environ['REQUEST_METHOD'], 'POST') @@ -150,13 +149,11 @@ class TestPRequestCommand(unittest.TestCase): self.assertEqual(self._out, ['abc']) def test_command_method_put(self): - from pyramid.compat import NativeIO - command = self._makeOne( ['', '--method=PUT', 'development.ini', '/'], [('Content-Type', 'text/html; charset=UTF-8')], ) - stdin = NativeIO() + stdin = StringIO() command.stdin = stdin command.run() self.assertEqual(self._environ['REQUEST_METHOD'], 'PUT') @@ -166,13 +163,11 @@ class TestPRequestCommand(unittest.TestCase): self.assertEqual(self._out, ['abc']) def test_command_method_patch(self): - from pyramid.compat import NativeIO - command = self._makeOne( ['', '--method=PATCH', 'development.ini', '/'], [('Content-Type', 'text/html; charset=UTF-8')], ) - stdin = NativeIO() + stdin = StringIO() command.stdin = stdin command.run() self.assertEqual(self._environ['REQUEST_METHOD'], 'PATCH') @@ -182,13 +177,11 @@ class TestPRequestCommand(unittest.TestCase): self.assertEqual(self._out, ['abc']) def test_command_method_propfind(self): - from pyramid.compat import NativeIO - command = self._makeOne( ['', '--method=PROPFIND', 'development.ini', '/'], [('Content-Type', 'text/html; charset=UTF-8')], ) - stdin = NativeIO() + stdin = StringIO() command.stdin = stdin command.run() self.assertEqual(self._environ['REQUEST_METHOD'], 'PROPFIND') @@ -196,13 +189,11 @@ class TestPRequestCommand(unittest.TestCase): self.assertEqual(self._out, ['abc']) def test_command_method_options(self): - from pyramid.compat import NativeIO - command = self._makeOne( ['', '--method=OPTIONS', 'development.ini', '/'], [('Content-Type', 'text/html; charset=UTF-8')], ) - stdin = NativeIO() + stdin = StringIO() command.stdin = stdin command.run() self.assertEqual(self._environ['REQUEST_METHOD'], 'OPTIONS') diff --git a/tests/test_scripts/test_pserve.py b/tests/test_scripts/test_pserve.py index b85f4ddb7..a573f2e5b 100644 --- a/tests/test_scripts/test_pserve.py +++ b/tests/test_scripts/test_pserve.py @@ -1,3 +1,4 @@ +from io import StringIO import os import unittest from . import dummy @@ -8,9 +9,7 @@ here = os.path.abspath(os.path.dirname(__file__)) class TestPServeCommand(unittest.TestCase): def setUp(self): - from pyramid.compat import NativeIO - - self.out_ = NativeIO() + self.out_ = StringIO() def out(self, msg): self.out_.write(msg) diff --git a/tests/test_scripts/test_pviews.py b/tests/test_scripts/test_pviews.py index 0b26a9cf3..c8d29113f 100644 --- a/tests/test_scripts/test_pviews.py +++ b/tests/test_scripts/test_pviews.py @@ -53,7 +53,8 @@ class TestPViewsCommand(unittest.TestCase): class View1(object): pass - request = dummy.DummyRequest({'PATH_INFO': '/a'}) + request = dummy.DummyRequest() + request.path_info = '/a' root = DefaultRootFactory(request) root_iface = providedBy(root) registry.registerAdapter( @@ -78,7 +79,8 @@ class TestPViewsCommand(unittest.TestCase): def view1(): # pragma: no cover pass - request = dummy.DummyRequest({'PATH_INFO': '/a'}) + request = dummy.DummyRequest() + request.path_info = '/a' root = DefaultRootFactory(request) root_iface = providedBy(root) registry.registerAdapter( @@ -105,7 +107,8 @@ class TestPViewsCommand(unittest.TestCase): class View1(object): pass - request = dummy.DummyRequest({'PATH_INFO': '/a'}) + request = dummy.DummyRequest() + request.path_info = '/a' root = DefaultRootFactory(request) root_iface = providedBy(root) view = View1() @@ -267,7 +270,8 @@ class TestPViewsCommand(unittest.TestCase): dummy.DummyRoute('b', '/a', factory=factory, matchdict={}), ] mapper = dummy.DummyMapper(*routes) - request = dummy.DummyRequest({'PATH_INFO': '/a'}) + request = dummy.DummyRequest() + request.path_info = '/a' result = command._find_multi_routes(mapper, request) self.assertEqual( result, @@ -288,7 +292,8 @@ class TestPViewsCommand(unittest.TestCase): dummy.DummyRoute('b', '/a', factory=factory, matchdict={}), ] mapper = dummy.DummyMapper(*routes) - request = dummy.DummyRequest({'PATH_INFO': '/a'}) + request = dummy.DummyRequest() + request.path_info = '/a' result = command._find_multi_routes(mapper, request) self.assertEqual(result, [{'match': {}, 'route': routes[1]}]) @@ -303,7 +308,8 @@ class TestPViewsCommand(unittest.TestCase): dummy.DummyRoute('b', '/a', factory=factory), ] mapper = dummy.DummyMapper(*routes) - request = dummy.DummyRequest({'PATH_INFO': '/a'}) + request = dummy.DummyRequest() + request.path_info = '/a' result = command._find_multi_routes(mapper, request) self.assertEqual(result, []) diff --git a/tests/test_session.py b/tests/test_session.py index 5e2a1ff55..8e5e82bb2 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -1,8 +1,8 @@ import base64 import json +import pickle import unittest from pyramid import testing -from pyramid.compat import pickle class SharedCookieSessionTests(object): @@ -607,13 +607,7 @@ class DummySerializer(object): return base64.b64encode(json.dumps(value).encode('utf-8')) def loads(self, value): - try: - return json.loads(base64.b64decode(value).decode('utf-8')) - - # base64.b64decode raises a TypeError on py2 instead of a ValueError - # and a ValueError is required for the session to handle it properly - except TypeError: - raise ValueError + return json.loads(base64.b64decode(value).decode('utf-8')) class DummySessionFactory(dict): diff --git a/tests/test_traversal.py b/tests/test_traversal.py index 61e480cbc..188ee803c 100644 --- a/tests/test_traversal.py +++ b/tests/test_traversal.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- import unittest +from urllib.parse import quote from pyramid.testing import cleanUp -from pyramid.compat import text_, native_, text_type, url_quote, PY2 +from pyramid.util import text_ class TraversalPathTests(unittest.TestCase): @@ -14,7 +15,7 @@ class TraversalPathTests(unittest.TestCase): def test_utf8(self): la = b'La Pe\xc3\xb1a' - encoded = url_quote(la) + encoded = quote(la) decoded = text_(la, 'utf-8') path = '/'.join([encoded, encoded]) result = self._callFUT(path) @@ -24,7 +25,7 @@ class TraversalPathTests(unittest.TestCase): from pyramid.exceptions import URLDecodeError la = text_(b'La Pe\xc3\xb1a', 'utf-8').encode('utf-16') - encoded = url_quote(la) + encoded = quote(la) path = '/'.join([encoded, encoded]) self.assertRaises(URLDecodeError, self._callFUT, path) @@ -71,8 +72,8 @@ class TraversalPathInfoTests(unittest.TestCase): def test_segments_are_unicode(self): result = self._callFUT('/foo/bar') - self.assertEqual(type(result[0]), text_type) - self.assertEqual(type(result[1]), text_type) + self.assertEqual(type(result[0]), str) + self.assertEqual(type(result[1]), str) def test_same_value_returned_if_cached(self): result1 = self._callFUT('/foo/bar') @@ -86,15 +87,14 @@ class TraversalPathInfoTests(unittest.TestCase): def test_highorder(self): la = b'La Pe\xc3\xb1a' - latin1 = native_(la) + latin1 = text_(la) result = self._callFUT(latin1) self.assertEqual(result, (text_(la, 'utf-8'),)) def test_highorder_undecodeable(self): from pyramid.exceptions import URLDecodeError - la = text_(b'La Pe\xc3\xb1a', 'utf-8') - notlatin1 = native_(la) + notlatin1 = text_(b'La Pe\xc3\xb1a', 'utf-8') self.assertRaises(URLDecodeError, self._callFUT, notlatin1) @@ -346,10 +346,7 @@ class ResourceTreeTraverserTests(unittest.TestCase): foo = DummyContext(bar, path) root = DummyContext(foo, 'root') policy = self._makeOne(root) - if PY2: - vhm_root = b'/Qu\xc3\xa9bec' - else: - vhm_root = b'/Qu\xc3\xa9bec'.decode('latin-1') + vhm_root = b'/Qu\xc3\xa9bec'.decode('latin-1') environ = self._getEnviron(HTTP_X_VHM_ROOT=vhm_root) request = DummyRequest(environ, path_info=text_('/bar')) result = policy(request) @@ -680,7 +677,7 @@ class FindResourceTests(unittest.TestCase): def test_absolute_unicode_found(self): # test for bug wiggy found in wild, traceback stack: - # root = u'/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF' + # root = '/%E6%B5%81%E8%A1%8C%E8%B6%8B%E5%8A%BF' # wiggy's code: section=find_resource(page, root) # find_resource L76: D = traverse(resource, path) # traverse L291: return traverser(request) @@ -873,15 +870,6 @@ class QuotePathSegmentTests(unittest.TestCase): result = self._callFUT(s) self.assertEqual(result, '12345') - def test_long(self): - from pyramid.compat import long - import sys - - s = long(sys.maxsize + 1) - result = self._callFUT(s) - expected = str(s) - self.assertEqual(result, expected) - def test_other(self): class Foo(object): def __str__(self): @@ -1226,18 +1214,18 @@ class Test__join_path_tuple(unittest.TestCase): def test_segments_with_unsafes(self): safe_segments = tuple( - u"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - u"-._~!$&'()*+,;=:@" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "-._~!$&'()*+,;=:@" ) result = self._callFUT(safe_segments) - self.assertEqual(result, u'/'.join(safe_segments)) + self.assertEqual(result, '/'.join(safe_segments)) unsafe_segments = tuple( chr(i) for i in range(0x20, 0x80) if not chr(i) in safe_segments - ) + (u'あ',) + ) + ('あ',) result = self._callFUT(unsafe_segments) self.assertEqual( result, - u'/'.join( + '/'.join( ''.join( '%%%02X' % (ord(c) if isinstance(c, str) else c) for c in unsafe_segment.encode('utf-8') diff --git a/tests/test_url.py b/tests/test_url.py index 94a0a61c9..648f48d53 100644 --- a/tests/test_url.py +++ b/tests/test_url.py @@ -3,7 +3,7 @@ import unittest from pyramid import testing -from pyramid.compat import text_, WIN +from pyramid.util import WIN, text_ class TestURLMethodsMixin(unittest.TestCase): @@ -25,6 +25,7 @@ class TestURLMethodsMixin(unittest.TestCase): def __init__(self, environ): self.environ = environ + self.scheme = environ.get('wsgi.url_scheme', 'http') request = Request(environ) request.registry = self.config.registry diff --git a/tests/test_urldispatch.py b/tests/test_urldispatch.py index 772250e89..5d77042ae 100644 --- a/tests/test_urldispatch.py +++ b/tests/test_urldispatch.py @@ -1,6 +1,6 @@ import unittest from pyramid import testing -from pyramid.compat import text_, PY2 +from pyramid.util import text_ class TestRoute(unittest.TestCase): @@ -59,9 +59,7 @@ class RoutesMapperTests(unittest.TestCase): def _getRequest(self, **kw): from pyramid.threadlocal import get_current_registry - environ = {'SERVER_NAME': 'localhost', 'wsgi.url_scheme': 'http'} - environ.update(kw) - request = DummyRequest(environ) + request = DummyRequest(**kw) reg = get_current_registry() request.registry = reg return request @@ -83,7 +81,7 @@ class RoutesMapperTests(unittest.TestCase): def test_no_route_matches(self): mapper = self._makeOne() - request = self._getRequest(PATH_INFO='/') + request = self._getRequest(path_info='/') result = mapper(request) self.assertEqual(result['match'], None) self.assertEqual(result['route'], None) @@ -130,19 +128,39 @@ class RoutesMapperTests(unittest.TestCase): def test___call__pathinfo_cant_be_decoded(self): from pyramid.exceptions import URLDecodeError + from pyramid.threadlocal import get_current_registry + + class DummyRequest: + @property + def path_info(self): + return b'\xff\xfe\xe6\x00'.decode('utf-8') mapper = self._makeOne() - if PY2: - path_info = b'\xff\xfe\xe6\x00' - else: - path_info = b'\xff\xfe\xe6\x00'.decode('latin-1') - request = self._getRequest(PATH_INFO=path_info) + request = DummyRequest() + request.registry = get_current_registry() self.assertRaises(URLDecodeError, mapper, request) + def test___call__pathinfo_KeyError(self): + from pyramid.threadlocal import get_current_registry + + class DummyRequest: + @property + def path_info(self): + # if the PATH_INFO is missing from the environ + raise KeyError + + mapper = self._makeOne() + mapper.connect('root', '') + request = DummyRequest() + request.registry = get_current_registry() + result = mapper(request) + self.assertEqual(result['route'], mapper.routes['root']) + self.assertEqual(result['match'], {}) + def test___call__route_matches(self): mapper = self._makeOne() mapper.connect('foo', 'archives/:action/:article') - request = self._getRequest(PATH_INFO='/archives/action1/article1') + request = self._getRequest(path_info='/archives/action1/article1') result = mapper(request) self.assertEqual(result['route'], mapper.routes['foo']) self.assertEqual(result['match']['action'], 'action1') @@ -153,7 +171,7 @@ class RoutesMapperTests(unittest.TestCase): mapper.connect( 'foo', 'archives/:action/:article', predicates=[lambda *arg: True] ) - request = self._getRequest(PATH_INFO='/archives/action1/article1') + request = self._getRequest(path_info='/archives/action1/article1') result = mapper(request) self.assertEqual(result['route'], mapper.routes['foo']) self.assertEqual(result['match']['action'], 'action1') @@ -167,7 +185,7 @@ class RoutesMapperTests(unittest.TestCase): predicates=[lambda *arg: True, lambda *arg: False], ) mapper.connect('bar', 'archives/:action/:article') - request = self._getRequest(PATH_INFO='/archives/action1/article1') + request = self._getRequest(path_info='/archives/action1/article1') result = mapper(request) self.assertEqual(result['route'], mapper.routes['bar']) self.assertEqual(result['match']['action'], 'action1') @@ -182,7 +200,7 @@ class RoutesMapperTests(unittest.TestCase): return True mapper.connect('foo', 'archives/:action/article1', predicates=[pred]) - request = self._getRequest(PATH_INFO='/archives/action1/article1') + request = self._getRequest(path_info='/archives/action1/article1') mapper(request) def test_cc_bug(self): @@ -194,13 +212,13 @@ class RoutesMapperTests(unittest.TestCase): 'juri', 'licenses/:license_code/:license_version/:jurisdiction' ) - request = self._getRequest(PATH_INFO='/licenses/1/v2/rdf') + request = self._getRequest(path_info='/licenses/1/v2/rdf') result = mapper(request) self.assertEqual(result['route'], mapper.routes['rdf']) self.assertEqual(result['match']['license_code'], '1') self.assertEqual(result['match']['license_version'], 'v2') - request = self._getRequest(PATH_INFO='/licenses/1/v2/usa') + request = self._getRequest(path_info='/licenses/1/v2/usa') result = mapper(request) self.assertEqual(result['route'], mapper.routes['juri']) self.assertEqual(result['match']['license_code'], '1') @@ -210,7 +228,7 @@ class RoutesMapperTests(unittest.TestCase): def test___call__root_route_matches(self): mapper = self._makeOne() mapper.connect('root', '') - request = self._getRequest(PATH_INFO='/') + request = self._getRequest(path_info='/') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) @@ -218,7 +236,7 @@ class RoutesMapperTests(unittest.TestCase): def test___call__root_route_matches2(self): mapper = self._makeOne() mapper.connect('root', '/') - request = self._getRequest(PATH_INFO='/') + request = self._getRequest(path_info='/') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) @@ -226,7 +244,7 @@ class RoutesMapperTests(unittest.TestCase): def test___call__root_route_when_path_info_empty(self): mapper = self._makeOne() mapper.connect('root', '/') - request = self._getRequest(PATH_INFO='') + request = self._getRequest(path_info='') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) @@ -234,7 +252,7 @@ class RoutesMapperTests(unittest.TestCase): def test___call__root_route_when_path_info_notempty(self): mapper = self._makeOne() mapper.connect('root', '/') - request = self._getRequest(PATH_INFO='/') + request = self._getRequest(path_info='/') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) @@ -242,7 +260,7 @@ class RoutesMapperTests(unittest.TestCase): def test___call__no_path_info(self): mapper = self._makeOne() mapper.connect('root', '/') - request = self._getRequest() + request = self._getRequest(path_info='') result = mapper(request) self.assertEqual(result['route'], mapper.routes['root']) self.assertEqual(result['match'], {}) @@ -646,8 +664,10 @@ class DummyContext(object): class DummyRequest(object): - def __init__(self, environ): - self.environ = environ + scheme = 'http' + + def __init__(self, **kw): + self.__dict__.update(kw) class DummyRoute(object): diff --git a/tests/test_util.py b/tests/test_util.py index a36655f6f..84bc9379f 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -1,5 +1,6 @@ +import sys import unittest -from pyramid.compat import PY2, text_, bytes_ +from pyramid.util import text_, bytes_ class Test_InstancePropertyHelper(unittest.TestCase): @@ -170,14 +171,10 @@ class Test_InstancePropertyHelper(unittest.TestCase): self.assertEqual(2, foo.y) def test_make_property_unicode(self): - from pyramid.compat import text_ from pyramid.exceptions import ConfigurationError cls = self._getTargetClass() - if PY2: - name = text_(b'La Pe\xc3\xb1a', 'utf-8') - else: - name = b'La Pe\xc3\xb1a' + name = b'La Pe\xc3\xb1a' def make_bad_name(): cls.make_property(lambda x: 1, name=name, reify=True) @@ -439,37 +436,11 @@ class Test_strings_differ(unittest.TestCase): self.assertFalse(self._callFUT('123', '123')) self.assertTrue(self._callFUT('123', '1234')) - def test_it_with_internal_comparator(self): - result = self._callFUT(b'foo', b'foo', compare_digest=None) - self.assertFalse(result) - - result = self._callFUT(b'123', b'abc', compare_digest=None) - self.assertTrue(result) - - def test_it_with_external_comparator(self): - class DummyComparator(object): - called = False - - def __init__(self, ret_val): - self.ret_val = ret_val - - def __call__(self, a, b): - self.called = True - return self.ret_val - - dummy_compare = DummyComparator(True) - result = self._callFUT(b'foo', b'foo', compare_digest=dummy_compare) - self.assertTrue(dummy_compare.called) + def test_it(self): + result = self._callFUT(b'foo', b'foo') self.assertFalse(result) - dummy_compare = DummyComparator(False) - result = self._callFUT(b'123', b'345', compare_digest=dummy_compare) - self.assertTrue(dummy_compare.called) - self.assertTrue(result) - - dummy_compare = DummyComparator(False) - result = self._callFUT(b'abc', b'abc', compare_digest=dummy_compare) - self.assertTrue(dummy_compare.called) + result = self._callFUT(b'123', b'abc') self.assertTrue(result) @@ -498,10 +469,7 @@ class Test_object_description(unittest.TestCase): self.assertEqual(self._callFUT(('a', 'b')), "('a', 'b')") def test_set(self): - if PY2: - self.assertEqual(self._callFUT(set(['a'])), "set(['a'])") - else: - self.assertEqual(self._callFUT(set(['a'])), "{'a'}") + self.assertEqual(self._callFUT(set(['a'])), "{'a'}") def test_list(self): self.assertEqual(self._callFUT(['a']), "['a']") @@ -839,31 +807,26 @@ class TestSentinel(unittest.TestCase): class TestCallableName(unittest.TestCase): - def test_valid_ascii(self): + def _callFUT(self, val): from pyramid.util import get_callable_name - from pyramid.compat import text_ - if PY2: - name = text_(b'hello world', 'utf-8') - else: - name = b'hello world' + return get_callable_name(val) - self.assertEqual(get_callable_name(name), 'hello world') + def test_valid_ascii_bytes(self): + name = b'hello world' + self.assertEqual(self._callFUT(name), 'hello world') - def test_invalid_ascii(self): - from pyramid.util import get_callable_name - from pyramid.compat import text_ + def test_valid_ascii_string(self): from pyramid.exceptions import ConfigurationError - def get_bad_name(): - if PY2: - name = text_(b'La Pe\xc3\xb1a', 'utf-8') - else: - name = b'La Pe\xc3\xb1a' + name = b'La Pe\xc3\xb1a'.decode('utf-8') + self.assertRaises(ConfigurationError, self._callFUT, name) - get_callable_name(name) + def test_invalid_ascii(self): + from pyramid.exceptions import ConfigurationError - self.assertRaises(ConfigurationError, get_bad_name) + name = b'La Pe\xc3\xb1a' + self.assertRaises(ConfigurationError, self._callFUT, name) class Test_hide_attrs(unittest.TestCase): @@ -1240,3 +1203,77 @@ class TestSimpleSerializer(unittest.TestCase): def test_dumps(self): inst = self._makeOne() self.assertEqual(inst.dumps('abc'), bytes_('abc')) + + +class TestUnboundMethods(unittest.TestCase): + class Dummy(object): + def run(self): # pragma: no cover + return 'OK' + + def _callFUT(self, val): + from pyramid.util import is_unbound_method + + return is_unbound_method(val) + + def test_bound_method(self): + self.assertFalse(self._callFUT(self.Dummy().run)) + + def test_unbound_method(self): + self.assertTrue(self._callFUT(self.Dummy.run)) + + def test_normal_func_unbound(self): + def func(): # pragma: no cover + return 'OK' + + self.assertFalse(self._callFUT(func)) + + +class TestReraise(unittest.TestCase): + def _callFUT(self, *args): + from pyramid.util import reraise + + return reraise(*args) + + def test_it(self): + # tests cribbed from six.py + def get_next(tb): + return tb.tb_next.tb_next.tb_next + + e = Exception('blah') + try: + raise e + except Exception: + tp, val, tb = sys.exc_info() + + try: + self._callFUT(tp, val, tb) + except Exception: + tp2, val2, tb2 = sys.exc_info() + self.assertIs(tp2, Exception) + self.assertIs(val2, e) + self.assertIs(get_next(tb2), tb) + + try: + self._callFUT(tp, val) + except Exception: + tp2, val2, tb2 = sys.exc_info() + self.assertIs(tp2, Exception) + self.assertIs(val2, e) + self.assertIsNot(get_next(tb2), tb) + + try: + self._callFUT(tp, val, tb2) + except Exception: + tp2, val2, tb3 = sys.exc_info() + self.assertIs(tp2, Exception) + self.assertIs(val2, e) + self.assertIs(get_next(tb3), tb2) + + try: + self._callFUT(tp, None, tb) + except Exception: + tp2, val2, tb2 = sys.exc_info() + self.assertIs(tp2, Exception) + self.assertIsNot(val2, val) + self.assertIsInstance(val2, Exception) + self.assertIs(get_next(tb2), tb) diff --git a/tests/test_view.py b/tests/test_view.py index f82480169..de40df1d5 100644 --- a/tests/test_view.py +++ b/tests/test_view.py @@ -417,12 +417,11 @@ class RenderViewToIterableTests(BaseTest, unittest.TestCase): from pyramid.request import Request from pyramid.config import Configurator from pyramid.view import render_view - from webob.compat import text_type config = Configurator(settings={}) def view(request): - request.response.text = text_type('<body></body>') + request.response.text = '<body></body>' return request.response config.add_view(name='test', view=view) |
