Django Rest框架JWT单元测试

django

1个回答

写回答

Django
Django

使用Django Rest框架进行JWT单元测试

Django Rest框架是一个基于Python的强大Web框架,它提供了许多工具和库,使开发人员能够快速构建和部署Web应用程序。其中,JWT(JSON Web Token)是一种用于身份验证和授权的开放标准,它使用JSON数据格式来安全传输信息。在本文中,我们将探讨如何使用Django Rest框架进行JWT单元测试,并提供相应的案例代码。

首先,我们需要安装DjangoDjango Rest框架。可以使用以下命令在Python虚拟环境中安装它们:

pip install Django

pip install Djangorestframework

接下来,需要创建一个Django项目。可以使用以下命令创建一个名为"jwt_test"的项目:

Django-admin startproject jwt_test

然后,进入项目目录并创建一个名为"api"的应用程序:

cd jwt_test

Python manage.py startapp api

在"api"应用程序中,我们将创建一个用户注册和登录的API视图,并使用JWT进行身份验证。

首先,在"api/views.py"文件中,添加以下代码:

Python

from rest_framework.views import APIView

from rest_framework.response import Response

from rest_framework.permissions import AllowAny

from rest_framework_jwt.settings import api_settings

from Django.contrib.auth.models import User

class UserRegistrationAPIView(APIView):

permission_classes = (AllowAny,)

def post(self, request):

username = request.data.get('username')

password = request.data.get('password')

if not username or not password:

return Response({'error': 'Please provide both username and password.'}, status=400)

try:

user = User.objects.create_user(username=username, password=password)

user.save()

return Response({'message': 'User registered successfully.'}, status=201)

except:

return Response({'error': 'FAIled to register user.'}, status=400)

class UserLoginAPIView(APIView):

permission_classes = (AllowAny,)

def post(self, request):

username = request.data.get('username')

password = request.data.get('password')

if not username or not password:

return Response({'error': 'Please provide both username and password.'}, status=400)

user = User.objects.filter(username=username).first()

if user is None:

return Response({'error': 'Invalid username.'}, status=400)

if not user.check_password(password):

return Response({'error': 'Invalid password.'}, status=400)

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER

jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

payload = jwt_payload_handler(user)

token = jwt_encode_handler(payload)

return Response({'token': token}, status=200)

接下来,在"api/urls.py"文件中,添加以下代码:

Python

from Django.urls import path

from .views import UserRegistrationAPIView, UserLoginAPIView

urlpatterns = [

path('register/', UserRegistrationAPIView.as_view(), name='user-registration'),

path('login/', UserLoginAPIView.as_view(), name='user-login'),

]

然后,在项目的根目录中的"jwt_test/urls.py"文件中,添加以下代码:

Python

from Django.contrib import admin

from Django.urls import path, include

urlpatterns = [

path('admin/', admin.site.urls),

path('api/', include('api.urls')),

]

现在,我们已经完成了API视图和URL配置的设置。接下来,我们将使用Django Rest框架提供的测试工具进行单元测试。

在"api/tests.py"文件中,添加以下代码:

Python

from Django.test import TestCase

from Django.urls import reverse

from rest_framework.test import APIClient

from rest_framework import status

class UserRegistrationAPIViewTest(TestCase):

def setUp(self):

self.client = APIClient()

self.url = reverse('user-registration')

def test_user_registration_success(self):

data = {'username': 'testuser', 'password': 'testpassword'}

response = self.client.post(self.url, data, format='JSon')

self.assertEqual(response.status_code, status.HTTP_201_CREATED)

def test_user_registration_missing_fields(self):

data = {'username': 'testuser'}

response = self.client.post(self.url, data, format='JSon')

self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

class UserLoginAPIViewTest(TestCase):

def setUp(self):

self.client = APIClient()

self.url = reverse('user-login')

def test_user_login_success(self):

data = {'username': 'testuser', 'password': 'testpassword'}

response = self.client.post(self.url, data, format='JSon')

self.assertEqual(response.status_code, status.HTTP_200_OK)

self.assertIn('token', response.data)

def test_user_login_invalid_credentials(self):

data = {'username': 'testuser', 'password': 'wrongpassword'}

response = self.client.post(self.url, data, format='JSon')

self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

上述代码中,我们使用了Django的TestCase类和Django Rest框架提供的APIClient类来执行单元测试。我们测试了用户注册和登录的API视图,并检查了响应状态码和返回数据。

现在,我们可以运行单元测试了。在项目的根目录中,运行以下命令来执行测试:

Python manage.py test api.tests

测试结果

测试结果应该是通过的,如果出现错误,请检查代码逻辑和配置是否正确。

在本文中,我们介绍了如何使用Django Rest框架进行JWT单元测试。我们创建了一个简单的用户注册和登录API,并使用Django Rest框架提供的测试工具进行了单元测试。这些测试可以帮助我们确保API的正确性和稳定性。

希望本文对你有所帮助,祝你在开发Web应用程序时取得成功!

参考代码:

Python

from Django.test import TestCase

from Django.urls import reverse

from rest_framework.test import APIClient

from rest_framework import status

class UserRegistrationAPIViewTest(TestCase):

def setUp(self):

self.client = APIClient()

self.url = reverse('user-registration')

def test_user_registration_success(self):

data = {'username': 'testuser', 'password': 'testpassword'}

response = self.client.post(self.url, data, format='JSon')

self.assertEqual(response.status_code, status.HTTP_201_CREATED)

def test_user_registration_missing_fields(self):

data = {'username': 'testuser'}

response = self.client.post(self.url, data, format='JSon')

self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

class UserLoginAPIViewTest(TestCase):

def setUp(self):

self.client = APIClient()

self.url = reverse('user-login')

def test_user_login_success(self):

data = {'username': 'testuser', 'password': 'testpassword'}

response = self.client.post(self.url, data, format='JSon')

self.assertEqual(response.status_code, status.HTTP_200_OK)

self.assertIn('token', response.data)

def test_user_login_invalid_credentials(self):

data = {'username': 'testuser', 'password': 'wrongpassword'}

response = self.client.post(self.url, data, format='JSon')

self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号