Issue
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?
Solution
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 is not able to find the translations directory during testing - try moving your test Python script or translations directory and see if it helps. I don't know how to customize the location of this directory in Flask-Babel, perhaps creating a symlink or running test from project root directory can help.
(Improvements: From the source code of flask-babel it looks for the translation folder with the following code:
@property
def translation_directories(self):
directories = self.app.config.get(
'BABEL_TRANSLATION_DIRECTORIES',
'translations'
).split(';')
for path in directories:
if os.path.isabs(path):
yield path
else:
yield os.path.join(self.app.root_path, path)
So for the test you can set the app["BABEL_TRANSLATION_DIRECTORIES"] to the an absolute path to have the test always find the translation or use print(app.root_path)
to see where it looks for the root path and link the translation there.
Answered By - loomchild
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.