gpt4 book ai didi

python - django-crispy-form : Unit test fails because of TypeError of helper object

转载 作者:行者123 更新时间:2023-11-28 17:40:38 28 4
gpt4 key购买 nike

有点基于this book的一章,我想对使用 django-crispy-form 创建的表单进行单元测试,但出现以下错误:

TypeError: helper object provided to {% crispy %} tag must be a crispy.helper.FormHelper object.

表单(myapp/forms.py):

class MyBaseForm(forms.models.ModelForm):

def __init__(self, *args, **kwargs):
super(MyBaseForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'id-myForm'
self.helper.form_method = 'POST'
self.helper.form_action = ''
self.helper.add_input(Submit('submit', 'Create'))

class Meta:
model = MyModel
# [...]

class MyNewForm(MyBaseForm):

def save(self):
return MyModel.create_new(data=self.cleaned_data['data'])

View (myapp/views.py):

@login_required
def event_new(request):
if request.method == 'POST':
form = MyNewForm(data=request.POST)
if form.is_valid():
event = form.save()
return redirect(event)
else:
form = MyNewForm()
return render(request, 'event_new.html', {'form': form})

测试:

@patch('myapp.views.MyNewForm')
class MyNewViewUnitTest(TestCase):

def setUp(self):
self.t = unittest.TestCase()
self.t.request = HttpRequest()
self.t.request.POST['data'] = 'data'
self.t.request.user = Mock()

def test_passes_POST_data_to_Form(self, mockMyNewForm):
event_new(self.t.request)
mockMyNewForm.assert_called_once_with(data=self.t.request.POST)

我是否也必须以某种方式模拟辅助对象?那将如何完成?非常感谢!

最佳答案

迟到的答案,但今天遇到了这个问题。您需要将模拟类的帮助器指定给 FormHelper,以便 crispy 模板中的“isinstance”调用通过。最简单的方法是为脆皮形式创建一个 MagicMock 子类:

class MockCrispyForm(MagicMock):
helper = MagicMock(spec=FormHelper)
helper.template = False # necessary for templates to render
def is_valid(self):
return True # optional if you want form to validate

@patch('myapp.views.MyNewForm', MockCrispyForm())
class MyNewViewUnitTest(TestCase):
def setUp(self):
self.t = unittest.TestCase()
self.t.request = HttpRequest()
self.t.request.POST['data'] = 'data'
self.t.request.user = Mock()

def test_passes_POST_data_to_Form(self):
event_new(self.t.request)
myapp.views.MyNewForm.assert_called_once_with(
data=self.t.request.POST
)

关于python - django-crispy-form : Unit test fails because of TypeError of helper object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24898912/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com