Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Unittest how to adjust client.post to set data in request.META

I am trying to test a view by posting data to the view, but the view uses a key/value from request.META. How do I adjust my client.post to ensure the request.META data is populated ?

The following example isn't working!

Example from unittest:

        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)

Code from the view:

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']
  
  ......

like image 277
MarkyMark1000 Avatar asked Dec 30 '25 09:12

MarkyMark1000


1 Answers

extra is not a separate argument to the post method, but rather an catch-all keyword arguments variable. To pass your headers, simply use:

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

Also, make sure to include a HTTP_ prefix in your headers list.

like image 92
GwynBleidD Avatar answered Jan 01 '26 10:01

GwynBleidD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!