python - UnitTest for Django Inline Formset
问题描述
I have a formset with custom validation logic:
forms.py
class MyFormSet(BaseInlineFormSet):
def clean(self):
super().clean()
forms = list(filter(lambda form: len(form.cleaned_data), self.forms))
if not forms or any(self.errors):
return
for form in forms:
...
And I use this custom formset in admin-site models:
admin.py
class MyInline(admin.TabularInline):
formset = MyFormSet
model = ClientAgreement
class ClientAdmin(admin.ModelAdmin):
form = Client
inlines = [
MyInline
]
So what I want to do now - test my custom clean logic in unit test. Inside the test I create formset with:
formset = inlineformset_factory(Client, ClientAgreement, formset=MyInlineFormSet, fields='all')
After that I create instance with my object:
object_formset = formset(instance=client1)
Now I can see all prepopulated test data inside object_formset according to ClientAdmin model.
But how can I pass changes to forms data to check my clean logic? Or maybe there is different path to solve this?
EDIT
Found out how to pass data into formset:
data = {
'client_agreements-TOTAL_FORMS': '2',
'client_agreements-INITIAL_FORMS': '2',
'client_agreements-1-id': self.second_client_agreement,
'client_agreements-1-agreement': self.second_client_agreement.agreement,
'client_agreements-1-is_default': False,
'client_agreements-0-id': self.online_client_agreement,
'client_agreements-0-agreement': self.first_client_agreement.agreement,
'client_agreements-0-is_default': True,
}
client_formset = formset(data, instance=self.second_client)
client_formset.save()
This leads to my goal - clean method in MyFormSet, but after super().clean() passed I receive error for each non-boolean field: 'Select a valid choice. That choice is not one of the available choices.' So I still can't reach my custom logic to test.
解决方案
推荐阅读
- c# - WPF - 触发包含在普通属性与 ObservableCollection 属性中的字段的更改
- sql-server - sql server 在现有列中插入值
- assembly - 如何结束我的汇编语言程序中的无限循环
- java - 如何在 JPA 中设置 CURRENT_TIMESTAMP 的默认值
- node.js - Mongodb Error withTransaction:给定的事务编号 1 与任何正在进行的事务不匹配。活跃事务数为-1
- r - shinyapps.io 上的 rdrop2 - 身份验证不起作用
- mysql - 比较 2 个表后返回特定日期的数据计数
- c# - windows窗体:设置背景图片
- laravel - Laravel Eager Loading 删除子项的空值
- excel - 自动比较按列分组的行并突出显示 Excel 中的不同单元格