test_cli.py
This file
Path
tests/test_cli.py
683 lines · 19.4 KiB · Python
Last changed by
Merge pull request #5063 from pallets/cli-routes-domainDavid Lordbefore adoption6931b25
History of this fileTake 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 Path910import click11import pytest12from _pytest.monkeypatch import notset13from click.testing import CliRunner1415from flask import Blueprint16from flask import current_app17from flask import Flask18from flask.cli import AppGroup19from 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 = Path.cwd()31test_path = (Path(__file__) / ".." / "test_apps").resolve()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 class Module:48 app = Flask("appname")4950 assert find_best_app(Module) == Module.app5152 class Module:53 application = Flask("appname")5455 assert find_best_app(Module) == Module.application5657 class Module:58 myapp = Flask("appname")5960 assert find_best_app(Module) == Module.myapp6162 class Module:63 @staticmethod64 def create_app():65 return Flask("appname")6667 app = find_best_app(Module)68 assert isinstance(app, Flask)69 assert app.name == "appname"7071 class Module:72 @staticmethod73 def create_app(**kwargs):74 return Flask("appname")7576 app = find_best_app(Module)77 assert isinstance(app, Flask)78 assert app.name == "appname"7980 class Module:81 @staticmethod82 def make_app():83 return Flask("appname")8485 app = find_best_app(Module)86 assert isinstance(app, Flask)87 assert app.name == "appname"8889 class Module:90 myapp = Flask("appname1")9192 @staticmethod93 def create_app():94 return Flask("appname2")9596 assert find_best_app(Module) == Module.myapp9798 class Module:99 myapp = Flask("appname1")100101 @staticmethod102 def create_app():103 return Flask("appname2")104105 assert find_best_app(Module) == Module.myapp106107 class Module:108 pass109110 pytest.raises(NoAppException, find_best_app, Module)111112 class Module:113 myapp1 = Flask("appname1")114 myapp2 = Flask("appname2")115116 pytest.raises(NoAppException, find_best_app, Module)117118 class Module:119 @staticmethod120 def create_app(foo, bar):121 return Flask("appname2")122123 pytest.raises(NoAppException, find_best_app, Module)124125 class Module:126 @staticmethod127 def create_app():128 raise TypeError("bad bad factory!")129130 pytest.raises(TypeError, find_best_app, Module)131132133@pytest.mark.parametrize(134 "value,path,result",135 (136 ("test", cwd, "test"),137 ("test.py", cwd, "test"),138 ("a/test", cwd / "a", "test"),139 ("test/__init__.py", cwd, "test"),140 ("test/__init__", cwd, "test"),141 # nested package142 (143 test_path / "cliapp" / "inner1" / "__init__",144 test_path,145 "cliapp.inner1",146 ),147 (148 test_path / "cliapp" / "inner1" / "inner2",149 test_path,150 "cliapp.inner1.inner2",151 ),152 # dotted name153 ("test.a.b", cwd, "test.a.b"),154 (test_path / "cliapp.app", test_path, "cliapp.app"),155 # not a Python file, will be caught during import156 (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),157 ),158)159def test_prepare_import(request, value, path, result):160 """Expect the correct path to be set and the correct import and app names161 to be returned.162163 :func:`prepare_exec_for_file` has a side effect where the parent directory164 of the given import is added to :data:`sys.path`. This is reset after the165 test runs.166 """167 original_path = sys.path[:]168169 def reset_path():170 sys.path[:] = original_path171172 request.addfinalizer(reset_path)173174 assert prepare_import(value) == result175 assert sys.path[0] == str(path)176177178@pytest.mark.parametrize(179 "iname,aname,result",180 (181 ("cliapp.app", None, "testapp"),182 ("cliapp.app", "testapp", "testapp"),183 ("cliapp.factory", None, "app"),184 ("cliapp.factory", "create_app", "app"),185 ("cliapp.factory", "create_app()", "app"),186 ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),187 # trailing comma space188 ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),189 # strip whitespace190 ("cliapp.factory", " create_app () ", "app"),191 ),192)193def test_locate_app(test_apps, iname, aname, result):194 assert locate_app(iname, aname).name == result195196197@pytest.mark.parametrize(198 "iname,aname",199 (200 ("notanapp.py", None),201 ("cliapp/app", None),202 ("cliapp.app", "notanapp"),203 # not enough arguments204 ("cliapp.factory", 'create_app2("foo")'),205 # invalid identifier206 ("cliapp.factory", "create_app("),207 # no app returned208 ("cliapp.factory", "no_app"),209 # nested import error210 ("cliapp.importerrorapp", None),211 # not a Python file212 ("cliapp.message.txt", None),213 ),214)215def test_locate_app_raises(test_apps, iname, aname):216 with pytest.raises(NoAppException):217 locate_app(iname, aname)218219220def test_locate_app_suppress_raise(test_apps):221 app = locate_app("notanapp.py", None, raise_if_not_found=False)222 assert app is None223224 # only direct import error is suppressed225 with pytest.raises(NoAppException):226 locate_app("cliapp.importerrorapp", None, raise_if_not_found=False)227228229def test_get_version(test_apps, capsys):230 from flask import __version__ as flask_version231 from werkzeug import __version__ as werkzeug_version232 from platform import python_version233234 class MockCtx:235 resilient_parsing = False236 color = None237238 def exit(self):239 return240241 ctx = MockCtx()242 get_version(ctx, None, "test")243 out, err = capsys.readouterr()244 assert f"Python {python_version()}" in out245 assert f"Flask {flask_version}" in out246 assert f"Werkzeug {werkzeug_version}" in out247248249def test_scriptinfo(test_apps, monkeypatch):250 obj = ScriptInfo(app_import_path="cliapp.app:testapp")251 app = obj.load_app()252 assert app.name == "testapp"253 assert obj.load_app() is app254255 # import app with module's absolute path256 cli_app_path = str(test_path / "cliapp" / "app.py")257258 obj = ScriptInfo(app_import_path=cli_app_path)259 app = obj.load_app()260 assert app.name == "testapp"261 assert obj.load_app() is app262 obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")263 app = obj.load_app()264 assert app.name == "testapp"265 assert obj.load_app() is app266267 def create_app():268 return Flask("createapp")269270 obj = ScriptInfo(create_app=create_app)271 app = obj.load_app()272 assert app.name == "createapp"273 assert obj.load_app() is app274275 obj = ScriptInfo()276 pytest.raises(NoAppException, obj.load_app)277278 # import app from wsgi.py in current directory279 monkeypatch.chdir(test_path / "helloworld")280 obj = ScriptInfo()281 app = obj.load_app()282 assert app.name == "hello"283284 # import app from app.py in current directory285 monkeypatch.chdir(test_path / "cliapp")286 obj = ScriptInfo()287 app = obj.load_app()288 assert app.name == "testapp"289290291def test_app_cli_has_app_context(app, runner):292 def _param_cb(ctx, param, value):293 # current_app should be available in parameter callbacks294 return bool(current_app)295296 @app.cli.command()297 @click.argument("value", callback=_param_cb)298 def check(value):299 app = click.get_current_context().obj.load_app()300 # the loaded app should be the same as current_app301 same_app = current_app._get_current_object() is app302 return same_app, value303304 cli = FlaskGroup(create_app=lambda: app)305 result = runner.invoke(cli, ["check", "x"], standalone_mode=False)306 assert result.return_value == (True, True)307308309def test_with_appcontext(runner):310 @click.command()311 @with_appcontext312 def testcmd():313 click.echo(current_app.name)314315 obj = ScriptInfo(create_app=lambda: Flask("testapp"))316317 result = runner.invoke(testcmd, obj=obj)318 assert result.exit_code == 0319 assert result.output == "testapp\n"320321322def test_appgroup_app_context(runner):323 @click.group(cls=AppGroup)324 def cli():325 pass326327 @cli.command()328 def test():329 click.echo(current_app.name)330331 @cli.group()332 def subgroup():333 pass334335 @subgroup.command()336 def test2():337 click.echo(current_app.name)338339 obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))340341 result = runner.invoke(cli, ["test"], obj=obj)342 assert result.exit_code == 0343 assert result.output == "testappgroup\n"344345 result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)346 assert result.exit_code == 0347 assert result.output == "testappgroup\n"348349350def test_flaskgroup_app_context(runner):351 def create_app():352 return Flask("flaskgroup")353354 @click.group(cls=FlaskGroup, create_app=create_app)355 def cli(**params):356 pass357358 @cli.command()359 def test():360 click.echo(current_app.name)361362 result = runner.invoke(cli, ["test"])363 assert result.exit_code == 0364 assert result.output == "flaskgroup\n"365366367@pytest.mark.parametrize("set_debug_flag", (True, False))368def test_flaskgroup_debug(runner, set_debug_flag):369 def create_app():370 app = Flask("flaskgroup")371 app.debug = True372 return app373374 @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)375 def cli(**params):376 pass377378 @cli.command()379 def test():380 click.echo(str(current_app.debug))381382 result = runner.invoke(cli, ["test"])383 assert result.exit_code == 0384 assert result.output == f"{not set_debug_flag}\n"385386387def test_flaskgroup_nested(app, runner):388 cli = click.Group("cli")389 flask_group = FlaskGroup(name="flask", create_app=lambda: app)390 cli.add_command(flask_group)391392 @flask_group.command()393 def show():394 click.echo(current_app.name)395396 result = runner.invoke(cli, ["flask", "show"])397 assert result.output == "flask_test\n"398399400def test_no_command_echo_loading_error():401 from flask.cli import cli402403 runner = CliRunner(mix_stderr=False)404 result = runner.invoke(cli, ["missing"])405 assert result.exit_code == 2406 assert "FLASK_APP" in result.stderr407 assert "Usage:" in result.stderr408409410def test_help_echo_loading_error():411 from flask.cli import cli412413 runner = CliRunner(mix_stderr=False)414 result = runner.invoke(cli, ["--help"])415 assert result.exit_code == 0416 assert "FLASK_APP" in result.stderr417 assert "Usage:" in result.stdout418419420def test_help_echo_exception():421 def create_app():422 raise Exception("oh no")423424 cli = FlaskGroup(create_app=create_app)425 runner = CliRunner(mix_stderr=False)426 result = runner.invoke(cli, ["--help"])427 assert result.exit_code == 0428 assert "Exception: oh no" in result.stderr429 assert "Usage:" in result.stdout430431432class TestRoutes:433 @pytest.fixture434 def app(self):435 app = Flask(__name__)436 app.add_url_rule(437 "/get_post/<int:x>/<int:y>",438 methods=["GET", "POST"],439 endpoint="yyy_get_post",440 )441 app.add_url_rule("/zzz_post", methods=["POST"], endpoint="aaa_post")442 return app443444 @pytest.fixture445 def invoke(self, app, runner):446 cli = FlaskGroup(create_app=lambda: app)447 return partial(runner.invoke, cli)448449 def expect_order(self, order, output):450 # skip the header and match the start of each row451 for expect, line in zip(order, output.splitlines()[2:]):452 # do this instead of startswith for nicer pytest output453 assert line[: len(expect)] == expect454455 def test_simple(self, invoke):456 result = invoke(["routes"])457 assert result.exit_code == 0458 self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)459460 def test_sort(self, app, invoke):461 default_output = invoke(["routes"]).output462 endpoint_output = invoke(["routes", "-s", "endpoint"]).output463 assert default_output == endpoint_output464 self.expect_order(465 ["static", "yyy_get_post", "aaa_post"],466 invoke(["routes", "-s", "methods"]).output,467 )468 self.expect_order(469 ["yyy_get_post", "static", "aaa_post"],470 invoke(["routes", "-s", "rule"]).output,471 )472 match_order = [r.endpoint for r in app.url_map.iter_rules()]473 self.expect_order(match_order, invoke(["routes", "-s", "match"]).output)474475 def test_all_methods(self, invoke):476 output = invoke(["routes"]).output477 assert "GET, HEAD, OPTIONS, POST" not in output478 output = invoke(["routes", "--all-methods"]).output479 assert "GET, HEAD, OPTIONS, POST" in output480481 def test_no_routes(self, runner):482 app = Flask(__name__, static_folder=None)483 cli = FlaskGroup(create_app=lambda: app)484 result = runner.invoke(cli, ["routes"])485 assert result.exit_code == 0486 assert "No routes were registered." in result.output487488 def test_subdomain(self, runner):489 app = Flask(__name__, static_folder=None)490 app.add_url_rule("/a", subdomain="a", endpoint="a")491 app.add_url_rule("/b", subdomain="b", endpoint="b")492 cli = FlaskGroup(create_app=lambda: app)493 result = runner.invoke(cli, ["routes"])494 assert result.exit_code == 0495 assert "Subdomain" in result.output496497 def test_host(self, runner):498 app = Flask(__name__, static_folder=None, host_matching=True)499 app.add_url_rule("/a", host="a", endpoint="a")500 app.add_url_rule("/b", host="b", endpoint="b")501 cli = FlaskGroup(create_app=lambda: app)502 result = runner.invoke(cli, ["routes"])503 assert result.exit_code == 0504 assert "Host" in result.output505506507def dotenv_not_available():508 try:509 import dotenv # noqa: F401510 except ImportError:511 return True512513 return False514515516need_dotenv = pytest.mark.skipif(517 dotenv_not_available(), reason="dotenv is not installed"518)519520521@need_dotenv522def test_load_dotenv(monkeypatch):523 # can't use monkeypatch.delitem since the keys don't exist yet524 for item in ("FOO", "BAR", "SPAM", "HAM"):525 monkeypatch._setitem.append((os.environ, item, notset))526527 monkeypatch.setenv("EGGS", "3")528 monkeypatch.chdir(test_path)529 assert load_dotenv()530 assert Path.cwd() == test_path531 # .flaskenv doesn't overwrite .env532 assert os.environ["FOO"] == "env"533 # set only in .flaskenv534 assert os.environ["BAR"] == "bar"535 # set only in .env536 assert os.environ["SPAM"] == "1"537 # set manually, files don't overwrite538 assert os.environ["EGGS"] == "3"539 # test env file encoding540 assert os.environ["HAM"] == "火腿"541 # Non existent file should not load542 assert not load_dotenv("non-existent-file")543544545@need_dotenv546def test_dotenv_path(monkeypatch):547 for item in ("FOO", "BAR", "EGGS"):548 monkeypatch._setitem.append((os.environ, item, notset))549550 load_dotenv(test_path / ".flaskenv")551 assert Path.cwd() == cwd552 assert "FOO" in os.environ553554555def test_dotenv_optional(monkeypatch):556 monkeypatch.setitem(sys.modules, "dotenv", None)557 monkeypatch.chdir(test_path)558 load_dotenv()559 assert "FOO" not in os.environ560561562@need_dotenv563def test_disable_dotenv_from_env(monkeypatch, runner):564 monkeypatch.chdir(test_path)565 monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")566 runner.invoke(FlaskGroup())567 assert "FOO" not in os.environ568569570def test_run_cert_path():571 # no key572 with pytest.raises(click.BadParameter):573 run_command.make_context("run", ["--cert", __file__])574575 # no cert576 with pytest.raises(click.BadParameter):577 run_command.make_context("run", ["--key", __file__])578579 # cert specified first580 ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])581 assert ctx.params["cert"] == (__file__, __file__)582583 # key specified first584 ctx = run_command.make_context("run", ["--key", __file__, "--cert", __file__])585 assert ctx.params["cert"] == (__file__, __file__)586587588def test_run_cert_adhoc(monkeypatch):589 monkeypatch.setitem(sys.modules, "cryptography", None)590591 # cryptography not installed592 with pytest.raises(click.BadParameter):593 run_command.make_context("run", ["--cert", "adhoc"])594595 # cryptography installed596 monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))597 ctx = run_command.make_context("run", ["--cert", "adhoc"])598 assert ctx.params["cert"] == "adhoc"599600 # no key with adhoc601 with pytest.raises(click.BadParameter):602 run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])603604605def test_run_cert_import(monkeypatch):606 monkeypatch.setitem(sys.modules, "not_here", None)607608 # ImportError609 with pytest.raises(click.BadParameter):610 run_command.make_context("run", ["--cert", "not_here"])611612 with pytest.raises(click.BadParameter):613 run_command.make_context("run", ["--cert", "flask"])614615 # SSLContext616 ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)617618 monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)619 ctx = run_command.make_context("run", ["--cert", "ssl_context"])620 assert ctx.params["cert"] is ssl_context621622 # no --key with SSLContext623 with pytest.raises(click.BadParameter):624 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])625626627def test_run_cert_no_ssl(monkeypatch):628 monkeypatch.setitem(sys.modules, "ssl", None)629630 with pytest.raises(click.BadParameter):631 run_command.make_context("run", ["--cert", "not_here"])632633634def test_cli_blueprints(app):635 """Test blueprint commands register correctly to the application"""636 custom = Blueprint("custom", __name__, cli_group="customized")637 nested = Blueprint("nested", __name__)638 merged = Blueprint("merged", __name__, cli_group=None)639 late = Blueprint("late", __name__)640641 @custom.cli.command("custom")642 def custom_command():643 click.echo("custom_result")644645 @nested.cli.command("nested")646 def nested_command():647 click.echo("nested_result")648649 @merged.cli.command("merged")650 def merged_command():651 click.echo("merged_result")652653 @late.cli.command("late")654 def late_command():655 click.echo("late_result")656657 app.register_blueprint(custom)658 app.register_blueprint(nested)659 app.register_blueprint(merged)660 app.register_blueprint(late, cli_group="late_registration")661662 app_runner = app.test_cli_runner()663664 result = app_runner.invoke(args=["customized", "custom"])665 assert "custom_result" in result.output666667 result = app_runner.invoke(args=["nested", "nested"])668 assert "nested_result" in result.output669670 result = app_runner.invoke(args=["merged"])671 assert "merged_result" in result.output672673 result = app_runner.invoke(args=["late_registration", "late"])674 assert "late_result" in result.output675676677def test_cli_empty(app):678 """If a Blueprint's CLI group is empty, do not register it."""679 bp = Blueprint("blue", __name__, cli_group="blue")680 app.register_blueprint(bp)681682 result = app.test_cli_runner().invoke(args=["blue", "--help"])683 assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"