简体   繁体   中英

Is it possible to test a REST API against documentation in Django?

I develop a RESTful API server using Django REST Framework, and while the app matures, entity signatures sometimes change.

While writing tests for this app, I began to wonder if there are tools to check that API returns data as stated in documentation, ie User entity contains all the required fields etc.

I know that there are API auto-documenting tools like django-rest-swagger and others, and maybe there is some tool that helps asserting that data returned to user has same signature as in documentation?

Why won't you test it with simple unit tests? I assume that you have your API urls mapped properly to Django'u url_patterns.

Then you can simply unit test them with Django REST Framework Test Cases

Here is a code snippet: from rest_framework.test import APITestCase

class InboxNotificationForPlayerViewTest(APITestCase):
    def test_returns_delivered_inbox_notifications(self):
        """..."""
        response = self.client.get(reverse(
            'notifications-api:inbox-for-player', kwargs={'player_id': self.subscriber.player_id}
        ))

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertItemsEqual(response.data, {
            'count': 3,
            'not_read': 2,
            'notifications': {
                'read': [
                    inbox_payload(classic),
                    inbox_payload(without_window)
                ],
                'not_read': [
                    inbox_payload(read)
                ]
            }
        })

I know that it is possibly quite long solution but I'm sure that it will help you in future development. Note that every change in response data format will be tracked per test-launch.

There are dedicated tools for API documentation (ie Swagger: http://swagger.io/ ). You can also google for "API contracting".

You can validate your server against API spec using DREDD ( http://dredd.readthedocs.io/en/latest/ ).

Bonus article: https://blog.codeship.com/api-documentation-when-preferences-matter/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM