如何测试 Django 应用程序中的删除视图?

How can I test delete view in Django app?

我想测试我的视图,但我的删除功能有问题。

   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)

这是我的模型:

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)

这是我要进行的测试:

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 )

但是我得到了

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

你能帮我做一下测试吗?

由于数据是在request.GET中编码的,因此应该在查询字符串中进行编码,所以:

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

然而,在查询字符串中定义它是很奇怪的。通常使用一个URL参数,或者在请求的内容上指定。