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

查看:24
本文介绍了如何在 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)

推荐答案

不幸的是,这并不像您目前所希望的那样容易.正如您可能已经注意到的那样,如果您没有调用其他为您设置了会话 cookie 的视图,那么直接使用 self.client.session 是行不通的.然后必须手动或通过其他视图设置会话存储/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.

有一个开放的票证可以更轻松地模拟与测试客户端的会话: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天全站免登陆