I'd like to do some unit tests to check my flask app translations. I have tried this piece of code:
def test_pt_br(self):
with app.test_request_context():
app.config['BABEL_DEFAULT_LOCALE'] = 'pt_BR'
rv = app.test_client().get('/')
assert 'Execute, melhore' in str(rv.data)
However, it does not work/pass although the app runs fine. What am I doing wrong?
The code you have shown seems to work for me. Please see here complete example based on your description: https://github.com/loomchild/flask_babel_test. When I run ./flask_babel_test_test.py both tests pass.
Could you provide complete source code that allows to reproduce the problem?
Currently I can imagine the following solutions (both of them are present in commented-out sections in the example code linked above):
There is some caching involved - try to execute flask.ext.babel.refresh() after updating default locale during the test and see if it helps.
If you retrieve browser language automatically from Accept-Language HTTP header using localeselector, for example like this:
@babel.localeselector
def get_locale():
translations = [str(translation) for translation in babel.list_translations()]
return request.accept_languages.best_match(translations)
Then instead of modifying app config during the test, specify a header:
rv = app.test_client().get('/', headers=[("Accept-Language", "pt_BR")])
Flask-Babel cannot find the translations
directory during testing. It looks for them in app["BABEL_TRANSLATION_DIRECTORIES"]
config setting (translations
by default). The path can be absolute or relative to app.root_path
(print this variable in your test if you are not sure where it points to). You can specify multiple paths separated by ;
.