【问题标题】:TestCase writing for Django authenticated API View为 Django 认证的 API 视图编写测试用例
【发布时间】:2019-06-16 12:28:35
【问题描述】:

我已经在 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)

sn-p 上面工作正常,但问题是.. 一旦我实施了身份验证系统,它就不起作用了

下面是我的settings.py

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

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

我希望即使我保持 IsAuthenticated 的许可,测试也应该运行良好。

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

【问题讨论】:

    标签: django django-rest-framework django-testing django-tests


    【解决方案1】:

    您应该在setUp方法中创建user对象,并使用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='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)
    

    【讨论】:

    • 谢谢,我有 force_authentication 的文档,但我无法实施。你能帮我在我的代码中做些什么吗?
    • 我无法实现这个,你能帮我吗?
    猜你喜欢
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2012-03-23
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多