How to check form validation logic in unit test driver in Django?

I want to check the is_valid part of the form validation logic. In my test driver, I:

   test_animal = Animal (name = "cat", number_paws = "4")
   test_animal_form = AnimalForm (instance = test_animal)
   assertEqual (test_animal_form.is_valid (), True)

The statement fails, but from what I see there should be no errors in the form. I do not see any validation errors on the form. Should this work as a test case if the test_animal instance should check when loaded into the form?

+7
django django-forms django-testing
source share
1 answer

The reason you see validation errors is because instance data is not used in validation, you must specify the data that is submitted to the form.

 test_animal = Animal(name="cat", number_paws="4") test_animal_form = AnimalForm(instance=test_animal) assertEqual(test_animal_form.is_valid(), False) # No data has been supplied yet. test_animal_form = AnimalForm({'name': "cat", 'number_paws': 4, }, instance=test_animal) assertEqual(test_animal_form.is_valid(), True) # Now that you have given it data, it can validate. 
+16
source share

All Articles