Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

661 lines · 18.5 KiB · Python

Last changed by

Merge pull request #4066 from dannysepler/pathlib-in-testDavid Lordbefore adoption19b905e

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 dotenv21from flask.cli import find_best_app22from flask.cli import FlaskGroup23from flask.cli import get_version24from flask.cli import load_dotenv25from flask.cli import locate_app26from flask.cli import main as cli_main27from 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    script_info = ScriptInfo()5152    class Module:53        app = Flask("appname")5455    assert find_best_app(script_info, Module) == Module.app5657    class Module:58        application = Flask("appname")5960    assert find_best_app(script_info, Module) == Module.application6162    class Module:63        myapp = Flask("appname")6465    assert find_best_app(script_info, Module) == Module.myapp6667    class Module:68        @staticmethod69        def create_app():70            return Flask("appname")7172    app = find_best_app(script_info, Module)73    assert isinstance(app, Flask)74    assert app.name == "appname"7576    class Module:77        @staticmethod78        def create_app(foo):79            return Flask("appname")8081    with pytest.deprecated_call(match="Script info"):82        app = find_best_app(script_info, Module)8384    assert isinstance(app, Flask)85    assert app.name == "appname"8687    class Module:88        @staticmethod89        def create_app(foo=None, script_info=None):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 make_app():101            return Flask("appname")102103    app = find_best_app(script_info, Module)104    assert isinstance(app, Flask)105    assert app.name == "appname"106107    class Module:108        myapp = Flask("appname1")109110        @staticmethod111        def create_app():112            return Flask("appname2")113114    assert find_best_app(script_info, Module) == Module.myapp115116    class Module:117        myapp = Flask("appname1")118119        @staticmethod120        def create_app():121            return Flask("appname2")122123    assert find_best_app(script_info, Module) == Module.myapp124125    class Module:126        pass127128    pytest.raises(NoAppException, find_best_app, script_info, Module)129130    class Module:131        myapp1 = Flask("appname1")132        myapp2 = Flask("appname2")133134    pytest.raises(NoAppException, find_best_app, script_info, Module)135136    class Module:137        @staticmethod138        def create_app(foo, bar):139            return Flask("appname2")140141    pytest.raises(NoAppException, find_best_app, script_info, Module)142143    class Module:144        @staticmethod145        def create_app():146            raise TypeError("bad bad factory!")147148    pytest.raises(TypeError, find_best_app, script_info, Module)149150151@pytest.mark.parametrize(152    "value,path,result",153    (154        ("test", cwd, "test"),155        ("test.py", cwd, "test"),156        ("a/test", cwd / "a", "test"),157        ("test/__init__.py", cwd, "test"),158        ("test/__init__", cwd, "test"),159        # nested package160        (161            test_path / "cliapp" / "inner1" / "__init__",162            test_path,163            "cliapp.inner1",164        ),165        (166            test_path / "cliapp" / "inner1" / "inner2",167            test_path,168            "cliapp.inner1.inner2",169        ),170        # dotted name171        ("test.a.b", cwd, "test.a.b"),172        (test_path / "cliapp.app", test_path, "cliapp.app"),173        # not a Python file, will be caught during import174        (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),175    ),176)177def test_prepare_import(request, value, path, result):178    """Expect the correct path to be set and the correct import and app names179    to be returned.180181    :func:`prepare_exec_for_file` has a side effect where the parent directory182    of the given import is added to :data:`sys.path`. This is reset after the183    test runs.184    """185    original_path = sys.path[:]186187    def reset_path():188        sys.path[:] = original_path189190    request.addfinalizer(reset_path)191192    assert prepare_import(value) == result193    assert sys.path[0] == str(path)194195196@pytest.mark.parametrize(197    "iname,aname,result",198    (199        ("cliapp.app", None, "testapp"),200        ("cliapp.app", "testapp", "testapp"),201        ("cliapp.factory", None, "app"),202        ("cliapp.factory", "create_app", "app"),203        ("cliapp.factory", "create_app()", "app"),204        ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),205        # trailing comma space206        ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),207        # strip whitespace208        ("cliapp.factory", " create_app () ", "app"),209    ),210)211def test_locate_app(test_apps, iname, aname, result):212    info = ScriptInfo()213    assert locate_app(info, iname, aname).name == result214215216@pytest.mark.parametrize(217    "iname,aname",218    (219        ("notanapp.py", None),220        ("cliapp/app", None),221        ("cliapp.app", "notanapp"),222        # not enough arguments223        ("cliapp.factory", 'create_app2("foo")'),224        # invalid identifier225        ("cliapp.factory", "create_app("),226        # no app returned227        ("cliapp.factory", "no_app"),228        # nested import error229        ("cliapp.importerrorapp", None),230        # not a Python file231        ("cliapp.message.txt", None),232    ),233)234def test_locate_app_raises(test_apps, iname, aname):235    info = ScriptInfo()236237    with pytest.raises(NoAppException):238        locate_app(info, iname, aname)239240241def test_locate_app_suppress_raise(test_apps):242    info = ScriptInfo()243    app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)244    assert app is None245246    # only direct import error is suppressed247    with pytest.raises(NoAppException):248        locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)249250251def test_get_version(test_apps, capsys):252    from flask import __version__ as flask_version253    from werkzeug import __version__ as werkzeug_version254    from platform import python_version255256    class MockCtx:257        resilient_parsing = False258        color = None259260        def exit(self):261            return262263    ctx = MockCtx()264    get_version(ctx, None, "test")265    out, err = capsys.readouterr()266    assert f"Python {python_version()}" in out267    assert f"Flask {flask_version}" in out268    assert f"Werkzeug {werkzeug_version}" in out269270271def test_scriptinfo(test_apps, monkeypatch):272    obj = ScriptInfo(app_import_path="cliapp.app:testapp")273    app = obj.load_app()274    assert app.name == "testapp"275    assert obj.load_app() is app276277    # import app with module's absolute path278    cli_app_path = str(test_path / "cliapp" / "app.py")279280    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():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(test_path / "helloworld")302    obj = ScriptInfo()303    app = obj.load_app()304    assert app.name == "hello"305306    # import app from app.py in current directory307    monkeypatch.chdir(test_path / "cliapp")308    obj = ScriptInfo()309    app = obj.load_app()310    assert app.name == "testapp"311312313def test_with_appcontext(runner):314    @click.command()315    @with_appcontext316    def testcmd():317        click.echo(current_app.name)318319    obj = ScriptInfo(create_app=lambda: Flask("testapp"))320321    result = runner.invoke(testcmd, obj=obj)322    assert result.exit_code == 0323    assert result.output == "testapp\n"324325326def test_appgroup(runner):327    @click.group(cls=AppGroup)328    def cli():329        pass330331    @cli.command(with_appcontext=True)332    def test():333        click.echo(current_app.name)334335    @cli.group()336    def subgroup():337        pass338339    @subgroup.command(with_appcontext=True)340    def test2():341        click.echo(current_app.name)342343    obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))344345    result = runner.invoke(cli, ["test"], obj=obj)346    assert result.exit_code == 0347    assert result.output == "testappgroup\n"348349    result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)350    assert result.exit_code == 0351    assert result.output == "testappgroup\n"352353354def test_flaskgroup(runner):355    def create_app():356        return Flask("flaskgroup")357358    @click.group(cls=FlaskGroup, create_app=create_app)359    def cli(**params):360        pass361362    @cli.command()363    def test():364        click.echo(current_app.name)365366    result = runner.invoke(cli, ["test"])367    assert result.exit_code == 0368    assert result.output == "flaskgroup\n"369370371@pytest.mark.parametrize("set_debug_flag", (True, False))372def test_flaskgroup_debug(runner, set_debug_flag):373    def create_app():374        app = Flask("flaskgroup")375        app.debug = True376        return app377378    @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)379    def cli(**params):380        pass381382    @cli.command()383    def test():384        click.echo(str(current_app.debug))385386    result = runner.invoke(cli, ["test"])387    assert result.exit_code == 0388    assert result.output == f"{not set_debug_flag}\n"389390391def test_no_command_echo_loading_error():392    from flask.cli import cli393394    runner = CliRunner(mix_stderr=False)395    result = runner.invoke(cli, ["missing"])396    assert result.exit_code == 2397    assert "FLASK_APP" in result.stderr398    assert "Usage:" in result.stderr399400401def test_help_echo_loading_error():402    from flask.cli import cli403404    runner = CliRunner(mix_stderr=False)405    result = runner.invoke(cli, ["--help"])406    assert result.exit_code == 0407    assert "FLASK_APP" in result.stderr408    assert "Usage:" in result.stdout409410411def test_help_echo_exception():412    def create_app():413        raise Exception("oh no")414415    cli = FlaskGroup(create_app=create_app)416    runner = CliRunner(mix_stderr=False)417    result = runner.invoke(cli, ["--help"])418    assert result.exit_code == 0419    assert "Exception: oh no" in result.stderr420    assert "Usage:" in result.stdout421422423class TestRoutes:424    @pytest.fixture425    def invoke(self, runner):426        def create_app():427            app = Flask(__name__)428            app.testing = True429430            @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])431            def yyy_get_post(x, y):432                pass433434            @app.route("/zzz_post", methods=["POST"])435            def aaa_post():436                pass437438            return app439440        cli = FlaskGroup(create_app=create_app)441        return partial(runner.invoke, cli)442443    @pytest.fixture444    def invoke_no_routes(self, runner):445        def create_app():446            app = Flask(__name__, static_folder=None)447            app.testing = True448449            return app450451        cli = FlaskGroup(create_app=create_app)452        return partial(runner.invoke, cli)453454    def expect_order(self, order, output):455        # skip the header and match the start of each row456        for expect, line in zip(order, output.splitlines()[2:]):457            # do this instead of startswith for nicer pytest output458            assert line[: len(expect)] == expect459460    def test_simple(self, invoke):461        result = invoke(["routes"])462        assert result.exit_code == 0463        self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)464465    def test_sort(self, invoke):466        default_output = invoke(["routes"]).output467        endpoint_output = invoke(["routes", "-s", "endpoint"]).output468        assert default_output == endpoint_output469        self.expect_order(470            ["static", "yyy_get_post", "aaa_post"],471            invoke(["routes", "-s", "methods"]).output,472        )473        self.expect_order(474            ["yyy_get_post", "static", "aaa_post"],475            invoke(["routes", "-s", "rule"]).output,476        )477        self.expect_order(478            ["aaa_post", "yyy_get_post", "static"],479            invoke(["routes", "-s", "match"]).output,480        )481482    def test_all_methods(self, invoke):483        output = invoke(["routes"]).output484        assert "GET, HEAD, OPTIONS, POST" not in output485        output = invoke(["routes", "--all-methods"]).output486        assert "GET, HEAD, OPTIONS, POST" in output487488    def test_no_routes(self, invoke_no_routes):489        result = invoke_no_routes(["routes"])490        assert result.exit_code == 0491        assert "No routes were registered." in result.output492493494need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")495496497@need_dotenv498def test_load_dotenv(monkeypatch):499    # can't use monkeypatch.delitem since the keys don't exist yet500    for item in ("FOO", "BAR", "SPAM", "HAM"):501        monkeypatch._setitem.append((os.environ, item, notset))502503    monkeypatch.setenv("EGGS", "3")504    monkeypatch.chdir(test_path)505    assert load_dotenv()506    assert Path.cwd() == test_path507    # .flaskenv doesn't overwrite .env508    assert os.environ["FOO"] == "env"509    # set only in .flaskenv510    assert os.environ["BAR"] == "bar"511    # set only in .env512    assert os.environ["SPAM"] == "1"513    # set manually, files don't overwrite514    assert os.environ["EGGS"] == "3"515    # test env file encoding516    assert os.environ["HAM"] == "火腿"517    # Non existent file should not load518    assert not load_dotenv("non-existent-file")519520521@need_dotenv522def test_dotenv_path(monkeypatch):523    for item in ("FOO", "BAR", "EGGS"):524        monkeypatch._setitem.append((os.environ, item, notset))525526    load_dotenv(test_path / ".flaskenv")527    assert Path.cwd() == cwd528    assert "FOO" in os.environ529530531def test_dotenv_optional(monkeypatch):532    monkeypatch.setattr("flask.cli.dotenv", None)533    monkeypatch.chdir(test_path)534    load_dotenv()535    assert "FOO" not in os.environ536537538@need_dotenv539def test_disable_dotenv_from_env(monkeypatch, runner):540    monkeypatch.chdir(test_path)541    monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")542    runner.invoke(FlaskGroup())543    assert "FOO" not in os.environ544545546def test_run_cert_path():547    # no key548    with pytest.raises(click.BadParameter):549        run_command.make_context("run", ["--cert", __file__])550551    # no cert552    with pytest.raises(click.BadParameter):553        run_command.make_context("run", ["--key", __file__])554555    ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])556    assert ctx.params["cert"] == (__file__, __file__)557558559def test_run_cert_adhoc(monkeypatch):560    monkeypatch.setitem(sys.modules, "cryptography", None)561562    # cryptography not installed563    with pytest.raises(click.BadParameter):564        run_command.make_context("run", ["--cert", "adhoc"])565566    # cryptography installed567    monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))568    ctx = run_command.make_context("run", ["--cert", "adhoc"])569    assert ctx.params["cert"] == "adhoc"570571    # no key with adhoc572    with pytest.raises(click.BadParameter):573        run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])574575576def test_run_cert_import(monkeypatch):577    monkeypatch.setitem(sys.modules, "not_here", None)578579    # ImportError580    with pytest.raises(click.BadParameter):581        run_command.make_context("run", ["--cert", "not_here"])582583    with pytest.raises(click.BadParameter):584        run_command.make_context("run", ["--cert", "flask"])585586    # SSLContext587    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)588589    monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)590    ctx = run_command.make_context("run", ["--cert", "ssl_context"])591    assert ctx.params["cert"] is ssl_context592593    # no --key with SSLContext594    with pytest.raises(click.BadParameter):595        run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])596597598def test_run_cert_no_ssl(monkeypatch):599    monkeypatch.setattr("flask.cli.ssl", None)600    with pytest.raises(click.BadParameter):601        run_command.make_context("run", ["--cert", "not_here"])602603604def test_cli_blueprints(app):605    """Test blueprint commands register correctly to the application"""606    custom = Blueprint("custom", __name__, cli_group="customized")607    nested = Blueprint("nested", __name__)608    merged = Blueprint("merged", __name__, cli_group=None)609    late = Blueprint("late", __name__)610611    @custom.cli.command("custom")612    def custom_command():613        click.echo("custom_result")614615    @nested.cli.command("nested")616    def nested_command():617        click.echo("nested_result")618619    @merged.cli.command("merged")620    def merged_command():621        click.echo("merged_result")622623    @late.cli.command("late")624    def late_command():625        click.echo("late_result")626627    app.register_blueprint(custom)628    app.register_blueprint(nested)629    app.register_blueprint(merged)630    app.register_blueprint(late, cli_group="late_registration")631632    app_runner = app.test_cli_runner()633634    result = app_runner.invoke(args=["customized", "custom"])635    assert "custom_result" in result.output636637    result = app_runner.invoke(args=["nested", "nested"])638    assert "nested_result" in result.output639640    result = app_runner.invoke(args=["merged"])641    assert "merged_result" in result.output642643    result = app_runner.invoke(args=["late_registration", "late"])644    assert "late_result" in result.output645646647def test_cli_empty(app):648    """If a Blueprint's CLI group is empty, do not register it."""649    bp = Blueprint("blue", __name__, cli_group="blue")650    app.register_blueprint(bp)651652    result = app.test_cli_runner().invoke(args=["blue", "--help"])653    assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"654655656def test_click_7_deprecated():657    with patch("flask.cli.cli"):658        if int(click.__version__[0]) < 8:659            pytest.deprecated_call(cli_main, match=".* Click 7 is deprecated")660        else:661            cli_main()