Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask blueprint unit-testing

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?

like image 637
danbruegge Avatar asked Nov 13 '13 19:11

danbruegge


People also ask

Is flask blueprint necessary?

You don't have to use blueprints. Just import current_app as app in your routes.py (or views.py, whatever) and you are free to go.

What is the use of blueprint in flask?

Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications.


2 Answers

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()
like image 101
echappy Avatar answered Oct 09 '22 20:10

echappy


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.

like image 22
tbicr Avatar answered Oct 09 '22 20:10

tbicr