in a Flask unit-test, how can I mock objects on the request-global `g` object? in a Flask unit-test, how can I mock objects on the request-global `g` object? flask flask

in a Flask unit-test, how can I mock objects on the request-global `g` object?


This works

test_app.py

from flask import Flask, gapp = Flask(__name__)def connect_db():    print 'I ended up inside the actual function'    return object()@app.before_requestdef before_request():    g.db = connect_db()@app.route('/')def root():    return 'Hello, World'

test.py

from mock import patchimport unittestfrom test_app import appdef not_a_db_hit():    print 'I did not hit the db'class FlaskTest(unittest.TestCase):    @patch('test_app.connect_db')    def test_root(self, mock_connect_db):        mock_connect_db.side_effect = not_a_db_hit        response = app.test_client().get('/')        self.assertEqual(response.status_code, 200)if __name__ == '__main__':    unittest.main()

So this will print out 'I did not hit the db', rather than 'I ended up inside the actual function'. Obviously you'll need to adapt the mocks to your actual use case.