如何在 django 测试用例中添加自定义标头?

Aar*_*shi 2 django django-rest-framework django-tests

我在 django Rest 框架中实现了一个自定义身份验证类,该类需要在标头中的用户注册时提供客户端 ID 和客户端密钥。我正在为用户注册编写测试用例,如下所示:-

User = get_user_model()
client = Client()


class TestUserRegister(TestCase):
    def setUp(self):
        # pass
        self.test_users = {
            'test_user': {
                'email': 'testuser@gmail.com',
                'password': 'Test@1234',
                'username': 'test',
                'company': 'test',
                'provider': 'email'
            }
        }

        response = client.post(
            reverse('user_register'),
            headers={
                "CLIENTID": <client id>,
                "CLIENTSECRET": <client secret>
            },
            data={
                'email': self.test_users['test_user']['email'],
                'username': self.test_users['test_user']['username'],
                'password': self.test_users['test_user']['password'],
                'company': self.test_users['test_user']['company'],
                'provider': self.test_users['test_user']['provider'],
            },
            content_type='application/json',
        )
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_register(self):
        response = client.post(
            reverse('user_register'),
            headers={
                "CLIENTID": <client id>,
                "CLIENTSECRET": <client secret>
            },
            data={
                "first_name": "john",
                "last_name": "williams",
                "email": "john@gmail.com",
                "password": "John@1234",
                "username": "john",
                "company": "john and co.",
                "provider": "email",
            },
            content_type="application/json"
        )

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
Run Code Online (Sandbox Code Playgroud)

这是我的自定义身份验证类:-

from oauth2_provider.models import Application
from rest_framework import authentication
from rest_framework.exceptions import APIException


class ClientAuthentication(authentication.BaseAuthentication):
    @staticmethod
    def get_client_credentials(request):
        try:
            client_id = request.headers.get('CLIENTID')
            client_secret = request.headers.get('CLIENTSECRET')
        except:
            raise APIException(detail="Missing Client Credentials", code=400)
        return {
            'client_id': client_id,
            'client_secret': client_secret
        }

    def authenticate(self, request):
        credentials = self.get_client_credentials(request)

        client_instance = Application.objects.filter(
            client_id=credentials['client_id'],
            client_secret=credentials['client_secret'],
        ).first()

        if not client_instance:
            raise APIException("Invalid client credentials", code=401)
        return client_instance, None
Run Code Online (Sandbox Code Playgroud)

但如果我不将自定义身份验证添加到我的注册视图中,它仍然会给我 500 内部服务器错误,一切都工作正常。我怎样才能解决这个问题?

hen*_*der 5

要添加自定义标头,您需要在它们前面加上 HTTP_ 前缀:

client.post(url, ..., HTTP_CLIENTID=<client id>, HTTP_CLIENTSECRET=<client secret>)
Run Code Online (Sandbox Code Playgroud)

或使用字典:

headers = {"HTTP_CLIENTID": "Some id", "HTTP_CLIENTSECRET": "some secret"}

client.post(url, **headers)
Run Code Online (Sandbox Code Playgroud)