django - 使用强制身份验证 Django Rest Framework 进行单元测试

标签 django rest django-rest-framework drf-queryset

我正在使用 django Rest 框架构建 RESTful API 服务,我已经达到了必须为 RESTful API 服务创建自动化测试的地步。

sessionList api 需要 token 身份验证,如果用户没有 token ,他将无法访问 session 集合。

当我使用 POSTMAN 和真实浏览器对其进行测试时,该 API 运行良好。

session 列表:

class SessionList(generics.ListCreateAPIView):
    authentication_classes = [TokenAuthentication, ]
    permission_classes = [IsAuthenticated, ]
    throttle_scope = 'session'
    throttle_classes = (ScopedRateThrottle,)

    name = 'session-list'

    filter_class = SessionFilter
    serializer_class = SessionSerializer
    ordering_fields = (
        'distance_in_miles',
        'speed'
    )

    def get_queryset(self):
        return Session.objects.filter(owner=self.request.user)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

然后我使用 DRF 测试创建了一个自动化测试

运行 session 测试:

class RunningSessionTest(APITestCase):

    def test_get_sessions(self):
        factory = APIRequestFactory()
        view = views.SessionList.as_view()
        user = User.objects.create_user(
            'user01', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582d2b3d2a6869183d20393528343d763b3735" rel="noreferrer noopener nofollow">[email protected]</a>', 'user01P4ssw0rD')

        request = factory.get('http://localhost:8000/sessions/')
        force_authenticate(request, user=user)
        response = view(request)
        assert Response.status_code == status.HTTP_200_OK

    def test_get_sessions_not_authenticated_user(self):
        factory = APIRequestFactory()
        view = views.SessionList.as_view()
        user = User.objects.create_user(
            'user01', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e3b3d2b3c7e7f0e2b362f233e222b602d2123" rel="noreferrer noopener nofollow">[email protected]</a>', 'user01P4ssw0rD')

        request = factory.get('http://localhost:8000/sessions/')
        response = view(request)
        assert Response.status_code == status.HTTP_401_UNAUTHORIZED

问题:在这两种情况下,无论用户是否拥有 token ,响应值都是 HTTP_200_OK

我尝试通过尝试不同的方法来实现测试来解决该问题。我使用了 APIRequestFactory,也使用了 APIClient,但得到了相同的结果。说实话,在阅读了多次文档后,我无法理解 APIClient 和 APIRequestFactory 之间的区别。

测试结果:

Traceback (most recent call last):
  File "C:\python_work\DjnagoREST\01\restful01\RunKeeper\tests.py", line 67, in test_get_sessions_not_authenticated_user
    assert Response.status_code == status.HTTP_401_UNAUTHORIZED
AssertionError

我将非常感谢您的帮助。

最佳答案

我想您需要将 Response.status_code 更改为 response.status_code

事实证明,Response.status_code(来自rest_framework.response.Response) 等于 200 :D

关于django - 使用强制身份验证 Django Rest Framework 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55033950/

相关文章:

django - 如何从Django管理员 View 链接到其他对象?

python - 与 Django 的 MySQL 连接错误

java - 使用 REST 端点返回字符串

python - Django REST框架: nested serializer not properly validating data

python - Django Formset - 检查行标记是否已删除

python - 如何向 django 查询添加静态用户字段

java - 带有投影的JAVA中的OData REST API

rest - 已被 CORS 策略阻止 : Response to preflight request doesn’t pass access control check

python - Django Rest中的字符串相关字段

python - 使用 django 和 JWT 在 N 分钟后重新登录