Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

664 lines · 18.5 KiB · Python

Last changed by

Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7

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 platform5import ssl6import sys7import types8from functools import partial9from pathlib import Path10from unittest.mock import patch1112import click13import pytest14from _pytest.monkeypatch import notset15from click.testing import CliRunner1617from flask import Blueprint18from flask import current_app19from flask import Flask20from flask.cli import AppGroup21from flask.cli import DispatchingApp22from flask.cli import dotenv23from flask.cli import find_best_app24from flask.cli import FlaskGroup25from flask.cli import get_version26from flask.cli import load_dotenv27from flask.cli import locate_app28from flask.cli import main as cli_main29from flask.cli import NoAppException30from flask.cli import prepare_import31from flask.cli import run_command32from flask.cli import ScriptInfo33from flask.cli import with_appcontext3435cwd = Path.cwd()36test_path = (Path(__file__) / ".." / "test_apps").resolve()373839@pytest.fixture40def runner():41    return CliRunner()424344def test_cli_name(test_apps):45    """Make sure the CLI object's name is the app's name and not the app itself"""46    from cliapp.app import testapp4748    assert testapp.cli.name == testapp.name495051def test_find_best_app(test_apps):52    class Module:53        app = Flask("appname")5455    assert find_best_app(Module) == Module.app5657    class Module:58        application = Flask("appname")5960    assert find_best_app(Module) == Module.application6162    class Module:63        myapp = Flask("appname")6465    assert find_best_app(Module) == Module.myapp6667    class Module:68        @staticmethod69        def create_app():70            return Flask("appname")7172    app = find_best_app(Module)73    assert isinstance(app, Flask)74    assert app.name == "appname"7576    class Module:77        @staticmethod78        def create_app(**kwargs):79            return Flask("appname")8081    app = find_best_app(Module)82    assert isinstance(app, Flask)83    assert app.name == "appname"8485    class Module:86        @staticmethod87        def make_app():88            return Flask("appname")8990    app = find_best_app(Module)91    assert isinstance(app, Flask)92    assert app.name == "appname"9394    class Module:95        myapp = Flask("appname1")9697        @staticmethod98        def create_app():99            return Flask("appname2")100101    assert find_best_app(Module) == Module.myapp102103    class Module:104        myapp = Flask("appname1")105106        @staticmethod107        def create_app():108            return Flask("appname2")109110    assert find_best_app(Module) == Module.myapp111112    class Module:113        pass114115    pytest.raises(NoAppException, find_best_app, Module)116117    class Module:118        myapp1 = Flask("appname1")119        myapp2 = Flask("appname2")120121    pytest.raises(NoAppException, find_best_app, Module)122123    class Module:124        @staticmethod125        def create_app(foo, bar):126            return Flask("appname2")127128    pytest.raises(NoAppException, find_best_app, Module)129130    class Module:131        @staticmethod132        def create_app():133            raise TypeError("bad bad factory!")134135    pytest.raises(TypeError, find_best_app, Module)136137138@pytest.mark.parametrize(139    "value,path,result",140    (141        ("test", cwd, "test"),142        ("test.py", cwd, "test"),143        ("a/test", cwd / "a", "test"),144        ("test/__init__.py", cwd, "test"),145        ("test/__init__", cwd, "test"),146        # nested package147        (148            test_path / "cliapp" / "inner1" / "__init__",149            test_path,150            "cliapp.inner1",151        ),152        (153            test_path / "cliapp" / "inner1" / "inner2",154            test_path,155            "cliapp.inner1.inner2",156        ),157        # dotted name158        ("test.a.b", cwd, "test.a.b"),159        (test_path / "cliapp.app", test_path, "cliapp.app"),160        # not a Python file, will be caught during import161        (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),162    ),163)164def test_prepare_import(request, value, path, result):165    """Expect the correct path to be set and the correct import and app names166    to be returned.167168    :func:`prepare_exec_for_file` has a side effect where the parent directory169    of the given import is added to :data:`sys.path`. This is reset after the170    test runs.171    """172    original_path = sys.path[:]173174    def reset_path():175        sys.path[:] = original_path176177    request.addfinalizer(reset_path)178179    assert prepare_import(value) == result180    assert sys.path[0] == str(path)181182183@pytest.mark.parametrize(184    "iname,aname,result",185    (186        ("cliapp.app", None, "testapp"),187        ("cliapp.app", "testapp", "testapp"),188        ("cliapp.factory", None, "app"),189        ("cliapp.factory", "create_app", "app"),190        ("cliapp.factory", "create_app()", "app"),191        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),192        # trailing comma space193        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),194        # strip whitespace195        ("cliapp.factory", " create_app () ", "app"),196    ),197)198def test_locate_app(test_apps, iname, aname, result):199    assert locate_app(iname, aname).name == result200201202@pytest.mark.parametrize(203    "iname,aname",204    (205        ("notanapp.py", None),206        ("cliapp/app", None),207        ("cliapp.app", "notanapp"),208        # not enough arguments209        ("cliapp.factory", 'create_app2("foo")'),210        # invalid identifier211        ("cliapp.factory", "create_app("),212        # no app returned213        ("cliapp.factory", "no_app"),214        # nested import error215        ("cliapp.importerrorapp", None),216        # not a Python file217        ("cliapp.message.txt", None),218    ),219)220def test_locate_app_raises(test_apps, iname, aname):221    with pytest.raises(NoAppException):222        locate_app(iname, aname)223224225def test_locate_app_suppress_raise(test_apps):226    app = locate_app("notanapp.py", None, raise_if_not_found=False)227    assert app is None228229    # only direct import error is suppressed230    with pytest.raises(NoAppException):231        locate_app("cliapp.importerrorapp", None, raise_if_not_found=False)232233234def test_get_version(test_apps, capsys):235    from flask import __version__ as flask_version236    from werkzeug import __version__ as werkzeug_version237    from platform import python_version238239    class MockCtx:240        resilient_parsing = False241        color = None242243        def exit(self):244            return245246    ctx = MockCtx()247    get_version(ctx, None, "test")248    out, err = capsys.readouterr()249    assert f"Python {python_version()}" in out250    assert f"Flask {flask_version}" in out251    assert f"Werkzeug {werkzeug_version}" in out252253254def test_scriptinfo(test_apps, monkeypatch):255    obj = ScriptInfo(app_import_path="cliapp.app:testapp")256    app = obj.load_app()257    assert app.name == "testapp"258    assert obj.load_app() is app259260    # import app with module's absolute path261    cli_app_path = str(test_path / "cliapp" / "app.py")262263    obj = ScriptInfo(app_import_path=cli_app_path)264    app = obj.load_app()265    assert app.name == "testapp"266    assert obj.load_app() is app267    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")268    app = obj.load_app()269    assert app.name == "testapp"270    assert obj.load_app() is app271272    def create_app():273        return Flask("createapp")274275    obj = ScriptInfo(create_app=create_app)276    app = obj.load_app()277    assert app.name == "createapp"278    assert obj.load_app() is app279280    obj = ScriptInfo()281    pytest.raises(NoAppException, obj.load_app)282283    # import app from wsgi.py in current directory284    monkeypatch.chdir(test_path / "helloworld")285    obj = ScriptInfo()286    app = obj.load_app()287    assert app.name == "hello"288289    # import app from app.py in current directory290    monkeypatch.chdir(test_path / "cliapp")291    obj = ScriptInfo()292    app = obj.load_app()293    assert app.name == "testapp"294295296@pytest.mark.xfail(platform.python_implementation() == "PyPy", reason="flaky on pypy")297def test_lazy_load_error(monkeypatch):298    """When using lazy loading, the correct exception should be299    re-raised.300    """301302    class BadExc(Exception):303        pass304305    def bad_load():306        raise BadExc307308    lazy = DispatchingApp(bad_load, use_eager_loading=False)309310    with pytest.raises(BadExc):311        # reduce flakiness by waiting for the internal loading lock312        with lazy._lock:313            lazy._flush_bg_loading_exception()314315316def test_with_appcontext(runner):317    @click.command()318    @with_appcontext319    def testcmd():320        click.echo(current_app.name)321322    obj = ScriptInfo(create_app=lambda: Flask("testapp"))323324    result = runner.invoke(testcmd, obj=obj)325    assert result.exit_code == 0326    assert result.output == "testapp\n"327328329def test_appgroup(runner):330    @click.group(cls=AppGroup)331    def cli():332        pass333334    @cli.command(with_appcontext=True)335    def test():336        click.echo(current_app.name)337338    @cli.group()339    def subgroup():340        pass341342    @subgroup.command(with_appcontext=True)343    def test2():344        click.echo(current_app.name)345346    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))347348    result = runner.invoke(cli, ["test"], obj=obj)349    assert result.exit_code == 0350    assert result.output == "testappgroup\n"351352    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)353    assert result.exit_code == 0354    assert result.output == "testappgroup\n"355356357def test_flaskgroup(runner):358    def create_app():359        return Flask("flaskgroup")360361    @click.group(cls=FlaskGroup, create_app=create_app)362    def cli(**params):363        pass364365    @cli.command()366    def test():367        click.echo(current_app.name)368369    result = runner.invoke(cli, ["test"])370    assert result.exit_code == 0371    assert result.output == "flaskgroup\n"372373374@pytest.mark.parametrize("set_debug_flag", (True, False))375def test_flaskgroup_debug(runner, set_debug_flag):376    def create_app():377        app = Flask("flaskgroup")378        app.debug = True379        return app380381    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)382    def cli(**params):383        pass384385    @cli.command()386    def test():387        click.echo(str(current_app.debug))388389    result = runner.invoke(cli, ["test"])390    assert result.exit_code == 0391    assert result.output == f"{not set_debug_flag}\n"392393394def test_no_command_echo_loading_error():395    from flask.cli import cli396397    runner = CliRunner(mix_stderr=False)398    result = runner.invoke(cli, ["missing"])399    assert result.exit_code == 2400    assert "FLASK_APP" in result.stderr401    assert "Usage:" in result.stderr402403404def test_help_echo_loading_error():405    from flask.cli import cli406407    runner = CliRunner(mix_stderr=False)408    result = runner.invoke(cli, ["--help"])409    assert result.exit_code == 0410    assert "FLASK_APP" in result.stderr411    assert "Usage:" in result.stdout412413414def test_help_echo_exception():415    def create_app():416        raise Exception("oh no")417418    cli = FlaskGroup(create_app=create_app)419    runner = CliRunner(mix_stderr=False)420    result = runner.invoke(cli, ["--help"])421    assert result.exit_code == 0422    assert "Exception: oh no" in result.stderr423    assert "Usage:" in result.stdout424425426class 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", "HAM"):504        monkeypatch._setitem.append((os.environ, item, notset))505506    monkeypatch.setenv("EGGS", "3")507    monkeypatch.chdir(test_path)508    assert load_dotenv()509    assert Path.cwd() == 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"518    # test env file encoding519    assert os.environ["HAM"] == "火腿"520    # Non existent file should not load521    assert not load_dotenv("non-existent-file")522523524@need_dotenv525def test_dotenv_path(monkeypatch):526    for item in ("FOO", "BAR", "EGGS"):527        monkeypatch._setitem.append((os.environ, item, notset))528529    load_dotenv(test_path / ".flaskenv")530    assert Path.cwd() == 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}"657658659def test_click_7_deprecated():660    with patch("flask.cli.cli"):661        if int(click.__version__[0]) < 8:662            pytest.deprecated_call(cli_main, match=".* Click 7 is deprecated")663        else:664            cli_main()