【问题标题】:How to add custom headers in django test cases?如何在 django 测试用例中添加自定义标头?
【发布时间】:2020-03-23 07:57:02
【问题描述】:

我在 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)

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

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

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

【问题讨论】:

  • 你使用的是哪个版本的 Django?
  • django 2.2.9 版本

标签: django django-rest-framework django-tests


【解决方案1】:

根据docs,传递标头的方式是作为附加关键字参数

client.post(url, ..., CLIENTID=<client id>, CLIENTSECRET=<client secret>)

【讨论】:

    【解决方案2】:

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

    client.post(url, ..., HTTP_CLIENTID=<client id>, HTTP_CLIENTSECRET=<client secret>)
    

    或使用字典:

    headers = {"HTTP_CLIENTID": "Some id", "HTTP_CLIENTSECRET": "some secret"}
    
    client.post(url, **headers)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 2018-11-28
      • 2013-08-22
      • 1970-01-01
      相关资源
      最近更新 更多