1

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:

  • An instance attribute (token)
  • A method (is_valid)

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?

3
  • 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: my_app.my_views.PaymentForm Commented Feb 21, 2022 at 7:04
  • 1
    Lol it was that, I always forgot the correct path in the patch, Thanks! Pls post it as an answer :) Commented Feb 21, 2022 at 7:07
  • Sure! Posted an answer Commented Feb 21, 2022 at 21:40

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.