Python Flask单击命令unittests-如何使用测试应用程序;使用“应用上下文”;室内装修设计师

Python Flask单击命令unittests-如何使用测试应用程序;使用“应用上下文”;室内装修设计师,python,unit-testing,flask,command-line-interface,pytest,Python,Unit Testing,Flask,Command Line Interface,Pytest,我不知道如何正确使用测试应用程序版本,而UnitTest(使用pytest)flask cli命令(使用click)使用和\u app\u context修饰。此装饰程序将pytest fixture应用程序替换为“普通”开发应用程序。我使用应用程序工厂模式 在简化版本中,我的命令如下所示(mind@with_appcontext): 没有@with_appcontextunittests工作得很好(它们通过pytest注入应用程序),但是命令本身没有,因为它需要应用程序上下文 我提取的pyte

我不知道如何正确使用测试应用程序版本,而UnitTest(使用pytest)flask cli命令(使用click)使用
和\u app\u context修饰。此装饰程序将pytest fixture应用程序替换为“普通”开发应用程序。我使用应用程序工厂模式

在简化版本中,我的命令如下所示(mind
@with_appcontext
):

没有
@with_appcontext
unittests工作得很好(它们通过pytest注入应用程序),但是命令本身没有,因为它需要应用程序上下文

我提取的pytest代码:

# pytest fixtures
@pytest.yield_fixture(scope='function')
def app():
    """An application for the tests."""
    _app = create_app(TestConfig)
    ctx = _app.test_request_context()
    ctx.push()

    yield _app

    ctx.pop()


@pytest.yield_fixture(scope='function')
def db(app):
    """A database for the tests."""
    _db.app = app
    with app.app_context():
        _db.create_all()

    yield _db

    # Explicitly close DB connection
    _db.session.close()
    _db.drop_all()


@pytest.mark.usefixtures('db')
class TestCreateSuperUser:
    # db fixture uses app fixture, works the same if app was injected here as well
    def test_user_is_created(self, cli_runner, db):
        result = cli_runner.invoke(
            createsuperuser,
            input='johnytheuser\nemail@email.com\nsecretpass\nsecretpass'
        )
        assert result.exit_code == 0
        assert 'SUCCESS' in result.output
        # etc.
我所有使用
app
db
设备的测试都很好,除了这些装饰的设备。我不确定如何使用设置应用程序本身的appcontext
装饰器来解决这个问题

提前感谢您的任何提示。

灵感来源于

在您的测试中:

def test_user_is_created(self, cli_runner, db, script_info):
    result = cli_runner.invoke(
        createsuperuser,
        input='johnytheuser\nemail@email.com\nsecretpass\nsecretpass',
        obj=obj,
    )

被接受的答案帮助我找到了一个解决方案,但并没有一蹴而就。这里是我的工作,以防其他人有类似的问题

@pytest.fixture(scope='session')
def脚本_信息(应用程序):
返回ScriptInfo(创建应用程序=lambda:app)
已创建def测试用户(self、cli运行程序、db、脚本信息):
结果=cli\u runner.invoke(
创建超级用户,
输入用户\nemail@email.com\NSCretPass\nSCretPass',
obj=脚本信息,
)

我在测试我的一个flask命令时遇到了同样的问题。尽管您的方法可行,但我认为有必要在此处查看flask文档:

Flask有自己的cli命令测试运行程序,它可能解决了我们的内置问题。因此,您也可以只使用
app.test\u cli\u runner()
,而不用lambda来修补
create\u app
函数

from flask.cli import ScriptInfo

    @pytest.fixture
    def script_info(app):
        return ScriptInfo(create_app=lambda info: app)
def test_user_is_created(self, cli_runner, db, script_info):
    result = cli_runner.invoke(
        createsuperuser,
        input='johnytheuser\nemail@email.com\nsecretpass\nsecretpass',
        obj=obj,
    )