Wednesday, July 3, 2013

Writing Form Tests

I am trying to extend the polls tutorial code to use a django form with tests.

I created this form, but ran into some issues when trying to test it. When looking up how to test it, I found this form from http://toastdriven.com/blog/2011/apr/17/guide-to-testing-in-django-2/ It also had tests.

When I try to run those tests on my form I get the error
"_VoteForm is not callable"
"AttributeError: '_VoteForm' object has no attribute 'instance'"

Which form is preferred? How can I write similar tests for _VoteForm
#my form
def vote_form_class(poll):      choices = [(i.id, _(i.choice_text)) for i in poll.choices.all()]        class _VoteForm(forms.Form):          vote = forms.ChoiceField(choices=choices, widget=forms.RadioSelect())            def save(self):              if not self.is_valid():                  raise forms.ValidationError("Poll Form was not validated before .save()")                data = self.cleaned_data              choice_id = data['vote']              choice = Choice.objects.get(id=choice_id)              choice.record_vote()        return _VoteForm


#form with tests
class PollForm(forms.Form):
   
def __init__(self, *args, **kwargs):
       
# We require an ``instance`` parameter.
       
self.instance = kwargs.pop('instance')

       
# We call ``super`` (without the ``instance`` param) to finish
       
# off the setup.
       
super(PollForm, self).__init__(*args, **kwargs)

       
# We add on a ``choice`` field based on the instance we've got.
       
# This has to be done here (instead of declaratively) because the
       
# ``Poll`` instance will change from request to request.
       
self.fields['choice'] = forms.ModelChoiceField(queryset=Choice.objects.filter(poll=self.instance.pk), empty_label=None, widget=forms.RadioSelect)


    def save(self):
       
if not self.is_valid():
           
raise forms.ValidationError("PollForm was not validated first before trying to call 'save'.")

        choice
= self.cleaned_data['choice']
        choice
.record_vote()
       
return choice



class PollFormTestCase(TestCase):
    fixtures
= ['polls_forms_testdata.json']

   
def setUp(self):
       
super(PollFormTestCase, self).setUp()
       
self.poll_1 = Poll.objects.get(pk=1)
       
self.poll_2 = Poll.objects.get(pk=2)

   
def test_init(self):
       
# Test successful init without data.
        form
= PollForm(instance=self.poll_1)
       
self.assertTrue(isinstance(form.instance, Poll))
       
self.assertEqual(form.instance.pk, self.poll_1.pk)
       
self.assertEqual([c for c in form.fields['choice'].choices], [(1, u'Yes'), (2, u'No')])

       
# Test successful init with data.
        form
= PollForm({'choice': 3}, instance=self.poll_2)
       
self.assertTrue(isinstance(form.instance, Poll))
       
self.assertEqual(form.instance.pk, self.poll_2.pk)
       
self.assertEqual([c for c in form.fields['choice'].choices], [(3, u'Alright.'), (4, u'Meh.'), (5, u'Not so good.')])

       
# Test a failed init without data.
       
self.assertRaises(KeyError, PollForm)

       
# Test a failed init with data.
       
self.assertRaises(KeyError, PollForm, {})


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate