How to use session in TestCase in Django?

前端 未结 5 1132
误落风尘
误落风尘 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:26

    If testing my django project with pytest, I can not see any modifications to the session that are made in the view. (That is because the Sessions middleware doesn't get called.)

    I found the following approach to be useful:

    from unittest.mock import patch
    from django.test import Client
    from django.contrib.sessions.backends import db
    
    def test_client_with_session():
        client = Client()
        session = {}  # the session object that will persist throughout the test
        with patch.object(db, "SessionStore", return_value=session):
            client.post('/url-that-sets-session-key/')
    
            assert session['some_key_set_by_the_view']
    
            client.get('/url-that-reads-session-key/')
    

    This approach has the benefit of not requiring database access.

提交回复
热议问题