Skip to content

Commit

Permalink
Validate resources before going to MongoEngine.
Browse files Browse the repository at this point in the history
  • Loading branch information
mitar committed May 15, 2012
1 parent 111207a commit c9bedc3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
11 changes: 9 additions & 2 deletions tastypie_mongoengine/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,15 @@ def full_hydrate(self, bundle):
if getattr(bundle.obj, field_object.attribute, None) is None: # False could be good
raise tastypie_exceptions.ApiFieldError("The '%s' field has no data and doesn't allow a default or null value." % field_object.instance_name)

# We validate MongoEngine object here so that possible exception
# is thrown before going to MongoEngine layer, wrapped in
# Django exception so that it is handled properly
# is_valid method is too early as bundle.obj is not yet ready then
try:
bundle.obj.validate()
except mongoengine.ValidationError, e:
raise exceptions.ValidationError(e.message)

return bundle

def build_schema(self):
Expand Down Expand Up @@ -370,8 +379,6 @@ def get_fields(self, fields=None, excludes=None):
final_fields[name] = api_field_class(**kwargs)
final_fields[name].instance_name = name

# TODO: What about MongoEngine custom validation methods for fields?

return final_fields

class MongoEngineListResource(MongoEngineResource):
Expand Down
9 changes: 9 additions & 0 deletions tests/test_project/test_app/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ def getUri(self, location):
def test_creating_content(self):
response = self.c.post(self.makeUrl('person'), '{"name": "Person 1"}', content_type='application/json')
self.assertEqual(response.status_code, 201)

response = self.c.post(self.makeUrl('person'), '{"name": null}', content_type='application/json')
self.assertContains(response, 'field has no data', status_code=400)

response = self.c.post(self.makeUrl('person'), '{"name": []}', content_type='application/json')
self.assertContains(response, 'only accepts string values', status_code=400)

response = self.c.post(self.makeUrl('person'), '{"name": {}}', content_type='application/json')
self.assertContains(response, 'only accepts string values', status_code=400)

response = self.c.post(self.makeUrl('person'), '{"name": "Person 2"}', content_type='application/json')
self.assertEqual(response.status_code, 201)
Expand Down

0 comments on commit c9bedc3

Please sign in to comment.