[英]How can I do the Unit testing of these custom permissions in my Django/Django REST project?
每個人。 我希望你一切都好。 我是 Django 新手,正在嘗試學習 RESTful 開發的基礎知識。 我只知道Python,所以這是我目前最合適的。
現在我正在嘗試為我的 API 實施單元測試。 這是一個簡單的 model 對 NBA 球員的姓名和身高實施 CRUD。 在我的模型中,我添加了一個 class 來描述這些數據並將其轉換為帶有 ModelViewSets 的視圖。 我想讓這些數據只對特定類型的用戶(讀寫用戶)可編輯,只對另一個(只讀用戶)可讀,並且對未經身份驗證的用戶無法訪問。 為此,我創建了一個自定義用戶 Model 並使用自定義權限將其轉換為我的視圖。 現在我想寫一些單元測試來檢查:
這是我的models.py
:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
ROLES = [('read-only', 'read-only'), ('read-write', 'read-write'),]
role = models.CharField(max_length=32, choices=ROLES, default='read-only')
# Create your models here.
class NBAplayers(models.Model):
first_name = models.CharField(max_length=100)
h_in = models.DecimalField(max_digits=5, decimal_places=2)
h_meters = models.DecimalField(max_digits=5, decimal_places=2)
last_name = models.CharField(max_length=120)
def __str__(self):
return self.first_name
我的views.py
:
from .models import NBAplayers, User
from .serializers import NBAplayersSerializer
from rest_framework.response import Response
from rest_framework import status, viewsets, permissions
class ReadOnlyPermission(permissions.BasePermission):
def has_permission(self, request, view):
requests = ('POST', 'PUT', 'DELETE', 'PATCH')
user = request.user
role = User.role
if user.is_anonymous: # Not Authenticated
return request.method == 'GET'
else:
if role == 'read-write':
return request.method in requests + ('GET',)
else: # Read Only User
return request.method == 'GET'
class NBAPlayersViewSet(viewsets.ModelViewSet):
serializer_class = NBAplayersSerializer
queryset = NBAplayers.objects.all()
permission_classes = [ReadOnlyPermission]
最后,我的urls.py
:
from django.contrib import admin
from django.urls import path, include
from .views import NBAPlayersViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('players', NBAPlayersViewSet, basename = 'Players list')
urlpatterns = [
#djoser basic authentication
#Routers URLs
path('', include(router.urls)),
path('players/<int:pk>/', include(router.urls)),
path('', include('djoser.urls')),
path('', include('djoser.urls.authtoken')),
]
使用AUTH_USER_MODEL = 'api_basic.User'
將自定義用戶添加到全局設置所需的所有代碼。 因此,我閱讀了文檔並觀看了一些視頻,試圖了解如何編寫正確的測試,但這些示例與這個問題並沒有那么接近。 我想請教一些正確方向的指點,以便我可以用它來構建測試的 rest。 這是我第一次寫單元測試。
預先感謝您提供的任何幫助或意見。 干杯!
這沒有什么棘手的。 例如,假設我有一項僅對管理員/員工用戶可用的服務。 這意味着您需要登錄並成為管理員。
在我的測試套件中,我將簡單地創建一個test_permissions
方法,我將在其中執行以下操作:
為了給你一個更具體的例子,這里有一個 DRF 的片段示例。 請注意,我正在使用自定義函數和 3rd 方庫來做一些事情,但邏輯保持不變:
class TestCaseSuite(Base):
def test_permissions(self):
user = UserFactory()
admin = AdminFactory()
# 401 Not authenticated
self.api_client.logout()
response = self.api_client.post(url, data=data)
assert response.status_code == 401
# 403 Not admin
self.api_client.force_authenticate(user)
response = self.api_client.post(url, data=data)
assert response.status_code == 403
# 201 Admin
self.api_client.logout()
self.api_client.force_authenticate(admin)
response = self.api_client.post(url, data=data)
assert response.status_code == self.success_code
# ...
# other tests for that service like:
# testing custom fields
# testing a successful call and the response output
# testing side-effects, like when sending an email or whatnot
# etc
需要注意的幾點:
setUp
方法中創建它(在每次測試之前觸發)因此,如果您想測試特定權限,您只需創建必要的對象/用戶並斷言您的期望:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.