Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

659 lines · 18.4 KiB · Python

Last changed by

Merge branch '2.1.x'David Lordbefore adoptionf976d5b

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 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 NoAppException28from flask.cli import prepare_import29from flask.cli import run_command30from flask.cli import ScriptInfo31from flask.cli import with_appcontext3233cwd = Path.cwd()34test_path = (Path(__file__) / ".." / "test_apps").resolve()353637@pytest.fixture38def runner():39    return CliRunner()404142def test_cli_name(test_apps):43    """Make sure the CLI object's name is the app's name and not the app itself"""44    from cliapp.app import testapp4546    assert testapp.cli.name == testapp.name474849def test_find_best_app(test_apps):50    class Module:51        app = Flask("appname")5253    assert find_best_app(Module) == Module.app5455    class Module:56        application = Flask("appname")5758    assert find_best_app(Module) == Module.application5960    class Module:61        myapp = Flask("appname")6263    assert find_best_app(Module) == Module.myapp6465    class Module:66        @staticmethod67        def create_app():68            return Flask("appname")6970    app = find_best_app(Module)71    assert isinstance(app, Flask)72    assert app.name == "appname"7374    class Module:75        @staticmethod76        def create_app(**kwargs):77            return Flask("appname")7879    app = find_best_app(Module)80    assert isinstance(app, Flask)81    assert app.name == "appname"8283    class Module:84        @staticmethod85        def make_app():86            return Flask("appname")8788    app = find_best_app(Module)89    assert isinstance(app, Flask)90    assert app.name == "appname"9192    class Module:93        myapp = Flask("appname1")9495        @staticmethod96        def create_app():97            return Flask("appname2")9899    assert find_best_app(Module) == Module.myapp100101    class Module:102        myapp = Flask("appname1")103104        @staticmethod105        def create_app():106            return Flask("appname2")107108    assert find_best_app(Module) == Module.myapp109110    class Module:111        pass112113    pytest.raises(NoAppException, find_best_app, Module)114115    class Module:116        myapp1 = Flask("appname1")117        myapp2 = Flask("appname2")118119    pytest.raises(NoAppException, find_best_app, Module)120121    class Module:122        @staticmethod123        def create_app(foo, bar):124            return Flask("appname2")125126    pytest.raises(NoAppException, find_best_app, Module)127128    class Module:129        @staticmethod130        def create_app():131            raise TypeError("bad bad factory!")132133    pytest.raises(TypeError, find_best_app, Module)134135136@pytest.mark.parametrize(137    "value,path,result",138    (139        ("test", cwd, "test"),140        ("test.py", cwd, "test"),141        ("a/test", cwd / "a", "test"),142        ("test/__init__.py", cwd, "test"),143        ("test/__init__", cwd, "test"),144        # nested package145        (146            test_path / "cliapp" / "inner1" / "__init__",147            test_path,148            "cliapp.inner1",149        ),150        (151            test_path / "cliapp" / "inner1" / "inner2",152            test_path,153            "cliapp.inner1.inner2",154        ),155        # dotted name156        ("test.a.b", cwd, "test.a.b"),157        (test_path / "cliapp.app", test_path, "cliapp.app"),158        # not a Python file, will be caught during import159        (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),160    ),161)162def test_prepare_import(request, value, path, result):163    """Expect the correct path to be set and the correct import and app names164    to be returned.165166    :func:`prepare_exec_for_file` has a side effect where the parent directory167    of the given import is added to :data:`sys.path`. This is reset after the168    test runs.169    """170    original_path = sys.path[:]171172    def reset_path():173        sys.path[:] = original_path174175    request.addfinalizer(reset_path)176177    assert prepare_import(value) == result178    assert sys.path[0] == str(path)179180181@pytest.mark.parametrize(182    "iname,aname,result",183    (184        ("cliapp.app", None, "testapp"),185        ("cliapp.app", "testapp", "testapp"),186        ("cliapp.factory", None, "app"),187        ("cliapp.factory", "create_app", "app"),188        ("cliapp.factory", "create_app()", "app"),189        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),190        # trailing comma space191        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),192        # strip whitespace193        ("cliapp.factory", " create_app () ", "app"),194    ),195)196def test_locate_app(test_apps, iname, aname, result):197    assert locate_app(iname, aname).name == result198199200@pytest.mark.parametrize(201    "iname,aname",202    (203        ("notanapp.py", None),204        ("cliapp/app", None),205        ("cliapp.app", "notanapp"),206        # not enough arguments207        ("cliapp.factory", 'create_app2("foo")'),208        # invalid identifier209        ("cliapp.factory", "create_app("),210        # no app returned211        ("cliapp.factory", "no_app"),212        # nested import error213        ("cliapp.importerrorapp", None),214        # not a Python file215        ("cliapp.message.txt", None),216    ),217)218def test_locate_app_raises(test_apps, iname, aname):219    with pytest.raises(NoAppException):220        locate_app(iname, aname)221222223def test_locate_app_suppress_raise(test_apps):224    app = locate_app("notanapp.py", None, raise_if_not_found=False)225    assert app is None226227    # only direct import error is suppressed228    with pytest.raises(NoAppException):229        locate_app("cliapp.importerrorapp", None, raise_if_not_found=False)230231232def test_get_version(test_apps, capsys):233    from flask import __version__ as flask_version234    from werkzeug import __version__ as werkzeug_version235    from platform import python_version236237    class MockCtx:238        resilient_parsing = False239        color = None240241        def exit(self):242            return243244    ctx = MockCtx()245    get_version(ctx, None, "test")246    out, err = capsys.readouterr()247    assert f"Python {python_version()}" in out248    assert f"Flask {flask_version}" in out249    assert f"Werkzeug {werkzeug_version}" in out250251252def test_scriptinfo(test_apps, monkeypatch):253    obj = ScriptInfo(app_import_path="cliapp.app:testapp")254    app = obj.load_app()255    assert app.name == "testapp"256    assert obj.load_app() is app257258    # import app with module's absolute path259    cli_app_path = str(test_path / "cliapp" / "app.py")260261    obj = ScriptInfo(app_import_path=cli_app_path)262    app = obj.load_app()263    assert app.name == "testapp"264    assert obj.load_app() is app265    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")266    app = obj.load_app()267    assert app.name == "testapp"268    assert obj.load_app() is app269270    def create_app():271        return Flask("createapp")272273    obj = ScriptInfo(create_app=create_app)274    app = obj.load_app()275    assert app.name == "createapp"276    assert obj.load_app() is app277278    obj = ScriptInfo()279    pytest.raises(NoAppException, obj.load_app)280281    # import app from wsgi.py in current directory282    monkeypatch.chdir(test_path / "helloworld")283    obj = ScriptInfo()284    app = obj.load_app()285    assert app.name == "hello"286287    # import app from app.py in current directory288    monkeypatch.chdir(test_path / "cliapp")289    obj = ScriptInfo()290    app = obj.load_app()291    assert app.name == "testapp"292293294@pytest.mark.xfail(platform.python_implementation() == "PyPy", reason="flaky on pypy")295def test_lazy_load_error(monkeypatch):296    """When using lazy loading, the correct exception should be297    re-raised.298    """299300    class BadExc(Exception):301        pass302303    def bad_load():304        raise BadExc305306    lazy = DispatchingApp(bad_load, use_eager_loading=False)307308    # reduce flakiness by waiting for the internal loading lock309    with lazy._lock:310        with pytest.raises(BadExc):311            lazy._flush_bg_loading_exception()312313314def test_with_appcontext(runner):315    @click.command()316    @with_appcontext317    def testcmd():318        click.echo(current_app.name)319320    obj = ScriptInfo(create_app=lambda: Flask("testapp"))321322    result = runner.invoke(testcmd, obj=obj)323    assert result.exit_code == 0324    assert result.output == "testapp\n"325326327def test_appgroup(runner):328    @click.group(cls=AppGroup)329    def cli():330        pass331332    @cli.command(with_appcontext=True)333    def test():334        click.echo(current_app.name)335336    @cli.group()337    def subgroup():338        pass339340    @subgroup.command(with_appcontext=True)341    def test2():342        click.echo(current_app.name)343344    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))345346    result = runner.invoke(cli, ["test"], obj=obj)347    assert result.exit_code == 0348    assert result.output == "testappgroup\n"349350    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)351    assert result.exit_code == 0352    assert result.output == "testappgroup\n"353354355def test_flaskgroup(runner):356    def create_app():357        return Flask("flaskgroup")358359    @click.group(cls=FlaskGroup, create_app=create_app)360    def cli(**params):361        pass362363    @cli.command()364    def test():365        click.echo(current_app.name)366367    result = runner.invoke(cli, ["test"])368    assert result.exit_code == 0369    assert result.output == "flaskgroup\n"370371372@pytest.mark.parametrize("set_debug_flag", (True, False))373def test_flaskgroup_debug(runner, set_debug_flag):374    def create_app():375        app = Flask("flaskgroup")376        app.debug = True377        return app378379    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)380    def cli(**params):381        pass382383    @cli.command()384    def test():385        click.echo(str(current_app.debug))386387    result = runner.invoke(cli, ["test"])388    assert result.exit_code == 0389    assert result.output == f"{not set_debug_flag}\n"390391392def test_no_command_echo_loading_error():393    from flask.cli import cli394395    runner = CliRunner(mix_stderr=False)396    result = runner.invoke(cli, ["missing"])397    assert result.exit_code == 2398    assert "FLASK_APP" in result.stderr399    assert "Usage:" in result.stderr400401402def test_help_echo_loading_error():403    from flask.cli import cli404405    runner = CliRunner(mix_stderr=False)406    result = runner.invoke(cli, ["--help"])407    assert result.exit_code == 0408    assert "FLASK_APP" in result.stderr409    assert "Usage:" in result.stdout410411412def test_help_echo_exception():413    def create_app():414        raise Exception("oh no")415416    cli = FlaskGroup(create_app=create_app)417    runner = CliRunner(mix_stderr=False)418    result = runner.invoke(cli, ["--help"])419    assert result.exit_code == 0420    assert "Exception: oh no" in result.stderr421    assert "Usage:" in result.stdout422423424class TestRoutes:425    @pytest.fixture426    def invoke(self, runner):427        def create_app():428            app = Flask(__name__)429            app.testing = True430431            @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])432            def yyy_get_post(x, y):433                pass434435            @app.route("/zzz_post", methods=["POST"])436            def aaa_post():437                pass438439            return app440441        cli = FlaskGroup(create_app=create_app)442        return partial(runner.invoke, cli)443444    @pytest.fixture445    def invoke_no_routes(self, runner):446        def create_app():447            app = Flask(__name__, static_folder=None)448            app.testing = True449450            return app451452        cli = FlaskGroup(create_app=create_app)453        return partial(runner.invoke, cli)454455    def expect_order(self, order, output):456        # skip the header and match the start of each row457        for expect, line in zip(order, output.splitlines()[2:]):458            # do this instead of startswith for nicer pytest output459            assert line[: len(expect)] == expect460461    def test_simple(self, invoke):462        result = invoke(["routes"])463        assert result.exit_code == 0464        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)465466    def test_sort(self, invoke):467        default_output = invoke(["routes"]).output468        endpoint_output = invoke(["routes", "-s", "endpoint"]).output469        assert default_output == endpoint_output470        self.expect_order(471            ["static", "yyy_get_post", "aaa_post"],472            invoke(["routes", "-s", "methods"]).output,473        )474        self.expect_order(475            ["yyy_get_post", "static", "aaa_post"],476            invoke(["routes", "-s", "rule"]).output,477        )478        self.expect_order(479            ["aaa_post", "yyy_get_post", "static"],480            invoke(["routes", "-s", "match"]).output,481        )482483    def test_all_methods(self, invoke):484        output = invoke(["routes"]).output485        assert "GET, HEAD, OPTIONS, POST" not in output486        output = invoke(["routes", "--all-methods"]).output487        assert "GET, HEAD, OPTIONS, POST" in output488489    def test_no_routes(self, invoke_no_routes):490        result = invoke_no_routes(["routes"])491        assert result.exit_code == 0492        assert "No routes were registered." in result.output493494495need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")496497498@need_dotenv499def test_load_dotenv(monkeypatch):500    # can't use monkeypatch.delitem since the keys don't exist yet501    for item in ("FOO", "BAR", "SPAM", "HAM"):502        monkeypatch._setitem.append((os.environ, item, notset))503504    monkeypatch.setenv("EGGS", "3")505    monkeypatch.chdir(test_path)506    assert load_dotenv()507    assert Path.cwd() == test_path508    # .flaskenv doesn't overwrite .env509    assert os.environ["FOO"] == "env"510    # set only in .flaskenv511    assert os.environ["BAR"] == "bar"512    # set only in .env513    assert os.environ["SPAM"] == "1"514    # set manually, files don't overwrite515    assert os.environ["EGGS"] == "3"516    # test env file encoding517    assert os.environ["HAM"] == "火腿"518    # Non existent file should not load519    assert not load_dotenv("non-existent-file")520521522@need_dotenv523def test_dotenv_path(monkeypatch):524    for item in ("FOO", "BAR", "EGGS"):525        monkeypatch._setitem.append((os.environ, item, notset))526527    load_dotenv(test_path / ".flaskenv")528    assert Path.cwd() == cwd529    assert "FOO" in os.environ530531532def test_dotenv_optional(monkeypatch):533    monkeypatch.setattr("flask.cli.dotenv", None)534    monkeypatch.chdir(test_path)535    load_dotenv()536    assert "FOO" not in os.environ537538539@need_dotenv540def test_disable_dotenv_from_env(monkeypatch, runner):541    monkeypatch.chdir(test_path)542    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")543    runner.invoke(FlaskGroup())544    assert "FOO" not in os.environ545546547def test_run_cert_path():548    # no key549    with pytest.raises(click.BadParameter):550        run_command.make_context("run", ["--cert", __file__])551552    # no cert553    with pytest.raises(click.BadParameter):554        run_command.make_context("run", ["--key", __file__])555556    # cert specified first557    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])558    assert ctx.params["cert"] == (__file__, __file__)559560    # key specified first561    ctx = run_command.make_context("run", ["--key", __file__, "--cert", __file__])562    assert ctx.params["cert"] == (__file__, __file__)563564565def test_run_cert_adhoc(monkeypatch):566    monkeypatch.setitem(sys.modules, "cryptography", None)567568    # cryptography not installed569    with pytest.raises(click.BadParameter):570        run_command.make_context("run", ["--cert", "adhoc"])571572    # cryptography installed573    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))574    ctx = run_command.make_context("run", ["--cert", "adhoc"])575    assert ctx.params["cert"] == "adhoc"576577    # no key with adhoc578    with pytest.raises(click.BadParameter):579        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])580581582def test_run_cert_import(monkeypatch):583    monkeypatch.setitem(sys.modules, "not_here", None)584585    # ImportError586    with pytest.raises(click.BadParameter):587        run_command.make_context("run", ["--cert", "not_here"])588589    with pytest.raises(click.BadParameter):590        run_command.make_context("run", ["--cert", "flask"])591592    # SSLContext593    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)594595    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)596    ctx = run_command.make_context("run", ["--cert", "ssl_context"])597    assert ctx.params["cert"] is ssl_context598599    # no --key with SSLContext600    with pytest.raises(click.BadParameter):601        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])602603604def test_run_cert_no_ssl(monkeypatch):605    monkeypatch.setattr("flask.cli.ssl", None)606    with pytest.raises(click.BadParameter):607        run_command.make_context("run", ["--cert", "not_here"])608609610def test_cli_blueprints(app):611    """Test blueprint commands register correctly to the application"""612    custom = Blueprint("custom", __name__, cli_group="customized")613    nested = Blueprint("nested", __name__)614    merged = Blueprint("merged", __name__, cli_group=None)615    late = Blueprint("late", __name__)616617    @custom.cli.command("custom")618    def custom_command():619        click.echo("custom_result")620621    @nested.cli.command("nested")622    def nested_command():623        click.echo("nested_result")624625    @merged.cli.command("merged")626    def merged_command():627        click.echo("merged_result")628629    @late.cli.command("late")630    def late_command():631        click.echo("late_result")632633    app.register_blueprint(custom)634    app.register_blueprint(nested)635    app.register_blueprint(merged)636    app.register_blueprint(late, cli_group="late_registration")637638    app_runner = app.test_cli_runner()639640    result = app_runner.invoke(args=["customized", "custom"])641    assert "custom_result" in result.output642643    result = app_runner.invoke(args=["nested", "nested"])644    assert "nested_result" in result.output645646    result = app_runner.invoke(args=["merged"])647    assert "merged_result" in result.output648649    result = app_runner.invoke(args=["late_registration", "late"])650    assert "late_result" in result.output651652653def test_cli_empty(app):654    """If a Blueprint's CLI group is empty, do not register it."""655    bp = Blueprint("blue", __name__, cli_group="blue")656    app.register_blueprint(bp)657658    result = app.test_cli_runner().invoke(args=["blue", "--help"])659    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"