Asmoox
Asmoox

Reputation: 652

Django form test non-field errors

I'd like to ask for a method to check if any kind of non-field errors was raised during form validation in Django. So far I found solution to do this during view testing. Well, it wasn't what I was looking for since I'm interested in doing it at form tests.

I know the way to look for fields' errors:

class FormTest(TestCase)
    def test_fields_errors(self):
        """
        Suppose form has one field which has to be filled
        """

        form = TestForm()
        form.full_clean()

        self.assertFalse(form.is_valid())
        self.assertIsInstance(
            form.errors.as_data()['required_field'][0],
            ValidationError
        )
        self.assertEquals(
            form.errors['deadline_datetime'][0],
            'This field must not be empty'
        )

Is there any way to do this when we deal with non-field errors?

Upvotes: 0

Views: 1247

Answers (1)

Asmoox
Asmoox

Reputation: 652

I answer my own question, but I also wanna start discussion if there is any better solution

With small help of debugger, I found that non-field errors appear in form.errors as well. But this time there wasn't any dict key named like non-field errors. All I found was a bit strange key __all__, but it allowed me to access demanded errors:

class FormTest(TestCase)
    def test_fields_errors(self):
    """
    Suppose form has two fields and either one has to be filled
    """

    form = TestForm()
    form.full_clean()

    self.assertFalse(form.is_valid())
    self.assertIsInstance(
            form.errors.as_data()['__all__'][0],
            ValidationError
    )
    assertEquals(
        errors['__all__'][0],
        'Fill at least one field'
    )

So, I was able to find the error I was looking for during testing non-field errors raise.

Upvotes: 2

Related Questions