Django测试框架中的login() [英] login() in Django testing framework
问题描述
我已经开始使用Django的测试框架,并且一切正常,直到我开始测试经过身份验证的页面为止.
I have started using Django's testing framework, and everything was working fine until I started testing authenticated pages.
为简单起见,我们说这是一个测试:
For the sake of simplicity, let's say that this is a test:
class SimpleTest(TestCase):
def setUp(self):
user = User.objects.create_user('temporary', 'temporary@gmail.com', 'temporary')
def test_secure_page(self):
c = Client()
print c.login(username='temporary', password='temporary')
response = c.get('/users/secure/', follow=True)
user = User.objects.get(username='temporary')
self.assertEqual(response.context['email'], 'temporary@gmail.com')
运行此测试后,它失败,并且我看到login()的打印返回值返回 True ,但是 response.content 被重定向到登录页面(如果登录失败,身份验证装饰器将重定向到登录页面.我在做身份验证的装饰器中设置了一个断点:
After I run this test, it fails, and I see that printing return value of login() returns True, but response.content gets redirected to login page (if login fails authentication decorator redirects to login page). I have put a break point in decorator that does authentication:
def authenticate(user):
if user.is_authenticated():
return True
return False
,它实际上返回 False . test_secure_page()中的第4行正确地检索了用户.
and it really returns False. Line 4 in test_secure_page() properly retrieves user.
这是查看功能:
@user_passes_test(authenticate, login_url='/users/login')
def secure(request):
user = request.user
return render_to_response('secure.html', {'email': user.email})
当然,如果我尝试通过应用程序登录(测试之外),一切正常.
Of course, if I try to login through application (outside of test), everything works fine.
推荐答案
问题是您没有将RequestContext
传递给模板.
The problem is that you're not passing RequestContext
to your template.
此外,您可能应该使用login_required
装饰器和TestCase
类中内置的客户端.
Also, you probably should use the login_required
decorator and the client built in the TestCase
class.
我会这样重写它:
#views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.contrib.auth import get_user_model
@login_required(login_url='/users/login')
def secure(request):
user = request.user
return render(request, 'secure.html', {'email': user.email})
#tests.py
class SimpleTest(TestCase):
def setUp(self):
User = get_user_model()
user = User.objects.create_user('temporary', 'temporary@gmail.com', 'temporary')
def test_secure_page(self):
User = get_user_model()
self.client.login(username='temporary', password='temporary')
response = self.client.get('/manufacturers/', follow=True)
user = User.objects.get(username='temporary')
self.assertEqual(response.context['email'], 'temporary@gmail.com')
这篇关于Django测试框架中的login()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!