【问题标题】:Django - How to add access token to Client.post in Django test?Django - 如何在 Django 测试中向 Client.post 添加访问令牌?
【发布时间】:2021-10-31 13:20:30
【问题描述】:

所以我在下面有一些代码。每个端点都有一个身份验证过程,如下所示。我希望能够将 cls.user 中的访问令牌附加到 Client.post,以便我可以测试所有端点并确保它们也正确进行身份验证。我怎样才能做到这一点?所以理想情况下,我会将<bearer> <access token> 附加到 request.Meta['HTTP_AUTHORIZATION']

test.py

import json
from cheers.models import *
from warrant import Cognito
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from cheers.models import GoalCategory, Post
from dummy_factory.Factories import UserFactory, GoalFactory


class PostTest(TestCase):
    @classmethod
    # Generates Test DB data to persist throughout all tests
    def setUpTestData(cls) -> None:
        cls.goal_category = 'health'
        GoalCategory.objects.create(category=cls.goal_category, emoji_url='url')
        cls.user = UserFactory()
        cls.goal = GoalFactory()
        user_obj = User.objects.get(pk=cls.user.phone_number)
        goal_obj = Goal.objects.get(pk=cls.goal.uuid)
        Post.objects.create(creator_id=user_obj, goal_id=goal_obj, body='Some text')
        cls.user = Cognito(<Some login credentials>)
        cls.user.authenticate(password=<password>)

    def test_create(self):
        response = self.client.post(reverse('post'),
                                    data=json.dumps({'creator_id': str(self.user.uuid),
                                                     'goal_id': str(self.goal.uuid),
                                                     'body': 'Some text #Test'}),
                                    content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

测试验证器功能

def cognito_authenticator(view_func):
    def wrapped_view(request, *args, **kwargs):
        # Check the cognito token from the request.
        token = request.META['HTTP_AUTHORIZATION'].split(' ')[1]

        try:
            jwt.decode_cognito_jwt(token)
        except Exception:
            # Fail if invalid
            return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED)  # Or HttpResponseForbidden()
        else:
            # Proceed with the view if valid
            return view_func(request, *args, **kwargs)

    return wrapped_view

【问题讨论】:

    标签: python django django-testing


    【解决方案1】:

    你可以这样设置标题:

    token = 'sometoken'
    response = self.client.post(
        reverse('post'),
        data=json.dumps({
            'creator_id': str(self.user.uuid),
            'goal_id': str(self.goal.uuid),
            'body': 'Some text #Test'
        }),
        content_type='application/json',
        **{'HTTP_AUTHORIZATION': f'Bearer {token}'}
    )
    

    然后使用以下命令访问标题:

    request.META['HTTP_AUTHORIZATION']
    

    【讨论】:

    • 是的,很抱歉只需要测试一下
    猜你喜欢
    • 2018-10-02
    • 1970-01-01
    • 2017-04-17
    • 2017-03-11
    • 2015-10-08
    • 2023-03-13
    • 2023-02-02
    • 2016-03-27
    • 1970-01-01
    相关资源
    最近更新 更多