首页 > 解决方案 > 烧瓶测试 - 尝试使用 SQLAlchemy 连接数据库时出现“RuntimeError:未找到应用程序”

问题描述

我用 pytest 编写测试代码来测试用 python 3 编写的 API。但我正在努力解决以下错误消息。python 代码在没有 pytest 的情况下可以正常工作,但只有在执行 pytest 代码时才会出现错误消息。我不认为问题来自低级问题,尽管它似乎是。老实说,这个错误背后的真正含义对我来说没有意义。这次的上下文似乎也与这个问题无关。(http://flask-sqlalchemy.pocoo.org/contexts/

有人可以给我一些解决方案的提示或提示吗?

* 我已经尝试根据这个问题解决这个问题('未找到应用程序。要么在视图函数中工作,要么推送应用程序上下文。')但它不适用于此代码。

可能与问题相关的代码部分。(test_auth.py)

    app = Flask(__name__)
    app.config.from_object(test)
    db_acs.init_app(app)
    logger = logging.getLogger(__name__)
    init_app(app, db_acs, logger)

错误

=========================================================================================== FAILURES ============================================================================================
____________________________________________________________________________________ test______________________________________________________________________________________

    def test():
        sqlpath = app.config['SQL_PATH']['getid']
        input_id = 'xxx'

>       rows = db_acs.dba(sqlpath, s1=input_id)

test_auth.py:68: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../xxx/xxx/db/dba.py:33: in dba
    connection = db.engine.connect()
../../../.pyenv/versions/3.6.5/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:877: in engine
    return self.get_engine()
../../../.pyenv/versions/3.6.5/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:886: in get_engine
    app = self.get_app(app)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <SQLAlchemy engine=None>, reference_app = None

    def get_app(self, reference_app=None):
        """Helper method that implements the logic to look up an
            application."""

        if reference_app is not None:
            return reference_app

        if current_app:
            return current_app._get_current_object()

        if self.app is not None:
            return self.app

        raise RuntimeError(
>           'No application found. Either work inside a view function or push'
            ' an application context. See'
            ' http://flask-sqlalchemy.pocoo.org/contexts/.'
        )
E       RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

标签: pythonunit-testingflasksqlalchemypytest

解决方案


在文件conftest.py中,你可以这样写:

@pytest.fixture(scope="session")
def app():
    app = create_app()  # Or app = Flask(__name__)
    return app

在你的 test_function 中:

def test_f(app):
    with app.app_context():
         # do your test

推荐阅读