Flask and Werkzeug: Testing a post request with custom headers

前端 未结 2 1576
南笙
南笙 2020-12-11 00:36

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

相关标签:
2条回答
  • 2020-12-11 00:44

    Werkzeug to the rescue!

    from werkzeug.test import EnvironBuilder, run_wsgi_app
    from werkzeug.wrappers import Request
    
    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
    
    0 讨论(0)
  • 2020-12-11 00:46

    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'});
    
    0 讨论(0)
提交回复
热议问题