【问题标题】:Django: Test client's context is empty from the shellDjango:测试客户端的上下文在外壳中为空
【发布时间】:2010-12-28 07:26:48
【问题描述】:

我无法从 ipython 访问 HttpResponse 对象的 context 属性。但是单元测试访问的是context

这里是单元测试。测试运行正常通过:

from django.test import Client, TestCase
from django.core import mail

class ClientTest(TestCase):
    def test_get_view(self):
        data = {'var': u'\xf2'}
        response = self.client.get('/test04/', data)

        # Check some response details
        self.assertContains(response, 'This is a test')
        self.assertEqual(response.context['var'], u'\xf2')

这是我在 shell 中使用的代码:

In [10]: from django.test import Client

In [11]: c = Client()

In [12]: r = c.get('/test04/', data)

In [13]: r.context

In [14]: type(r.context)
Out[14]: <type 'NoneType'>

response.context 在 shell 中没有,而response.context 存在于单元测试中。

为什么HttpResponse 在 shell 和单元测试之间的行为不一致?

【问题讨论】:

  • 我自己试过了,在 Django shell 中既没有设置上下文也没有设置模板。我猜 Client 不打算在交互式 shell 中使用。测试运行器在运行测试之前会进行一些检测,这些检测不会通过 shell 触发。见django.test.testcases

标签: django unit-testing testing


【解决方案1】:

您可以在 Django 测试代码中看到,它在特殊工具中将猴子补丁添加到 make template rendering send a signal,而 test client listens to 则可以annotate the response object with the rendered templates and their contexts

要附加此信号,您​​必须在 shell 会话中调用 django.test.utils.setup_test_environment() 函数(具有其他副作用),或者仅复制 monkeypatch 模板渲染的行。不太难,但我同意如果可以重构这个特定的调试方面以使其更容易在测试之外使用,那就太好了。就我个人而言,我不介意这些信息是否总是在 DEBUG 为 True 时收集,而不仅仅是在测试中。

【讨论】:

    猜你喜欢
    • 2011-05-07
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2018-02-16
    • 2017-01-26
    • 2016-06-10
    相关资源
    最近更新 更多