Skip to content

Commit

Permalink
Merge pull request #423 from Cornices/105-current-service
Browse files Browse the repository at this point in the history
Add a request.current_service attribute (fixes #105)
  • Loading branch information
leplatrem committed Dec 15, 2016
2 parents 85ce171 + 57bc447 commit 519e480
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 11 deletions.
6 changes: 2 additions & 4 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,15 @@ CHANGELOG

- Add support for validation with specific JSON Content-Types
(i.e application/merge-patch+json).
- Add ``X-Content-Type-Options: nosniff`` headers to responses (fixes #102)
- Add a ``request.current_service`` attribute (fixes #105)

**Bug fixes**

- Fix ``cornice.cors.get_cors_preflight_view`` to make it parse
`Access-Control-Request-Headers` header correctly event if its value
contains zero number of white spaces between commas (#422)

**Enhancements**

- Add ``X-Content-Type-Options: nosniff`` headers to responses (fixes #102)

**Internal changes**

- Clean-up an inconsistency in ``cornice.service.decorate_view()`` function
Expand Down
3 changes: 2 additions & 1 deletion cornice/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
handle_exceptions,
register_resource_views,
)
from cornice.util import ContentTypePredicate
from cornice.util import ContentTypePredicate, current_service
from pyramid.events import NewRequest
from pyramid.httpexceptions import HTTPNotFound, HTTPForbidden
from pyramid.security import NO_PERMISSION_REQUIRED
Expand Down Expand Up @@ -79,6 +79,7 @@ def includeme(config):
config.add_subscriber(wrap_request, NewRequest)
config.add_renderer('simplejson', util.json_renderer)
config.add_view_predicate('content_type', ContentTypePredicate)
config.add_request_method(current_service, reify=True)

settings = config.get_settings()
if asbool(settings.get('handle_exceptions', True)):
Expand Down
17 changes: 17 additions & 0 deletions cornice/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,20 @@ def func_name(f):
return '{0}.{1}'.format(f.im_class.__name__, f.__name__) # Python 2
else: # pragma: no cover
return f.__name__ # Python 2


def current_service(request):
"""Return the Cornice service matching the specified request.
:returns: the service or None if unmatched.
:rtype: cornice.Service
"""
if request.matched_route:
services = request.registry.cornice_services
pattern = request.matched_route.pattern
try:
service = services[pattern]
except KeyError:
return None
else:
return service
22 changes: 16 additions & 6 deletions tests/test_pyramidhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,20 @@ def test_no_sniff_is_added_to_responses(self):
self.assertEqual(response.headers['X-Content-Type-Options'], 'nosniff')


test_service = Service(name="jardinet", path="/jardinet", traverse="/jardinet")
test_service.add_view('GET', lambda _:_)
test_service = Service(name="jardinet", path="/jardinet", traverse='/')
test_service.add_view('GET', lambda request: request.current_service.name)


class TestCurrentService(TestCase):
def setUp(self):
self.config = testing.setUp()
self.config.include("cornice")
self.config.scan("tests.test_pyramidhook")
self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

def test_current_service_on_request(self):
resp = self.app.get("/jardinet")
self.assertEqual(resp.json, "jardinet")


class TestRouteWithTraverse(TestCase):
Expand All @@ -229,10 +241,8 @@ def test_route_construction(self):
config.add_route = mock.MagicMock()

register_service_views(config, test_service)
self.assertTrue(
('traverse', '/jardinet'),
config.add_route.called_args,
)
config.add_route.assert_called_with('jardinet', '/jardinet',
traverse='/')

def test_route_with_prefix(self):
config = testing.setUp(settings={})
Expand Down
17 changes: 17 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,20 @@ def test_extract_form_urlencoded_data_is_deprecated(self):
with mock.patch('cornice.util.warnings') as mocked:
util.extract_form_urlencoded_data(mock.MagicMock())
self.assertTrue(mocked.warn.called)


class CurrentServiceTest(unittest.TestCase):

def test_current_service_returns_the_service_for_existing_patterns(self):
request = mock.MagicMock()
request.matched_route.pattern = '/buckets'
request.registry.cornice_services = {'/buckets': mock.sentinel.service}

self.assertEqual(util.current_service(request), mock.sentinel.service)

def test_current_service_returns_none_for_unexisting_patterns(self):
request = mock.MagicMock()
request.matched_route.pattern = '/unexisting'
request.registry.cornice_services = {}

self.assertEqual(util.current_service(request), None)

0 comments on commit 519e480

Please sign in to comment.