我目前正在为我们的项目编写测试,但我遇到了一个问题。我们有一个视图的这一部分,它将用户重定向回他们来自的页面,包括一条错误消息(存储在会话中):
if request.GET.get('error_code'):
"""
Something went wrong or the call was cancelled
"""
errorCode = request.GET.get('error_code')
if errorCode == 4201:
request.session['errormessage'] = _('Action cancelled by the user')
return HttpResponseRedirect('/socialMedia/manageAccessToken')
一旦HttpResponseRedirect启动,新视图所做的第一件事就是扫描会话,以查看会话中是否存储了任何错误消息。如果有,我们将它们放在字典中,然后从会话中删除它:
def manageAccessToken(request):
"""
View that handles all things related to the access tokens for Facebook,
Twitter and Linkedin.
"""
contextDict = {}
try:
contextDict['errormessage'] = request.session['errormessage']
contextDict['successmessage'] = request.session['successmessage']
del request.session['errormessage']
del request.session['successmessage']
except KeyError:
pass
我们现在应该在字典中有错误消息,但在打印字典后,错误消息不存在。我还在HttpResponseRedirect之前打印了会话,但会话也是一个空字典。
这是测试:
class oauthCallbacks(TestCase):
"""
Class to test the different oauth callbacks
"""
def setUp(self):
self.user = User.objects.create(
email='test@django.com'
)
self.c = Client()
def test_oauthCallbackFacebookErrorCode(self):
"""
Tests the Facebook oauth callback view
This call contains an error code, so we will be redirected to the
manage accesstoken page. We check if we get the error message
"""
self.c.force_login(self.user)
response = self.c.get('/socialMedia/oauthCallbackFacebook/',
data={'error_code': 4201},
follow=True,
)
self.assertEqual('Action cancelled by the user', response.context['errormessage'])
看起来在测试期间无法直接从视图访问或写入会话。但是,我可以通过使用以下代码在测试中手动设置它来访问会话中的值:
session = self.c.session
session['errormessage'] = 'This is an error message'
session.save()
然而,这不是我想要的,因为我需要视图设置会话,因为整个视图中有许多不同的错误消息。有谁知道如何解决这个问题?提前谢谢!
答案 0 :(得分:0)
仔细观察后我发现了问题,它在视图中:
errorCode = request.GET.get('error_code')
if errorCode == 4201:
request.session['errormessage'] = _('Action cancelled by the user')
errorCode变量是一个字符串,我将它与一个整数进行比较。我通过将第二行更改为:
来修复它if int(errorCode) == 4201: