Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a flask application that is setting up a database connection in a before_filter, very similar to this:

@app.before_request
def before_request():
    g.db = connect_db()

Now: I am writing some unit-tests and I do not want them to hit the database. I want to replace g.db with a mock object that I can set expectations on.

My tests are using app.test_client(), as is demonstrated in the flask documentation here. An example test looks something like

def test(self):
    response = app.test_client().post('/endpoint', data={..})
    self.assertEqual(response.status_code, 200)
    ...

The tests work and pass, but they are hitting the database and as I said I want to replace db access with mock objects. I do not see any way in test_client to access the g object or alter the before_filters.

like image 241
Gabe Moothart Avatar asked Jan 03 '13 00:01

Gabe Moothart


People also ask

How do you write a unit test for Flask?

Write Flask-specific unit and functional test functions with pytest. Run tests with pytest. Create fixtures for initializing the state for test functions. Determine code coverage of your tests with coverage.py.


1 Answers

This works

test_app.py

from flask import Flask, g

app = Flask(__name__)

def connect_db():
    print 'I ended up inside the actual function'
    return object()

@app.before_request
def before_request():
    g.db = connect_db()


@app.route('/')
def root():
    return 'Hello, World'

test.py

from mock import patch
import unittest

from test_app import app


def 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.

like image 177
aychedee Avatar answered Nov 23 '22 08:11

aychedee