Search code examples
djangodjango-modelsdjango-testingdjango-tests

I can't update the Model instance while Testing


I'm testing a CBV on Update and each time the model instance can't seems to update.

console output

>       self.assertEqual(product.showoff, data['showoff'])
E       AssertionError: 'uMsvXoRJbwFeieMvoCmR' != 'showoff 33333'
E       - uMsvXoRJbwFeieMvoCmR
E       + showoff 33333

views.py

class ProductUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    model = Product
    form_class = ProductForm
    template_name = "mainapp/product_update.html"
    success_message = 'Successfully Updated a Product entry'

    def dispatch(self, *args, **kwargs):
        return super(self.__class__, self).dispatch(self.request, *args, **kwargs)

    def form_valid(self, form):
        self.object = form.save(commit=False)
        #migh need to remove that line
        #self.object.author = self.request.user
        return super(self.__class__, self).form_valid(form)


product_update = login_required(ProductUpdateView.as_view())

tests.py

def test_ProductUpdateView_should_update_the_product_content(self):
    #Delete all Products
    Product.objects.all().delete()

    #Create user (fixture)
    user = mixer.blend('auth.User', is_superuser=True)

    #create a Product (fixture)
    product = mixer.blend('mainapp.Product')

    #Fields to update
    data = dict( showoff='showoff 33333', )

    #Preparing to post to the Update url
    url = reverse('wadiyabi:product_update', kwargs={'pk': product.pk})
    request = RequestFactory().post(url, data=data)

    #assign a user
    request.user = user

    #Post to Update URL
    response = views.ProductUpdateView.as_view()(request, pk=product.pk)

    #Assertion: status code
    self.assertEqual(response.status_code, 200)
    #Refresh the db and Get the latest Product
    product.refresh_from_db()
    product = Product.objects.get(pk=product.pk)
    #pytest.set_trace()

    #Assertion
    self.assertEqual(product.showoff, data['showoff'])

forms.py

class ProductForm(ModelForm):
    class Meta:
        model = Product
        fields = ['photo', 'showoff', 'quantity', 'price']

Solution

  • You are saving the model only if the form is valid. This is your form

    class ProductForm(ModelForm):
        class Meta:
            model = Product
            fields = ['photo', 'showoff', 'quantity', 'price']
    

    It has four fields. But your simulated form post has only one field in it

    data = dict( showoff='showoff 33333', )
    
    #Preparing to post to the Update url
    url = reverse('wadiyabi:product_update', kwargs={'pk': product.pk})
    request = RequestFactory().post(url, data=data)
    

    So your form is never going to be valid. As a result the model never gets saved. Hence the result.