How to use session in TestCase in Django?

前端 未结 5 1118
误落风尘
误落风尘 2020-12-10 03:36

I would like to read some session variables from a test (Django TestCase)

How to do that in a clean way ?

def test_add_docs(self):
    \"\"\"
    Tes         


        
5条回答
  •  生来不讨喜
    2020-12-10 04:16

    Unfortunately, this is not a easy as you would hope for at the moment. As you might have noticed, just using self.client.session directly will not work if you have not called other views that has set up the sessions with appropriate session cookies for you. The session store/cookie must then be set up manually, or via other views.

    There is an open ticket to make it easier to mock sessions with the test client: https://code.djangoproject.com/ticket/10899

    In addition to the workaround in the ticket, there is a trick that can be used if you are using django.contrib.auth. The test clients login() method sets up a session store/cookie that can be used later in the test.

    If you have any other views that sets sessions, requesting them will do the trick too (you probably have another view that sets sessions, otherwise your view that reads the sessions will be pretty unusable).

    from django.test import TestCase
    from django.contrib.auth.models import User
    
    class YourTest(TestCase):
        def test_add_docs(self):
            # If you already have another user, you might want to use it instead
            User.objects.create_superuser('admin', 'foo@foo.com', 'admin')
    
            # self.client.login sets up self.client.session to be usable
            self.client.login(username='admin', password='admin')
    
            session = self.client.session
            session['documents_to_share_ids'] = [1]
            session.save()
    
            response = self.client.get('/')  # request.session['documents_to_share_ids'] will be available
    

提交回复
热议问题