gpt4 book ai didi

python - 在 Django 中测试 extra_context

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:16 26 4
gpt4 key购买 nike

我正在尝试测试用户提供的 extra_context 是否被正确处理在 View 中。

这是我的测试方法:

# tests.py (of course it's a part of TestCase class)
def test_should_use_definied_extra_context(self):
response = self.client.get(reverse('contact_question_create'), {
'extra_context': {'foo': 'bar', 'callable': lambda: 'called'}
})
eq_(response.context['foo'], 'bar')
eq_(response.context['callable'], 'called')

这是我的 View 函数:

# views.py (my view function)
def contact_question_create(request, success_url=None, form_class=None,
template_name="contact/contact_form.html",
extra_context=None, **kwargs):
if form_class is None:
form_class = forms.DefaultContactForm

if request.method == 'POST':
form = form_class(data=request.POST, files=request.FILES)
if form.is_valid():
signals.question_posted.send(sender='contact_question_create_view',
form_data=form.cleaned_data)
if success_url is None:
pass # TODO: implement this case
else:
return redirect(sucess_url)
else:
form = form_class()

if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value

return render_to_response(template_name,
{'form':form},
context_instance=context)

运行测试时,出现以下 KeyError 异常:

======================================================================
ERROR: test_should_use_definied_extra_context (mpozyczka.apps.contact.tests.ContactViewShouldUseRequestedValues)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py",
line 279, in run testMethod()
File "/Users/bx2/Dropbox/Projekty/mpozyczka/src/mpozyczka/apps/contact/tests.py",
line 56, in test_should_use_definied_extra_context
eq_(response.context['foo'], 'bar')
File "/Users/bx2/Dropbox/Projekty/mpozyczka/parts/django/django/test/utils.py",
line 35, in __getitem__ raise KeyError(key)
KeyError: 'foo'

我觉得我太累了,我没有看到问题 - 关于我错过了什么的任何线索?

最佳答案

您需要使用以下解决方案:

def contact_question_create(request, success_url=None, form_class=None,
template_name="contact/contact_form.html",
extra_context=None, **kwargs):

# your view code here

context = {'defult':'foo'}

if extra_context:
context.update(extra_context)

return render_to_response(template_name,
context,
context_instance=RequestContext(request, context))

测试它时,您需要在 url.py 或调用您的 View 的 View 中传递 extra_context

def my_view(reuest):
return contact_question_create(extra_context={'foo':'bar'})

关于python - 在 Django 中测试 extra_context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3817199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com