1

I've a view which is add_product. So, now I want to unit test this view using python unittest framework. In my add_product function I'm checking that if user is a superuser and if the request.method == 'POST' how can I write those logics in test_views?

views.py

def add_product(request):

    if request.user.is_superuser:

        if request.method == 'POST':
            product_name = request.POST['product_name']
            product_category = request.POST['product_category']
            product_price = request.POST['product_price']
            product_photo = request.FILES['product_photo']
            product_description = request.POST['product_description']

            add_product = Product(product_name = product_name, category = product_category, price = product_price,
                                  description = product_description, pub_date = datetime.today(), image = product_photo)
            add_product.save()

            return render(request, 'home/home.html')

        else:
            return HttpResponse("404-Not Found")

    else:
        return render(request, 'html_view_with_error', {"error" : "PERMISSION DENIED"})

here is my try so far

test_views

    def test_add_product(self):

        product = Product.objects.create(

            product_id = 16,
            product_name = "Mango",
            category = "Fruit",
            price = 350,
            description = "Fresh Mangoes",
            pub_date = "2022-02-18",
            
        )

        client = Client()
        response = client.get(reverse('home'))
        self.assertEquals(response.status_code, 200)
        self.assertEqual(str(product), "Mango")
  • 1
    This answer will help you: https://stackoverflow.com/questions/36940384/how-do-i-setup-a-unit-test-user-for-django-app-the-unit-test-cant-login – Nechoj Apr 15 '22 at 18:07

0 Answers0