【问题标题】:Is it possible to test a REST API against documentation in Django?是否可以针对 Django 中的文档测试 REST API?
【发布时间】:2016-09-25 10:45:43
【问题描述】:

我使用 Django REST Framework 开发了一个 RESTful API 服务器,当应用成熟时,实体签名有时会发生变化。

在为这个应用程序编写测试时,我开始怀疑是否有工具可以检查 API 是否返回文档中所述的数据,即用户实体包含所有必需的字段等。

我知道有 API 自动记录工具,例如 django-rest-swagger 等,也许有一些工具可以帮助断言返回给用户的数据与文档中的签名相同?

【问题讨论】:

    标签: python django rest testing


    【解决方案1】:

    有用于 API 文档的专用工具(即 Swagger:http://swagger.io/)。您也可以在 Google 上搜索“API 合同”。

    您可以使用 DREDD (http://dredd.readthedocs.io/en/latest/) 根据 API 规范验证您的服务器。

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

    【讨论】:

      【解决方案2】:

      你为什么不用简单的单元测试来测试它? 我假设您已将 API url 正确映射到 Django'u url_patterns。

      然后您可以使用 Django REST Framework Test Cases 简单地对它们进行单元测试

      这是一个代码sn-p: 从 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)
                      ]
                  }
              })
      

      我知道这可能是一个很长的解决方案,但我相信它会在未来的开发中帮助您。请注意,每次测试启动都会跟踪响应数据格式的每次更改。

      【讨论】:

      • 此解决方案并不能消除问题 - 文档可以更改,而测试不会注意到这一点。完整的规范必须存储在某个地方,并且是 API 测试的唯一真实来源
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      相关资源
      最近更新 更多