Flask and Werkzeug: Testing a post request with custom headers

Question:

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?

Asked By: theicfire

||

Answers:

Werkzeug to the rescue!

from werkzeug.test import EnvironBuilder, run_wsgi_app

builder = EnvironBuilder(path='/v0/scenes/bucket/foo', method='POST', data={'image': (StringIO('fake image'), 'image.png')}, 
    headers={'content-md5': 'some hash'})
env = builder.get_environ()

(app_iter, status, headers) = run_wsgi_app(http.app.wsgi_app, env)
status = int(status[:3]) # output will be something like 500 INTERNAL SERVER ERROR
Answered By: theicfire

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'});
Answered By: tbicr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.