如何在Django Rest框架中为基于通用类的视图编写API测试用例?

时间:2019-07-23 06:34:19

标签: django django-rest-framework

我在这里为一些create,update视图编写一些api测试用例,但是我尝试这样做。但这给了我错误。我可能做错了什么?有什么解决方案吗?

self.assertEqual(response.status_code,status.HTTP_200_OK)
AssertionError: 403 != 200

----------------------------------------------------------------------
Ran 2 tests in 0.031s

FAILED (failures=2)
Destroying test database for alias 'default'...

urls.py

app_name = 'product'
urlpatterns = [
    path('create/', ProductCreateAPIView.as_view(), name='create-product'),
    path('list/', ProductListAPIView.as_view(), name='list-product'),
    path('detail/<int:pk>/', ProductDetailAPIView.as_view(), name='detail-product'),
]

views.py

class ProductCreateAPIView(generics.CreateAPIView):
    serializer_class = ProductSerializer
    permission_classes = [IsAdminUser]
class ProductListAPIView(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = [IsAdminUser]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['name', 'description', 'category']
class ProductDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = [IsAdminUser]

tests.py

CREATE_PRODUCT_URL = reverse('product:create-product')
LIST_PRODUCT_URL = reverse('product:list-product')
class CreateProductTest(APITestCase):
    def setUp(self):
        self.client = Client()
    def test_details(self):
        response = self.client.post(CREATE_PRODUCT_URL,format='json')
        print(response.status_code)
        self.assertEqual(response.status_code,status.HTTP_201_CREATED)
class ListProductTest(APITestCase):
    def setUp(self):
        self.client = Client()
    def test_details(self):
        response = self.client.get(LIST_PRODUCT_URL,format='json')
        print(response.status_code)
        self.assertEqual(response.status_code,status.HTTP_200_OK)

2 个答案:

答案 0 :(得分:2)

由于IsAdminUser权限,所有视图仅允许超级用户使用,因此您将获得403代码。

您需要通过以管理员用户身份登录进行测试。您可以使用login的{​​{1}}方法来做到这一点。

对于“创建”测试方法,您需要在输入中提供有效的产品,以测试要创建产品的视图。

这是您的Client()CreateProductTest的示例测试用例:

ListProductTest

答案 1 :(得分:1)

要遵循的步骤

  1. 使用setUp方法创建用户
  2. test_<method>中认证用户
  3. 发送请求以包含数据的网址
CREATE_PRODUCT_URL = reverse('product:create-product')

class CreateProductTest(APITestCase):
    def setUp(self):
        self.client = Client()
        self.user = User(username="testuser", email="testemail@test.com")
        self.user.is_staff = True
        self.user.set_password('secret')
        self.user.save()

    def test_details(self):
        self.assertTrue(self.client.login(username="testuser", password="secret"))
        post_data = {} # your data here in dict
        response = self.client.post(CREATE_PRODUCT_URL, post_data, format='json')
        print(response.status_code)
        self.assertEqual(response.status_code,status.HTTP_201_CREATED)