首页 > 解决方案 > Django Unittest如何调整client.post以在request.META中设置数据

问题描述

我试图通过将数据发布到视图来测试视图,但视图使用 request.META 中的键/值。如何调整我的 client.post 以确保填充 request.META 数据?

以下示例不起作用!

来自单元测试的示例:

        with mock.patch("......") as gt:
            header = {'SOME_SIGNATURE': 'BLAH'}
            gt.side_effect = ValueError
            response = self.client.post('/webhook/', data={'input': 'hi'}, 
                                    content_type='application/json', follow=False,
                                    secure=False, extra=header)
            self.assertEqual(response.status_code, 400)

视图中的代码:

def my_webhook_view(request):

  # Extract Data from Webhook
  payload = request.body

  # THIS LINE CAUSES MY UNITTESTS TO FAIL
  sig_header = request.META['HTTP_SOME_SIGNATURE']
  
  ......

标签: djangounit-testingpostclient

解决方案


extra不是post方法的单独参数,而是包罗万象的关键字参数变量。要传递您的标头,只需使用:

        response = self.client.post('/webhook/', data={'input': 'hi'}, 
                                content_type='application/json', follow=False,
                                secure=False, **header)

此外,请确保HTTP_在标题列表中包含前缀。


推荐阅读