我一直在努力模拟表单类以在基于类的视图中替换它的实例。但看起来是这样,因为表单位于类属性中,所以会发生这种情况before我用我的模拟替换了表单类。例证:
应用程序/views.py
from app.forms import SomeForm # For some reason, this _is_ my mock...
class SomeViewClass(View):
form = SomeForm # ... while this is the _real_ SomeForm
def post(self, request):
form = self.form(request.POST, request.FILES)
# Hacked around with pdb here
# (Pdb) self.form = SomeForm <-- Force the mock into the object
# (Pdb) form = self.form(request.POST, request.FILES)
# (Pdb) form.is_valid() is now True
# (Pdb) continue <--- Test finishes, and asserts are OK.
if form.is_valid(): # This fails, as I'm running the real code
# code, code, code
应用程序/测试/test_views.py
from mock import MagicMock, patch
from django.tests import Client, TestCase
@patch('app.views.SomeForm')
def test_post_valid_form_should_pass(self, mocked_form_class):
""" Replacing SomeForm in SomeViewClass to pas the is_valid test
"""
form_instance = MagicMock(spec=SomeForm())
form_instance.is_valid.return_value = True
mocked_form_class.return_value = form_instance
self.client.login(**self.credentials)
# code, code, code
正如您在插入的评论中看到的app/views.py
,我强行重装了self.form
并重新定义变量form
使用 pdb,这使我的测试通过了。
似乎由于某种原因,SomeViewClass
在我开始修补之前已[注册,实例化,...]SomeForm
。对此有什么想法吗?