(Flask) Faking request.environ['REMOTE_USER'] for testing (Flask) Faking request.environ['REMOTE_USER'] for testing flask flask

(Flask) Faking request.environ['REMOTE_USER'] for testing


Figured out the answer to my own question from Setting (mocking) request headers for Flask app unit test. There is an environ_base parameter that you can pass request environment variables into. It is documented in werkzeug.test.EnvironBuilder.

    def test_insert_cash_flow_through_post(self):    """Test that you can insert a cash flow through post."""    assert not CashFlow.query.first()    self.client.post("/index?account=main",                     environ_base={'REMOTE_USER': 'foo'},                     data=dict(settlement_date='01/01/2016',                               transaction_type='Other',                               certainty='Certain',                               transaction_amount=1))    assert CashFlow.query.first().user == 'foo'


You don't have to fake it. You can set it in your test.

from flask import requestdef test_something():    request.environ['REMOTE_USER'] = 'some user'    do_something_with_remote_user()    del request.environ['REMOTE_USER']

If you're worried about preserving any value that may already have been set, you can easily do that, too.

def test_something():    original_remote_user = request.environ.get('REMOTE_USER')    do_something_with_remote_user()    request.environ['REMOTE_USER'] = original_remote_user

You can also handle this at a higher scope, but without knowing how your tests are structured, it's hard to tell you how to do that.