Flask blueprint unit-testing Flask blueprint unit-testing flask flask

Flask blueprint unit-testing


I did the following if this helps anyone. I basically made the test file my Flask application

from flask import Flaskimport unittestapp = Flask(__name__)from blueprint_file import blueprintapp.register_blueprint(blueprint, url_prefix='')class BluePrintTestCase(unittest.TestCase):    def setUp(self):        self.app = app.test_client()    def test_health(self):        rv = self.app.get('/blueprint_path')        print rv.dataif __name__ == '__main__':    unittest.main()


Blueprints are very similar to application. I guess that you want test test_client requests.

If you want test blueprint as part of your application then look like no differences there are with application.

If you want test blueprint as extension then you can create test application with own blueprint and test it.


I have multiple APIs in one app and therefore multiple blueprints with url_prefix. I did not like that I have to prefix all paths when testing on of the APIs. I used the following class to wrap the test_client for blueprints:

class BlueprintClient():    def __init__(self, app_client, blueprint_url_prefix):        self.app_client = app_client        self.blueprint_url_prefix = blueprint_url_prefix.strip('/')    def _delegate(self, method, path, *args, **kwargs):        app_client_function = getattr(self.app_client, method)        prefixed_path = '/%s/%s' % (self.blueprint_url_prefix, path.lstrip('/'))        return app_client_function(prefixed_path, *args, **kwargs)    def get(self, *args, **kwargs):        return self._delegate('get', *args, **kwargs)    def post(self, *args, **kwargs):        return self._delegate('post', *args, **kwargs)    def put(self, *args, **kwargs):        return self._delegate('put', *args, **kwargs)    def delete(self, *args, **kwargs):        return self._delegate('delete', *args, **kwargs)app_client = app.test_client()api_client = BlueprintClient(app_client, '/api/v1')api2_client = BlueprintClient(app_client, '/api/v2')