【问题标题】:How to set the _dont_enforce_csrf_checks using the django test client如何使用 django 测试客户端设置 _dont_enforce_csrf_checks
【发布时间】:2013-02-04 14:12:07
【问题描述】:

我正在尝试使用 django 测试客户端在更高级别的集成测试期间强制执行 csrf 检查,但我不确定如何手动翻转此位(在调用客户端之前)

这是我目前失败的情况(我得到的是 201 而不是下面的 403)

def test_should_get_403_when_csrf_enforced(self):
    self.client.enforce_csrf_checks=False
    response = self.client.post(url, {'name': 'foobar'})
    self.assertEqual(403, response.status_code)

【问题讨论】:

    标签: python django csrf


    【解决方案1】:

    我最终得到了这个解决方案,首先你必须设置 csrf 令牌,然后你需要在手动新建客户端时翻转 enforce_csrf_check

    def test_should_get_403_when_csrf_enforced(self):
        self.client = test.Client(enforce_csrf_checks=True)
        self.client.cookies[settings.CSRF_COOKIE_NAME] = 'asdf'                                                  
        response = self.client.post(url, {'name': 'foobar'})
        self.assertEqual(403, response.status_code)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 2018-10-12
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      相关资源
      最近更新 更多