我已经在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',
)
}
如果我在Permisison中更改为AllowAny
,测试效果很好,但如果保持IsAuthenticated
而不是AllowAny
,则不起作用。
我希望即使我保持IsAuthenticated
权限,测试也能很好地运行。
谁能建议我怎么做?我没有得到要更改的内容或在我的tests.py
文件中添加的内容。
您应该在方法中创建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='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)