Setting (mocking) request headers for Flask app unit test Setting (mocking) request headers for Flask app unit test flask flask

Setting (mocking) request headers for Flask app unit test


You need to pass in environ_base when you call get() or post(). E.g.,

client = app.test_client()response = client.get('/your/url/',                       environ_base={'HTTP_USER_AGENT': 'Chrome, etc'})

Then your request.user_agent should be whatever you pass in, and you can access it via request.headers['User-Agent'].

See http://werkzeug.pocoo.org/docs/test/#testing-api for more info.


Even though what @chris-mckinnel wrote works, I wouldn't opt to use environ_base in this case.

You can easily do something as shown below:

with app.test_request_context('url', headers={'User-Agent': 'Your value'}):    pass

This should do the job and at the same time it keeps your code explicit - explicit is better than implicit.

If you want to know what you can pass to the test_request_context reference the EnvironBuilder definition; which can be found here.