我已经看过关于 SO 的两个答案,它们可能已经有了我的答案,但坦率地说,我只是不理解它们
两个 SO 问题都使用不同的方法。
我试图使用的方法是这样的。我创建了这个类:
from rest_framework.test import APIClient
from django.test import testcases
from django.contrib.auth.models import User
class RemoteAuthenticatedTest(testcases.TestCase):
client_class = APIClient
def setUp(self):
self.username = 'mister_neutron'
self.user = User.objects.create_user(username='mister_neutron',
email='mister_neutron@example.com',
password='F4kePaSs0d')
super(RemoteAuthenticatedTest, self).setUp()
我的单元测试如下所示:
class InfoViewTestCase(RemoteAuthenticatedTest):
def create_info_record(self):
from random import randint
blade = 'test-blade-host-name-%s' % (randint(0, 100))
breachs = randint(0,100)
dimm = 'test dimm slot %s' % (randint(0,100))
url = reverse('info:info_creat')
data = {
'blade_hostname': blade,
'breach_count': breachs,
'dimm_slot': dimm,
}
response = self.client.post(url,
data,
format='json',
REMOTE_USER=self.username)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Info.objects.count(), 1)
self.assertEqual(Info.objects.get().blade_hostname, blade)
我的 settings.py 文件中有这个:
#Authentications
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
相关分类