Shrikant Kakani
Shrikant Kakani

Reputation: 1561

Django Unit tests for forms

Let's assume that I've a form defined as:

class NumbersABForm(forms.Form):
    a = forms.FloatField(required=False)
    b = forms.FloatField(required=False)

    def clean(self):
        if self.cleaned_data['a'] < self.cleaned_data['b']:
            raise ValueError('a < b')

I want to define unit test cases for this form as follows:

class NumbersABFormTest(TestCase):
    def test_invalid(self):
        try:
            form = NumbersABForm({
                'a': 10.0,
                'b': 5.0
            })
            self.assertFalse(form.is_valid())
        except ValueError:
            self.assertEqual(form.errors, {'a < b'})

Exception is thrown but 'form.errors' is empty. I don't understand how this works. Also, after calling form.is_valid() before which was returning False, calling it again returns True. I don't know how this is possible. Is there something I'm missing?

Upvotes: 0

Views: 149

Answers (1)

Risadinha
Risadinha

Reputation: 16666

You have confused ValueError with ValidationError:

from django.core.exceptions import ValidationError

class NumbersABForm(forms.Form):
    a = forms.FloatField(required=False)
    b = forms.FloatField(required=False)

    def clean(self):
        if self.cleaned_data['a'] < self.cleaned_data['b']:
            raise ValidationError('a < b')

and you should not try to catch it because is_valid() should not raise it but instead add an error to the form:

class NumbersABFormTest(TestCase):
    def test_invalid(self):
        form = NumbersABForm({
            'a': 10.0,
            'b': 5.0
        })
        self.assertFalse(form.is_valid())
        self.assertDictEqual(form.errors, {'__all__': 'a < b'})

Upvotes: 1

Related Questions