简体   繁体   English

是否可以针对Django中的文档测试REST API?

[英]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. 我使用Django REST Framework开发了RESTful API服务器,并且随着应用程序的成熟,实体签名有时会发生变化。

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. 在为此应用编写测试时,我开始怀疑是否有工具可以按照文档中所述检查API是否返回数据,即用户实体包含所有必填字段等。

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? 我知道有django-rest-swagger之类的API自动文档编制工具,也许还有一些工具可以帮助断言返回给用户的数据具有与文档相同的签名?

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. 我假设您已将API网址正确映射到Django'u url_patterns。

Then you can simply unit test them with Django REST Framework Test Cases 然后,你可以简单地单元Django的REST框架对其进行测试的测试用例

Here is a code snippet: from rest_framework.test import APITestCase 这是一个代码段:从rest_framework.test导入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/ ). 有专门的API文档工具(例如Swagger: http : //swagger.io/ )。 You can also google for "API contracting". 您也可以通过Google搜索“ API合同”。

You can validate your server against API spec using DREDD ( http://dredd.readthedocs.io/en/latest/ ). 您可以使用DREDD( http://dredd.readthedocs.io/en/latest/ )根据API规范验证服务器。

Bonus article: https://blog.codeship.com/api-documentation-when-preferences-matter/ 奖励文章: https : //blog.codeship.com/api-documentation-when-preferences-matter/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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