from rest_framework.test import APITestCase
class TestMyProtectedView(APITestCase):
def setUp(self) -> None:
self.client.login(user, password)
def test_view(self):
# now you can access your view with logged-in user in setUp
response = self.client.get('/api/views/')
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
from rest_framework import status
# Create your tests here.
class UserLoginTestCase(TestCase):
def setUp(self):
self.client = APIClient()
self.admin_user = get_user_model().objects.create_superuser(
email='admin@example.com',
password='testpass123',
)
def test_user_create_or_collect_token(self):
"""User check token created if in post save signal format"""
token = Token.objects.get(user__email=self.admin_user.email)
self.assertTrue(token.key)
def test_user_authenticated(self):
"""Check if user is authenticated"""
token = Token.objects.get(user__email=self.admin_user.email)
self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
r = self.client.get(reverse('user:me'))
self.assertEqual(r.status_code, status.HTTP_200_OK)
def test_user_login(self):
"""test user login"""
url = reverse('user:login')
data = {
'username': 'admin@example.com',
'password': 'testpass123'
}
r = self.client.post(url, data, format='json')
self.assertEqual(r.status_code, status.HTTP_200_OK)
self.assertTrue(r.data['token'])
2条答案
按热度按时间cgh8pdjw1#
这取决于你的
authentication system
,如果你使用Django的默认认证,你可以使用它的辅助方法login(**credentials)
或force_login
https://docs.djangoproject.com/en/4.1/topics/testing/tools/#django.test.Client.login如果你使用Django Rest Framework和额外的第三方认证系统,你可以使用它的测试类
9bfwbjaz2#
就像Django和DRF文档中所描述的那样。
tests.py
urls.py
views.py
通常情况下,测试是为积极和消极的结果编写的。
请注意,在本例中,我有一个自定义的用户模型,并且还扩展了内置的ObtainAuthToken视图。