django / python视图测试(来自ModelForm的数据)

时间:2013-10-23 15:19:26

标签: python django unit-testing testing

我有一个django视图,它将请求中的数据添加到数据库中(我使用ModelForms完成了这一操作)。我有这个ModelForms类:

class AddForm(forms.ModelForm):

class Meta:
    model = Product
    fields = ('name', 'price', 'category',)

和我在表单中输入数据时我在视图中传递数据:

    if request.method == 'POST': # If the form has been submitted...
    name_add = request.POST.get("name")
    form = AddForm(request.POST) # A form bound to the POST datas
    not_add = 0
    if form.is_valid(): # All validation rules pass
        for n in Product.objects.filter(dashboard = curr_dashboard):
            if n.name == name_add:
                not_add = 1
        if not_add != 1:
            obj = form.save(commit=False)
            obj.dashboard = curr_dashboard
            obj.save()
            curr_buylist.add_product(obj.id)
            return HttpResponseRedirect(request.get_full_path()) # Redirect after POST
        else:
            forms.ValidationError("You already have this")
            return HttpResponseRedirect(request.get_full_path())

else:
    form = AddForm() # An unbound form

问题是,当我试图测试它时,它无法测试,因为我没有请求(我不知道传递一些数据)这是我在测试中的内容:

    def test_model_form(self):
    product = Product(name="SomeProduct")
    product_form = AddForm({'name': 'sothingtest', 'price': 100, 'category': 1}, instance= product)
    self.assertEquals(product_form.is_valid(), True)

但它仅测试AddForm类

1 个答案:

答案 0 :(得分:0)

我不确定这是你在找什么,但我会这样做:

将验证移至表单

class AddForm(forms.ModelForm):
    def clean_name(self):
        name = self.cleaned_data.get('name', '').strip()
        if Product.objects.filter(dashboard=curr_dashboard,
                                  name=name).count():
            raise forms.ValidationError(_("name is not unique"))
        return name

    class Meta:
        model = Product
        fields = ('name', 'price', 'category',)

并在视图中

if request.method == 'POST': # If the form has been submitted...
    form = AddForm(request.POST, instance=Product(dashboard=curr_dashboard) # A form bound to  the POST datas
    if form.is_valid(): # All validation rules pass
        obj = form.save()
        curr_buylist.add_product(obj.id)
        return HttpResponseRedirect(request.get_full_path()) # Redirect after POST
    else:
        return {'form': form} # just return invalid form with validation errors inside

要测试这个使用django TestClient(如果你想测试end2end行为)。如果您想要写单元测试您应该创建自己的请求,并填充请求字典。

如果您想要或写下对于您的if的测试,您可以模拟表单并测试if逻辑。