pythondjangopython-unittestdjango-unittestpython-unittest.mock

How to mock instance attribute of django form


I'm doing a unit test where I'm mocking a Django form, but I'm having some trouble because I need to mock two things from the form:

I'm using the form in a view, importing it like this:

from profiles.forms import PaymentForm

And I have tried the following to mock it:

    @patch('profiles.forms.PaymentForm')
    def test_when_processing_a_payment_then_the_event_is_tracked(self, payment_form_class):
        payment_form_class.is_valid.return_value = True
        payment_form_class.cleaned_data = {'token': 1}

This approach does not work, is_valid returns false.

    @patch('profiles.forms.PaymentForm')
    def test_when_processing_a_payment_then_the_event_is_tracked(self, payment_form_class):
        payment_form_class.return_value.is_valid = True
        payment_form_class.return_value.cleaned_data = {'token': 1}

This neither.

I'm using Django and unittest. I have successfully mocked the is_valid with a helper function of our code base, but it does not seem to work with instance attributes. Any idea how to solve this?


Solution

  • You might need to mock the form on where it is used in your view since it's already imported there before your mock runs.

    So something like:

    @patch('my_app.my_views.PaymentForm')