mocking Flask before_first_request

Viewed 1858

I have a Flask app and it has a before_first_request method defined. The method loads some cached data for the application. I am trying to run some unit tests, and the cached data is in the way. How can I mock the method.

@app.before_first_request
def load_caches():
    print "loading caches..."
# cache loading here.

in my test file, I define a global test_client as follows:

from unittest import TestCase
from .. import application
import mock


test_app = application.app.test_client()

My test classes follow that. The issue is that my test_app loads the cache and I need to mock that in my tests.

3 Answers

You can manually remove hooks in your test client:

test_app = application.app.test_client()
test_app.before_first_request_funcs = []

I did not find a way to mock the function directly, but i can mock functions called within it:

@app.before_first_request
def before_first_request():
    load_caches()

def load_caches():
    print "loading caches..."
Related