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

测试使用Cookie/session的django web应用程序,django,unit-testing,session,testing,cookies,Django,Unit Testing,Session,Testing,Cookies,在views.py中: get\u 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/',{})

在views.py中:

get\u 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,我不知道如何正确测试它。这是回溯。
回溯(最近一次呼叫最后一次):

文件“”,第2行,在
文件“/usr/lib/pymodules/python2.6/django/test/client.py”,第313行,在post中
响应=自我请求(**r)
文件“/usr/lib/pymodules/python2.6/django/core/handlers/base.py”,第92行,在get_响应中
响应=回调(请求,*回调参数,**回调参数)
文件“/var/lib/django/data/。/webpage/views.py”,第237行,在getCostInfo中
get_dict=Site.objects.getDictionary(request.COOKIES['siteid'])
KeyError:“站点ID”
浏览了一些在线示例,但找不到深入处理cookie/会话的内容。任何有用链接的想法或指导都将受到高度赞赏

看一下这一部分

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

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)

ah session.save()给了这个AttributeError:“dict”对象没有属性“save”。评论该部分确实有效。这应该是一个良好的开端。请您告诉我,当siteid存储在会话中时,它为什么有效。谢谢Jack。因为会话中没有
siteid
。我在请求中也有存储用户的选择。会话['choice']在我的视图中。它又在抱怨了,所以我尝试在测试中像session.update一样更新client.session({'choice':'technology'})。这不起作用。它给了我关键错误“选择”。知道吗?很抱歉,这里不适合发布。如果您不理解这一点,可能需要学习更多关于Python词典的知识。键错误是指字典中不存在键“choice”。这意味着您需要先进行设置。刚发现这可能是我尝试会话时发生的情况。保存()
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)