Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

688 lines · 19.1 KiB · Python

Last changed by

Merge pull request #4174 from na2shell/fix_4170David Lordbefore adoptionef3a82a

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 partial8from pathlib import Path9from unittest.mock import patch1011import 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 dotenv22from flask.cli import find_best_app23from flask.cli import FlaskGroup24from flask.cli import get_version25from flask.cli import load_dotenv26from flask.cli import locate_app27from flask.cli import main as cli_main28from flask.cli import NoAppException29from flask.cli import prepare_import30from flask.cli import run_command31from flask.cli import ScriptInfo32from flask.cli import with_appcontext3334cwd = Path.cwd()35test_path = (Path(__file__) / ".." / "test_apps").resolve()363738@pytest.fixture39def runner():40    return CliRunner()414243def test_cli_name(test_apps):44    """Make sure the CLI object's name is the app's name and not the app itself"""45    from cliapp.app import testapp4647    assert testapp.cli.name == testapp.name484950def test_find_best_app(test_apps):51    script_info = ScriptInfo()5253    class Module:54        app = Flask("appname")5556    assert find_best_app(script_info, Module) == Module.app5758    class Module:59        application = Flask("appname")6061    assert find_best_app(script_info, Module) == Module.application6263    class Module:64        myapp = Flask("appname")6566    assert find_best_app(script_info, Module) == Module.myapp6768    class Module:69        @staticmethod70        def create_app():71            return Flask("appname")7273    app = find_best_app(script_info, Module)74    assert isinstance(app, Flask)75    assert app.name == "appname"7677    class Module:78        @staticmethod79        def create_app(**kwargs):80            return Flask("appname")8182    app = find_best_app(script_info, Module)83    assert isinstance(app, Flask)84    assert app.name == "appname"8586    class Module:87        @staticmethod88        def create_app(foo):89            return Flask("appname")9091    with pytest.deprecated_call(match="Script info"):92        app = find_best_app(script_info, Module)9394    assert isinstance(app, Flask)95    assert app.name == "appname"9697    class Module:98        @staticmethod99        def create_app(foo=None, script_info=None):100            return Flask("appname")101102    with pytest.deprecated_call(match="script_info"):103        app = find_best_app(script_info, Module)104105    assert isinstance(app, Flask)106    assert app.name == "appname"107108    class Module:109        @staticmethod110        def make_app():111            return Flask("appname")112113    app = find_best_app(script_info, Module)114    assert isinstance(app, Flask)115    assert app.name == "appname"116117    class Module:118        myapp = Flask("appname1")119120        @staticmethod121        def create_app():122            return Flask("appname2")123124    assert find_best_app(script_info, Module) == Module.myapp125126    class Module:127        myapp = Flask("appname1")128129        @staticmethod130        def create_app():131            return Flask("appname2")132133    assert find_best_app(script_info, Module) == Module.myapp134135    class Module:136        pass137138    pytest.raises(NoAppException, find_best_app, script_info, Module)139140    class Module:141        myapp1 = Flask("appname1")142        myapp2 = Flask("appname2")143144    pytest.raises(NoAppException, find_best_app, script_info, Module)145146    class Module:147        @staticmethod148        def create_app(foo, bar):149            return Flask("appname2")150151    pytest.raises(NoAppException, find_best_app, script_info, Module)152153    class Module:154        @staticmethod155        def create_app():156            raise TypeError("bad bad factory!")157158    pytest.raises(TypeError, find_best_app, script_info, Module)159160161@pytest.mark.parametrize(162    "value,path,result",163    (164        ("test", cwd, "test"),165        ("test.py", cwd, "test"),166        ("a/test", cwd / "a", "test"),167        ("test/__init__.py", cwd, "test"),168        ("test/__init__", cwd, "test"),169        # nested package170        (171            test_path / "cliapp" / "inner1" / "__init__",172            test_path,173            "cliapp.inner1",174        ),175        (176            test_path / "cliapp" / "inner1" / "inner2",177            test_path,178            "cliapp.inner1.inner2",179        ),180        # dotted name181        ("test.a.b", cwd, "test.a.b"),182        (test_path / "cliapp.app", test_path, "cliapp.app"),183        # not a Python file, will be caught during import184        (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),185    ),186)187def test_prepare_import(request, value, path, result):188    """Expect the correct path to be set and the correct import and app names189    to be returned.190191    :func:`prepare_exec_for_file` has a side effect where the parent directory192    of the given import is added to :data:`sys.path`. This is reset after the193    test runs.194    """195    original_path = sys.path[:]196197    def reset_path():198        sys.path[:] = original_path199200    request.addfinalizer(reset_path)201202    assert prepare_import(value) == result203    assert sys.path[0] == str(path)204205206@pytest.mark.parametrize(207    "iname,aname,result",208    (209        ("cliapp.app", None, "testapp"),210        ("cliapp.app", "testapp", "testapp"),211        ("cliapp.factory", None, "app"),212        ("cliapp.factory", "create_app", "app"),213        ("cliapp.factory", "create_app()", "app"),214        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),215        # trailing comma space216        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),217        # strip whitespace218        ("cliapp.factory", " create_app () ", "app"),219    ),220)221def test_locate_app(test_apps, iname, aname, result):222    info = ScriptInfo()223    assert locate_app(info, iname, aname).name == result224225226@pytest.mark.parametrize(227    "iname,aname",228    (229        ("notanapp.py", None),230        ("cliapp/app", None),231        ("cliapp.app", "notanapp"),232        # not enough arguments233        ("cliapp.factory", 'create_app2("foo")'),234        # invalid identifier235        ("cliapp.factory", "create_app("),236        # no app returned237        ("cliapp.factory", "no_app"),238        # nested import error239        ("cliapp.importerrorapp", None),240        # not a Python file241        ("cliapp.message.txt", None),242    ),243)244def test_locate_app_raises(test_apps, iname, aname):245    info = ScriptInfo()246247    with pytest.raises(NoAppException):248        locate_app(info, iname, aname)249250251def test_locate_app_suppress_raise(test_apps):252    info = ScriptInfo()253    app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)254    assert app is None255256    # only direct import error is suppressed257    with pytest.raises(NoAppException):258        locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)259260261def test_get_version(test_apps, capsys):262    from flask import __version__ as flask_version263    from werkzeug import __version__ as werkzeug_version264    from platform import python_version265266    class MockCtx:267        resilient_parsing = False268        color = None269270        def exit(self):271            return272273    ctx = MockCtx()274    get_version(ctx, None, "test")275    out, err = capsys.readouterr()276    assert f"Python {python_version()}" in out277    assert f"Flask {flask_version}" in out278    assert f"Werkzeug {werkzeug_version}" in out279280281def test_scriptinfo(test_apps, monkeypatch):282    obj = ScriptInfo(app_import_path="cliapp.app:testapp")283    app = obj.load_app()284    assert app.name == "testapp"285    assert obj.load_app() is app286287    # import app with module's absolute path288    cli_app_path = str(test_path / "cliapp" / "app.py")289290    obj = ScriptInfo(app_import_path=cli_app_path)291    app = obj.load_app()292    assert app.name == "testapp"293    assert obj.load_app() is app294    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")295    app = obj.load_app()296    assert app.name == "testapp"297    assert obj.load_app() is app298299    def create_app():300        return Flask("createapp")301302    obj = ScriptInfo(create_app=create_app)303    app = obj.load_app()304    assert app.name == "createapp"305    assert obj.load_app() is app306307    obj = ScriptInfo()308    pytest.raises(NoAppException, obj.load_app)309310    # import app from wsgi.py in current directory311    monkeypatch.chdir(test_path / "helloworld")312    obj = ScriptInfo()313    app = obj.load_app()314    assert app.name == "hello"315316    # import app from app.py in current directory317    monkeypatch.chdir(test_path / "cliapp")318    obj = ScriptInfo()319    app = obj.load_app()320    assert app.name == "testapp"321322323def test_lazy_load_error(monkeypatch):324    """When using lazy loading, the correct exception should be325    re-raised.326    """327328    class BadExc(Exception):329        pass330331    def bad_load():332        raise BadExc333334    lazy = DispatchingApp(bad_load, use_eager_loading=False)335336    with pytest.raises(BadExc):337        lazy._flush_bg_loading_exception()338339340def test_with_appcontext(runner):341    @click.command()342    @with_appcontext343    def testcmd():344        click.echo(current_app.name)345346    obj = ScriptInfo(create_app=lambda: Flask("testapp"))347348    result = runner.invoke(testcmd, obj=obj)349    assert result.exit_code == 0350    assert result.output == "testapp\n"351352353def test_appgroup(runner):354    @click.group(cls=AppGroup)355    def cli():356        pass357358    @cli.command(with_appcontext=True)359    def test():360        click.echo(current_app.name)361362    @cli.group()363    def subgroup():364        pass365366    @subgroup.command(with_appcontext=True)367    def test2():368        click.echo(current_app.name)369370    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))371372    result = runner.invoke(cli, ["test"], obj=obj)373    assert result.exit_code == 0374    assert result.output == "testappgroup\n"375376    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)377    assert result.exit_code == 0378    assert result.output == "testappgroup\n"379380381def test_flaskgroup(runner):382    def create_app():383        return Flask("flaskgroup")384385    @click.group(cls=FlaskGroup, create_app=create_app)386    def cli(**params):387        pass388389    @cli.command()390    def test():391        click.echo(current_app.name)392393    result = runner.invoke(cli, ["test"])394    assert result.exit_code == 0395    assert result.output == "flaskgroup\n"396397398@pytest.mark.parametrize("set_debug_flag", (True, False))399def test_flaskgroup_debug(runner, set_debug_flag):400    def create_app():401        app = Flask("flaskgroup")402        app.debug = True403        return app404405    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)406    def cli(**params):407        pass408409    @cli.command()410    def test():411        click.echo(str(current_app.debug))412413    result = runner.invoke(cli, ["test"])414    assert result.exit_code == 0415    assert result.output == f"{not set_debug_flag}\n"416417418def test_no_command_echo_loading_error():419    from flask.cli import cli420421    runner = CliRunner(mix_stderr=False)422    result = runner.invoke(cli, ["missing"])423    assert result.exit_code == 2424    assert "FLASK_APP" in result.stderr425    assert "Usage:" in result.stderr426427428def test_help_echo_loading_error():429    from flask.cli import cli430431    runner = CliRunner(mix_stderr=False)432    result = runner.invoke(cli, ["--help"])433    assert result.exit_code == 0434    assert "FLASK_APP" in result.stderr435    assert "Usage:" in result.stdout436437438def test_help_echo_exception():439    def create_app():440        raise Exception("oh no")441442    cli = FlaskGroup(create_app=create_app)443    runner = CliRunner(mix_stderr=False)444    result = runner.invoke(cli, ["--help"])445    assert result.exit_code == 0446    assert "Exception: oh no" in result.stderr447    assert "Usage:" in result.stdout448449450class TestRoutes:451    @pytest.fixture452    def invoke(self, runner):453        def create_app():454            app = Flask(__name__)455            app.testing = True456457            @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])458            def yyy_get_post(x, y):459                pass460461            @app.route("/zzz_post", methods=["POST"])462            def aaa_post():463                pass464465            return app466467        cli = FlaskGroup(create_app=create_app)468        return partial(runner.invoke, cli)469470    @pytest.fixture471    def invoke_no_routes(self, runner):472        def create_app():473            app = Flask(__name__, static_folder=None)474            app.testing = True475476            return app477478        cli = FlaskGroup(create_app=create_app)479        return partial(runner.invoke, cli)480481    def expect_order(self, order, output):482        # skip the header and match the start of each row483        for expect, line in zip(order, output.splitlines()[2:]):484            # do this instead of startswith for nicer pytest output485            assert line[: len(expect)] == expect486487    def test_simple(self, invoke):488        result = invoke(["routes"])489        assert result.exit_code == 0490        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)491492    def test_sort(self, invoke):493        default_output = invoke(["routes"]).output494        endpoint_output = invoke(["routes", "-s", "endpoint"]).output495        assert default_output == endpoint_output496        self.expect_order(497            ["static", "yyy_get_post", "aaa_post"],498            invoke(["routes", "-s", "methods"]).output,499        )500        self.expect_order(501            ["yyy_get_post", "static", "aaa_post"],502            invoke(["routes", "-s", "rule"]).output,503        )504        self.expect_order(505            ["aaa_post", "yyy_get_post", "static"],506            invoke(["routes", "-s", "match"]).output,507        )508509    def test_all_methods(self, invoke):510        output = invoke(["routes"]).output511        assert "GET, HEAD, OPTIONS, POST" not in output512        output = invoke(["routes", "--all-methods"]).output513        assert "GET, HEAD, OPTIONS, POST" in output514515    def test_no_routes(self, invoke_no_routes):516        result = invoke_no_routes(["routes"])517        assert result.exit_code == 0518        assert "No routes were registered." in result.output519520521need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")522523524@need_dotenv525def test_load_dotenv(monkeypatch):526    # can't use monkeypatch.delitem since the keys don't exist yet527    for item in ("FOO", "BAR", "SPAM", "HAM"):528        monkeypatch._setitem.append((os.environ, item, notset))529530    monkeypatch.setenv("EGGS", "3")531    monkeypatch.chdir(test_path)532    assert load_dotenv()533    assert Path.cwd() == test_path534    # .flaskenv doesn't overwrite .env535    assert os.environ["FOO"] == "env"536    # set only in .flaskenv537    assert os.environ["BAR"] == "bar"538    # set only in .env539    assert os.environ["SPAM"] == "1"540    # set manually, files don't overwrite541    assert os.environ["EGGS"] == "3"542    # test env file encoding543    assert os.environ["HAM"] == "火腿"544    # Non existent file should not load545    assert not load_dotenv("non-existent-file")546547548@need_dotenv549def test_dotenv_path(monkeypatch):550    for item in ("FOO", "BAR", "EGGS"):551        monkeypatch._setitem.append((os.environ, item, notset))552553    load_dotenv(test_path / ".flaskenv")554    assert Path.cwd() == cwd555    assert "FOO" in os.environ556557558def test_dotenv_optional(monkeypatch):559    monkeypatch.setattr("flask.cli.dotenv", None)560    monkeypatch.chdir(test_path)561    load_dotenv()562    assert "FOO" not in os.environ563564565@need_dotenv566def test_disable_dotenv_from_env(monkeypatch, runner):567    monkeypatch.chdir(test_path)568    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")569    runner.invoke(FlaskGroup())570    assert "FOO" not in os.environ571572573def test_run_cert_path():574    # no key575    with pytest.raises(click.BadParameter):576        run_command.make_context("run", ["--cert", __file__])577578    # no cert579    with pytest.raises(click.BadParameter):580        run_command.make_context("run", ["--key", __file__])581582    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])583    assert ctx.params["cert"] == (__file__, __file__)584585586def test_run_cert_adhoc(monkeypatch):587    monkeypatch.setitem(sys.modules, "cryptography", None)588589    # cryptography not installed590    with pytest.raises(click.BadParameter):591        run_command.make_context("run", ["--cert", "adhoc"])592593    # cryptography installed594    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))595    ctx = run_command.make_context("run", ["--cert", "adhoc"])596    assert ctx.params["cert"] == "adhoc"597598    # no key with adhoc599    with pytest.raises(click.BadParameter):600        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])601602603def test_run_cert_import(monkeypatch):604    monkeypatch.setitem(sys.modules, "not_here", None)605606    # ImportError607    with pytest.raises(click.BadParameter):608        run_command.make_context("run", ["--cert", "not_here"])609610    with pytest.raises(click.BadParameter):611        run_command.make_context("run", ["--cert", "flask"])612613    # SSLContext614    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)615616    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)617    ctx = run_command.make_context("run", ["--cert", "ssl_context"])618    assert ctx.params["cert"] is ssl_context619620    # no --key with SSLContext621    with pytest.raises(click.BadParameter):622        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])623624625def test_run_cert_no_ssl(monkeypatch):626    monkeypatch.setattr("flask.cli.ssl", None)627    with pytest.raises(click.BadParameter):628        run_command.make_context("run", ["--cert", "not_here"])629630631def test_cli_blueprints(app):632    """Test blueprint commands register correctly to the application"""633    custom = Blueprint("custom", __name__, cli_group="customized")634    nested = Blueprint("nested", __name__)635    merged = Blueprint("merged", __name__, cli_group=None)636    late = Blueprint("late", __name__)637638    @custom.cli.command("custom")639    def custom_command():640        click.echo("custom_result")641642    @nested.cli.command("nested")643    def nested_command():644        click.echo("nested_result")645646    @merged.cli.command("merged")647    def merged_command():648        click.echo("merged_result")649650    @late.cli.command("late")651    def late_command():652        click.echo("late_result")653654    app.register_blueprint(custom)655    app.register_blueprint(nested)656    app.register_blueprint(merged)657    app.register_blueprint(late, cli_group="late_registration")658659    app_runner = app.test_cli_runner()660661    result = app_runner.invoke(args=["customized", "custom"])662    assert "custom_result" in result.output663664    result = app_runner.invoke(args=["nested", "nested"])665    assert "nested_result" in result.output666667    result = app_runner.invoke(args=["merged"])668    assert "merged_result" in result.output669670    result = app_runner.invoke(args=["late_registration", "late"])671    assert "late_result" in result.output672673674def test_cli_empty(app):675    """If a Blueprint's CLI group is empty, do not register it."""676    bp = Blueprint("blue", __name__, cli_group="blue")677    app.register_blueprint(bp)678679    result = app.test_cli_runner().invoke(args=["blue", "--help"])680    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"681682683def test_click_7_deprecated():684    with patch("flask.cli.cli"):685        if int(click.__version__[0]) < 8:686            pytest.deprecated_call(cli_main, match=".* Click 7 is deprecated")687        else:688            cli_main()