【问题标题】:assertRaises BadRequest isn't workingassertRaises BadRequest 不起作用
【发布时间】:2016-08-10 11:33:48
【问题描述】:

我正在使用 django sweetpie 来创建我的宁静端点。所以是时候制作登录端点了,(还没有完成)。

accounts/api/resources.py

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        allowed_methods = ['post']
        serializer = Serializer(formats=['json'])

    def prepend_urls(self, *args, **kwargs):
        return [
            url(r'^(?P<resource_name>%s)/login/$' % self._meta.resource_name,
                self.wrap_view('dispatch_login'), name='api_dispatch_login')
        ]

    def dispatch_login(self, request, **kwargs):
        self.method_check(request, allowed=['post'])

        data = self._meta.serializer.from_json(request.body)  # This raises the exception.

        return self.create_response(request, {}, status=200)

accounts/tests.py

class UserApiTestCase(TestCase):
    def setUp(self):
        self.uri = reverse('api_dispatch_login', kwargs={'api_name': 'v1',
                           'resource_name': 'user'})

    def test_login_user_credentials_sent_in_body_request(self):
        with self.assertRaises(BadRequest):
            self.client.post(self.uri, content_type='application/json')

通过使用终端模拟器和 curl 使用 Web 服务,我可以看到引发了异常。

$ curl localhost:8000/api/v1/user/login/ --request POST
{"error": "Request is not valid JSON."}

但是在运行测试时,断言失败了。

FAIL: test_login_user_credentials_sent_in_body_request (accounts.tests.UserApiTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/slackmart/code/superproject/accounts/tests.py", line 29, in test_login_user_credentials_sent_in_body_request
    self.client.post(self.uri, content_type='application/json')
AssertionError: BadRequest not raised

【问题讨论】:

    标签: django tastypie restful-architecture django-testing


    【解决方案1】:

    https://github.com/django-tastypie/django-tastypie/blob/master/docs/release_notes/dev.rst

    添加了 UnsupportedSerializationFormat 和 UnsupportedDeserializationFormat 异常,这些异常被捕获并 导致 HttpNotAcceptable(406 状态)和 HttpUnsupportedMediaType (415 状态)响应,分别。以前这些相同类型的 错误将显示为 400 BadRequest 错误。

    最近对 Tastypie 进行了更改,以使其更符合 HTTP 和更具体的错误代码。您需要查找 406 或 415 状态代码,而不是 400。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多