Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

670 lines · 18.5 KiB · Python

Last changed by

Merge pull request #4606 from pallets/cli-importsDavid Lordbefore adoption31aad11

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 Path1011import click12import pytest13from _pytest.monkeypatch import notset14from click.testing import CliRunner1516from flask import Blueprint17from flask import current_app18from flask import Flask19from flask.cli import AppGroup20from flask.cli import DispatchingApp21from flask.cli import find_best_app22from flask.cli import FlaskGroup23from flask.cli import get_version24from flask.cli import load_dotenv25from flask.cli import locate_app26from flask.cli import NoAppException27from flask.cli import prepare_import28from flask.cli import run_command29from flask.cli import ScriptInfo30from flask.cli import with_appcontext3132cwd = Path.cwd()33test_path = (Path(__file__) / ".." / "test_apps").resolve()343536@pytest.fixture37def runner():38    return CliRunner()394041def test_cli_name(test_apps):42    """Make sure the CLI object's name is the app's name and not the app itself"""43    from cliapp.app import testapp4445    assert testapp.cli.name == testapp.name464748def test_find_best_app(test_apps):49    class Module:50        app = Flask("appname")5152    assert find_best_app(Module) == Module.app5354    class Module:55        application = Flask("appname")5657    assert find_best_app(Module) == Module.application5859    class Module:60        myapp = Flask("appname")6162    assert find_best_app(Module) == Module.myapp6364    class Module:65        @staticmethod66        def create_app():67            return Flask("appname")6869    app = find_best_app(Module)70    assert isinstance(app, Flask)71    assert app.name == "appname"7273    class Module:74        @staticmethod75        def create_app(**kwargs):76            return Flask("appname")7778    app = find_best_app(Module)79    assert isinstance(app, Flask)80    assert app.name == "appname"8182    class Module:83        @staticmethod84        def make_app():85            return Flask("appname")8687    app = find_best_app(Module)88    assert isinstance(app, Flask)89    assert app.name == "appname"9091    class Module:92        myapp = Flask("appname1")9394        @staticmethod95        def create_app():96            return Flask("appname2")9798    assert find_best_app(Module) == Module.myapp99100    class Module:101        myapp = Flask("appname1")102103        @staticmethod104        def create_app():105            return Flask("appname2")106107    assert find_best_app(Module) == Module.myapp108109    class Module:110        pass111112    pytest.raises(NoAppException, find_best_app, Module)113114    class Module:115        myapp1 = Flask("appname1")116        myapp2 = Flask("appname2")117118    pytest.raises(NoAppException, find_best_app, Module)119120    class Module:121        @staticmethod122        def create_app(foo, bar):123            return Flask("appname2")124125    pytest.raises(NoAppException, find_best_app, Module)126127    class Module:128        @staticmethod129        def create_app():130            raise TypeError("bad bad factory!")131132    pytest.raises(TypeError, find_best_app, Module)133134135@pytest.mark.parametrize(136    "value,path,result",137    (138        ("test", cwd, "test"),139        ("test.py", cwd, "test"),140        ("a/test", cwd / "a", "test"),141        ("test/__init__.py", cwd, "test"),142        ("test/__init__", cwd, "test"),143        # nested package144        (145            test_path / "cliapp" / "inner1" / "__init__",146            test_path,147            "cliapp.inner1",148        ),149        (150            test_path / "cliapp" / "inner1" / "inner2",151            test_path,152            "cliapp.inner1.inner2",153        ),154        # dotted name155        ("test.a.b", cwd, "test.a.b"),156        (test_path / "cliapp.app", test_path, "cliapp.app"),157        # not a Python file, will be caught during import158        (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),159    ),160)161def test_prepare_import(request, value, path, result):162    """Expect the correct path to be set and the correct import and app names163    to be returned.164165    :func:`prepare_exec_for_file` has a side effect where the parent directory166    of the given import is added to :data:`sys.path`. This is reset after the167    test runs.168    """169    original_path = sys.path[:]170171    def reset_path():172        sys.path[:] = original_path173174    request.addfinalizer(reset_path)175176    assert prepare_import(value) == result177    assert sys.path[0] == str(path)178179180@pytest.mark.parametrize(181    "iname,aname,result",182    (183        ("cliapp.app", None, "testapp"),184        ("cliapp.app", "testapp", "testapp"),185        ("cliapp.factory", None, "app"),186        ("cliapp.factory", "create_app", "app"),187        ("cliapp.factory", "create_app()", "app"),188        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),189        # trailing comma space190        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),191        # strip whitespace192        ("cliapp.factory", " create_app () ", "app"),193    ),194)195def test_locate_app(test_apps, iname, aname, result):196    assert locate_app(iname, aname).name == result197198199@pytest.mark.parametrize(200    "iname,aname",201    (202        ("notanapp.py", None),203        ("cliapp/app", None),204        ("cliapp.app", "notanapp"),205        # not enough arguments206        ("cliapp.factory", 'create_app2("foo")'),207        # invalid identifier208        ("cliapp.factory", "create_app("),209        # no app returned210        ("cliapp.factory", "no_app"),211        # nested import error212        ("cliapp.importerrorapp", None),213        # not a Python file214        ("cliapp.message.txt", None),215    ),216)217def test_locate_app_raises(test_apps, iname, aname):218    with pytest.raises(NoAppException):219        locate_app(iname, aname)220221222def test_locate_app_suppress_raise(test_apps):223    app = locate_app("notanapp.py", None, raise_if_not_found=False)224    assert app is None225226    # only direct import error is suppressed227    with pytest.raises(NoAppException):228        locate_app("cliapp.importerrorapp", None, raise_if_not_found=False)229230231def test_get_version(test_apps, capsys):232    from flask import __version__ as flask_version233    from werkzeug import __version__ as werkzeug_version234    from platform import python_version235236    class MockCtx:237        resilient_parsing = False238        color = None239240        def exit(self):241            return242243    ctx = MockCtx()244    get_version(ctx, None, "test")245    out, err = capsys.readouterr()246    assert f"Python {python_version()}" in out247    assert f"Flask {flask_version}" in out248    assert f"Werkzeug {werkzeug_version}" in out249250251def test_scriptinfo(test_apps, monkeypatch):252    obj = ScriptInfo(app_import_path="cliapp.app:testapp")253    app = obj.load_app()254    assert app.name == "testapp"255    assert obj.load_app() is app256257    # import app with module's absolute path258    cli_app_path = str(test_path / "cliapp" / "app.py")259260    obj = ScriptInfo(app_import_path=cli_app_path)261    app = obj.load_app()262    assert app.name == "testapp"263    assert obj.load_app() is app264    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")265    app = obj.load_app()266    assert app.name == "testapp"267    assert obj.load_app() is app268269    def create_app():270        return Flask("createapp")271272    obj = ScriptInfo(create_app=create_app)273    app = obj.load_app()274    assert app.name == "createapp"275    assert obj.load_app() is app276277    obj = ScriptInfo()278    pytest.raises(NoAppException, obj.load_app)279280    # import app from wsgi.py in current directory281    monkeypatch.chdir(test_path / "helloworld")282    obj = ScriptInfo()283    app = obj.load_app()284    assert app.name == "hello"285286    # import app from app.py in current directory287    monkeypatch.chdir(test_path / "cliapp")288    obj = ScriptInfo()289    app = obj.load_app()290    assert app.name == "testapp"291292293@pytest.mark.xfail(platform.python_implementation() == "PyPy", reason="flaky on pypy")294def test_lazy_load_error(monkeypatch):295    """When using lazy loading, the correct exception should be296    re-raised.297    """298299    class BadExc(Exception):300        pass301302    def bad_load():303        raise BadExc304305    lazy = DispatchingApp(bad_load, use_eager_loading=False)306307    # reduce flakiness by waiting for the internal loading lock308    with lazy._lock:309        with pytest.raises(BadExc):310            lazy._flush_bg_loading_exception()311312313def test_with_appcontext(runner):314    @click.command()315    @with_appcontext316    def testcmd():317        click.echo(current_app.name)318319    obj = ScriptInfo(create_app=lambda: Flask("testapp"))320321    result = runner.invoke(testcmd, obj=obj)322    assert result.exit_code == 0323    assert result.output == "testapp\n"324325326def test_appgroup(runner):327    @click.group(cls=AppGroup)328    def cli():329        pass330331    @cli.command(with_appcontext=True)332    def test():333        click.echo(current_app.name)334335    @cli.group()336    def subgroup():337        pass338339    @subgroup.command(with_appcontext=True)340    def test2():341        click.echo(current_app.name)342343    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))344345    result = runner.invoke(cli, ["test"], obj=obj)346    assert result.exit_code == 0347    assert result.output == "testappgroup\n"348349    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)350    assert result.exit_code == 0351    assert result.output == "testappgroup\n"352353354def test_flaskgroup(runner):355    def create_app():356        return Flask("flaskgroup")357358    @click.group(cls=FlaskGroup, create_app=create_app)359    def cli(**params):360        pass361362    @cli.command()363    def test():364        click.echo(current_app.name)365366    result = runner.invoke(cli, ["test"])367    assert result.exit_code == 0368    assert result.output == "flaskgroup\n"369370371@pytest.mark.parametrize("set_debug_flag", (True, False))372def test_flaskgroup_debug(runner, set_debug_flag):373    def create_app():374        app = Flask("flaskgroup")375        app.debug = True376        return app377378    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)379    def cli(**params):380        pass381382    @cli.command()383    def test():384        click.echo(str(current_app.debug))385386    result = runner.invoke(cli, ["test"])387    assert result.exit_code == 0388    assert result.output == f"{not set_debug_flag}\n"389390391def test_no_command_echo_loading_error():392    from flask.cli import cli393394    runner = CliRunner(mix_stderr=False)395    result = runner.invoke(cli, ["missing"])396    assert result.exit_code == 2397    assert "FLASK_APP" in result.stderr398    assert "Usage:" in result.stderr399400401def test_help_echo_loading_error():402    from flask.cli import cli403404    runner = CliRunner(mix_stderr=False)405    result = runner.invoke(cli, ["--help"])406    assert result.exit_code == 0407    assert "FLASK_APP" in result.stderr408    assert "Usage:" in result.stdout409410411def test_help_echo_exception():412    def create_app():413        raise Exception("oh no")414415    cli = FlaskGroup(create_app=create_app)416    runner = CliRunner(mix_stderr=False)417    result = runner.invoke(cli, ["--help"])418    assert result.exit_code == 0419    assert "Exception: oh no" in result.stderr420    assert "Usage:" in result.stdout421422423class TestRoutes:424    @pytest.fixture425    def invoke(self, runner):426        def create_app():427            app = Flask(__name__)428            app.testing = True429430            @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])431            def yyy_get_post(x, y):432                pass433434            @app.route("/zzz_post", methods=["POST"])435            def aaa_post():436                pass437438            return app439440        cli = FlaskGroup(create_app=create_app)441        return partial(runner.invoke, cli)442443    @pytest.fixture444    def invoke_no_routes(self, runner):445        def create_app():446            app = Flask(__name__, static_folder=None)447            app.testing = True448449            return app450451        cli = FlaskGroup(create_app=create_app)452        return partial(runner.invoke, cli)453454    def expect_order(self, order, output):455        # skip the header and match the start of each row456        for expect, line in zip(order, output.splitlines()[2:]):457            # do this instead of startswith for nicer pytest output458            assert line[: len(expect)] == expect459460    def test_simple(self, invoke):461        result = invoke(["routes"])462        assert result.exit_code == 0463        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)464465    def test_sort(self, invoke):466        default_output = invoke(["routes"]).output467        endpoint_output = invoke(["routes", "-s", "endpoint"]).output468        assert default_output == endpoint_output469        self.expect_order(470            ["static", "yyy_get_post", "aaa_post"],471            invoke(["routes", "-s", "methods"]).output,472        )473        self.expect_order(474            ["yyy_get_post", "static", "aaa_post"],475            invoke(["routes", "-s", "rule"]).output,476        )477        self.expect_order(478            ["aaa_post", "yyy_get_post", "static"],479            invoke(["routes", "-s", "match"]).output,480        )481482    def test_all_methods(self, invoke):483        output = invoke(["routes"]).output484        assert "GET, HEAD, OPTIONS, POST" not in output485        output = invoke(["routes", "--all-methods"]).output486        assert "GET, HEAD, OPTIONS, POST" in output487488    def test_no_routes(self, invoke_no_routes):489        result = invoke_no_routes(["routes"])490        assert result.exit_code == 0491        assert "No routes were registered." in result.output492493494def dotenv_not_available():495    try:496        import dotenv  # noqa: F401497    except ImportError:498        return True499500    return False501502503need_dotenv = pytest.mark.skipif(504    dotenv_not_available(), reason="dotenv is not installed"505)506507508@need_dotenv509def test_load_dotenv(monkeypatch):510    # can't use monkeypatch.delitem since the keys don't exist yet511    for item in ("FOO", "BAR", "SPAM", "HAM"):512        monkeypatch._setitem.append((os.environ, item, notset))513514    monkeypatch.setenv("EGGS", "3")515    monkeypatch.chdir(test_path)516    assert load_dotenv()517    assert Path.cwd() == test_path518    # .flaskenv doesn't overwrite .env519    assert os.environ["FOO"] == "env"520    # set only in .flaskenv521    assert os.environ["BAR"] == "bar"522    # set only in .env523    assert os.environ["SPAM"] == "1"524    # set manually, files don't overwrite525    assert os.environ["EGGS"] == "3"526    # test env file encoding527    assert os.environ["HAM"] == "火腿"528    # Non existent file should not load529    assert not load_dotenv("non-existent-file")530531532@need_dotenv533def test_dotenv_path(monkeypatch):534    for item in ("FOO", "BAR", "EGGS"):535        monkeypatch._setitem.append((os.environ, item, notset))536537    load_dotenv(test_path / ".flaskenv")538    assert Path.cwd() == cwd539    assert "FOO" in os.environ540541542def test_dotenv_optional(monkeypatch):543    monkeypatch.setitem(sys.modules, "dotenv", None)544    monkeypatch.chdir(test_path)545    load_dotenv()546    assert "FOO" not in os.environ547548549@need_dotenv550def test_disable_dotenv_from_env(monkeypatch, runner):551    monkeypatch.chdir(test_path)552    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")553    runner.invoke(FlaskGroup())554    assert "FOO" not in os.environ555556557def test_run_cert_path():558    # no key559    with pytest.raises(click.BadParameter):560        run_command.make_context("run", ["--cert", __file__])561562    # no cert563    with pytest.raises(click.BadParameter):564        run_command.make_context("run", ["--key", __file__])565566    # cert specified first567    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])568    assert ctx.params["cert"] == (__file__, __file__)569570    # key specified first571    ctx = run_command.make_context("run", ["--key", __file__, "--cert", __file__])572    assert ctx.params["cert"] == (__file__, __file__)573574575def test_run_cert_adhoc(monkeypatch):576    monkeypatch.setitem(sys.modules, "cryptography", None)577578    # cryptography not installed579    with pytest.raises(click.BadParameter):580        run_command.make_context("run", ["--cert", "adhoc"])581582    # cryptography installed583    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))584    ctx = run_command.make_context("run", ["--cert", "adhoc"])585    assert ctx.params["cert"] == "adhoc"586587    # no key with adhoc588    with pytest.raises(click.BadParameter):589        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])590591592def test_run_cert_import(monkeypatch):593    monkeypatch.setitem(sys.modules, "not_here", None)594595    # ImportError596    with pytest.raises(click.BadParameter):597        run_command.make_context("run", ["--cert", "not_here"])598599    with pytest.raises(click.BadParameter):600        run_command.make_context("run", ["--cert", "flask"])601602    # SSLContext603    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)604605    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)606    ctx = run_command.make_context("run", ["--cert", "ssl_context"])607    assert ctx.params["cert"] is ssl_context608609    # no --key with SSLContext610    with pytest.raises(click.BadParameter):611        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])612613614def test_run_cert_no_ssl(monkeypatch):615    monkeypatch.setitem(sys.modules, "ssl", None)616617    with pytest.raises(click.BadParameter):618        run_command.make_context("run", ["--cert", "not_here"])619620621def test_cli_blueprints(app):622    """Test blueprint commands register correctly to the application"""623    custom = Blueprint("custom", __name__, cli_group="customized")624    nested = Blueprint("nested", __name__)625    merged = Blueprint("merged", __name__, cli_group=None)626    late = Blueprint("late", __name__)627628    @custom.cli.command("custom")629    def custom_command():630        click.echo("custom_result")631632    @nested.cli.command("nested")633    def nested_command():634        click.echo("nested_result")635636    @merged.cli.command("merged")637    def merged_command():638        click.echo("merged_result")639640    @late.cli.command("late")641    def late_command():642        click.echo("late_result")643644    app.register_blueprint(custom)645    app.register_blueprint(nested)646    app.register_blueprint(merged)647    app.register_blueprint(late, cli_group="late_registration")648649    app_runner = app.test_cli_runner()650651    result = app_runner.invoke(args=["customized", "custom"])652    assert "custom_result" in result.output653654    result = app_runner.invoke(args=["nested", "nested"])655    assert "nested_result" in result.output656657    result = app_runner.invoke(args=["merged"])658    assert "merged_result" in result.output659660    result = app_runner.invoke(args=["late_registration", "late"])661    assert "late_result" in result.output662663664def test_cli_empty(app):665    """If a Blueprint's CLI group is empty, do not register it."""666    bp = Blueprint("blue", __name__, cli_group="blue")667    app.register_blueprint(bp)668669    result = app.test_cli_runner().invoke(args=["blue", "--help"])670    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"