在Django中如何使用TestCase中的会话? [英] How to use session in TestCase in Django?

查看:259
本文介绍了在Django中如何使用TestCase中的会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从测试(Django TestCase)中读取一些会话变量

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):
    """
    Test add docs
    """
    # I would access to the session here:
    self.request.session['documents_to_share_ids'] = [1]

    response = self.client.get(reverse(self.document_add_view_id, args=[1]), follow=True)
    self.assertEquals(response.status_code, 200)


推荐答案

不幸的是,这并不容易,因为你希望在这一刻。正如你可能已经注意到的,直接使用 self.client.session 将不起作用,如果您尚未调用已设置与适当会话Cookie的会话的其他视图。然后必须手动或通过其他视图设置会话存储/ cookie。

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.

有一个打开的机票,可以更容易地与测试客户端模拟会话: a href =https://code.djangoproject.com/ticket/10899 =noreferrer> https://code.djangoproject.com/ticket/10899

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

除了机票中的解决方法之外,如果您使用 django.contrib.auth ,则可以使用一个技巧。测试客户端 login()方法设置可以在测试中稍后使用的会话存储/ cookie。

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

这篇关于在Django中如何使用TestCase中的会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆