Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

656 lines · 18.4 KiB · Python

Last changed by

Merge pull request #3564 from pallets/cli-ast-parseDavid Lordbefore adoption2062d98

History of this file

Take it

1# This file was part of Flask-CLI and was modified under the terms of2# its Revised BSD License. Copyright © 2015 CERN.3import os4import ssl5import sys6import types7from functools import partial89import click10import pytest11from _pytest.monkeypatch import notset12from click.testing import CliRunner1314from flask import Blueprint15from flask import current_app16from flask import Flask17from flask.cli import AppGroup18from flask.cli import dotenv19from flask.cli import find_best_app20from flask.cli import FlaskGroup21from flask.cli import get_version22from flask.cli import load_dotenv23from flask.cli import locate_app24from flask.cli import NoAppException25from flask.cli import prepare_import26from flask.cli import run_command27from flask.cli import ScriptInfo28from flask.cli import with_appcontext2930cwd = os.getcwd()31test_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))323334@pytest.fixture35def runner():36    return CliRunner()373839def test_cli_name(test_apps):40    """Make sure the CLI object's name is the app's name and not the app itself"""41    from cliapp.app import testapp4243    assert testapp.cli.name == testapp.name444546def test_find_best_app(test_apps):47    """Test if `find_best_app` behaves as expected with different combinations of input."""  # noqa: B95048    script_info = ScriptInfo()4950    class Module:51        app = Flask("appname")5253    assert find_best_app(script_info, Module) == Module.app5455    class Module:56        application = Flask("appname")5758    assert find_best_app(script_info, Module) == Module.application5960    class Module:61        myapp = Flask("appname")6263    assert find_best_app(script_info, Module) == Module.myapp6465    class Module:66        @staticmethod67        def create_app():68            return Flask("appname")6970    app = find_best_app(script_info, Module)71    assert isinstance(app, Flask)72    assert app.name == "appname"7374    class Module:75        @staticmethod76        def create_app(foo):77            return Flask("appname")7879    with pytest.deprecated_call(match="Script info"):80        app = find_best_app(script_info, Module)8182    assert isinstance(app, Flask)83    assert app.name == "appname"8485    class Module:86        @staticmethod87        def create_app(foo=None, script_info=None):88            return Flask("appname")8990    with pytest.deprecated_call(match="script_info"):91        app = find_best_app(script_info, Module)9293    assert isinstance(app, Flask)94    assert app.name == "appname"9596    class Module:97        @staticmethod98        def make_app():99            return Flask("appname")100101    app = find_best_app(script_info, Module)102    assert isinstance(app, Flask)103    assert app.name == "appname"104105    class Module:106        myapp = Flask("appname1")107108        @staticmethod109        def create_app():110            return Flask("appname2")111112    assert find_best_app(script_info, Module) == Module.myapp113114    class Module:115        myapp = Flask("appname1")116117        @staticmethod118        def create_app():119            return Flask("appname2")120121    assert find_best_app(script_info, Module) == Module.myapp122123    class Module:124        pass125126    pytest.raises(NoAppException, find_best_app, script_info, Module)127128    class Module:129        myapp1 = Flask("appname1")130        myapp2 = Flask("appname2")131132    pytest.raises(NoAppException, find_best_app, script_info, Module)133134    class Module:135        @staticmethod136        def create_app(foo, bar):137            return Flask("appname2")138139    pytest.raises(NoAppException, find_best_app, script_info, Module)140141    class Module:142        @staticmethod143        def create_app():144            raise TypeError("bad bad factory!")145146    pytest.raises(TypeError, find_best_app, script_info, Module)147148149@pytest.mark.parametrize(150    "value,path,result",151    (152        ("test", cwd, "test"),153        ("test.py", cwd, "test"),154        ("a/test", os.path.join(cwd, "a"), "test"),155        ("test/__init__.py", cwd, "test"),156        ("test/__init__", cwd, "test"),157        # nested package158        (159            os.path.join(test_path, "cliapp", "inner1", "__init__"),160            test_path,161            "cliapp.inner1",162        ),163        (164            os.path.join(test_path, "cliapp", "inner1", "inner2"),165            test_path,166            "cliapp.inner1.inner2",167        ),168        # dotted name169        ("test.a.b", cwd, "test.a.b"),170        (os.path.join(test_path, "cliapp.app"), test_path, "cliapp.app"),171        # not a Python file, will be caught during import172        (173            os.path.join(test_path, "cliapp", "message.txt"),174            test_path,175            "cliapp.message.txt",176        ),177    ),178)179def test_prepare_import(request, value, path, result):180    """Expect the correct path to be set and the correct import and app names181    to be returned.182183    :func:`prepare_exec_for_file` has a side effect where the parent directory184    of the given import is added to :data:`sys.path`. This is reset after the185    test runs.186    """187    original_path = sys.path[:]188189    def reset_path():190        sys.path[:] = original_path191192    request.addfinalizer(reset_path)193194    assert prepare_import(value) == result195    assert sys.path[0] == path196197198@pytest.mark.parametrize(199    "iname,aname,result",200    (201        ("cliapp.app", None, "testapp"),202        ("cliapp.app", "testapp", "testapp"),203        ("cliapp.factory", None, "app"),204        ("cliapp.factory", "create_app", "app"),205        ("cliapp.factory", "create_app()", "app"),206        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),207        # trailing comma space208        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),209        # strip whitespace210        ("cliapp.factory", " create_app () ", "app"),211    ),212)213def test_locate_app(test_apps, iname, aname, result):214    info = ScriptInfo()215    assert locate_app(info, iname, aname).name == result216217218@pytest.mark.parametrize(219    "iname,aname",220    (221        ("notanapp.py", None),222        ("cliapp/app", None),223        ("cliapp.app", "notanapp"),224        # not enough arguments225        ("cliapp.factory", 'create_app2("foo")'),226        # invalid identifier227        ("cliapp.factory", "create_app("),228        # no app returned229        ("cliapp.factory", "no_app"),230        # nested import error231        ("cliapp.importerrorapp", None),232        # not a Python file233        ("cliapp.message.txt", None),234    ),235)236def test_locate_app_raises(test_apps, iname, aname):237    info = ScriptInfo()238239    with pytest.raises(NoAppException):240        locate_app(info, iname, aname)241242243def test_locate_app_suppress_raise():244    info = ScriptInfo()245    app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)246    assert app is None247248    # only direct import error is suppressed249    with pytest.raises(NoAppException):250        locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)251252253def test_get_version(test_apps, capsys):254    from flask import __version__ as flask_version255    from werkzeug import __version__ as werkzeug_version256    from platform import python_version257258    class MockCtx:259        resilient_parsing = False260        color = None261262        def exit(self):263            return264265    ctx = MockCtx()266    get_version(ctx, None, "test")267    out, err = capsys.readouterr()268    assert f"Python {python_version()}" in out269    assert f"Flask {flask_version}" in out270    assert f"Werkzeug {werkzeug_version}" in out271272273def test_scriptinfo(test_apps, monkeypatch):274    """Test of ScriptInfo."""275    obj = ScriptInfo(app_import_path="cliapp.app:testapp")276    app = obj.load_app()277    assert app.name == "testapp"278    assert obj.load_app() is app279280    # import app with module's absolute path281    cli_app_path = os.path.abspath(282        os.path.join(os.path.dirname(__file__), "test_apps", "cliapp", "app.py")283    )284    obj = ScriptInfo(app_import_path=cli_app_path)285    app = obj.load_app()286    assert app.name == "testapp"287    assert obj.load_app() is app288    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")289    app = obj.load_app()290    assert app.name == "testapp"291    assert obj.load_app() is app292293    def create_app():294        return Flask("createapp")295296    obj = ScriptInfo(create_app=create_app)297    app = obj.load_app()298    assert app.name == "createapp"299    assert obj.load_app() is app300301    obj = ScriptInfo()302    pytest.raises(NoAppException, obj.load_app)303304    # import app from wsgi.py in current directory305    monkeypatch.chdir(306        os.path.abspath(307            os.path.join(os.path.dirname(__file__), "test_apps", "helloworld")308        )309    )310    obj = ScriptInfo()311    app = obj.load_app()312    assert app.name == "hello"313314    # import app from app.py in current directory315    monkeypatch.chdir(316        os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps", "cliapp"))317    )318    obj = ScriptInfo()319    app = obj.load_app()320    assert app.name == "testapp"321322323def test_with_appcontext(runner):324    """Test of with_appcontext."""325326    @click.command()327    @with_appcontext328    def testcmd():329        click.echo(current_app.name)330331    obj = ScriptInfo(create_app=lambda: Flask("testapp"))332333    result = runner.invoke(testcmd, obj=obj)334    assert result.exit_code == 0335    assert result.output == "testapp\n"336337338def test_appgroup(runner):339    """Test of with_appcontext."""340341    @click.group(cls=AppGroup)342    def cli():343        pass344345    @cli.command(with_appcontext=True)346    def test():347        click.echo(current_app.name)348349    @cli.group()350    def subgroup():351        pass352353    @subgroup.command(with_appcontext=True)354    def test2():355        click.echo(current_app.name)356357    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))358359    result = runner.invoke(cli, ["test"], obj=obj)360    assert result.exit_code == 0361    assert result.output == "testappgroup\n"362363    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)364    assert result.exit_code == 0365    assert result.output == "testappgroup\n"366367368def test_flaskgroup(runner):369    """Test FlaskGroup."""370371    def create_app():372        return Flask("flaskgroup")373374    @click.group(cls=FlaskGroup, create_app=create_app)375    def cli(**params):376        pass377378    @cli.command()379    def test():380        click.echo(current_app.name)381382    result = runner.invoke(cli, ["test"])383    assert result.exit_code == 0384    assert result.output == "flaskgroup\n"385386387@pytest.mark.parametrize("set_debug_flag", (True, False))388def test_flaskgroup_debug(runner, set_debug_flag):389    """Test FlaskGroup debug flag behavior."""390391    def create_app():392        app = Flask("flaskgroup")393        app.debug = True394        return app395396    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)397    def cli(**params):398        pass399400    @cli.command()401    def test():402        click.echo(str(current_app.debug))403404    result = runner.invoke(cli, ["test"])405    assert result.exit_code == 0406    assert result.output == f"{not set_debug_flag}\n"407408409def test_print_exceptions(runner):410    """Print the stacktrace if the CLI."""411412    def create_app():413        raise Exception("oh no")414        return Flask("flaskgroup")415416    @click.group(cls=FlaskGroup, create_app=create_app)417    def cli(**params):418        pass419420    result = runner.invoke(cli, ["--help"])421    assert result.exit_code == 0422    assert "Exception: oh no" in result.output423    assert "Traceback" in result.output424425426class TestRoutes:427    @pytest.fixture428    def invoke(self, runner):429        def create_app():430            app = Flask(__name__)431            app.testing = True432433            @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])434            def yyy_get_post(x, y):435                pass436437            @app.route("/zzz_post", methods=["POST"])438            def aaa_post():439                pass440441            return app442443        cli = FlaskGroup(create_app=create_app)444        return partial(runner.invoke, cli)445446    @pytest.fixture447    def invoke_no_routes(self, runner):448        def create_app():449            app = Flask(__name__, static_folder=None)450            app.testing = True451452            return app453454        cli = FlaskGroup(create_app=create_app)455        return partial(runner.invoke, cli)456457    def expect_order(self, order, output):458        # skip the header and match the start of each row459        for expect, line in zip(order, output.splitlines()[2:]):460            # do this instead of startswith for nicer pytest output461            assert line[: len(expect)] == expect462463    def test_simple(self, invoke):464        result = invoke(["routes"])465        assert result.exit_code == 0466        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)467468    def test_sort(self, invoke):469        default_output = invoke(["routes"]).output470        endpoint_output = invoke(["routes", "-s", "endpoint"]).output471        assert default_output == endpoint_output472        self.expect_order(473            ["static", "yyy_get_post", "aaa_post"],474            invoke(["routes", "-s", "methods"]).output,475        )476        self.expect_order(477            ["yyy_get_post", "static", "aaa_post"],478            invoke(["routes", "-s", "rule"]).output,479        )480        self.expect_order(481            ["aaa_post", "yyy_get_post", "static"],482            invoke(["routes", "-s", "match"]).output,483        )484485    def test_all_methods(self, invoke):486        output = invoke(["routes"]).output487        assert "GET, HEAD, OPTIONS, POST" not in output488        output = invoke(["routes", "--all-methods"]).output489        assert "GET, HEAD, OPTIONS, POST" in output490491    def test_no_routes(self, invoke_no_routes):492        result = invoke_no_routes(["routes"])493        assert result.exit_code == 0494        assert "No routes were registered." in result.output495496497need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")498499500@need_dotenv501def test_load_dotenv(monkeypatch):502    # can't use monkeypatch.delitem since the keys don't exist yet503    for item in ("FOO", "BAR", "SPAM"):504        monkeypatch._setitem.append((os.environ, item, notset))505506    monkeypatch.setenv("EGGS", "3")507    monkeypatch.chdir(os.path.join(test_path, "cliapp", "inner1"))508    assert load_dotenv()509    assert os.getcwd() == test_path510    # .flaskenv doesn't overwrite .env511    assert os.environ["FOO"] == "env"512    # set only in .flaskenv513    assert os.environ["BAR"] == "bar"514    # set only in .env515    assert os.environ["SPAM"] == "1"516    # set manually, files don't overwrite517    assert os.environ["EGGS"] == "3"518519    # Non existent file should not load520    assert not load_dotenv("non-existent-file")521522523@need_dotenv524def test_dotenv_path(monkeypatch):525    for item in ("FOO", "BAR", "EGGS"):526        monkeypatch._setitem.append((os.environ, item, notset))527528    cwd = os.getcwd()529    load_dotenv(os.path.join(test_path, ".flaskenv"))530    assert os.getcwd() == cwd531    assert "FOO" in os.environ532533534def test_dotenv_optional(monkeypatch):535    monkeypatch.setattr("flask.cli.dotenv", None)536    monkeypatch.chdir(test_path)537    load_dotenv()538    assert "FOO" not in os.environ539540541@need_dotenv542def test_disable_dotenv_from_env(monkeypatch, runner):543    monkeypatch.chdir(test_path)544    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")545    runner.invoke(FlaskGroup())546    assert "FOO" not in os.environ547548549def test_run_cert_path():550    # no key551    with pytest.raises(click.BadParameter):552        run_command.make_context("run", ["--cert", __file__])553554    # no cert555    with pytest.raises(click.BadParameter):556        run_command.make_context("run", ["--key", __file__])557558    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])559    assert ctx.params["cert"] == (__file__, __file__)560561562def test_run_cert_adhoc(monkeypatch):563    monkeypatch.setitem(sys.modules, "cryptography", None)564565    # cryptography not installed566    with pytest.raises(click.BadParameter):567        run_command.make_context("run", ["--cert", "adhoc"])568569    # cryptography installed570    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))571    ctx = run_command.make_context("run", ["--cert", "adhoc"])572    assert ctx.params["cert"] == "adhoc"573574    # no key with adhoc575    with pytest.raises(click.BadParameter):576        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])577578579def test_run_cert_import(monkeypatch):580    monkeypatch.setitem(sys.modules, "not_here", None)581582    # ImportError583    with pytest.raises(click.BadParameter):584        run_command.make_context("run", ["--cert", "not_here"])585586    with pytest.raises(click.BadParameter):587        run_command.make_context("run", ["--cert", "flask"])588589    # SSLContext590    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)591592    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)593    ctx = run_command.make_context("run", ["--cert", "ssl_context"])594    assert ctx.params["cert"] is ssl_context595596    # no --key with SSLContext597    with pytest.raises(click.BadParameter):598        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])599600601def test_run_cert_no_ssl(monkeypatch):602    monkeypatch.setattr("flask.cli.ssl", None)603    with pytest.raises(click.BadParameter):604        run_command.make_context("run", ["--cert", "not_here"])605606607def test_cli_blueprints(app):608    """Test blueprint commands register correctly to the application"""609    custom = Blueprint("custom", __name__, cli_group="customized")610    nested = Blueprint("nested", __name__)611    merged = Blueprint("merged", __name__, cli_group=None)612    late = Blueprint("late", __name__)613614    @custom.cli.command("custom")615    def custom_command():616        click.echo("custom_result")617618    @nested.cli.command("nested")619    def nested_command():620        click.echo("nested_result")621622    @merged.cli.command("merged")623    def merged_command():624        click.echo("merged_result")625626    @late.cli.command("late")627    def late_command():628        click.echo("late_result")629630    app.register_blueprint(custom)631    app.register_blueprint(nested)632    app.register_blueprint(merged)633    app.register_blueprint(late, cli_group="late_registration")634635    app_runner = app.test_cli_runner()636637    result = app_runner.invoke(args=["customized", "custom"])638    assert "custom_result" in result.output639640    result = app_runner.invoke(args=["nested", "nested"])641    assert "nested_result" in result.output642643    result = app_runner.invoke(args=["merged"])644    assert "merged_result" in result.output645646    result = app_runner.invoke(args=["late_registration", "late"])647    assert "late_result" in result.output648649650def test_cli_empty(app):651    """If a Blueprint's CLI group is empty, do not register it."""652    bp = Blueprint("blue", __name__, cli_group="blue")653    app.register_blueprint(bp)654655    result = app.test_cli_runner().invoke(args=["blue", "--help"])656    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"