Measuring forms in unit tests
I can't seem to mock the behavior of the form when unit testing.
My form is a simple ModelForm and is in profiles.forms
. The view is (again) a simple view that validates the form and then redirects it.
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 called on the layout, which means the ProfileForm is not fixed.
Where did I go wrong?
+3
source to share
1 answer
I managed to fix the taunt is_valid
as follows:
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 can use mock_profile_form.assert_called_once()
to check if the layout was called.
+1
source to share