Pierre GM
Pierre GM

Reputation: 20339

Templates when unit testing a Flask application

I'm writing unit tests for a Flask application that has roughly the following organization:

/myapplication
    runner.py
    /myapplication
        __init__.py
    /special
        __init__.py
        views.py
        models.py
    /static
    /templates
        index.html
        /special
            index_special.html
    /tests
        __init__.py
        /special
            __init__.py
            test_special.py

In particular, I want to test that the special module works as expected.

I have defined the following:

While the application itself works fine, the test_connect unit-test fails with a TemplateNotFound: special/index_special.html exception.

How could I tell the tests where to find the corresponding templates ? Bypassing the rendering of templates using Flask-testing is not really an option...

Upvotes: 3

Views: 3006

Answers (1)

DazWorrall
DazWorrall

Reputation: 14210

You can pass template_folder to the application object constructor:

app = Flask(__name__, template_folder='../templates')

You may have to use an absolute path, I'm not sure.

http://flask.pocoo.org/docs/api/#flask.Flask

I mostly tend to have a create_app function with my application code and use that in my tests, just so the application object is consistent. I'll only create a separate app if I want to test a single blueprint or something small in isolation.

def create_app(conf_obj=BaseSettings, conf_file='/etc/mysettings.cfg'):
    app = Flask(__name__)
    app.config.from_object(conf_obj)
    app.config.from_pyfile(conf_file, silent=True)
    .... blueprints etc
    return app

Then in my tests:

class TestFoo(unittest.TestCase):

    def setUp(self):
        self.app = create_app(TestSettings)
        ....

Upvotes: 2

Related Questions