Django:在测试客户端上设置Cookie? [英] Django: set cookie on test client?

查看:42
本文介绍了Django:在测试客户端上设置Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Django站点设置了一些中间件,这些中间件可在每次请求时检查cookie,如果未设置,则将用户转发到其他地方.

My Django site is set up with some middleware that on each request, checks for a cookie, and if it is not set, forwards the user elsewhere.

我现在想在该站点上运行一些测试.这是我的代码:

I now want to run some tests on the site. This is my code:

def test_contactform(self):
    response = self.client.get('/contact/')
    self.assertEqual(response.status_code, 200)
    print response
    self.assertTrue('Contact me' in response.content)

不幸的是,这失败并显示:

Unfortunately, this fails with:

Vary: Cookie
Content-Type: text/html; charset=utf-8
Location: http://testserver/ldap/?next=/contact/
Traceback (most recent call last):
  File "tests.py", line 43, in test_contactform
    self.assertEqual(response.status_code, 200)
AssertionError: 302 != 200

我可以(i)在Django测试客户端上设置cookie(如果可以的话)还是(ii)要求Django测试客户端遵循重定向并针对最终页面进行测试?

Can I either (i) set a cookie on the Django test client (and if so how) or (ii) require the Django test client to follow the redirect and test against the final page?

推荐答案

client.get 方法采用 follow 参数,该参数允许其遵循重定向:

The client.get method takes a follow argument which allows it to follow redirects:

response = self.client.get('/contact/', follow=True)

这篇关于Django:在测试客户端上设置Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆