Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

692 lines · 19.3 KiB · Python

Last changed by

Merge pull request #4294 from pallets/flaky-lazy-testDavid Lordbefore adoption8ddf80c

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    script_info = ScriptInfo()5354    class Module:55        app = Flask("appname")5657    assert find_best_app(script_info, Module) == Module.app5859    class Module:60        application = Flask("appname")6162    assert find_best_app(script_info, Module) == Module.application6364    class Module:65        myapp = Flask("appname")6667    assert find_best_app(script_info, Module) == Module.myapp6869    class Module:70        @staticmethod71        def create_app():72            return Flask("appname")7374    app = find_best_app(script_info, Module)75    assert isinstance(app, Flask)76    assert app.name == "appname"7778    class Module:79        @staticmethod80        def create_app(**kwargs):81            return Flask("appname")8283    app = find_best_app(script_info, Module)84    assert isinstance(app, Flask)85    assert app.name == "appname"8687    class Module:88        @staticmethod89        def create_app(foo):90            return Flask("appname")9192    with pytest.deprecated_call(match="Script info"):93        app = find_best_app(script_info, Module)9495    assert isinstance(app, Flask)96    assert app.name == "appname"9798    class Module:99        @staticmethod100        def create_app(foo=None, script_info=None):101            return Flask("appname")102103    with pytest.deprecated_call(match="script_info"):104        app = find_best_app(script_info, Module)105106    assert isinstance(app, Flask)107    assert app.name == "appname"108109    class Module:110        @staticmethod111        def make_app():112            return Flask("appname")113114    app = find_best_app(script_info, Module)115    assert isinstance(app, Flask)116    assert app.name == "appname"117118    class Module:119        myapp = Flask("appname1")120121        @staticmethod122        def create_app():123            return Flask("appname2")124125    assert find_best_app(script_info, Module) == Module.myapp126127    class Module:128        myapp = Flask("appname1")129130        @staticmethod131        def create_app():132            return Flask("appname2")133134    assert find_best_app(script_info, Module) == Module.myapp135136    class Module:137        pass138139    pytest.raises(NoAppException, find_best_app, script_info, Module)140141    class Module:142        myapp1 = Flask("appname1")143        myapp2 = Flask("appname2")144145    pytest.raises(NoAppException, find_best_app, script_info, Module)146147    class Module:148        @staticmethod149        def create_app(foo, bar):150            return Flask("appname2")151152    pytest.raises(NoAppException, find_best_app, script_info, Module)153154    class Module:155        @staticmethod156        def create_app():157            raise TypeError("bad bad factory!")158159    pytest.raises(TypeError, find_best_app, script_info, Module)160161162@pytest.mark.parametrize(163    "value,path,result",164    (165        ("test", cwd, "test"),166        ("test.py", cwd, "test"),167        ("a/test", cwd / "a", "test"),168        ("test/__init__.py", cwd, "test"),169        ("test/__init__", cwd, "test"),170        # nested package171        (172            test_path / "cliapp" / "inner1" / "__init__",173            test_path,174            "cliapp.inner1",175        ),176        (177            test_path / "cliapp" / "inner1" / "inner2",178            test_path,179            "cliapp.inner1.inner2",180        ),181        # dotted name182        ("test.a.b", cwd, "test.a.b"),183        (test_path / "cliapp.app", test_path, "cliapp.app"),184        # not a Python file, will be caught during import185        (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),186    ),187)188def test_prepare_import(request, value, path, result):189    """Expect the correct path to be set and the correct import and app names190    to be returned.191192    :func:`prepare_exec_for_file` has a side effect where the parent directory193    of the given import is added to :data:`sys.path`. This is reset after the194    test runs.195    """196    original_path = sys.path[:]197198    def reset_path():199        sys.path[:] = original_path200201    request.addfinalizer(reset_path)202203    assert prepare_import(value) == result204    assert sys.path[0] == str(path)205206207@pytest.mark.parametrize(208    "iname,aname,result",209    (210        ("cliapp.app", None, "testapp"),211        ("cliapp.app", "testapp", "testapp"),212        ("cliapp.factory", None, "app"),213        ("cliapp.factory", "create_app", "app"),214        ("cliapp.factory", "create_app()", "app"),215        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),216        # trailing comma space217        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),218        # strip whitespace219        ("cliapp.factory", " create_app () ", "app"),220    ),221)222def test_locate_app(test_apps, iname, aname, result):223    info = ScriptInfo()224    assert locate_app(info, iname, aname).name == result225226227@pytest.mark.parametrize(228    "iname,aname",229    (230        ("notanapp.py", None),231        ("cliapp/app", None),232        ("cliapp.app", "notanapp"),233        # not enough arguments234        ("cliapp.factory", 'create_app2("foo")'),235        # invalid identifier236        ("cliapp.factory", "create_app("),237        # no app returned238        ("cliapp.factory", "no_app"),239        # nested import error240        ("cliapp.importerrorapp", None),241        # not a Python file242        ("cliapp.message.txt", None),243    ),244)245def test_locate_app_raises(test_apps, iname, aname):246    info = ScriptInfo()247248    with pytest.raises(NoAppException):249        locate_app(info, iname, aname)250251252def test_locate_app_suppress_raise(test_apps):253    info = ScriptInfo()254    app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)255    assert app is None256257    # only direct import error is suppressed258    with pytest.raises(NoAppException):259        locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)260261262def test_get_version(test_apps, capsys):263    from flask import __version__ as flask_version264    from werkzeug import __version__ as werkzeug_version265    from platform import python_version266267    class MockCtx:268        resilient_parsing = False269        color = None270271        def exit(self):272            return273274    ctx = MockCtx()275    get_version(ctx, None, "test")276    out, err = capsys.readouterr()277    assert f"Python {python_version()}" in out278    assert f"Flask {flask_version}" in out279    assert f"Werkzeug {werkzeug_version}" in out280281282def test_scriptinfo(test_apps, monkeypatch):283    obj = ScriptInfo(app_import_path="cliapp.app:testapp")284    app = obj.load_app()285    assert app.name == "testapp"286    assert obj.load_app() is app287288    # import app with module's absolute path289    cli_app_path = str(test_path / "cliapp" / "app.py")290291    obj = ScriptInfo(app_import_path=cli_app_path)292    app = obj.load_app()293    assert app.name == "testapp"294    assert obj.load_app() is app295    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")296    app = obj.load_app()297    assert app.name == "testapp"298    assert obj.load_app() is app299300    def create_app():301        return Flask("createapp")302303    obj = ScriptInfo(create_app=create_app)304    app = obj.load_app()305    assert app.name == "createapp"306    assert obj.load_app() is app307308    obj = ScriptInfo()309    pytest.raises(NoAppException, obj.load_app)310311    # import app from wsgi.py in current directory312    monkeypatch.chdir(test_path / "helloworld")313    obj = ScriptInfo()314    app = obj.load_app()315    assert app.name == "hello"316317    # import app from app.py in current directory318    monkeypatch.chdir(test_path / "cliapp")319    obj = ScriptInfo()320    app = obj.load_app()321    assert app.name == "testapp"322323324@pytest.mark.xfail(platform.python_implementation() == "PyPy", reason="flaky on pypy")325def test_lazy_load_error(monkeypatch):326    """When using lazy loading, the correct exception should be327    re-raised.328    """329330    class BadExc(Exception):331        pass332333    def bad_load():334        raise BadExc335336    lazy = DispatchingApp(bad_load, use_eager_loading=False)337338    with pytest.raises(BadExc):339        # reduce flakiness by waiting for the internal loading lock340        with lazy._lock:341            lazy._flush_bg_loading_exception()342343344def test_with_appcontext(runner):345    @click.command()346    @with_appcontext347    def testcmd():348        click.echo(current_app.name)349350    obj = ScriptInfo(create_app=lambda: Flask("testapp"))351352    result = runner.invoke(testcmd, obj=obj)353    assert result.exit_code == 0354    assert result.output == "testapp\n"355356357def test_appgroup(runner):358    @click.group(cls=AppGroup)359    def cli():360        pass361362    @cli.command(with_appcontext=True)363    def test():364        click.echo(current_app.name)365366    @cli.group()367    def subgroup():368        pass369370    @subgroup.command(with_appcontext=True)371    def test2():372        click.echo(current_app.name)373374    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))375376    result = runner.invoke(cli, ["test"], obj=obj)377    assert result.exit_code == 0378    assert result.output == "testappgroup\n"379380    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)381    assert result.exit_code == 0382    assert result.output == "testappgroup\n"383384385def test_flaskgroup(runner):386    def create_app():387        return Flask("flaskgroup")388389    @click.group(cls=FlaskGroup, create_app=create_app)390    def cli(**params):391        pass392393    @cli.command()394    def test():395        click.echo(current_app.name)396397    result = runner.invoke(cli, ["test"])398    assert result.exit_code == 0399    assert result.output == "flaskgroup\n"400401402@pytest.mark.parametrize("set_debug_flag", (True, False))403def test_flaskgroup_debug(runner, set_debug_flag):404    def create_app():405        app = Flask("flaskgroup")406        app.debug = True407        return app408409    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)410    def cli(**params):411        pass412413    @cli.command()414    def test():415        click.echo(str(current_app.debug))416417    result = runner.invoke(cli, ["test"])418    assert result.exit_code == 0419    assert result.output == f"{not set_debug_flag}\n"420421422def test_no_command_echo_loading_error():423    from flask.cli import cli424425    runner = CliRunner(mix_stderr=False)426    result = runner.invoke(cli, ["missing"])427    assert result.exit_code == 2428    assert "FLASK_APP" in result.stderr429    assert "Usage:" in result.stderr430431432def test_help_echo_loading_error():433    from flask.cli import cli434435    runner = CliRunner(mix_stderr=False)436    result = runner.invoke(cli, ["--help"])437    assert result.exit_code == 0438    assert "FLASK_APP" in result.stderr439    assert "Usage:" in result.stdout440441442def test_help_echo_exception():443    def create_app():444        raise Exception("oh no")445446    cli = FlaskGroup(create_app=create_app)447    runner = CliRunner(mix_stderr=False)448    result = runner.invoke(cli, ["--help"])449    assert result.exit_code == 0450    assert "Exception: oh no" in result.stderr451    assert "Usage:" in result.stdout452453454class TestRoutes:455    @pytest.fixture456    def invoke(self, runner):457        def create_app():458            app = Flask(__name__)459            app.testing = True460461            @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])462            def yyy_get_post(x, y):463                pass464465            @app.route("/zzz_post", methods=["POST"])466            def aaa_post():467                pass468469            return app470471        cli = FlaskGroup(create_app=create_app)472        return partial(runner.invoke, cli)473474    @pytest.fixture475    def invoke_no_routes(self, runner):476        def create_app():477            app = Flask(__name__, static_folder=None)478            app.testing = True479480            return app481482        cli = FlaskGroup(create_app=create_app)483        return partial(runner.invoke, cli)484485    def expect_order(self, order, output):486        # skip the header and match the start of each row487        for expect, line in zip(order, output.splitlines()[2:]):488            # do this instead of startswith for nicer pytest output489            assert line[: len(expect)] == expect490491    def test_simple(self, invoke):492        result = invoke(["routes"])493        assert result.exit_code == 0494        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)495496    def test_sort(self, invoke):497        default_output = invoke(["routes"]).output498        endpoint_output = invoke(["routes", "-s", "endpoint"]).output499        assert default_output == endpoint_output500        self.expect_order(501            ["static", "yyy_get_post", "aaa_post"],502            invoke(["routes", "-s", "methods"]).output,503        )504        self.expect_order(505            ["yyy_get_post", "static", "aaa_post"],506            invoke(["routes", "-s", "rule"]).output,507        )508        self.expect_order(509            ["aaa_post", "yyy_get_post", "static"],510            invoke(["routes", "-s", "match"]).output,511        )512513    def test_all_methods(self, invoke):514        output = invoke(["routes"]).output515        assert "GET, HEAD, OPTIONS, POST" not in output516        output = invoke(["routes", "--all-methods"]).output517        assert "GET, HEAD, OPTIONS, POST" in output518519    def test_no_routes(self, invoke_no_routes):520        result = invoke_no_routes(["routes"])521        assert result.exit_code == 0522        assert "No routes were registered." in result.output523524525need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")526527528@need_dotenv529def test_load_dotenv(monkeypatch):530    # can't use monkeypatch.delitem since the keys don't exist yet531    for item in ("FOO", "BAR", "SPAM", "HAM"):532        monkeypatch._setitem.append((os.environ, item, notset))533534    monkeypatch.setenv("EGGS", "3")535    monkeypatch.chdir(test_path)536    assert load_dotenv()537    assert Path.cwd() == test_path538    # .flaskenv doesn't overwrite .env539    assert os.environ["FOO"] == "env"540    # set only in .flaskenv541    assert os.environ["BAR"] == "bar"542    # set only in .env543    assert os.environ["SPAM"] == "1"544    # set manually, files don't overwrite545    assert os.environ["EGGS"] == "3"546    # test env file encoding547    assert os.environ["HAM"] == "火腿"548    # Non existent file should not load549    assert not load_dotenv("non-existent-file")550551552@need_dotenv553def test_dotenv_path(monkeypatch):554    for item in ("FOO", "BAR", "EGGS"):555        monkeypatch._setitem.append((os.environ, item, notset))556557    load_dotenv(test_path / ".flaskenv")558    assert Path.cwd() == cwd559    assert "FOO" in os.environ560561562def test_dotenv_optional(monkeypatch):563    monkeypatch.setattr("flask.cli.dotenv", None)564    monkeypatch.chdir(test_path)565    load_dotenv()566    assert "FOO" not in os.environ567568569@need_dotenv570def test_disable_dotenv_from_env(monkeypatch, runner):571    monkeypatch.chdir(test_path)572    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")573    runner.invoke(FlaskGroup())574    assert "FOO" not in os.environ575576577def test_run_cert_path():578    # no key579    with pytest.raises(click.BadParameter):580        run_command.make_context("run", ["--cert", __file__])581582    # no cert583    with pytest.raises(click.BadParameter):584        run_command.make_context("run", ["--key", __file__])585586    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])587    assert ctx.params["cert"] == (__file__, __file__)588589590def test_run_cert_adhoc(monkeypatch):591    monkeypatch.setitem(sys.modules, "cryptography", None)592593    # cryptography not installed594    with pytest.raises(click.BadParameter):595        run_command.make_context("run", ["--cert", "adhoc"])596597    # cryptography installed598    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))599    ctx = run_command.make_context("run", ["--cert", "adhoc"])600    assert ctx.params["cert"] == "adhoc"601602    # no key with adhoc603    with pytest.raises(click.BadParameter):604        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])605606607def test_run_cert_import(monkeypatch):608    monkeypatch.setitem(sys.modules, "not_here", None)609610    # ImportError611    with pytest.raises(click.BadParameter):612        run_command.make_context("run", ["--cert", "not_here"])613614    with pytest.raises(click.BadParameter):615        run_command.make_context("run", ["--cert", "flask"])616617    # SSLContext618    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)619620    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)621    ctx = run_command.make_context("run", ["--cert", "ssl_context"])622    assert ctx.params["cert"] is ssl_context623624    # no --key with SSLContext625    with pytest.raises(click.BadParameter):626        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])627628629def test_run_cert_no_ssl(monkeypatch):630    monkeypatch.setattr("flask.cli.ssl", None)631    with pytest.raises(click.BadParameter):632        run_command.make_context("run", ["--cert", "not_here"])633634635def test_cli_blueprints(app):636    """Test blueprint commands register correctly to the application"""637    custom = Blueprint("custom", __name__, cli_group="customized")638    nested = Blueprint("nested", __name__)639    merged = Blueprint("merged", __name__, cli_group=None)640    late = Blueprint("late", __name__)641642    @custom.cli.command("custom")643    def custom_command():644        click.echo("custom_result")645646    @nested.cli.command("nested")647    def nested_command():648        click.echo("nested_result")649650    @merged.cli.command("merged")651    def merged_command():652        click.echo("merged_result")653654    @late.cli.command("late")655    def late_command():656        click.echo("late_result")657658    app.register_blueprint(custom)659    app.register_blueprint(nested)660    app.register_blueprint(merged)661    app.register_blueprint(late, cli_group="late_registration")662663    app_runner = app.test_cli_runner()664665    result = app_runner.invoke(args=["customized", "custom"])666    assert "custom_result" in result.output667668    result = app_runner.invoke(args=["nested", "nested"])669    assert "nested_result" in result.output670671    result = app_runner.invoke(args=["merged"])672    assert "merged_result" in result.output673674    result = app_runner.invoke(args=["late_registration", "late"])675    assert "late_result" in result.output676677678def test_cli_empty(app):679    """If a Blueprint's CLI group is empty, do not register it."""680    bp = Blueprint("blue", __name__, cli_group="blue")681    app.register_blueprint(bp)682683    result = app.test_cli_runner().invoke(args=["blue", "--help"])684    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"685686687def test_click_7_deprecated():688    with patch("flask.cli.cli"):689        if int(click.__version__[0]) < 8:690            pytest.deprecated_call(cli_main, match=".* Click 7 is deprecated")691        else:692            cli_main()