在django Rest框架中编写测试用例时如何添加标题?

Ahm*_*sin 0 python django django-models django-testing django-rest-framework

我正在尝试为我的项目编写测试用例。现在的问题是,我不知道如何在标头中传递自定义关键字参数。下面是我的测试用例类。

class ProjectTestClass(APITestCase,URLPatternsTestCase):

    allow_database_queries: True

    def projects_notifications_list(self,token,project_key):
        url = reverse('projects:project_noti_list',kwargs={"category": "all"})
        response = self.client.get(
            url,
            format='json', 
            HTTP_AUTHORIZATION="JWT "+token,
            headers={"platform-subscriber-id":project_key}
            )
        print("data -> ",response.data)

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

如您所见,我在标头中传递了 plaform-subsciber-id 。但收到错误 {'message': '标题中需要平台订阅者 id'}。看来 id 没有在标头中正确配置。有人知道这个吗?

小智 7

这是在测试中更新标头的方法:

headers = {'platform-subscriber-id': project_key}

self.client.credentials(**headers)

DRF 文档说:The credentials method can be used to set headers that will then be included on all subsequent requests by the test client.