测试使用cookie / session的django web应用程序

时间:2011-03-30 18:33:33

标签: django unit-testing session testing cookies

在views.py中:

  

get_dict = Site.objects.getDictionary(request.COOKIES['siteid'])

{根据来自cookie的id获取包含网站信息的字典}
在tests.py中:

from django.test import TestCase
class WebAppTest(TestCase):
    def test_status(self):
        response = self.client.get('/main/',{})
        response.status_code # --->passed with code 200
        response = self.client.get('/webpage/',{'blog':1})
        response.status_code # ----> this is failing

为了呈现博客页面,它会转到一个视图,在该视图中,它使用现有cookie获取字典,处理它,渲染模板,这在运行应用程序时工作正常。但测试失败了。从未测试过Django webapps我不知道如何正确测试它。这是追溯 回溯(最近一次调用最后一次):

File "<console>", line 2, in <module>
  File "/usr/lib/pymodules/python2.6/django/test/client.py", line 313, in post
    response = self.request(**r)
  File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py", line 92, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/var/lib/django/data/../webpage/views.py", line 237, in getCostInfo
    get_dict = Site.objects.getDictionary(request.COOKIES['siteid'])
KeyError: 'siteid'

通过一些在线样本,但找不到与cookies /会话深度相关的内容。我们非常感谢您对有用链接的任何想法或指示。

1 个答案:

答案 0 :(得分:6)

查看Persistent StateDjango Testing docs部分。

在你的情况下,我希望你的测试更像是:

from django.test import TestCase
from django.test.client import Client
class WebAppTest(TestCase):
    def setUp(self):
        self.client = Client()
        session = self.client.session
        session['siteid'] = 69 ## Or any valid siteid.
        session.save()
    def test_status(self):
        response = self.client.get('/main/',{})
        self.assertEqual(response.status_code, 200)   
        response = self.client.get('/webpage/',{'blog':1})
        self.assertEqual(response.status_code, 200)