如何在具有 permission_classes = (IsAuthenticated,) 的 Django REST API 端点上编写单元测试

How to write a unit test on Django REST API endpoint that has permission_classes = (IsAuthenticated,)

大家好我想在我的 Django 应用程序上编写单元测试,以测试不同的 API 端点但似乎我无法弄清楚我们这里的问题是一个 snap 代码到目前为止我做了什么:

urls.py :

path('translate/display/', DisplayTranslation.as_view(), name='display_translation'),

对应的DRF view.py :

class DisplayTranslation(generics.ListAPIView):
    queryset = Translation.objects.all()
    serializer_class = TranslationSerializers
    permission_classes = (IsAuthenticated,)

这是我到目前为止在我的单元上所做的 test.py :

apiclient = APIClient()

class TranslationTestCases(APITestCase):
    def setUp(self):
        self.role = baker.make(Roles)
        self.user = baker.make(Users, user_role=self.role)
        self.token = reverse('token_obtain_pair', kwargs={'email': self.user.email, 'password': self.user.password})
        self.translation = baker.make(Translation, _quantity=10)
    
    def test_get_all_translations(self):
        header = {'HTTP_AUTHORIZATION': 'Token {}'.format(self.token)} 
        response = self.client.get(reverse('display_translation'), {}, **header)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 10)

这是我 运行 测试时遇到的错误: in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'token_obtain_pair' with keyword arguments '{'email': 'dZbQNWCjif@example.com', 'password': 'PfQzPqqVVLAdLZtJyVUxVjkGJEgRABYdHxMRhCGZJWxnZxpxEgUkgUKklENrWlBiYOCxhaDtJXdtXCtNdOJYtSWTzIrdvPnrmezXBNjEYYTpyZWjOLMnMIBMAfYnLwcC'}' not found. 1 pattern(s) tried: ['token/$']

更多信息,在我的 Django 应用程序的身份验证中,我使用了 DRF、rest_auth 和 SimpleJWT 库。

我可以做些什么来改进我的代码?或替代解决方案?我找不到与我类似的问题。

基本可以用

@patch.object(DisplayTranslation, "permission_classes", [])
def test_get_all_translations(self):
    ...

https://docs.python.org/3/library/unittest.mock.html#patch-object

有身份验证:

urlpatterns = [
    ...
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    ...
]

class TranslationTestCases(APITestCase):
    def setUp(self):
        self.api_client = APIClient()
        self.role = baker.make(Roles)
        self.user = baker.make(Users, user_role=self.role)
        self.token_url = reverse('token_obtain_pair')
        self.translation = baker.make(Translation, _quantity=10)
        response = self.api_client.post(self.token_url, {"username": self.user.username, "password": self.user.password})
        self.token = response.json()["access"]
    
    def test_get_all_translations(self):
        header = {'HTTP_AUTHORIZATION': 'Bearer {}'.format(self.token)} 
        ...

https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html