Mocking forms in view unit tests
Asked Answered
P

1

7

I can't seem to be able to mock the behaviour of a form when unit testing views.

My form is a simple ModelForm and resides in profiles.forms. The view is (again) a simple view that checks whether the form is valid and then redirects.

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from profiles.forms import ProfileForm

def home(request):
    form = ProfileForm()

    if request.method == 'POST':
        form = ProfileForm(request.POST)

        if form.is_valid():
            profile = form.save()
            return HttpResponseRedirect(reverse("thanks"))

My test looks like this:

class TestViewHomePost(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_form(self):
        with mock.patch('profiles.views.ProfileForm') as mock_profile_form:
            mock_profile_form.is_valid.return_value = True
            request = self.factory.post(reverse("home"), data={})
            response = home(request)
            logger.debug(mock_profile_form.is_valid.call_count)    # "0"

is_valid is not being called on the mock, which means ProfileForm is not patched.

Where did I make a mistake?

Pore answered 23/4, 2017 at 12:5 Comment(0)
C
3

I was able to fix mocking is_valid as following:

def test_form(self):
        with mock.patch('profiles.views.ProfileForm.is_valid') as mock_profile_form:
            mock_profile_form.return_value = True
            request = self.factory.post(reverse("home"), data={})
            response = home(request)

note: and you could use mock_profile_form.assert_called_once() to check if the mock has been called.

Claviform answered 9/8, 2017 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.