在django中测试extra_context

时间:2010-09-28 21:30:46

标签: python django unit-testing tdd

我正在尝试测试用户提供的extra_context是否已正确处理 在视图中。

这是我的测试方法:

# 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')

这是我的观点功能:

# 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'

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

1 个答案:

答案 0 :(得分:3)

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

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或调用视图的视图中传递extra_context

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