【问题标题】:Django Unittest how to adjust client.post to set data in request.METADjango Unittest如何调整client.post以在request.META中设置数据
【发布时间】:2021-03-26 10:34:08
【问题描述】:

我正在尝试通过将数据发布到视图来测试视图,但该视图使用 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']
  
  ......

【问题讨论】:

    标签: django unit-testing post client


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 2017-08-10
    • 2017-12-05
    • 2016-11-07
    • 2015-09-20
    • 2021-10-31
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多