Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

702 lines · 19.9 KiB · Python

Last changed by

update env file precedence (#5630)David Lordbefore adoption7522c4b

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 importlib.metadata4import os5import platform6import ssl7import sys8import types9from functools import partial10from pathlib import Path1112import 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 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    class MockCtx:233        resilient_parsing = False234        color = None235236        def exit(self):237            return238239    ctx = MockCtx()240    get_version(ctx, None, "test")241    out, err = capsys.readouterr()242    assert f"Python {platform.python_version()}" in out243    assert f"Flask {importlib.metadata.version('flask')}" in out244    assert f"Werkzeug {importlib.metadata.version('werkzeug')}" in out245246247def test_scriptinfo(test_apps, monkeypatch):248    obj = ScriptInfo(app_import_path="cliapp.app:testapp")249    app = obj.load_app()250    assert app.name == "testapp"251    assert obj.load_app() is app252253    # import app with module's absolute path254    cli_app_path = str(test_path / "cliapp" / "app.py")255256    obj = ScriptInfo(app_import_path=cli_app_path)257    app = obj.load_app()258    assert app.name == "testapp"259    assert obj.load_app() is app260    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")261    app = obj.load_app()262    assert app.name == "testapp"263    assert obj.load_app() is app264265    def create_app():266        return Flask("createapp")267268    obj = ScriptInfo(create_app=create_app)269    app = obj.load_app()270    assert app.name == "createapp"271    assert obj.load_app() is app272273    obj = ScriptInfo()274    pytest.raises(NoAppException, obj.load_app)275276    # import app from wsgi.py in current directory277    monkeypatch.chdir(test_path / "helloworld")278    obj = ScriptInfo()279    app = obj.load_app()280    assert app.name == "hello"281282    # import app from app.py in current directory283    monkeypatch.chdir(test_path / "cliapp")284    obj = ScriptInfo()285    app = obj.load_app()286    assert app.name == "testapp"287288289def test_app_cli_has_app_context(app, runner):290    def _param_cb(ctx, param, value):291        # current_app should be available in parameter callbacks292        return bool(current_app)293294    @app.cli.command()295    @click.argument("value", callback=_param_cb)296    def check(value):297        app = click.get_current_context().obj.load_app()298        # the loaded app should be the same as current_app299        same_app = current_app._get_current_object() is app300        return same_app, value301302    cli = FlaskGroup(create_app=lambda: app)303    result = runner.invoke(cli, ["check", "x"], standalone_mode=False)304    assert result.return_value == (True, True)305306307def test_with_appcontext(runner):308    @click.command()309    @with_appcontext310    def testcmd():311        click.echo(current_app.name)312313    obj = ScriptInfo(create_app=lambda: Flask("testapp"))314315    result = runner.invoke(testcmd, obj=obj)316    assert result.exit_code == 0317    assert result.output == "testapp\n"318319320def test_appgroup_app_context(runner):321    @click.group(cls=AppGroup)322    def cli():323        pass324325    @cli.command()326    def test():327        click.echo(current_app.name)328329    @cli.group()330    def subgroup():331        pass332333    @subgroup.command()334    def test2():335        click.echo(current_app.name)336337    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))338339    result = runner.invoke(cli, ["test"], obj=obj)340    assert result.exit_code == 0341    assert result.output == "testappgroup\n"342343    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)344    assert result.exit_code == 0345    assert result.output == "testappgroup\n"346347348def test_flaskgroup_app_context(runner):349    def create_app():350        return Flask("flaskgroup")351352    @click.group(cls=FlaskGroup, create_app=create_app)353    def cli(**params):354        pass355356    @cli.command()357    def test():358        click.echo(current_app.name)359360    result = runner.invoke(cli, ["test"])361    assert result.exit_code == 0362    assert result.output == "flaskgroup\n"363364365@pytest.mark.parametrize("set_debug_flag", (True, False))366def test_flaskgroup_debug(runner, set_debug_flag):367    def create_app():368        app = Flask("flaskgroup")369        app.debug = True370        return app371372    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)373    def cli(**params):374        pass375376    @cli.command()377    def test():378        click.echo(str(current_app.debug))379380    result = runner.invoke(cli, ["test"])381    assert result.exit_code == 0382    assert result.output == f"{not set_debug_flag}\n"383384385def test_flaskgroup_nested(app, runner):386    cli = click.Group("cli")387    flask_group = FlaskGroup(name="flask", create_app=lambda: app)388    cli.add_command(flask_group)389390    @flask_group.command()391    def show():392        click.echo(current_app.name)393394    result = runner.invoke(cli, ["flask", "show"])395    assert result.output == "flask_test\n"396397398def test_no_command_echo_loading_error():399    from flask.cli import cli400401    try:402        runner = CliRunner(mix_stderr=False)403    except (DeprecationWarning, TypeError):404        # Click >= 8.2405        runner = CliRunner()406407    result = runner.invoke(cli, ["missing"])408    assert result.exit_code == 2409    assert "FLASK_APP" in result.stderr410    assert "Usage:" in result.stderr411412413def test_help_echo_loading_error():414    from flask.cli import cli415416    try:417        runner = CliRunner(mix_stderr=False)418    except (DeprecationWarning, TypeError):419        # Click >= 8.2420        runner = CliRunner()421422    result = runner.invoke(cli, ["--help"])423    assert result.exit_code == 0424    assert "FLASK_APP" in result.stderr425    assert "Usage:" in result.stdout426427428def test_help_echo_exception():429    def create_app():430        raise Exception("oh no")431432    cli = FlaskGroup(create_app=create_app)433434    try:435        runner = CliRunner(mix_stderr=False)436    except (DeprecationWarning, TypeError):437        # Click >= 8.2438        runner = CliRunner()439440    result = runner.invoke(cli, ["--help"])441    assert result.exit_code == 0442    assert "Exception: oh no" in result.stderr443    assert "Usage:" in result.stdout444445446class TestRoutes:447    @pytest.fixture448    def app(self):449        app = Flask(__name__)450        app.add_url_rule(451            "/get_post/<int:x>/<int:y>",452            methods=["GET", "POST"],453            endpoint="yyy_get_post",454        )455        app.add_url_rule("/zzz_post", methods=["POST"], endpoint="aaa_post")456        return app457458    @pytest.fixture459    def invoke(self, app, runner):460        cli = FlaskGroup(create_app=lambda: app)461        return partial(runner.invoke, cli)462463    def expect_order(self, order, output):464        # skip the header and match the start of each row465        for expect, line in zip(order, output.splitlines()[2:]):466            # do this instead of startswith for nicer pytest output467            assert line[: len(expect)] == expect468469    def test_simple(self, invoke):470        result = invoke(["routes"])471        assert result.exit_code == 0472        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)473474    def test_sort(self, app, invoke):475        default_output = invoke(["routes"]).output476        endpoint_output = invoke(["routes", "-s", "endpoint"]).output477        assert default_output == endpoint_output478        self.expect_order(479            ["static", "yyy_get_post", "aaa_post"],480            invoke(["routes", "-s", "methods"]).output,481        )482        self.expect_order(483            ["yyy_get_post", "static", "aaa_post"],484            invoke(["routes", "-s", "rule"]).output,485        )486        match_order = [r.endpoint for r in app.url_map.iter_rules()]487        self.expect_order(match_order, invoke(["routes", "-s", "match"]).output)488489    def test_all_methods(self, invoke):490        output = invoke(["routes"]).output491        assert "GET, HEAD, OPTIONS, POST" not in output492        output = invoke(["routes", "--all-methods"]).output493        assert "GET, HEAD, OPTIONS, POST" in output494495    def test_no_routes(self, runner):496        app = Flask(__name__, static_folder=None)497        cli = FlaskGroup(create_app=lambda: app)498        result = runner.invoke(cli, ["routes"])499        assert result.exit_code == 0500        assert "No routes were registered." in result.output501502    def test_subdomain(self, runner):503        app = Flask(__name__, static_folder=None)504        app.add_url_rule("/a", subdomain="a", endpoint="a")505        app.add_url_rule("/b", subdomain="b", endpoint="b")506        cli = FlaskGroup(create_app=lambda: app)507        result = runner.invoke(cli, ["routes"])508        assert result.exit_code == 0509        assert "Subdomain" in result.output510511    def test_host(self, runner):512        app = Flask(__name__, static_folder=None, host_matching=True)513        app.add_url_rule("/a", host="a", endpoint="a")514        app.add_url_rule("/b", host="b", endpoint="b")515        cli = FlaskGroup(create_app=lambda: app)516        result = runner.invoke(cli, ["routes"])517        assert result.exit_code == 0518        assert "Host" in result.output519520521def dotenv_not_available():522    try:523        import dotenv  # noqa: F401524    except ImportError:525        return True526527    return False528529530need_dotenv = pytest.mark.skipif(531    dotenv_not_available(), reason="dotenv is not installed"532)533534535@need_dotenv536def test_load_dotenv(monkeypatch):537    # can't use monkeypatch.delitem since the keys don't exist yet538    for item in ("FOO", "BAR", "SPAM", "HAM"):539        monkeypatch._setitem.append((os.environ, item, notset))540541    monkeypatch.setenv("EGGS", "3")542    monkeypatch.chdir(test_path)543    assert load_dotenv()544    assert Path.cwd() == test_path545    # .flaskenv doesn't overwrite .env546    assert os.environ["FOO"] == "env"547    # set only in .flaskenv548    assert os.environ["BAR"] == "bar"549    # set only in .env550    assert os.environ["SPAM"] == "1"551    # set manually, files don't overwrite552    assert os.environ["EGGS"] == "3"553    # test env file encoding554    assert os.environ["HAM"] == "火腿"555    # Non existent file should not load556    assert not load_dotenv("non-existent-file", load_defaults=False)557558559@need_dotenv560def test_dotenv_path(monkeypatch):561    for item in ("FOO", "BAR", "EGGS"):562        monkeypatch._setitem.append((os.environ, item, notset))563564    load_dotenv(test_path / ".flaskenv")565    assert Path.cwd() == cwd566    assert "FOO" in os.environ567568569def test_dotenv_optional(monkeypatch):570    monkeypatch.setitem(sys.modules, "dotenv", None)571    monkeypatch.chdir(test_path)572    load_dotenv()573    assert "FOO" not in os.environ574575576@need_dotenv577def test_disable_dotenv_from_env(monkeypatch, runner):578    monkeypatch.chdir(test_path)579    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")580    runner.invoke(FlaskGroup())581    assert "FOO" not in os.environ582583584def test_run_cert_path():585    # no key586    with pytest.raises(click.BadParameter):587        run_command.make_context("run", ["--cert", __file__])588589    # no cert590    with pytest.raises(click.BadParameter):591        run_command.make_context("run", ["--key", __file__])592593    # cert specified first594    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])595    assert ctx.params["cert"] == (__file__, __file__)596597    # key specified first598    ctx = run_command.make_context("run", ["--key", __file__, "--cert", __file__])599    assert ctx.params["cert"] == (__file__, __file__)600601602def test_run_cert_adhoc(monkeypatch):603    monkeypatch.setitem(sys.modules, "cryptography", None)604605    # cryptography not installed606    with pytest.raises(click.BadParameter):607        run_command.make_context("run", ["--cert", "adhoc"])608609    # cryptography installed610    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))611    ctx = run_command.make_context("run", ["--cert", "adhoc"])612    assert ctx.params["cert"] == "adhoc"613614    # no key with adhoc615    with pytest.raises(click.BadParameter):616        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])617618619def test_run_cert_import(monkeypatch):620    monkeypatch.setitem(sys.modules, "not_here", None)621622    # ImportError623    with pytest.raises(click.BadParameter):624        run_command.make_context("run", ["--cert", "not_here"])625626    with pytest.raises(click.BadParameter):627        run_command.make_context("run", ["--cert", "flask"])628629    # SSLContext630    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)631632    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)633    ctx = run_command.make_context("run", ["--cert", "ssl_context"])634    assert ctx.params["cert"] is ssl_context635636    # no --key with SSLContext637    with pytest.raises(click.BadParameter):638        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])639640641def test_run_cert_no_ssl(monkeypatch):642    monkeypatch.setitem(sys.modules, "ssl", None)643644    with pytest.raises(click.BadParameter):645        run_command.make_context("run", ["--cert", "not_here"])646647648def test_cli_blueprints(app):649    """Test blueprint commands register correctly to the application"""650    custom = Blueprint("custom", __name__, cli_group="customized")651    nested = Blueprint("nested", __name__)652    merged = Blueprint("merged", __name__, cli_group=None)653    late = Blueprint("late", __name__)654655    @custom.cli.command("custom")656    def custom_command():657        click.echo("custom_result")658659    @nested.cli.command("nested")660    def nested_command():661        click.echo("nested_result")662663    @merged.cli.command("merged")664    def merged_command():665        click.echo("merged_result")666667    @late.cli.command("late")668    def late_command():669        click.echo("late_result")670671    app.register_blueprint(custom)672    app.register_blueprint(nested)673    app.register_blueprint(merged)674    app.register_blueprint(late, cli_group="late_registration")675676    app_runner = app.test_cli_runner()677678    result = app_runner.invoke(args=["customized", "custom"])679    assert "custom_result" in result.output680681    result = app_runner.invoke(args=["nested", "nested"])682    assert "nested_result" in result.output683684    result = app_runner.invoke(args=["merged"])685    assert "merged_result" in result.output686687    result = app_runner.invoke(args=["late_registration", "late"])688    assert "late_result" in result.output689690691def test_cli_empty(app):692    """If a Blueprint's CLI group is empty, do not register it."""693    bp = Blueprint("blue", __name__, cli_group="blue")694    app.register_blueprint(bp)695696    result = app.test_cli_runner().invoke(args=["blue", "--help"])697    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"698699700def test_run_exclude_patterns():701    ctx = run_command.make_context("run", ["--exclude-patterns", __file__])702    assert ctx.params["exclude_patterns"] == [__file__]