在我的测试中,我有一些代码:
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)
我的问题是这个检查必须经过使用ldap的基本http身份验证,而且速度很慢。
有没有办法模拟用户登录?
答案 0 :(得分:2)
您应该创建用户,因为测试每次都会创建测试数据库(而不是您的)。
User.objects.create_user(username=<client_username>, password=<client_password>)
现在创建客户端并登录
self.c = django.test.client.Client()
self.c.login(username=<client_username>, password=<client_password>)
答案 1 :(得分:0)
您可以为每个客户端请求覆盖请求标头,例如:
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)