Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

662 lines · 18.6 KiB · Python

Last changed by

Merge pull request #3932 from greyli/set-encodingDavid Lordbefore adoption3316604

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    script_info = ScriptInfo()4849    class Module:50        app = Flask("appname")5152    assert find_best_app(script_info, Module) == Module.app5354    class Module:55        application = Flask("appname")5657    assert find_best_app(script_info, Module) == Module.application5859    class Module:60        myapp = Flask("appname")6162    assert find_best_app(script_info, Module) == Module.myapp6364    class Module:65        @staticmethod66        def create_app():67            return Flask("appname")6869    app = find_best_app(script_info, Module)70    assert isinstance(app, Flask)71    assert app.name == "appname"7273    class Module:74        @staticmethod75        def create_app(foo):76            return Flask("appname")7778    with pytest.deprecated_call(match="Script info"):79        app = find_best_app(script_info, Module)8081    assert isinstance(app, Flask)82    assert app.name == "appname"8384    class Module:85        @staticmethod86        def create_app(foo=None, script_info=None):87            return Flask("appname")8889    with pytest.deprecated_call(match="script_info"):90        app = find_best_app(script_info, Module)9192    assert isinstance(app, Flask)93    assert app.name == "appname"9495    class Module:96        @staticmethod97        def make_app():98            return Flask("appname")99100    app = find_best_app(script_info, Module)101    assert isinstance(app, Flask)102    assert app.name == "appname"103104    class Module:105        myapp = Flask("appname1")106107        @staticmethod108        def create_app():109            return Flask("appname2")110111    assert find_best_app(script_info, Module) == Module.myapp112113    class Module:114        myapp = Flask("appname1")115116        @staticmethod117        def create_app():118            return Flask("appname2")119120    assert find_best_app(script_info, Module) == Module.myapp121122    class Module:123        pass124125    pytest.raises(NoAppException, find_best_app, script_info, Module)126127    class Module:128        myapp1 = Flask("appname1")129        myapp2 = Flask("appname2")130131    pytest.raises(NoAppException, find_best_app, script_info, Module)132133    class Module:134        @staticmethod135        def create_app(foo, bar):136            return Flask("appname2")137138    pytest.raises(NoAppException, find_best_app, script_info, Module)139140    class Module:141        @staticmethod142        def create_app():143            raise TypeError("bad bad factory!")144145    pytest.raises(TypeError, find_best_app, script_info, Module)146147148@pytest.mark.parametrize(149    "value,path,result",150    (151        ("test", cwd, "test"),152        ("test.py", cwd, "test"),153        ("a/test", os.path.join(cwd, "a"), "test"),154        ("test/__init__.py", cwd, "test"),155        ("test/__init__", cwd, "test"),156        # nested package157        (158            os.path.join(test_path, "cliapp", "inner1", "__init__"),159            test_path,160            "cliapp.inner1",161        ),162        (163            os.path.join(test_path, "cliapp", "inner1", "inner2"),164            test_path,165            "cliapp.inner1.inner2",166        ),167        # dotted name168        ("test.a.b", cwd, "test.a.b"),169        (os.path.join(test_path, "cliapp.app"), test_path, "cliapp.app"),170        # not a Python file, will be caught during import171        (172            os.path.join(test_path, "cliapp", "message.txt"),173            test_path,174            "cliapp.message.txt",175        ),176    ),177)178def test_prepare_import(request, value, path, result):179    """Expect the correct path to be set and the correct import and app names180    to be returned.181182    :func:`prepare_exec_for_file` has a side effect where the parent directory183    of the given import is added to :data:`sys.path`. This is reset after the184    test runs.185    """186    original_path = sys.path[:]187188    def reset_path():189        sys.path[:] = original_path190191    request.addfinalizer(reset_path)192193    assert prepare_import(value) == result194    assert sys.path[0] == path195196197@pytest.mark.parametrize(198    "iname,aname,result",199    (200        ("cliapp.app", None, "testapp"),201        ("cliapp.app", "testapp", "testapp"),202        ("cliapp.factory", None, "app"),203        ("cliapp.factory", "create_app", "app"),204        ("cliapp.factory", "create_app()", "app"),205        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),206        # trailing comma space207        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),208        # strip whitespace209        ("cliapp.factory", " create_app () ", "app"),210    ),211)212def test_locate_app(test_apps, iname, aname, result):213    info = ScriptInfo()214    assert locate_app(info, iname, aname).name == result215216217@pytest.mark.parametrize(218    "iname,aname",219    (220        ("notanapp.py", None),221        ("cliapp/app", None),222        ("cliapp.app", "notanapp"),223        # not enough arguments224        ("cliapp.factory", 'create_app2("foo")'),225        # invalid identifier226        ("cliapp.factory", "create_app("),227        # no app returned228        ("cliapp.factory", "no_app"),229        # nested import error230        ("cliapp.importerrorapp", None),231        # not a Python file232        ("cliapp.message.txt", None),233    ),234)235def test_locate_app_raises(test_apps, iname, aname):236    info = ScriptInfo()237238    with pytest.raises(NoAppException):239        locate_app(info, iname, aname)240241242def test_locate_app_suppress_raise(test_apps):243    info = ScriptInfo()244    app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)245    assert app is None246247    # only direct import error is suppressed248    with pytest.raises(NoAppException):249        locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)250251252def test_get_version(test_apps, capsys):253    from flask import __version__ as flask_version254    from werkzeug import __version__ as werkzeug_version255    from platform import python_version256257    class MockCtx:258        resilient_parsing = False259        color = None260261        def exit(self):262            return263264    ctx = MockCtx()265    get_version(ctx, None, "test")266    out, err = capsys.readouterr()267    assert f"Python {python_version()}" in out268    assert f"Flask {flask_version}" in out269    assert f"Werkzeug {werkzeug_version}" in out270271272def test_scriptinfo(test_apps, monkeypatch):273    obj = ScriptInfo(app_import_path="cliapp.app:testapp")274    app = obj.load_app()275    assert app.name == "testapp"276    assert obj.load_app() is app277278    # import app with module's absolute path279    cli_app_path = os.path.abspath(280        os.path.join(os.path.dirname(__file__), "test_apps", "cliapp", "app.py")281    )282    obj = ScriptInfo(app_import_path=cli_app_path)283    app = obj.load_app()284    assert app.name == "testapp"285    assert obj.load_app() is app286    obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")287    app = obj.load_app()288    assert app.name == "testapp"289    assert obj.load_app() is app290291    def create_app():292        return Flask("createapp")293294    obj = ScriptInfo(create_app=create_app)295    app = obj.load_app()296    assert app.name == "createapp"297    assert obj.load_app() is app298299    obj = ScriptInfo()300    pytest.raises(NoAppException, obj.load_app)301302    # import app from wsgi.py in current directory303    monkeypatch.chdir(304        os.path.abspath(305            os.path.join(os.path.dirname(__file__), "test_apps", "helloworld")306        )307    )308    obj = ScriptInfo()309    app = obj.load_app()310    assert app.name == "hello"311312    # import app from app.py in current directory313    monkeypatch.chdir(314        os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps", "cliapp"))315    )316    obj = ScriptInfo()317    app = obj.load_app()318    assert app.name == "testapp"319320321def test_with_appcontext(runner):322    @click.command()323    @with_appcontext324    def testcmd():325        click.echo(current_app.name)326327    obj = ScriptInfo(create_app=lambda: 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    @click.group(cls=AppGroup)336    def cli():337        pass338339    @cli.command(with_appcontext=True)340    def test():341        click.echo(current_app.name)342343    @cli.group()344    def subgroup():345        pass346347    @subgroup.command(with_appcontext=True)348    def test2():349        click.echo(current_app.name)350351    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))352353    result = runner.invoke(cli, ["test"], obj=obj)354    assert result.exit_code == 0355    assert result.output == "testappgroup\n"356357    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)358    assert result.exit_code == 0359    assert result.output == "testappgroup\n"360361362def test_flaskgroup(runner):363    def create_app():364        return Flask("flaskgroup")365366    @click.group(cls=FlaskGroup, create_app=create_app)367    def cli(**params):368        pass369370    @cli.command()371    def test():372        click.echo(current_app.name)373374    result = runner.invoke(cli, ["test"])375    assert result.exit_code == 0376    assert result.output == "flaskgroup\n"377378379@pytest.mark.parametrize("set_debug_flag", (True, False))380def test_flaskgroup_debug(runner, set_debug_flag):381    def create_app():382        app = Flask("flaskgroup")383        app.debug = True384        return app385386    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)387    def cli(**params):388        pass389390    @cli.command()391    def test():392        click.echo(str(current_app.debug))393394    result = runner.invoke(cli, ["test"])395    assert result.exit_code == 0396    assert result.output == f"{not set_debug_flag}\n"397398399def test_no_command_echo_loading_error():400    from flask.cli import cli401402    runner = CliRunner(mix_stderr=False)403    result = runner.invoke(cli, ["missing"])404    assert result.exit_code == 2405    assert "FLASK_APP" in result.stderr406    assert "Usage:" in result.stderr407408409def test_help_echo_loading_error():410    from flask.cli import cli411412    runner = CliRunner(mix_stderr=False)413    result = runner.invoke(cli, ["--help"])414    assert result.exit_code == 0415    assert "FLASK_APP" in result.stderr416    assert "Usage:" in result.stdout417418419def test_help_echo_exception():420    def create_app():421        raise Exception("oh no")422423    cli = FlaskGroup(create_app=create_app)424    runner = CliRunner(mix_stderr=False)425    result = runner.invoke(cli, ["--help"])426    assert result.exit_code == 0427    assert "Exception: oh no" in result.stderr428    assert "Usage:" in result.stdout429430431class TestRoutes:432    @pytest.fixture433    def invoke(self, runner):434        def create_app():435            app = Flask(__name__)436            app.testing = True437438            @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])439            def yyy_get_post(x, y):440                pass441442            @app.route("/zzz_post", methods=["POST"])443            def aaa_post():444                pass445446            return app447448        cli = FlaskGroup(create_app=create_app)449        return partial(runner.invoke, cli)450451    @pytest.fixture452    def invoke_no_routes(self, runner):453        def create_app():454            app = Flask(__name__, static_folder=None)455            app.testing = True456457            return app458459        cli = FlaskGroup(create_app=create_app)460        return partial(runner.invoke, cli)461462    def expect_order(self, order, output):463        # skip the header and match the start of each row464        for expect, line in zip(order, output.splitlines()[2:]):465            # do this instead of startswith for nicer pytest output466            assert line[: len(expect)] == expect467468    def test_simple(self, invoke):469        result = invoke(["routes"])470        assert result.exit_code == 0471        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)472473    def test_sort(self, invoke):474        default_output = invoke(["routes"]).output475        endpoint_output = invoke(["routes", "-s", "endpoint"]).output476        assert default_output == endpoint_output477        self.expect_order(478            ["static", "yyy_get_post", "aaa_post"],479            invoke(["routes", "-s", "methods"]).output,480        )481        self.expect_order(482            ["yyy_get_post", "static", "aaa_post"],483            invoke(["routes", "-s", "rule"]).output,484        )485        self.expect_order(486            ["aaa_post", "yyy_get_post", "static"],487            invoke(["routes", "-s", "match"]).output,488        )489490    def test_all_methods(self, invoke):491        output = invoke(["routes"]).output492        assert "GET, HEAD, OPTIONS, POST" not in output493        output = invoke(["routes", "--all-methods"]).output494        assert "GET, HEAD, OPTIONS, POST" in output495496    def test_no_routes(self, invoke_no_routes):497        result = invoke_no_routes(["routes"])498        assert result.exit_code == 0499        assert "No routes were registered." in result.output500501502need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")503504505@need_dotenv506def test_load_dotenv(monkeypatch):507    # can't use monkeypatch.delitem since the keys don't exist yet508    for item in ("FOO", "BAR", "SPAM", "HAM"):509        monkeypatch._setitem.append((os.environ, item, notset))510511    monkeypatch.setenv("EGGS", "3")512    monkeypatch.chdir(test_path)513    assert load_dotenv()514    assert os.getcwd() == test_path515    # .flaskenv doesn't overwrite .env516    assert os.environ["FOO"] == "env"517    # set only in .flaskenv518    assert os.environ["BAR"] == "bar"519    # set only in .env520    assert os.environ["SPAM"] == "1"521    # set manually, files don't overwrite522    assert os.environ["EGGS"] == "3"523    # test env file encoding524    assert os.environ["HAM"] == "火腿"525    # Non existent file should not load526    assert not load_dotenv("non-existent-file")527528529@need_dotenv530def test_dotenv_path(monkeypatch):531    for item in ("FOO", "BAR", "EGGS"):532        monkeypatch._setitem.append((os.environ, item, notset))533534    cwd = os.getcwd()535    load_dotenv(os.path.join(test_path, ".flaskenv"))536    assert os.getcwd() == cwd537    assert "FOO" in os.environ538539540def test_dotenv_optional(monkeypatch):541    monkeypatch.setattr("flask.cli.dotenv", None)542    monkeypatch.chdir(test_path)543    load_dotenv()544    assert "FOO" not in os.environ545546547@need_dotenv548def test_disable_dotenv_from_env(monkeypatch, runner):549    monkeypatch.chdir(test_path)550    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")551    runner.invoke(FlaskGroup())552    assert "FOO" not in os.environ553554555def test_run_cert_path():556    # no key557    with pytest.raises(click.BadParameter):558        run_command.make_context("run", ["--cert", __file__])559560    # no cert561    with pytest.raises(click.BadParameter):562        run_command.make_context("run", ["--key", __file__])563564    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])565    assert ctx.params["cert"] == (__file__, __file__)566567568def test_run_cert_adhoc(monkeypatch):569    monkeypatch.setitem(sys.modules, "cryptography", None)570571    # cryptography not installed572    with pytest.raises(click.BadParameter):573        run_command.make_context("run", ["--cert", "adhoc"])574575    # cryptography installed576    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))577    ctx = run_command.make_context("run", ["--cert", "adhoc"])578    assert ctx.params["cert"] == "adhoc"579580    # no key with adhoc581    with pytest.raises(click.BadParameter):582        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])583584585def test_run_cert_import(monkeypatch):586    monkeypatch.setitem(sys.modules, "not_here", None)587588    # ImportError589    with pytest.raises(click.BadParameter):590        run_command.make_context("run", ["--cert", "not_here"])591592    with pytest.raises(click.BadParameter):593        run_command.make_context("run", ["--cert", "flask"])594595    # SSLContext596    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)597598    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)599    ctx = run_command.make_context("run", ["--cert", "ssl_context"])600    assert ctx.params["cert"] is ssl_context601602    # no --key with SSLContext603    with pytest.raises(click.BadParameter):604        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])605606607def test_run_cert_no_ssl(monkeypatch):608    monkeypatch.setattr("flask.cli.ssl", None)609    with pytest.raises(click.BadParameter):610        run_command.make_context("run", ["--cert", "not_here"])611612613def test_cli_blueprints(app):614    """Test blueprint commands register correctly to the application"""615    custom = Blueprint("custom", __name__, cli_group="customized")616    nested = Blueprint("nested", __name__)617    merged = Blueprint("merged", __name__, cli_group=None)618    late = Blueprint("late", __name__)619620    @custom.cli.command("custom")621    def custom_command():622        click.echo("custom_result")623624    @nested.cli.command("nested")625    def nested_command():626        click.echo("nested_result")627628    @merged.cli.command("merged")629    def merged_command():630        click.echo("merged_result")631632    @late.cli.command("late")633    def late_command():634        click.echo("late_result")635636    app.register_blueprint(custom)637    app.register_blueprint(nested)638    app.register_blueprint(merged)639    app.register_blueprint(late, cli_group="late_registration")640641    app_runner = app.test_cli_runner()642643    result = app_runner.invoke(args=["customized", "custom"])644    assert "custom_result" in result.output645646    result = app_runner.invoke(args=["nested", "nested"])647    assert "nested_result" in result.output648649    result = app_runner.invoke(args=["merged"])650    assert "merged_result" in result.output651652    result = app_runner.invoke(args=["late_registration", "late"])653    assert "late_result" in result.output654655656def test_cli_empty(app):657    """If a Blueprint's CLI group is empty, do not register it."""658    bp = Blueprint("blue", __name__, cli_group="blue")659    app.register_blueprint(bp)660661    result = app.test_cli_runner().invoke(args=["blue", "--help"])662    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"