Flask click command unittests - how to use testing app with "with_appcontext" decorator? Flask click command unittests - how to use testing app with "with_appcontext" decorator? flask flask

Flask click command unittests - how to use testing app with "with_appcontext" decorator?


Inspiration taken from https://github.com/pallets/flask/blob/master/tests/test_cli.py#L254.

from flask.cli import ScriptInfo    @pytest.fixture    def script_info(app):        return ScriptInfo(create_app=lambda info: app)

In your test:

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,    )


The accepted answer helped me figure out a solution, but did not work out of the box. Here is what worked for me in case anyone else has a similar issue

@pytest.fixture(scope='session')def script_info(app):    return ScriptInfo(create_app=lambda:  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=script_info,    )


I had the same problem testing one of my flask commands. Although your approach works, I think it is valuable to have a look at the flask documentation here:https://flask.palletsprojects.com/en/1.1.x/testing/#testing-cli-commands

Flask has its own test runner for cli commands that probably has a fix to our problem builtin. So instead of patching the create_app function with a lambda you could also just use app.test_cli_runner() and it works out of the box.