jeudi 25 juin 2020

Testing a POST request in Django

I have a function in my Django App that add a product to a favorite database. I need to write a test of it.

def add(request):
    data = {'success': False} 
    if request.method=='POST':
        product = request.POST.get('product')
        user = request.user       
        splitted = product.split(' ')
        sub_product = Product.objects.get(pk=(splitted[1]))
        original_product = Product.objects.get(pk=(splitted[0]))       
        p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product)
        p.save()        
        data['success'] = True
    return JsonResponse(data)

I know I have to write something like that:

 class AddDeleteProduct(TestCase):   
    
    def setUp(self):
        User.objects.create(username='Toto', email='toto@gmail.com')
            
    def test_add_product(self):       
        old_count = SavedProduct.objects.count()
        response = self.client.post(reverse('finder:add', {
        'product': '12 22'
        }))
        new_count = SavedProduct.objects.count()
        self.assertEqual(new_count, old_count + 1)

But I have some trouble passing the datas to the function. My 'product' comes from an AJAX call and I get it from this button value:

<div class='sub_button'>            
     <form class="add_btn" method='post'>
     <button class='added btn' value= ' ' ><i class=' fas fa-save'></i></button>                                
 </div> 

Aucun commentaire:

Enregistrer un commentaire