ColtonProvias / sqlalchemy-jsonapi

JSONAPI implementation for use with SQLAlchemy
MIT License
70 stars 27 forks source link

Unclear error message on post_collection with OneToMany relationship #42

Open kaitj91 opened 7 years ago

kaitj91 commented 7 years ago

For background information let's look at this test:

    def test_add_resource_with_invalid_relationships(self):
        """Create resource with invalid relationship returns 400.

        A BadRequestError is raised.
        """
        payload = {
            'data': {
                'attributes': {
                    'first': 'Sally',
                    'last': 'Smith',
                    'username': 'SallySmith1',
                    'password': 'password',
                },
                'type': 'users',
                'relationships': {
                    'posts': {
                        'data': {
                            'type': 'posts',
                            'id': 1
                        }
                    }
                }
            }
        }

        with self.assertRaises(errors.BadRequestError) as error:
            models.serializer.post_collection(
                self.session, payload, 'users')

        self.assertEqual(error.exception.detail, 'posts must be an array')
        self.assertEqual(error.exception.status_code, 400)

As we can see the error message produced by the library is somewhat confusing. If we actually look at the check that is occuring it is:

                    if not isinstance(data_rel, list):
                        raise BadRequestError(
                            '{} must be an array'.format(key)

This is interesting because if we actually look at what data_rel is, it is defined as we see by this chunk of code:

                data_rel = data['data']['relationships'][api_key]
                if 'data' not in data_rel.keys():
                    raise BadRequestError(
                        'Missing data key in relationship {}'.format(key))
                data_rel = data_rel['data']

so data_rel is actually {'type': 'posts', 'id': 1}. Thus when the check to see if data_rel is a list, it is not but the detail of the BadRequestError is saying that the 'posts must be an array', since 'posts' is the key.

I believe that this detail message should be changed to say 'posts data must be an array'. This might be trivial for someone that knows jsonapi well. However, if someone were trying to simply figure out how to format their response correctly after receiving this error message it would be confusing.