我正在编写一个登录视图,并想为该视图添加一个单元测试。我的观点是这样的:
def login(request):
if request.POST:
usrname = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=usrname, password=password)
if user is not None:
auth_login(request, user)
return redirect('/core/home/')
else:
context = {'error_message': "Invalid username or password"}
return render(request, 'core/login.html', context)
else:
c = {}
c.update(csrf(request))
return render_to_response('core/login.html',c)
def home(request):
if request.user.is_authenticated():
context = {'user' : request.user}
return render(request, 'core/home.html', context)
else:
return render(request, 'core/login.html')
我的单元测试如下所示:
class CoreViewTests(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_login_view_with_valid_user(self):
uf = UserFactory()
user = uf.make_user("ValidUser1", "12345", "user@abc.com")
self.assertEqual(user.username, "ValidUser1")
request = self.factory.post('/core/login', {"username": "ValidUser1", "password": "12345"})
response = login(request)
self.assertEqual(response.status_code, 200)
单元测试崩溃,因为他们找不到会话对象。我通过定义一个虚拟会话字典来遵循网站上的几个教程,但它没有帮助。
谁能告诉我如何为需要处理会话对象的视图编写单元测试?
谢谢。