I tried to mock form with mock.patch and can`t. I have this code
forms.py
class CreatePostForm(object):
pass
views.py:
from forms import CreatePostForm
def doit():
print CreatePostForm()
and I want to to test this view in isolation. I tried to patch form with mock.patch and i wrote something like that:
tests.py:
from mock import patch
import views
with patch('forms.CreatePostForm') as Form:
views.doit()
I tried to google for solution and find nothing
Answered: thanks @dstanek for good answer and good sample of code
When you use patch you specify the target of the object you want to mock. This is usually the place where it is imported, not where it is defined.
This is because by the time your test runs the views
module has already been imported. If you are importing the class like I'm doing in my example below then the views
module will contain a reference to the forms.CreatePostForm
. So changing forms.CreatePostForm
would not change this reference. Things would be different if you imported the module as specified forms.CreatePostForm
in your view.
I've included an extremely minimal example below.
forms.py
class CreatePostForm(object):
pass
views.py:
from forms import CreatePostForm
def doit():
print CreatePostForm()
tests.py:
from mock import patch
import views
with patch('views.CreatePostForm') as Form:
views.doit()