首页 > 解决方案 > 为 Django 认证的 API 视图编写测试用例

问题描述

我已经在 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='doe@f.com')
        self.contact.save()

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

上面的代码片段工作正常,但问题是.. 一旦我实现了身份验证系统,它就不起作用

下面是我的settings.py

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

如果我更改为AllowAny许可,则测试效果很好,但如果保留IsAuthenticated而不是AllowAny,则它不起作用。

我希望即使我IsAuthenticated得到许可,测试也应该运行良好。

谁能建议我该怎么做?我没有得到要更改的内容或tests.py文件中添加的内容。

标签: djangodjango-rest-frameworkdjango-testingdjango-tests

解决方案


您应该在方法中创建user对象setUp,并使用client.login()orforce_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='doe@f.com')
        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': 'ad@kjfd.com'
        })
        self.assertEqual(Contact.objects.count(), 2)

推荐阅读