测试时在Django中使用会话对象? [英] using session objects in django while testing?

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

问题描述

我创建了一个包含三个应用程序的小型django项目,现在正在为其中一个编写测试。我需要在差异视图和差异模板之间传递一些信息,但是这些信息对用户不应该可见。我的第一个尝试是以HTML形式将这些信息作为隐藏字段进行传递,但随后有人指出,这并没有使其完全不可见。因此,我将此信息存储在request.session词典中,一切正常。

I've created a small django project with three applications, and I'm now writing tests for one of them. I needed to pass some information between differente views and differents templates,but that information should not be visible to the user. My first attempt was to pass this informatio as hidden fields in a HTML form, but then it was pointed to me that that did not make it completely invisible. So, I stored this information in the request.session dictionary and it went all right.

也就是说,我的问题是在测试时出现的。根据django文档(http://docs.djangoproject.com/en/1.2/topics/testing/),在测试期间必须修改会话字典时,应首先将其存储在变量中,然后对其进行修改,然后保存

That said, my problem arised while testing. According to the django documentation (http://docs.djangoproject.com/en/1.2/topics/testing/) when you have to modify the session dictionary during testing you should first store it in a variable, modify it, and then save the variable.

所以我的测试代码如下:

So my testing code is something like this:

class Test_Atacar(TestCase):
    fixtures = ["testBase.json"]

    def test_attack_without_troops(self):
        red_player = Player.objects.get(color=RED)
        self.failUnless(red_player != None)
        session = self.client.session
        session["player_id"] = red_player.id
        session.save()
        response = self.client.get("/espectador/sadfxc/", follow=True)

但是当我运行python manage.py测试时,我得到了AttributeError,说该字典没有属性save()。
我在其他地方(http://code.djangoproject.com/ticket/11475)读到,在操作会话之前,我应该尝试对任何其他URL进行self.client.get,这样它才能成为真实的会话会话,但我一直遇到相同的AttributeError。

But when I run the python manage.py test, I get an AttributeError, saying that dict, has no attribute save(). I read somewhere else (http://code.djangoproject.com/ticket/11475) that I should try doing a self.client.get to any other URL BEFORE manipulating the session so that it would become a "real" session, but I kept getting the same AttributeError.

推荐答案

当您在测试过程中必须修改会话字典时应该首先将其存储在变量中,对其进行修改,然后保存该变量

这一行表示,如果您要对某些会话变量,请勿将其直接添加到会话中。将数据存储在变量中,在该变量中进行更改,然后将该变量放入会话字典中。会话就像其他字典一样。

This line means that if you want to make some changes into some of the session variables, do not make them directly into session. Store the data in the variable, make changes in that variable and then put that variable into session dictionary. session is like any other dictionary.

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

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