开发者

Django Unittesting adding a variable to the session

In my unittest I need to add a variable to the session, because that variable is used in the view which is being tested. The django documentation says this is possible in the following way (https://docs.djangoproject.com/en/1.3/topics/testing/#django.test.client.Client.session):

def test_something(self):
    session = self.client.session
    session['somekey'] = 'test'
    session.sav开发者_JAVA百科e()

This code example actually doesn't work, because you will get the error that a dict doesn't have a function save. I also tried various other ways to change the contents inside the session dict, but haven't found a way to change it yet. I know what it means, what i get back is a dict object so it doesnt have the save function. But the session dict also doesn't update when adding keys.

The documentation statues when using self.client.session it should return a SessionStore object instead of a dictionary.


Seems right now there is a bug in Django, so it doesn't work for unauthenticated users to change the session. This is the corresponding ticket: https://code.djangoproject.com/ticket/11475 .

A work around is to create a dummy view in which the session variables are set and calling that view with the Client.get('url_of_dummy_view').


The ticket referenced by @Sam Stoelinga has been closed as a duplicate. The corresponding ticket can be found here.

To save session data you will have to use an authenticated user. I found a solution here.

class BlogAdminTestCase(TestCase):
    def setUp(self):
        # Setup Test User
        User.objects.create_user(
            username='foo',
            password='bar'
        )

        # Must login to modify session variables
        self.client.login(username='foo', password='bar')

        s = self.client.session
        s['my_session_variable'] = 'Yay!'
        s.save()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜