Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask and Werkzeug: Testing a post request with custom headers

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?

like image 653
theicfire Avatar asked Aug 16 '13 00:08

theicfire


2 Answers

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'});
like image 102
tbicr Avatar answered Nov 01 '22 20:11

tbicr


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
like image 29
theicfire Avatar answered Nov 01 '22 22:11

theicfire