我的测试用例在 Django 中的 PUT 和 DELETE 方法失败

my testcases are failing in django for PUT and DELTE methods

我已经用 django_rest_framework.when 构建了一个基本的 crud api 我为 GET 编写了测试用例并且 POST 它工作正常,但是当我为 PUT 和 Delete 编写测试时它给了我错误。

tests.py

import json
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from .models import Customer
from .serializers import CustomerSerializer


class PostCustomerTest(APITestCase):

    def test_post(self):
        data = {
            "name": "john",
            "address": "address",
            "phoneNumber": "2645662",
            "gstin": "26456",
            "outstandingbalance": 2356.26 }
        
        response = self.client.post("/api/",data)
        self.assertEqual(response.status_code,status.HTTP_201_CREATED)

    def test_get(self):
        response = self.client.get('/api',{},True)
        self.assertEquals(response.status_code,status.HTTP_200_OK)

    def test_put(self):
        data = {
            "name": "test",
            "address": "address",
            "phoneNumber": "2645662",
            "gstin": "26456",
            "outstandingbalance": .36
            }

        response = self.client.put("/api/1/",data)
        serializer = CustomerSerializer(data)
        print(response.status_code)
        # self.assertEquals(response.data,serializer.data)
        self.assertEqual(response.status_code,status.HTTP_200_OK)
    
    def test_delete(self):
        response = self.client.delete("api/1/")

        self.assertEquals(response.status_code,status.HTTP_200_OK)

views.py

class CustomerView(APIView):

    def get_object(self, pk):
        try:
            return Customer.objects.get(pk=pk)
        except Customer.DoesNotExist:
            raise Http404

    def get(self,request,format=None):
        cus = Customer.objects.all()
        serializer = CustomerSerializer(cus,many=True)

        return Response(serializer.data,status=status.HTTP_200_OK)

    def post(self,request,format=None):

        serializer = CustomerSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            print("after Save")
            return Response({
                'Status':True,
                'Message':"Customer Added Successfully",
            },status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

    def put(self, request, pk, format=None):
        customer = self.get_object(pk)
        serializer = CustomerSerializer(customer, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        customer = self.get_object(pk)
        customer.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

models.py

class Customer(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=50)
    phoneNumber = models.CharField(max_length=50)
    gstin = models.CharField(max_length=50)
    outstandingbalance = models.FloatField()

    def __str__(self):
        return self.name

serializers.py

from rest_framework import serializers
from .models import *

class CustomerSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Customer
        fields = '__all__'

urls.py

from django.urls import path
from . import views

from rest_framework.urlpatterns import format_suffix_patterns


urlpatterns = [
    path('',views.CustomerView.as_view(),name='customer_get_post'),
    path('<int:pk>/',views.CustomerView.as_view(),name='customer_put_delete')
]

urlpatterns = format_suffix_patterns(urlpatterns)

project/urls.py

path('api/',include('api.urls'))

我遇到的错误是

AssertionError: 404 != 200

为什么会出现 404,对象将在 POST 测试用例中创建,对吧..? 我是测试用例的新手,如果有人能帮助我那就太好了。

您不应该假设测试的顺序 运行,主键本身也不会是一个。通常使用setUpTestData方法在数据库端创建数据,所以:

class PostCustomerTest(APITestCase):

    @classmethod
    def setUpTestData(cls):
        cls.item1 = Customer.objects.create(
            name='test1'
            address ='test2'
            phoneNumber='0123456789'
            gstin='test3'
            outstandingbalance=13.02
        )
        cls.item2 = Customer.objects.create(
            name='test4'
            address ='test5'
            phoneNumber='987654321'
            gstin='test6'
            outstandingbalance=14.25
        )

    # …

    def test_put(self):
        data = {
            'name': 'test',
            'address': 'address',
            'phoneNumber': '2645662',
            'gstin': '26456',
            'outstandingbalance': .36
        }
        response = self.client.put(f'/api/<b>{self.item1.pk}</b>/',data)
        serializer = CustomerSerializer(data)
        print(response.status_code)
        self.assertEqual(response.status_code,status.HTTP_200_OK)
    
    def test_delete(self):
        response = self.client.delete(f'api/<b>{self.item2.pk}</b>/')
        self.assertEquals(response.status_code,status.HTTP_200_OK)