Flask and Werkzeug: Testing a post request with custom headers

theicfire picture theicfire · Aug 16, 2013 · Viewed 31.3k times · Source

I'm currently testing my app with suggestions from http://flask.pocoo.org/docs/testing/, but I would like to add a header to a post request.

My request is currently:

self.app.post('/v0/scenes/test/foo', data=dict(image=(StringIO('fake image'), 'image.png')))

but I would like to add a content-md5 to the request. Is this possible?

My investigations:

Flask Client (in flask/testing.py) extends Werkzeug's Client, documented here: http://werkzeug.pocoo.org/docs/test/

As you can see, post uses open. But open only has:

Parameters: 
 as_tuple – Returns a tuple in the form (environ, result)
 buffered – Set this to True to buffer the application run. This will automatically close the application for you as well.
 follow_redirects – Set this to True if the Client should follow HTTP redirects.

So it looks like it's not supported. How might I get such a feature working, though?

Answer

tbicr picture tbicr · Aug 16, 2013

open also take *args and **kwargs which used as EnvironBuilder arguments. So you can add just headers argument to your first post request:

with self.app.test_client() as client:
    client.post('/v0/scenes/test/foo',
                data=dict(image=(StringIO('fake image'), 'image.png')),
                headers={'content-md5': 'some hash'});