sqlalchemy-jsonapi
sqlalchemy-jsonapi copied to clipboard
Post_collection is not raising BadRequestError when payload relationships data is not array of dictionaries
It is very important that the library is able to return some sort of response that let's the user know they submitted an invalid request by raising a BadRequestError and returning a 400 and some sort of description explaining why.
Through testing post_collection, I found that we are not raising a BadRequestError when we send a payload where the relationships data is not an array of dictionaries.
For example:
def test_add_resource_when_relationships_data_has_invalid_format(self):
"""Create resource when relationships data is not an array of dictionaries returns 400.
A BadRequestError is raised.
"""
payload = {
'data': {
'attributes': {
'first': 'Sally',
'last': 'Smith',
'username': 'SallySmith1',
'password': 'password',
},
'type': 'users',
'relationships': {
'posts': {
'data': ['foo']
}
}
}
}
with self.assertRaises(errors.BadRequestError) as error:
models.serializer.post_collection(
self.session, payload, 'users')
self.assertEqual(
error.exception.detail, 'posts data must be an array of objects')
self.assertEqual(error.exception.status_code, 400)
This test fails because there is no check for this in place in post_collection. Thus when I try to run this test a AttributeError occurs. Specifically the AttributeError is occuring because we are failing to check
if not isinstance(item, dict):
raise BadRequestError('{} data must be an array of objects'.format(api_key))
at the beginning of the for loop below:
for item in data_rel:
if not {'type', 'id'} in set(item.keys()):
raise BadRequestError(
'{} must have type and id keys'.format(key))
Because we do not have this check a AttributeError occurs because the item does not have any keys when trying to execute item.keys().
This is an easy fix that would provide an informative error message to users who send badly formatted payloads.