当我们在Django Rest框架中编写测试用例时,如何添加标头?

发布于 2025-02-11 08:00:51 字数 796 浏览 1 评论 0原文

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

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)

如您所见,我正在将标题中的Plaform-Subsciber-ID传递。但是获得 {'message':'平台订户ID的错误是'} 。似乎ID在标题中未正确配置。有人知道吗?

I'm trying to write test cases for my project. Now the problem is, that I don't figure out how to pass custom keyword arguments in the header. Here's my test case class below.

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)

as you can see I'm passing plaform-subsciber-id in the header. but getting an error that {'message': 'Platform subscriber id is required in header'}. It seems like id is not properly configured in the header. Does anybody know this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

安稳善良 2025-02-18 08:00:51

这就是您在测试中更新标头的方式:

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

self.client.client.credentials(** headers)

drf文档说:: 凭据方法可用于设置标题,然后将其包含在测试客户端的所有后续请求中。

This is how you update headers in tests:

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

self.client.credentials(**headers)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文