Skip to content

Commit

Permalink
Merge pull request #374 from Cornices/99-check-errors-location
Browse files Browse the repository at this point in the history
Only accept known locations in request.errors.add() (fixes #99)
  • Loading branch information
leplatrem authored Oct 19, 2016
2 parents ad28352 + 86b9813 commit b99e186
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Breaking changes

- Get rid of Buildout files (#369)
- Errors list ``request.errors`` has no ``request`` anymore (fixes #328)
- ``request.errors.add()`` now only accepts one of ``header``, ``body``, ``url``,
``path``, ``querystring``, ``cookies`` or ``method`` as first argument (fixes #99)

Bug fixes

Expand Down
5 changes: 5 additions & 0 deletions cornice/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ def __init__(self, status=400):

def add(self, location, name=None, description=None, **kw):
"""Registers a new error."""
allowed = ('body', 'querystring', 'url', 'header', 'path',
'cookies', 'method')
if location != '' and location not in allowed:
raise ValueError('%r not in %s' % (location, allowed))

self.append(dict(
location=location,
name=name,
Expand Down
23 changes: 23 additions & 0 deletions cornice/tests/test_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from cornice.tests.support import TestCase

from cornice.errors import Errors


class TestErrorsHelper(TestCase):
def setUp(self):
self.errors = Errors()

def test_add_to_supported_location(self):
self.errors.add('')
self.errors.add('body', description='!')
self.errors.add('querystring', name='field')
self.errors.add('url')
self.errors.add('header')
self.errors.add('path')
self.errors.add('cookies')
self.errors.add('method')
self.assertEqual(len(self.errors), 8)

def test_raises_an_exception_when_location_is_unsupported(self):
with self.assertRaises(ValueError):
self.errors.add('something')
2 changes: 1 addition & 1 deletion docs/source/validation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ This means something like this::
def validate_it(self, request, **kw):
# pseudo-code validation logic
if whatever is wrong:
request.errors.add('something')
request.errors.add('body', description="Something is wrong")

@service.get(klass=MyClass, validators=('validate_it',))
def view(request):
Expand Down

0 comments on commit b99e186

Please sign in to comment.