Search code examples
djangodjango-formsdjango-testing

How can I test a form's validation logic in a unit test driver in Django?


I want to test the is_valid portion of a form's validation logic. In my test driver I have:

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

The assertion fails, but from what I see there shouldn't be any errors in the form. I don't see any validation errors in the form. Should this work as a test case if the test_animal instance when loaded into the form should validate?


Solution

  • The reason you're seeing the validation errors is because instance data isn't used in validation, you have to specify the data being sent 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.