简体   繁体   English

在Django中测试期间没有存储会话数据

[英]Session data not being stored during testing in Django

I am currently writing tests for our project, and I ran into an issue. 我目前正在为我们的项目编写测试,我遇到了一个问题。 We have this section of a view, which will redirect the user back to the page where they came from including an error message (that's being stored in the session): 我们有一个视图的这一部分,它将用户重定向回他们来自的页面,包括一条错误消息(存储在会话中):

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')

Once the HttpResponseRedirect kicks in, the first thing that the new view does is scan the session, to see if any error messages are stored in the session. 一旦HttpResponseRedirect启动,新视图所做的第一件事就是扫描会话,以查看会话中是否存储了任何错误消息。 If there are, we place them in a dictionary and then delete it from the session: 如果有,我们将它们放在字典中,然后从会话中删除它:

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

We should now have the error message in a dictionary, but after printing the dictionary the error message is not there. 我们现在应该在字典中有错误消息,但在打印字典后,错误消息不存在。 I also printed the session just before the HttpResponseRedirect, but the session is an empty dictionary there as well. 我还在HttpResponseRedirect之前打印了会话,但会话也是一个空字典。

This is the test: 这是测试:

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'])

It looks like the session can not be accessed or written to directly from the views during testing. 看起来在测试期间无法直接从视图访问或写入会话。 I can, however, access a value in the session by manually setting it in the test by using the following bit of code: 但是,我可以通过使用以下代码在测试中手动设置它来访问会话中的值:

    session = self.c.session
    session['errormessage'] = 'This is an error message'
    session.save()

This is however not what I want, because I need the session to be set by the view as there are many different error messages in the entire view. 然而,这不是我想要的,因为我需要视图设置会话,因为整个视图中有许多不同的错误消息。 Does anyone know how to solve this? 有谁知道如何解决这个问题? Thanks in advance! 提前致谢!

After taking a closer look I found the issue, it is in the view itself: 仔细看后我发现了问题,它在视图中:

errorCode = request.GET.get('error_code')
if errorCode == 4201:
    request.session['errormessage'] = _('Action cancelled by the user')

The errorCode variable is a string, and I was comparing it to an integer. errorCode变量是一个字符串,我将它与一个整数进行比较。 I fixed it by changing the second line to: 我通过将第二行更改为:

if int(errorCode) == 4201:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM