为 Django 验证的 API 视图编写测试用例

问题描述 投票:0回答:1

我已经成功写了一个

TestCase
并且工作正常。

首先看看我的代码:

下面是我的

tests.py

from django.shortcuts import reverse
from rest_framework.test import APITestCase
from ng.models import Contact


class TestNoteApi(APITestCase):
    def setUp(self):
        # create movie
        self.contact = Contact(userId=254, name="The Space Between Us", phone=2017, email='[email protected]')
        self.contact.save()

    def test_movie_creation(self):
        response = self.client.post(reverse('getAndPost'), {
            'userId': 253,
            'name': 'Bee Movie',
            'phone': 2007,
            'email': '[email protected]'
        })
        self.assertEqual(Contact.objects.count(), 2)

上面的代码片段工作正常,但问题是......一旦我实现了 DRF 身份验证系统,测试就失败了。

下面是我的

settings.py
:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

带有

@permission_classes
AllowAny
装饰器工作得很好,但如果我将值更改为
IsAuthenticated
测试就会失败。

我希望测试能够很好地运行,即使使用

IsAuthenticated
装饰器中的
@permission_classes
值也是如此。

任何人都可以建议我该怎么做吗?我不明白要在我的

tests.py
文件中更改或添加哪些内容。

django django-rest-framework django-testing django-tests
1个回答
0
投票

您应该在

user
方法中创建
setUp
对象,并使用
client.login()
force_authenticate()
发出经过身份验证的请求:

class TestNoteApi(APITestCase):
    def setUp(self):
        # create user
        self.user = User.objects.create(username="test", password="test") 
        # create movie
        self.contact = Contact(userId=254, name="The Space Between Us", phone=2017, email='[email protected]')
        self.contact.save()

    def test_movie_creation(self):
        # authenticate client before request 
        self.client.login(username='test', password='test')
        # or 
        self.clint.force_authenticate(user=self.user)
        response = self.client.post(reverse('getAndPost'), {
            'userId': 253,
            'name': 'Bee Movie',
            'phone': 2007,
            'email': '[email protected]'
        })
        self.assertEqual(Contact.objects.count(), 2)
© www.soinside.com 2019 - 2024. All rights reserved.