Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

652 lines · 18.5 KiB · Python

Last changed by

remove unused module docstringsDavid Lordbefore adoptionf2f027d

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 partial89import click10import pytest11from _pytest.monkeypatch import notset12from click.testing import CliRunner1314from flask import Blueprint15from flask import current_app16from flask import Flask17from flask.cli import AppGroup18from flask.cli import dotenv19from flask.cli import find_best_app20from flask.cli import FlaskGroup21from flask.cli import get_version22from flask.cli import load_dotenv23from flask.cli import locate_app24from flask.cli import NoAppException25from flask.cli import prepare_import26from flask.cli import run_command27from flask.cli import ScriptInfo28from flask.cli import with_appcontext2930cwd = os.getcwd()31test_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))323334@pytest.fixture35def runner():36    return CliRunner()373839def test_cli_name(test_apps):40    """Make sure the CLI object's name is the app's name and not the app itself"""41    from cliapp.app import testapp4243    assert testapp.cli.name == testapp.name444546def test_find_best_app(test_apps):47    """Test if `find_best_app` behaves as expected with different combinations of input."""  # noqa: B95048    script_info = ScriptInfo()4950    class Module:51        app = Flask("appname")5253    assert find_best_app(script_info, Module) == Module.app5455    class Module:56        application = Flask("appname")5758    assert find_best_app(script_info, Module) == Module.application5960    class Module:61        myapp = Flask("appname")6263    assert find_best_app(script_info, Module) == Module.myapp6465    class Module:66        @staticmethod67        def create_app():68            return Flask("appname")6970    assert isinstance(find_best_app(script_info, Module), Flask)71    assert find_best_app(script_info, Module).name == "appname"7273    class Module:74        @staticmethod75        def create_app(foo):76            return Flask("appname")7778    assert isinstance(find_best_app(script_info, Module), Flask)79    assert find_best_app(script_info, Module).name == "appname"8081    class Module:82        @staticmethod83        def create_app(foo=None, script_info=None):84            return Flask("appname")8586    assert isinstance(find_best_app(script_info, Module), Flask)87    assert find_best_app(script_info, Module).name == "appname"8889    class Module:90        @staticmethod91        def make_app():92            return Flask("appname")9394    assert isinstance(find_best_app(script_info, Module), Flask)95    assert find_best_app(script_info, Module).name == "appname"9697    class Module:98        myapp = Flask("appname1")99100        @staticmethod101        def create_app():102            return Flask("appname2")103104    assert find_best_app(script_info, Module) == Module.myapp105106    class Module:107        myapp = Flask("appname1")108109        @staticmethod110        def create_app():111            return Flask("appname2")112113    assert find_best_app(script_info, Module) == Module.myapp114115    class Module:116        pass117118    pytest.raises(NoAppException, find_best_app, script_info, Module)119120    class Module:121        myapp1 = Flask("appname1")122        myapp2 = Flask("appname2")123124    pytest.raises(NoAppException, find_best_app, script_info, Module)125126    class Module:127        @staticmethod128        def create_app(foo, bar):129            return Flask("appname2")130131    pytest.raises(NoAppException, find_best_app, script_info, Module)132133    class Module:134        @staticmethod135        def create_app():136            raise TypeError("bad bad factory!")137138    pytest.raises(TypeError, find_best_app, script_info, Module)139140141@pytest.mark.parametrize(142    "value,path,result",143    (144        ("test", cwd, "test"),145        ("test.py", cwd, "test"),146        ("a/test", os.path.join(cwd, "a"), "test"),147        ("test/__init__.py", cwd, "test"),148        ("test/__init__", cwd, "test"),149        # nested package150        (151            os.path.join(test_path, "cliapp", "inner1", "__init__"),152            test_path,153            "cliapp.inner1",154        ),155        (156            os.path.join(test_path, "cliapp", "inner1", "inner2"),157            test_path,158            "cliapp.inner1.inner2",159        ),160        # dotted name161        ("test.a.b", cwd, "test.a.b"),162        (os.path.join(test_path, "cliapp.app"), test_path, "cliapp.app"),163        # not a Python file, will be caught during import164        (165            os.path.join(test_path, "cliapp", "message.txt"),166            test_path,167            "cliapp.message.txt",168        ),169    ),170)171def test_prepare_import(request, value, path, result):172    """Expect the correct path to be set and the correct import and app names173    to be returned.174175    :func:`prepare_exec_for_file` has a side effect where the parent directory176    of the given import is added to :data:`sys.path`. This is reset after the177    test runs.178    """179    original_path = sys.path[:]180181    def reset_path():182        sys.path[:] = original_path183184    request.addfinalizer(reset_path)185186    assert prepare_import(value) == result187    assert sys.path[0] == path188189190@pytest.mark.parametrize(191    "iname,aname,result",192    (193        ("cliapp.app", None, "testapp"),194        ("cliapp.app", "testapp", "testapp"),195        ("cliapp.factory", None, "app"),196        ("cliapp.factory", "create_app", "app"),197        ("cliapp.factory", "create_app()", "app"),198        # no script_info199        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),200        # trailing comma space201        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),202        # takes script_info203        ("cliapp.factory", 'create_app3("foo")', "app3_foo_spam"),204        # strip whitespace205        ("cliapp.factory", " create_app () ", "app"),206    ),207)208def test_locate_app(test_apps, iname, aname, result):209    info = ScriptInfo()210    info.data["test"] = "spam"211    assert locate_app(info, iname, aname).name == result212213214@pytest.mark.parametrize(215    "iname,aname",216    (217        ("notanapp.py", None),218        ("cliapp/app", None),219        ("cliapp.app", "notanapp"),220        # not enough arguments221        ("cliapp.factory", 'create_app2("foo")'),222        # invalid identifier223        ("cliapp.factory", "create_app("),224        # no app returned225        ("cliapp.factory", "no_app"),226        # nested import error227        ("cliapp.importerrorapp", None),228        # not a Python file229        ("cliapp.message.txt", None),230    ),231)232def test_locate_app_raises(test_apps, iname, aname):233    info = ScriptInfo()234235    with pytest.raises(NoAppException):236        locate_app(info, iname, aname)237238239def test_locate_app_suppress_raise():240    info = ScriptInfo()241    app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)242    assert app is None243244    # only direct import error is suppressed245    with pytest.raises(NoAppException):246        locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)247248249def test_get_version(test_apps, capsys):250    from flask import __version__ as flask_version251    from werkzeug import __version__ as werkzeug_version252    from platform import python_version253254    class MockCtx:255        resilient_parsing = False256        color = None257258        def exit(self):259            return260261    ctx = MockCtx()262    get_version(ctx, None, "test")263    out, err = capsys.readouterr()264    assert f"Python {python_version()}" in out265    assert f"Flask {flask_version}" in out266    assert f"Werkzeug {werkzeug_version}" in out267268269def test_scriptinfo(test_apps, monkeypatch):270    """Test of ScriptInfo."""271    obj = ScriptInfo(app_import_path="cliapp.app:testapp")272    app = obj.load_app()273    assert app.name == "testapp"274    assert obj.load_app() is app275276    # import app with module's absolute path277    cli_app_path = os.path.abspath(278        os.path.join(os.path.dirname(__file__), "test_apps", "cliapp", "app.py")279    )280    obj = ScriptInfo(app_import_path=cli_app_path)281    app = obj.load_app()282    assert app.name == "testapp"283    assert obj.load_app() is app284    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")285    app = obj.load_app()286    assert app.name == "testapp"287    assert obj.load_app() is app288289    def create_app(info):290        return Flask("createapp")291292    obj = ScriptInfo(create_app=create_app)293    app = obj.load_app()294    assert app.name == "createapp"295    assert obj.load_app() is app296297    obj = ScriptInfo()298    pytest.raises(NoAppException, obj.load_app)299300    # import app from wsgi.py in current directory301    monkeypatch.chdir(302        os.path.abspath(303            os.path.join(os.path.dirname(__file__), "test_apps", "helloworld")304        )305    )306    obj = ScriptInfo()307    app = obj.load_app()308    assert app.name == "hello"309310    # import app from app.py in current directory311    monkeypatch.chdir(312        os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps", "cliapp"))313    )314    obj = ScriptInfo()315    app = obj.load_app()316    assert app.name == "testapp"317318319def test_with_appcontext(runner):320    """Test of with_appcontext."""321322    @click.command()323    @with_appcontext324    def testcmd():325        click.echo(current_app.name)326327    obj = ScriptInfo(create_app=lambda info: Flask("testapp"))328329    result = runner.invoke(testcmd, obj=obj)330    assert result.exit_code == 0331    assert result.output == "testapp\n"332333334def test_appgroup(runner):335    """Test of with_appcontext."""336337    @click.group(cls=AppGroup)338    def cli():339        pass340341    @cli.command(with_appcontext=True)342    def test():343        click.echo(current_app.name)344345    @cli.group()346    def subgroup():347        pass348349    @subgroup.command(with_appcontext=True)350    def test2():351        click.echo(current_app.name)352353    obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))354355    result = runner.invoke(cli, ["test"], obj=obj)356    assert result.exit_code == 0357    assert result.output == "testappgroup\n"358359    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)360    assert result.exit_code == 0361    assert result.output == "testappgroup\n"362363364def test_flaskgroup(runner):365    """Test FlaskGroup."""366367    def create_app(info):368        return Flask("flaskgroup")369370    @click.group(cls=FlaskGroup, create_app=create_app)371    def cli(**params):372        pass373374    @cli.command()375    def test():376        click.echo(current_app.name)377378    result = runner.invoke(cli, ["test"])379    assert result.exit_code == 0380    assert result.output == "flaskgroup\n"381382383@pytest.mark.parametrize("set_debug_flag", (True, False))384def test_flaskgroup_debug(runner, set_debug_flag):385    """Test FlaskGroup debug flag behavior."""386387    def create_app(info):388        app = Flask("flaskgroup")389        app.debug = True390        return app391392    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)393    def cli(**params):394        pass395396    @cli.command()397    def test():398        click.echo(str(current_app.debug))399400    result = runner.invoke(cli, ["test"])401    assert result.exit_code == 0402    assert result.output == f"{not set_debug_flag}\n"403404405def test_print_exceptions(runner):406    """Print the stacktrace if the CLI."""407408    def create_app(info):409        raise Exception("oh no")410        return Flask("flaskgroup")411412    @click.group(cls=FlaskGroup, create_app=create_app)413    def cli(**params):414        pass415416    result = runner.invoke(cli, ["--help"])417    assert result.exit_code == 0418    assert "Exception: oh no" in result.output419    assert "Traceback" in result.output420421422class TestRoutes:423    @pytest.fixture424    def invoke(self, runner):425        def create_app(info):426            app = Flask(__name__)427            app.testing = True428429            @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])430            def yyy_get_post(x, y):431                pass432433            @app.route("/zzz_post", methods=["POST"])434            def aaa_post():435                pass436437            return app438439        cli = FlaskGroup(create_app=create_app)440        return partial(runner.invoke, cli)441442    @pytest.fixture443    def invoke_no_routes(self, runner):444        def create_app(info):445            app = Flask(__name__, static_folder=None)446            app.testing = True447448            return app449450        cli = FlaskGroup(create_app=create_app)451        return partial(runner.invoke, cli)452453    def expect_order(self, order, output):454        # skip the header and match the start of each row455        for expect, line in zip(order, output.splitlines()[2:]):456            # do this instead of startswith for nicer pytest output457            assert line[: len(expect)] == expect458459    def test_simple(self, invoke):460        result = invoke(["routes"])461        assert result.exit_code == 0462        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)463464    def test_sort(self, invoke):465        default_output = invoke(["routes"]).output466        endpoint_output = invoke(["routes", "-s", "endpoint"]).output467        assert default_output == endpoint_output468        self.expect_order(469            ["static", "yyy_get_post", "aaa_post"],470            invoke(["routes", "-s", "methods"]).output,471        )472        self.expect_order(473            ["yyy_get_post", "static", "aaa_post"],474            invoke(["routes", "-s", "rule"]).output,475        )476        self.expect_order(477            ["aaa_post", "yyy_get_post", "static"],478            invoke(["routes", "-s", "match"]).output,479        )480481    def test_all_methods(self, invoke):482        output = invoke(["routes"]).output483        assert "GET, HEAD, OPTIONS, POST" not in output484        output = invoke(["routes", "--all-methods"]).output485        assert "GET, HEAD, OPTIONS, POST" in output486487    def test_no_routes(self, invoke_no_routes):488        result = invoke_no_routes(["routes"])489        assert result.exit_code == 0490        assert "No routes were registered." in result.output491492493need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")494495496@need_dotenv497def test_load_dotenv(monkeypatch):498    # can't use monkeypatch.delitem since the keys don't exist yet499    for item in ("FOO", "BAR", "SPAM"):500        monkeypatch._setitem.append((os.environ, item, notset))501502    monkeypatch.setenv("EGGS", "3")503    monkeypatch.chdir(os.path.join(test_path, "cliapp", "inner1"))504    assert load_dotenv()505    assert os.getcwd() == test_path506    # .flaskenv doesn't overwrite .env507    assert os.environ["FOO"] == "env"508    # set only in .flaskenv509    assert os.environ["BAR"] == "bar"510    # set only in .env511    assert os.environ["SPAM"] == "1"512    # set manually, files don't overwrite513    assert os.environ["EGGS"] == "3"514515    # Non existent file should not load516    assert not load_dotenv("non-existent-file")517518519@need_dotenv520def test_dotenv_path(monkeypatch):521    for item in ("FOO", "BAR", "EGGS"):522        monkeypatch._setitem.append((os.environ, item, notset))523524    cwd = os.getcwd()525    load_dotenv(os.path.join(test_path, ".flaskenv"))526    assert os.getcwd() == cwd527    assert "FOO" in os.environ528529530def test_dotenv_optional(monkeypatch):531    monkeypatch.setattr("flask.cli.dotenv", None)532    monkeypatch.chdir(test_path)533    load_dotenv()534    assert "FOO" not in os.environ535536537@need_dotenv538def test_disable_dotenv_from_env(monkeypatch, runner):539    monkeypatch.chdir(test_path)540    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")541    runner.invoke(FlaskGroup())542    assert "FOO" not in os.environ543544545def test_run_cert_path():546    # no key547    with pytest.raises(click.BadParameter):548        run_command.make_context("run", ["--cert", __file__])549550    # no cert551    with pytest.raises(click.BadParameter):552        run_command.make_context("run", ["--key", __file__])553554    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])555    assert ctx.params["cert"] == (__file__, __file__)556557558def test_run_cert_adhoc(monkeypatch):559    monkeypatch.setitem(sys.modules, "cryptography", None)560561    # cryptography not installed562    with pytest.raises(click.BadParameter):563        run_command.make_context("run", ["--cert", "adhoc"])564565    # cryptography installed566    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))567    ctx = run_command.make_context("run", ["--cert", "adhoc"])568    assert ctx.params["cert"] == "adhoc"569570    # no key with adhoc571    with pytest.raises(click.BadParameter):572        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])573574575def test_run_cert_import(monkeypatch):576    monkeypatch.setitem(sys.modules, "not_here", None)577578    # ImportError579    with pytest.raises(click.BadParameter):580        run_command.make_context("run", ["--cert", "not_here"])581582    with pytest.raises(click.BadParameter):583        run_command.make_context("run", ["--cert", "flask"])584585    # SSLContext586    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)587588    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)589    ctx = run_command.make_context("run", ["--cert", "ssl_context"])590    assert ctx.params["cert"] is ssl_context591592    # no --key with SSLContext593    with pytest.raises(click.BadParameter):594        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])595596597def test_run_cert_no_ssl(monkeypatch):598    monkeypatch.setattr("flask.cli.ssl", None)599    with pytest.raises(click.BadParameter):600        run_command.make_context("run", ["--cert", "not_here"])601602603def test_cli_blueprints(app):604    """Test blueprint commands register correctly to the application"""605    custom = Blueprint("custom", __name__, cli_group="customized")606    nested = Blueprint("nested", __name__)607    merged = Blueprint("merged", __name__, cli_group=None)608    late = Blueprint("late", __name__)609610    @custom.cli.command("custom")611    def custom_command():612        click.echo("custom_result")613614    @nested.cli.command("nested")615    def nested_command():616        click.echo("nested_result")617618    @merged.cli.command("merged")619    def merged_command():620        click.echo("merged_result")621622    @late.cli.command("late")623    def late_command():624        click.echo("late_result")625626    app.register_blueprint(custom)627    app.register_blueprint(nested)628    app.register_blueprint(merged)629    app.register_blueprint(late, cli_group="late_registration")630631    app_runner = app.test_cli_runner()632633    result = app_runner.invoke(args=["customized", "custom"])634    assert "custom_result" in result.output635636    result = app_runner.invoke(args=["nested", "nested"])637    assert "nested_result" in result.output638639    result = app_runner.invoke(args=["merged"])640    assert "merged_result" in result.output641642    result = app_runner.invoke(args=["late_registration", "late"])643    assert "late_result" in result.output644645646def test_cli_empty(app):647    """If a Blueprint's CLI group is empty, do not register it."""648    bp = Blueprint("blue", __name__, cli_group="blue")649    app.register_blueprint(bp)650651    result = app.test_cli_runner().invoke(args=["blue", "--help"])652    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"