Reputation: 20339
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:
in special/views.py
:
mod = Blueprint('special', __name__, template_folder="templates")
@mod.route('/standard')
def info():
return render_template('special/index_special.html')
in myapplication/__init__.py
:
app = Flask(__name__)
def register_blueprints(app):
from special.views import mod as special_blueprint
app.register_blueprint(special_blueprint, url_prefix='/special')
register_blueprints(app)
in myapplication/tests/test_special.py
class TestSpecial:
@classmethod
def create_app(cls):
app = Flask(__name__)
register_blueprints(app)
return app
@classmethod
def setup_class(cls):
cls.app = cls.create_app()
cls.client = cls.app.test_client()
def test_connect(self):
r = self.client.get('/standard')
assert r.status_code == 200
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
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