【问题标题】:Django: Checking content type of response in testsDjango:在测试中检查响应的内容类型
【发布时间】:2019-06-02 09:23:52
【问题描述】:

我有 Django 视图,它返回内容类型为“application/json”的 HTTPResponse。在我的测试中,我想验证是否设置了预期的内容类型。

docs,我看到一个HTTPResponse 我可以传递的content_type 有一个参数,把它作为一个属性没有得到。这是为什么呢?

在我的 views.py 中,我构建并发送一个 HTTPResponse,如下所示:

j = json.dumps(j)
return HttpResponse(j, content_type='application/json')

在我的tests.py 中,我想做类似的事情

self.assertEqual(response.content_type, 'application/json')

但是如果没有 HTTPResponse 对象的属性,那当然会失败,AttributeError: 'HttpResponse' object has no attribute 'content_type'

如何在 Django 中获取响应的内容类型?对 HTTP 的工作方式有误解吗?

【问题讨论】:

  • 运行print(dir(response)) 看看有没有content_type 属性
  • 感谢您的提示!我不知道这种可能性,查看所有属性帮助我解决了问题!

标签: django testing content-type


【解决方案1】:

最简单的方法是response['content-type'],在您的情况下将返回'application/json'。所以要测试你会使用:

self.assertEqual(response['content-type'], 'application/json')

【讨论】:

    【解决方案2】:

    Django 的doc HttpResponse 提到:

    HttpResponse.__getitem__(header)
    返回给定标头名称的值。不区分大小写。

    此 MDN doc 提到,在 HTTP 响应中,内容类型是名称为 Content-Type 的标头。

    所以下面的代码返回了 Django HttpResponse 的内容类型:

    response.__getitem__('Content-Type')
    

    这可以在 Django 测试中用于断言 Content Type 具有特定值,例如断言 HttpResponse 的 Content Type 是 application/json

    self.assertEqual(response.__getitem__('content-type'), 'application/json')
    

    【讨论】:

    • 你能解释一下你的代码到底做了什么吗?这样,遇到这个问题的其他人就有机会自己解决类似的问题。
    • response['content-type'] 似乎与 response.__getitem__('content-type') "under te hood" 相同。使用第一个执行第二个。
    【解决方案3】:

    事实证明,Django 中的 HTTPResponse 对象有一个 _content_type_for_repr 属性。 这是它包含的内容(对我来说):

    print(response._content_type_for_repr)
    , "application/json"
    

    我不知道为什么它是这种格式,但是切片它让我得到了我想要的地方: self.assertEqual(response._content_type_for_repr[3:-1], 'application/json')

    (如果有人对此有更优雅的解决方案,请不要犹豫发布它!)

    【讨论】:

      猜你喜欢
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 1970-01-01
      • 2018-01-23
      相关资源
      最近更新 更多