在Django单元测试中使用会话对象 [英] Using session object in Django unit test
问题描述
我正在写一个登录视图,并希望为视图添加单元测试。我的看法如下:
I am writing a login view and would like to add a unit test for the view. My view looks like this:
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')
我的单位测试如下所示:
And my unit test looks like this:
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)
单元测试崩溃,因为它们找不到会话对象。我通过定义一个虚拟会话字典来跟踪网站上的几个教程,但没有帮助。
The unit test crash because they cannot find the session object. I follow couple tutorial on the websites by defining a dummy session dictionary but it doesn't help.
任何人都可以为我写一个单元测试视图需要处理会话对象?
Can anyone shed some light for me how to write a unit test for a view that need to deal with session object?
谢谢。
推荐答案
从 RequestFactory
对象的文档中:
它不支持中间件。会话和验证属性必须由测试本身提供,视需要才能正常工作。
It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.
您可以尝试手动设置<$如你所说,c $ c> request.session 是一个具有适当内容的字典。可能会更容易使用老式的 Django测试客户端。
You could try manually setting request.session
to be a dictionary with appropriate stuff in it, as you say. It might turn out to be easier to use the old-fashioned Django test client though.
这篇关于在Django单元测试中使用会话对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!