Home > Enterprise >  How can I test delete view in Django app?
How can I test delete view in Django app?

Time:11-05

I want to test my View but I have problem with my delete function.

   class AnimalView(APIView):
        def delete(self, request, format = None):              
            id = int(request.GET.get('id'))
            try:
                animal = Animal.objects.get(id=id)
            except:
                return Response(status=status.HTTP_404_NOT_FOUND)
            animal.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)

This is my model:

class Animal(models.Model):
    name = models.CharField(unique=True, max_length=30, blank=False, null=False)
    class Meta:
        managed = True
        db_table = 'animal'
        ordering = ['name']
    def __str__(self):
        return str(self.name)

and this is the test that I'm trying to make:

class TestURL(TestCase):
    def setUp(self):
        self.client = Client()
    def test_animal_delete(self):
        animal = Animal.objects.create(name = 'TestAnimal')
        response = self.client.delete(reverse("category_animal"), json.dumps({'id' : animal.id}))
        self.assertEqual(status.HTTP_204_NO_CONTENT,response.status_code )

But I'm getting a

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

Can you please help me with my test?

CodePudding user response:

Since the data is encoded in request.GET, this should be encoded in the querystring, so:

response = self.client.delete(f'{reverse("category_animal")}?id={animal.id}')

It is however quite odd to define this in the query string. Usually one uses a URL parameter, or it is specified on the content of the request.

  • Related