开发者

using session objects in django while testing?

开发者 https://www.devze.com 2023-01-27 00:03 出处:网络
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 i

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.

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"]

   开发者_如何学JAVA 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)

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.


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

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.


@anand I know it's weird but it indeeds work. What I had to do to make it work, besides not manipulating directly the variable was to make a self.client.get("/dummy/") where dummy is an URL that uses a dummy view. This view only modifies the attribute of the request it gets as argument. Honestly, I don't know what goes on behind the scenes that makes this work

0

精彩评论

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

关注公众号