如何编写单元测试以检查Django模型形式是否有效?

时间:2019-05-09 14:27:26

标签: django-forms

我正在尝试测试模型表格是否有效。

在测试功能中,我创建了两个以我的自定义窗体为特征的模型。我添加数据以填写表单的必填字段。

当我运行测试并在表单上调用is_valid()时,测试失败,并且表单出现错误,表明我添加的选项为not one of the available choices。这向我表明我错误地将Option实例添加到了表单或测试中。我不确定如何。

如何使模型表格对测试有效?

tests.py

    def test_valid_data(self):
        question_1 = Question(
            question_text='What is the width of the telephone?',
            date_published=timezone.now(),
            collection=Collection.objects.create()
        )
        question_1.save()
        option_1 = question_1.options.create(
            question=question_1,
            option_text='Five centimetres'
        )
        option_1.save()
        data = {'question_text': question_1.question_text, 'selected_option': option_1.option_text,}
        form = QuestionForm(data=data)
        print(form)
        self.assertTrue(form.is_valid())

forms.py

class QuestionForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(QuestionForm, self).__init__(*args, **kwargs)
        self.fields['selected_option'] = forms.ChoiceField(
            choices=[
                (f'{option.pk}', f'{option}')
                for option in Option.objects.filter(question_id=self.instance.pk)
            ],
            widget=RadioSelect,
            required=True,
            error_messages={
                'required': 'The question form lacks a selected_option'
            }

        )

    class Meta:
        model = Question
        fields = ('question_text',)
        labels = {
            'question_text': ''
        }
        widgets = {
            'question_text': forms.Textarea(attrs={'cols': '40', 'rows': '2'})
        }

models.py

class Question(models.Model):
    question_text = models.CharField(max_length=400)
    collection = models.ForeignKey(Collection, on_delete=models.PROTECT, default=None)
    date_published = models.DateTimeField('date published')

    def __str__(self) -> str:
        return self.question_text


class Option(models.Model):
    option_text = models.CharField(max_length=400)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)

    class Meta:
        default_related_name = 'options'

    def __str__(self) -> str:
        return self.option_text

预期:is_valid()-> True

实际:is_valid()-> False

1 个答案:

答案 0 :(得分:1)

此问题是由您在QuestionForm.__init__中定义选项的方式引起的:

choices=[
    (f'{option.pk}', f'{option}')
    for option in Option.objects.filter(question_id=self.instance.pk)
],

您已基于与您发起的choices相关的pk实例的Question创建了QuestionForm

在测试中(以及在管理员中),当您通过输入以下内容来初始化表单时,form未绑定到Question的任何实例 form = QuestionForm(data=data)

因此,查询Option.objects.filter(question_id=self.instance.pk)返回None,因为self.instance.pkNone

因此,由于QuestionForm

,您在保存choices = []之前会收到错误消息

如果您按下“保存”按钮或执行form.save(),查询将返回结果。