Skip to content

Commit

Permalink
Improve serializer bad relationship error
Browse files Browse the repository at this point in the history
Fixes a possible string formatting error in the error clause
  • Loading branch information
duk3luk3 committed Jan 8, 2018
1 parent fe9d6f2 commit 6defe78
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
14 changes: 10 additions & 4 deletions sqlalchemy_jsonapi/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ class Permissions(Enum):
EDIT = 102
DELETE = 103

class MissingKey:
def __init__(self, elem):
self.elem = elem

def __repr__(self):
return '<{} elem={}>'.format(self.__class__.__name__, self.elem)

ALL_PERMISSIONS = {
Permissions.VIEW, Permissions.CREATE, Permissions.EDIT, Permissions.DELETE
Expand Down Expand Up @@ -980,15 +986,15 @@ def post_collection(self, session, data, api_type):
data['data'].setdefault('attributes', {})

data_keys = set(map((
lambda x: resource.__jsonapi_map_to_py__.get(x, None)),
lambda x: resource.__jsonapi_map_to_py__.get(x, MissingKey(x))),
data['data'].get('relationships', {}).keys()))
model_keys = set(resource.__mapper__.relationships.keys())
if not data_keys <= model_keys:
data_keys = set([key.elem if isinstance(key, MissingKey) else key for key in data_keys])
# pragma: no cover
raise BadRequestError(
'{} not relationships for {}'.format(
', '.join(list(data_keys -
model_keys)), model.__jsonapi_type__))
'{} not relationships for {}'.format(
', '.join([repr(key) for key in list(data_keys - model_keys)]), model.__jsonapi_type__))

attrs_to_ignore = {'__mapper__', 'id'}

Expand Down
27 changes: 26 additions & 1 deletion sqlalchemy_jsonapi/tests/test_collection_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from sqlalchemy_jsonapi.errors import (
InvalidTypeForEndpointError, MissingTypeError, PermissionDeniedError,
ValidationError, MissingContentTypeError)
ValidationError, MissingContentTypeError, BadRequestError)
from faker import Faker

fake = Faker()
Expand Down Expand Up @@ -183,3 +183,28 @@ def test_409_for_wrong_field_name(client):
'/api/users/', data=json.dumps(payload),
content_type='application/vnd.api+json').validate(
409, ValidationError)


def test_400_for_unknown_relationship_type(user, client):
payload = {
'data': {
'type': 'blog-posts',
'attributes': {
'title': 'Some title',
'content': 'Hello, World!',
'is-published': True
},
'relationships': {
'bogon': {
'data': {
'type': 'users',
'id': str(user.id)
}
}
}
}
}
client.post(
'/api/blog-posts/', data=json.dumps(payload),
content_type='application/vnd.api+json').validate(
400, BadRequestError)

0 comments on commit 6defe78

Please sign in to comment.