[英]Django tests - simulate that user is logged in
In my tests I have a following bit of code: 在测试中,我有以下代码:
def setUp(self):
self.client.defaults['HTTP_AUTHORIZATION'] = 'Basic ' + base64.b64encode(
'{username}:{password}'.format(**self.login_data)
)
def test_list_view(self):
response = self.client.get(reverse('data_list'))
self.assertEqual(response.status_code, 200)
My problem is that this check has to go through basic http authentication which uses ldap and it's pretty slow. 我的问题是,此检查必须通过使用ldap的基本http身份验证,而且速度很慢。
Is there a way I can simulate that user is logged in? 有没有一种方法可以模拟该用户已登录?
You should create user because tests create test database (not your) everytime. 您应该创建用户,因为测试每次都会创建测试数据库(而不是您自己)。
User.objects.create_user(username=<client_username>, password=<client_password>)
Now create Client and login 现在创建客户端并登录
self.c = django.test.client.Client()
self.c.login(username=<client_username>, password=<client_password>)
You can override request headers for every client request like this example: 您可以像以下示例一样为每个客户端请求覆盖请求标头:
def test_report_wrong_password(self):
headers = dict()
headers['HTTP_AUTHORIZATION'] = 'Basic ' + base64.b64encode('user_name:password')
response = self.client.post(
'/report/',
content_type='application/json',
data=json.dumps(JSON_DATA),
**headers)
self.assertEqual(response.status_code, 401)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.