【问题标题】:testing django web app that uses cookies/session测试使用 cookie/会话的 django web 应用程序
【发布时间】:2011-07-26 07:46:47
【问题描述】:

在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 我不确定如何正确测试它。这是回溯。
Traceback(最近一次调用最后一次):

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'

浏览了一些在线示例,但找不到深入处理 cookie/会话的内容。任何想法或指向有用链接的指示都将受到高度赞赏。

【问题讨论】:

    标签: django unit-testing session testing cookies


    【解决方案1】:

    查看Django Testing docsPersistent State 部分。

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

    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)
    

    【讨论】:

    • 啊 session.save() 给出了这个 AttributeError: 'dict' object has no attribute 'save'。评论那部分确实有效。这应该是一个好的开始。你能告诉我为什么当 siteid 存储在会话中时它确实有效。谢谢杰克。
    • 因为会话中没有siteid
    • 在我看来,我在 request.session['choice'] 中也有商店用户的选择。它再次抱怨,所以我确实尝试在测试中更新 client.session,如 session.update({'choice':'technology'})。这不起作用。它给了我关键错误“选择”。知道吗?抱歉,如果这里不适合发帖。
    • 如果您不了解这一点,您可能需要进一步了解 Python 中的字典。一个关键错误是说字典中不存在键“选择”。这意味着您需要先进行设置。
    • 刚刚发现这可能是我尝试 session.save () code.djangoproject.com/ticket/11475 时发生的事情
    猜你喜欢
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    相关资源
    最近更新 更多