Permalink
Browse files

De-BFGify the master, update version to appropriate 1.1, setup approp…

…riate dependencies. Fix tests.
  • Loading branch information...
1 parent 2fb4d52 commit f79b141ccfcda10789d0f37d53842b102d188764 @bbangert bbangert committed Oct 12, 2011
Showing with 81 additions and 308 deletions.
  1. +4 −0 .gitignore
  2. +10 −76 pylons/controllers/util.py
  3. +1 −3 pylons/templating.py
  4. +7 −7 setup.py
  5. +59 −111 tests/test_units/test_controller.py
  6. +0 −104 tests/test_units/test_url.py
  7. +0 −7 tests/test_units/test_util.py
View
4 .gitignore
@@ -0,0 +1,4 @@
+*.pyc
+*.egg-info
+tests/test_units/cache/
+tests/test_units/session/
View
86 pylons/controllers/util.py
@@ -20,99 +20,35 @@
import re
try:
import cPickle as pickle
-except ImportError: # pragma: no cover
+except ImportError:
import pickle
try:
from hashlib import sha1
-except ImportError: # pragma: no cover
+except ImportError:
import sha as sha1
-from beaker.session import SessionObject
-from repoze.bfg.decorator import reify
-from repoze.bfg.interfaces import ISettings
-from repoze.bfg.request import Request as RepozeBFGRequest
+from webob import Request as WebObRequest
from webob import Response as WebObResponse
from webob.exc import status_map
import pylons
-from pylons.util import PylonsContext
-__all__ = ['abort', 'etag_cache', 'redirect', 'Request', 'Response']
+__all__ = ['abort', 'etag_cache', 'redirect', 'redirect_to', 'Request',
+ 'Response']
log = logging.getLogger(__name__)
IF_NONE_MATCH = re.compile('(?:W/)?(?:"([^"]*)",?\s*)')
-class Request(RepozeBFGRequest):
+class Request(WebObRequest):
"""WebOb Request subclass
The WebOb :class:`webob.Request` has no charset, or other defaults. This subclass
adds defaults, along with several methods for backwards
compatibility with paste.wsgiwrappers.WSGIRequest.
- """
- def __init__(self, *args, **kw):
- RepozeBFGRequest.__init__(self, *args, **kw)
- attrs = self.__dict__
- attrs['tmpl_context'] = PylonsContext()
-
- @reify
- def settings(self):
- return self.registry.queryUtility(ISettings)
-
- @reify
- def session(self):
- """Create and return the session object
-
- This also adds a response callback, which ensures that the
- session is written out, and the appropriate cookie's are
- set if necessary on the response object.
-
- """
- exception_abort = self.registry.session_exception
- sess_opts = self.registry.session_options
- if not sess_opts:
- raise Exception("Can't use the session without configuring sessions")
- session = SessionObject(self.environ, **sess_opts)
- def session_callback(request, response):
- exception = getattr(request, 'exception', None)
- if exception is not None and exception_abort:
- return None
- if session.accessed():
- session.persist()
- if session.__dict__['_headers']['set_cookie']:
- cookie = session.__dict__['_headers']['cookie_out']
- if cookie:
- response.headerlist.append(('Set-cookie', cookie))
- self._sess_callback = session_callback
- self.add_response_callback(session_callback)
- return session
-
- def abort_session(self):
- """Aborts a session
-
- This causes a session that was used to be removed from the
- request, and any saves that were pending will not be persisted.
- Nor will any cookie be written out indicating the session was
- accessed.
-
- Once a session is aborted, any further use of the `request.session`
- object will not result in changes being persisted, or update the
- accessed time for an existing session.
-
- """
- try:
- sess_callback = self._sess_callback
- except AttributeError:
- raise Exception("You cannot cancel a session if there was no"
- " session in use.")
- callbacks = []
- for cb in self.response_callbacks:
- if cb != sess_callback:
- callbacks.append(cb)
- self.response_callbacks = callbacks
-
+ """
def determine_browser_charset(self):
"""Legacy method to return the
:attr:`webob.Request.accept_charset`"""
@@ -180,9 +116,6 @@ def has_header(self, header):
def get_content(self):
return self.body
- def write(self, content):
- self.body_file.write(content)
-
def wsgi_response(self):
return self.status, self.headers, self.body
@@ -259,8 +192,9 @@ def forward(wsgi_app):
def abort(status_code=None, detail="", headers=None, comment=None):
"""Aborts the request immediately by returning an HTTP exception
- For 300 series, a headers dict will need to be supplied with the
- appropriate 'Location' set for the redirect.
+ In the event that the status_code is a 300 series error, the detail
+ attribute will be used as the Location header should one not be
+ specified in the headers attribute.
"""
exc = status_map[status_code](detail=detail, headers=headers,
View
4 pylons/templating.py
@@ -103,13 +103,11 @@ def index(self):
"""
import logging
-from repoze.bfg.renderers import render
-from repoze.bfg.renderers import render_to_response
from webhelpers.html import literal
import pylons
-__all__ = ['render_genshi', 'render_jinja2', 'render_mako', 'render_to_response', 'render']
+__all__ = ['render_genshi', 'render_jinja2', 'render_mako', 'render_response']
PYLONS_VARS = ['c', 'app_globals', 'config', 'h', 'render', 'request',
'session', 'translator', 'ungettext', '_', 'N_']
View
14 setup.py
@@ -7,7 +7,7 @@
use_setuptools()
from setuptools import setup, find_packages
-version = '1.2'
+version = '1.1'
tests_require = ['nose', 'Jinja2>=2.2.1']
if not sys.platform.startswith('java'):
@@ -113,12 +113,12 @@ def index(self):
test_suite='nose.collector',
tests_require=tests_require,
install_requires=[
- "Routes>=1.12", "WebHelpers>=0.6.4", "Beaker>=1.3",
- "Paste>=1.7.2", "PasteDeploy>=1.3.3", "PasteScript>=1.7.3",
- "FormEncode>=1.2.1", "simplejson>=2.0.8", "decorator>=2.3.2",
- "nose>=0.10.4", "Mako>=0.3.4", "WebError>=0.10.1",
- "WebTest>=1.1", "Tempita>=0.2", "MarkupSafe>=0.11",
- "repoze.bfg >= 1.3a15", "repoze.bfg.mako>=0.3"
+ "Routes>=1.12.3", "WebHelpers>=0.6.4", "Beaker>=1.5.4",
+ "Paste>=1.7.5.1", "PasteDeploy>=1.5.0", "PasteScript>=1.7.4.2",
+ "FormEncode>=1.2.4", "simplejson>=2.2.1", "decorator>=3.3.2",
+ "nose>=1.1.2", "Mako>=0.5.0", "WebError>=0.10.1",
+ "WebTest>=1.3.1", "Tempita>=0.5.1", "MarkupSafe>=0.15",
+ "WebOb>=1.1.1",
],
dependency_links=[
"http://www.pylonshq.com/download/1.0"
View
170 tests/test_units/test_controller.py
@@ -1,97 +1,87 @@
# -*- coding: utf-8 -*-
-import unittest
-
from paste.fixture import TestApp
from paste.registry import RegistryManager
from webob.exc import status_map
-from __init__ import TestWSGIController, TestMiddleware
+import pylons
+from pylons.controllers import WSGIController
+from pylons.testutil import SetupCacheGlobal, ControllerWrap
+from __init__ import TestWSGIController, TestMiddleware
-def make_controllers():
- import pylons
- from pylons.controllers import WSGIController
-
- class BasicWSGIController(WSGIController):
- def __init__(self):
- self._pylons_log_debug = True
+class BasicWSGIController(WSGIController):
+ def __init__(self):
+ self._pylons_log_debug = True
- def __before__(self):
- pylons.response.headers['Cache-Control'] = 'private'
-
- def __after__(self):
- pylons.response.set_cookie('big_message', 'goodbye')
+ def __before__(self):
+ pylons.response.headers['Cache-Control'] = 'private'
- def index(self):
- return 'hello world'
-
- def yield_fun(self):
- def its():
- x = 0
- while x < 100:
- yield 'hi'
- x += 1
- return its()
+ def __after__(self):
+ pylons.response.set_cookie('big_message', 'goodbye')
- def strme(self):
- return "hi there"
+ def index(self):
+ return 'hello world'
+
+ def yield_fun(self):
+ def its():
+ x = 0
+ while x < 100:
+ yield 'hi'
+ x += 1
+ return its()
- def use_redirect(self):
- pylons.response.set_cookie('message', 'Hello World')
- exc = status_map[301]
- raise exc('/elsewhere').exception
+ def strme(self):
+ return "hi there"
- def use_customnotfound(self):
- exc = status_map[404]
- raise exc('Custom not found').exception
+ def use_redirect(self):
+ pylons.response.set_cookie('message', 'Hello World')
+ exc = status_map[301]
+ raise exc('/elsewhere').exception
- def header_check(self):
- pylons.response.headers['Content-Type'] = 'text/plain'
- return "Hello all!"
+ def use_customnotfound(self):
+ exc = status_map[404]
+ raise exc('Custom not found').exception
- def swallow_all(self, **kwargs):
- return "We got back %s" % kwargs
+ def header_check(self):
+ pylons.response.headers['Content-Type'] = 'text/plain'
+ return "Hello all!"
- def nothing(self):
- return
+ def nothing(self):
+ return
- def params(self):
- items = pylons.request.params.mixed().items()
- items.sort()
- return str(items)
+ def params(self):
+ items = pylons.request.params.mixed().items()
+ items.sort()
+ return str(items)
- def list(self):
- return ['from', ' a ', 'list']
+ def list(self):
+ return ['from', ' a ', 'list']
- class FilteredWSGIController(WSGIController):
- def __init__(self):
- self.before = 0
- self.after = 0
+class FilteredWSGIController(WSGIController):
+ def __init__(self):
+ self.before = 0
+ self.after = 0
- def __before__(self):
- self.before += 1
+ def __before__(self):
+ self.before += 1
- def __after__(self):
- self.after += 1
- action = pylons.request.environ['pylons.routes_dict'].get('action')
- if action in ('after_response', 'after_string_response'):
- pylons.response.write(' from __after__')
+ def __after__(self):
+ self.after += 1
+ action = pylons.request.environ['pylons.routes_dict'].get('action')
+ if action in ('after_response', 'after_string_response'):
+ pylons.response.write(' from __after__')
- def index(self):
- return 'hi all, before is %s' % self.before
+ def index(self):
+ return 'hi all, before is %s' % self.before
- def after_response(self):
- return 'hi'
+ def after_response(self):
+ return 'hi'
- def after_string_response(self):
- return 'hello'
-
- return BasicWSGIController, FilteredWSGIController
+ def after_string_response(self):
+ return 'hello'
class TestBasicWSGI(TestWSGIController):
def __init__(self, *args, **kargs):
- from pylons.testutil import ControllerWrap, SetupCacheGlobal
- BasicWSGIController, FilteredWSGIController = make_controllers()
TestWSGIController.__init__(self, *args, **kargs)
self.baseenviron = {}
app = ControllerWrap(BasicWSGIController)
@@ -162,7 +152,7 @@ def test_nothing(self):
assert resp.response.headers['Cache-Control'] == 'private'
def test_unicode_action(self):
- self.baseenviron['pylons.routes_dict']['action'] = u'ОбсуждениеКомпаний'
+ self.baseenviron['pylons.routes_dict']['action'] = u'ОбсуждениеКомпаний'
resp = self.app.get('/', status=404)
def test_params(self):
@@ -177,18 +167,9 @@ def test_params(self):
def test_list(self):
self.baseenviron['pylons.routes_dict']['action'] = 'list'
assert 'from a list' in self.app.get('/')
-
- def test_eat_kwargs(self):
- import pylons
- pylons.config['pylons.tmpl_context_attach_args'] = True
- self.baseenviron['pylons.routes_dict']['action'] = 'swallow_all'
- assert "We got back {'action': 'swallow_all'," in self.app.get('/')
-
class TestFilteredWSGI(TestWSGIController):
def __init__(self, *args, **kargs):
- from pylons.testutil import ControllerWrap, SetupCacheGlobal
- BasicWSGIController, FilteredWSGIController = make_controllers()
TestWSGIController.__init__(self, *args, **kargs)
self.baseenviron = {}
app = ControllerWrap(FilteredWSGIController)
@@ -216,36 +197,3 @@ def test_after_string_response(self):
def test_start_response(self):
self.baseenviron['pylons.routes_dict']['action'] = 'start_response'
self.app.get('/', status=404)
-
-class TestBeforeAfterAsCallables(TestWSGIController):
- def __init__(self, *args, **kargs):
- TestWSGIController.__init__(self, *args, **kargs)
-
- class Callable(object):
- def __init__(self): self.called = False
- def __call__(self, *args, **kargs): self.called = True
-
- self.before_callable = Callable()
- self.after_callable = Callable()
-
- from pylons.controllers import WSGIController
- class Controller(WSGIController):
- def index(self): return 'index'
- __before__ = self.before_callable
- __after__ = self.after_callable
-
- from pylons.testutil import ControllerWrap, SetupCacheGlobal
- self.baseenviron = {}
- app = ControllerWrap(Controller)
- app = self.sap = SetupCacheGlobal(app, self.baseenviron)
- app = RegistryManager(app)
- self.app = TestApp(app)
-
- def test_after_called(self):
- self.get_response(action='index')
- assert self.after_callable.called
-
- def test_before_called(self):
- self.get_response(action='index')
- assert self.before_callable.called
-
View
104 tests/test_units/test_url.py
@@ -1,104 +0,0 @@
-import unittest
-
-from repoze.bfg.testing import cleanUp
-
-
-class TestRouteUrl(unittest.TestCase):
- def setUp(self):
- cleanUp()
-
- def tearDown(self):
- cleanUp()
-
- def _callFUT(self, *arg, **kw):
- from pylons.url import route_url
- return route_url(*arg, **kw)
-
- def test_with_elements(self):
- from repoze.bfg.interfaces import IRoutesMapper
- request = _makeRequest()
- mapper = DummyRoutesMapper(result='/1/2/3')
- request.registry.registerUtility(mapper, IRoutesMapper)
- result = self._callFUT('flub', request, 'extra1', 'extra2',
- a=1, b=2, c=3, _query={'a':1},
- _anchor=u"foo")
- self.assertEqual(result,
- 'http://example.com:5432/1/2/3/extra1/extra2?a=1#foo')
-
- def test_no_elements(self):
- from repoze.bfg.interfaces import IRoutesMapper
- request = _makeRequest()
- mapper = DummyRoutesMapper(result='/1/2/3')
- request.registry.registerUtility(mapper, IRoutesMapper)
- result = self._callFUT('flub', request, a=1, b=2, c=3, _query={'a':1},
- _anchor=u"foo")
- self.assertEqual(result,
- 'http://example.com:5432/1/2/3?a=1#foo')
-
- def test_it_generation_error(self):
- from repoze.bfg.interfaces import IRoutesMapper
- request = _makeRequest()
- mapper = DummyRoutesMapper(raise_exc=KeyError)
- request.registry.registerUtility(mapper, IRoutesMapper)
- mapper.raise_exc = KeyError
- self.assertRaises(KeyError, self._callFUT, 'flub', request, a=1)
-
- def test_generate_doesnt_receive_query_or_anchor(self):
- from repoze.bfg.interfaces import IRoutesMapper
- mapper = DummyRoutesMapper(result='')
- from zope.component import getSiteManager
- sm = getSiteManager()
- sm.registerUtility(mapper, IRoutesMapper)
- request = DummyRequest()
- result = self._callFUT('flub', request, _query=dict(name='some_name'))
- self.assertEqual(mapper.kw, {}) # shouldnt have anchor/query
- self.assertEqual(result, 'http://example.com:5432?name=some_name')
-
- def test_with_app_url(self):
- from repoze.bfg.interfaces import IRoutesMapper
- request = _makeRequest()
- mapper = DummyRoutesMapper(result='/1/2/3')
- request.registry.registerUtility(mapper, IRoutesMapper)
- result = self._callFUT('flub', request, _app_url='http://example2.com')
- self.assertEqual(result, 'http://example2.com/1/2/3')
-
- def test_custom_url_gen(self):
- from repoze.bfg.interfaces import IRoutesMapper
- request = _makeRequest()
- mapper = DummyRoutesMapper(result='/smith', routes={'flub': DummyRoute})
- request.registry.registerUtility(mapper, IRoutesMapper)
- result = self._callFUT('flub', request, a=1, b=2, c=3, _query={'a':1})
- self.assertEqual(result, 'http://example.com:5432/smith')
-
-
-
-class DummyRequest:
- application_url = 'http://example.com:5432' # app_url never ends with slash
- def __init__(self, environ=None):
- if environ is None:
- environ = {}
- self.environ = environ
-
-class DummyRoutesMapper:
- raise_exc = None
- def __init__(self, result='/1/2/3', raise_exc=False, routes={}):
- self.result = result
- self.routes = routes
-
- def generate(self, *route_args, **kw):
- self.kw = kw
- if self.raise_exc:
- raise self.raise_exc
- return self.result
-
-class DummyRoute:
- @staticmethod
- def custom_url_generator(route_name, request, *elements, **kw):
- return route_name, request, [], {}
-
-
-def _makeRequest(environ=None):
- from repoze.bfg.registry import Registry
- request = DummyRequest(environ)
- request.registry = Registry()
- return request
View
7 tests/test_units/test_util.py
@@ -1,7 +0,0 @@
-import unittest
-
-class Test_resolve_dotted(unittest.TestCase):
- def test_it(self):
- from pylons.util import resolve_dotted
- result = resolve_dotted('pylons.util:resolve_dotted')
- self.failUnless(result is resolve_dotted)

0 comments on commit f79b141

Please sign in to comment.