如何测试Django创建和更新视图

时间:2019-04-24 11:16:10

标签: django pytest django-testing

为简化起见,我无法获得创建或更新模型的测试。我已经写了UpdateViewCreateView,但是我无法通过测试。这里是视图:

class InventoryCreateView(CreateView):

    model = BaseInventory
    context_object_name = 'item'
    fields = [
        'product_id',
        'name',
        'color_primary',
        'color_secondary',
        'category',
        'description',
        'gender',
    ]

    template_name = 'inventory_list/product_detail.html'

class InventoryUpdateView(UpdateView):
    model = BaseInventory
    context_object_name = 'item'
    pk_url_kwarg = 'product_id'

    fields = [
        'product_id',
        'name',
        'color_primary',
        'color_secondary',
        'category',
        'description',
        'gender',
        ]

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['colors'] = Color.objects.all()
        return context

    template_name = 'inventory_list/product_detail.html'

这是我尝试创建的测试:

def test_create_inventory_view(self):
    """Test to see if inventory can be created"""
    form = {
        'product_id': 'vp12312',
        'name': 'Not a panda',
        'color_primary': self.color,
        'color_secondary': self.color,
        'category': BaseInventory.SHOES,
        'description': "Yellow panda",
        'gender': BaseInventory.MALE,
    }

    request = self.factory.post(InventoryCreateView, data=form)
    response = InventoryCreateView.as_view()(request)
    print(request)

    assert BaseInventory.objects.count() == 1
    assert 'inventory_list/product_detail.html' in response.template_name
    assert response.status_code == 302

def test_inventory_update_view(self):
    """Test for updating object"""
    item = BaseInventoryFactory(description='And everything you do')

    data = {
        'product_id': item.product_id,
        'name': item.name,
        'color_primary': item.color_primary,
        'color_secondary': item.color_secondary,
        'category': item.category,
        'description': 'Yeah they were all yellow',
        'gender': item.gender
    }

    request = self.factory.post('inventory_list:product-update',data,
                                kwargs={'product_id': item.product_id},
                                )
    response = InventoryUpdateView.as_view()(request, product_id=item.product_id)

    assert response.status_code == 302

    item.refresh_from_db()
    assert item.description == data['description']

这两个测试均导致状态代码为200,并且既不创建也不更新数据。我做错了什么吗?

0 个答案:

没有答案
相关问题