我无法访问context
的属性HttpResponse
来自 ipython 的对象。但单元测试访问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 测试代码中看到它在特殊仪器中进行了猴子补丁让模板渲染发送信号 http://code.djangoproject.com/browser/django/trunk/django/test/utils.py?rev=11917#L24,其中测试客户端聆听 http://code.djangoproject.com/browser/django/trunk/django/test/client.py?rev=11917#L224所以它可以使用渲染的模板及其上下文注释响应对象 http://code.djangoproject.com/browser/django/trunk/django/test/client.py?rev=11917#L254.
要附加此信号,您必须在 shell 会话中调用 django.test.utils.setup_test_environment() 函数(这有其他副作用),或者仅复制 Monkeypatch 模板渲染的行。不太难,但我同意如果可以重构这个特定的调试方面以使其更容易在测试之外使用,那就太好了。就我个人而言,我不介意这些信息是否总是在 DEBUG 为 True 时收集,而不仅仅是在测试时收集。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)