Django:测试客户端的上下文是空的 [英] Django: Test client's context is empty from the shell
问题描述
我无法从ipython访问 HttpResponse
对象的上下文
属性。但是单元测试访问上下文
。
I cannot access the context
attribute of an HttpResponse
object from ipython. But the unit test accesses context
.
这是单元测试。测试运行正常:
Here is the unit test. The test run passes properly:
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中:
Here is the code that I used in the 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
存在于单元测试中。
response.context
is none in the shell whereas response.context
exists in the unit test.
为什么 HttpResponse
在shell和单元测试之间不一致?
Why does HttpResponse
behave inconsistently between the shell and unit test?
推荐答案
您可以在Django测试代码中查看特定工具中的monkeypatches到使模板呈现发送信号,其中测试客户端侦听,所以它可以使用渲染的模板及其上下文注释响应对象。
You can see in the Django test code where it monkeypatches in special instrumentation to make template rendering send a signal, which the test client listens to so it can annotate the response object with the rendered templates and their contexts.
要附加此信号,您必须调用shell会话中的django.test.utils.setup_test_environment()函数(具有其他副作用)或重复只是线条monkeypatch模板渲染。不是太难了,但是我同意如果这个特定的调试方面可以被重构,以便在测试之外更容易使用,那将是很好的。我个人不介意,如果这个信息总是在DEBUG为True时收集,而不仅仅是被测试。
For this signal to be attached, you'd have to either call the django.test.utils.setup_test_environment() function in your shell session (which has other side effects), or duplicate just the lines that monkeypatch template rendering. Not too hard, but I agree it'd be nice if this particular debugging aspect could be refactored out to make it easier to use outside of tests. Personally I wouldn't mind if this information was always collected when DEBUG is True, not just under test.
这篇关于Django:测试客户端的上下文是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!