使用Flask-Babel进行Flask测试设置

时间:2016-07-03 12:53:33

标签: unit-testing flask babel

我希望使用setUp模块unittest

使用工厂创建我的Flask应用程序(create_app)使用Flask-Babel for i18n /

def create_app(config=None, app_name=None, blueprints=None):
    # Create Flask App instance
    app_name = app_name or __name__
    app = Flask(app_name)
    app.config.from_pyfile(config)

    configure_hook(app)
    configure_blueprints(app, blueprints)
    configure_extensions(app)
    configure_jinja_filters(app)
    configure_logging(app)
    configure_error_handlers(app)
    configure_cli(app)

    return app

create_app函数调用configure_extensions(app),如下所示:

def configure_extensions(app):
    """Initialize Flask Extensions."""
    db.init_app(app)
    babel.init_app(app)
    csrf.init_app(app)

    @babel.localeselector
    def get_locale():
        # If logged in, load user locale settings.
        user = getattr(g, 'user', None)

        if user is not None:
            return user.locale

        # Otherwise, choose the language from user browser.
        return request.accept_languages.best_match(
            app.config['BABEL_LANGUAGES'].keys())

    @babel.timezoneselector
    def get_timezone():
        user = getattr(g, 'user', None)

        if user is not None:
            return user.timezone

当我运行app时,它工作正常,但我无法正确创建单元测试,因为它断言如下错误:

File "C:\projects\rabiang\venv\lib\site-packages\flask_babel\__init__.py", line 127, in localeselector
'a localeselector function is already registered'
    AssertionError: a localeselector function is already registered

由于消息" localeselector函数已经注册",我认为在调用每个测试方法时调用setUp unittest @classmethod方法会产生问题。因此,我改变了setUpClass # -*- coding: utf-8 -*- import unittest from app import create_app, db from app.blueprints.auth import auth from app.blueprints.forum import forum from app.blueprints.main import main from app.blueprints.page import page class BasicsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): blueprints = [main, page, auth, forum] app = create_app(config='../test.cfg', blueprints=blueprints) cls.app = app.test_client() db.create_all() @classmethod def tearDownClass(cls): db.session.remove() db.drop_all() def test_app_exists(self): self.assertFalse(BasicsTestCase.app is None) if __name__ == '__main__': unittest.main() ,如下所示:

@babel.localeselector

但是,@babel.timezoneselectorpip install beautifulsoup4装饰器无法正常工作。

1 个答案:

答案 0 :(得分:0)

我通过使用unittest函数setUpClass设置应用程序一次来修复它。 另见答案Run setUp only once