Hi,
I'm trying to test if the extra_context provided by the user was correctly processed in the view.
Here is my test approach:
# 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')
And here is my view function:
# 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)
When running the test I'm getting following KeyError exception:
======================================================================
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'
I think I'm too tired and I don't see the problem - any clues about what am I missing?