1
我在django管理中添加了一些內聯驗證,如果模型實例上的某個字段不存在,則不會保存內聯。我不想增加額外的最後期限,如果沒有已經是最後期限:在Django中內聯單元測試驗證admin
class DeadlineInlineFormset(forms.models.BaseInlineFormSet):
def clean(self):
super(DeadlineInlineFormset, self).clean()
# make sure deadline is set
if not self.instance.deadline:
raise ValidationError(_("Doesn't validate"))
class DeadlineInline(admin.StackedInline):
model = AdditionalDeadline
formset = DeadlineInlineFormset
class GrantAdmin(admin.ModelAdmin):
...
inlines = [DeadlineInline]
...
這工作得很好,但我掙扎單元測試。到目前爲止,我有:
class GrantAdminTestCase(TestCase):
fixtures = [...]
def test_forms(self):
# create the form from a model instance.
# it should validate but it doesn't
g = Grant.objects.first()
form = GrantAdminForm(instance=g)
self.assertEqual(form.is_valid(), True)
# remove deadline and add additional deadlines
# It shouldn't be valid because deadline is None
g.deadline = None
g.additional_deadlines.add(
Deadline(deadline=datetime.now())
)
self.assertEqual(form.is_valid(), False)
即使模型實例有效,第一個斷言失敗。第二個斷言通過但不應該因爲它現在應該是無效的。 所以一定是錯誤的。
我也不確定這是否是正確的做法。在模型中進行驗證會更容易嗎?甚至在形式而不是形式?
編輯:相當多的,這是不對的,我已經改變了一些東西,但它仍然沒有工作:
def test_forms(self):
g = Grant.objects.first()
form = GrantAdminForm(model_to_dict(g))
self.assertEqual(form.is_valid(), True)
DeadlineFormSet = inlineformset_factory(Grant, Deadline)
# should be invalid
g.deadline = None
g.additional_deadlines.add(Deadline(deadline=datetime.now()))
formset = DeadlineFormSet(instance=g)
self.assertEqual(formset.is_valid(), False)
# should be valid
g = Grant.objects.first()
formset = DeadlineFormSet(instance=g)
self.assertEqual(formset.is_valid(), True)
前兩個斷言通過,但最後卻沒有。