Flask blueprint unit-testing

danbruegge picture danbruegge · Nov 13, 2013 · Viewed 8.2k times · Source

Is there a good practice to unit-test a flask blueprint?

http://flask.pocoo.org/docs/testing/

I didn't found something that helped me or that is simple enough.

// Edit
Here are my code:

# -*- coding: utf-8 -*-
import sys
import os
import unittest
import flask

sys.path = [os.path.abspath('')] + sys.path

from app import create_app
from views import bp


class SimplepagesTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app('development.py')
        self.test_client = self.app.test_client()

    def tearDown(self):
        pass

    def test_show(self):
        page = self.test_client.get('/')
        assert '404 Not Found' not in page.data


if __name__ == '__main__':
    unittest.main()

In this case, i test the blueprint. Not the entire app. To test the blueprint i've added the root path of the app to sys.path. Now i can import the create_app function to ...create the app. I also init the test_client.

I think i've found a good solution. Or will is there a better way?

Answer

echappy picture echappy · Sep 16, 2015

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

from flask import Flask
import unittest

app = Flask(__name__)

from blueprint_file import blueprint
app.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.data


if __name__ == '__main__':
    unittest.main()