我目前正在尝试为内置的django登录页面编写单元测试,并且不断收到此错误。
ERROR: test_login_success (User.tests.LoginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\---------------\User\tests.py", line 74, in test_login_success
self.assertTrue(response.data['authenticated'])
AttributeError: 'TemplateResponse' object has no attribute 'data'
代码:
没有视图功能,因为我使用了Django内置的登录页面
test.py
def test_login_success(self):
testuser = User.objects.create_user(username = 'howdycowboy', password= 'Testing123' )
response=self.client.post(self.login_url,{'username':'howdycowboy', 'password': 'Testing123'},format='text/html')
#self.assertEqual(response.status_code ,302)
self.assertTrue(response.data['authenticated'])
#HTML code
{% extends 'User/base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% endblock %}
我也尝试过self.assertEqual(response.status_code ,302)
登录后便会重定向,但由于某种原因response.statuscode为200。
% (response.status_code, status_code)
AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302)