test_cli.py
This file
Path
tests/test_cli.py
703 lines · 19.8 KiB · Python
Last changed by
Merge branch 'stable'David Lordbefore adoption6a2f545
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 importlib.metadata4import os5import platform6import ssl7import sys8import types9from functools import partial10from pathlib import Path1112import click13import pytest14from click.testing import CliRunner1516from flask import Blueprint17from flask import current_app18from flask import Flask19from flask.cli import AppGroup20from flask.cli import find_best_app21from flask.cli import FlaskGroup22from flask.cli import get_version23from flask.cli import load_dotenv24from flask.cli import locate_app25from flask.cli import NoAppException26from flask.cli import prepare_import27from flask.cli import run_command28from flask.cli import ScriptInfo29from flask.cli import with_appcontext3031cwd = Path.cwd()32test_path = (Path(__file__) / ".." / "test_apps").resolve()333435@pytest.fixture36def runner():37 return CliRunner()383940def test_cli_name(test_apps):41 """Make sure the CLI object's name is the app's name and not the app itself"""42 from cliapp.app import testapp4344 assert testapp.cli.name == testapp.name454647def test_find_best_app(test_apps):48 class Module:49 app = Flask("appname")5051 assert find_best_app(Module) == Module.app5253 class Module:54 application = Flask("appname")5556 assert find_best_app(Module) == Module.application5758 class Module:59 myapp = Flask("appname")6061 assert find_best_app(Module) == Module.myapp6263 class Module:64 @staticmethod65 def create_app():66 return Flask("appname")6768 app = find_best_app(Module)69 assert isinstance(app, Flask)70 assert app.name == "appname"7172 class Module:73 @staticmethod74 def create_app(**kwargs):75 return Flask("appname")7677 app = find_best_app(Module)78 assert isinstance(app, Flask)79 assert app.name == "appname"8081 class Module:82 @staticmethod83 def make_app():84 return Flask("appname")8586 app = find_best_app(Module)87 assert isinstance(app, Flask)88 assert app.name == "appname"8990 class Module:91 myapp = Flask("appname1")9293 @staticmethod94 def create_app():95 return Flask("appname2")9697 assert find_best_app(Module) == Module.myapp9899 class Module:100 myapp = Flask("appname1")101102 @staticmethod103 def create_app():104 return Flask("appname2")105106 assert find_best_app(Module) == Module.myapp107108 class Module:109 pass110111 pytest.raises(NoAppException, find_best_app, Module)112113 class Module:114 myapp1 = Flask("appname1")115 myapp2 = Flask("appname2")116117 pytest.raises(NoAppException, find_best_app, Module)118119 class Module:120 @staticmethod121 def create_app(foo, bar):122 return Flask("appname2")123124 pytest.raises(NoAppException, find_best_app, Module)125126 class Module:127 @staticmethod128 def create_app():129 raise TypeError("bad bad factory!")130131 pytest.raises(TypeError, find_best_app, Module)132133134@pytest.mark.parametrize(135 "value,path,result",136 (137 ("test", cwd, "test"),138 ("test.py", cwd, "test"),139 ("a/test", cwd / "a", "test"),140 ("test/__init__.py", cwd, "test"),141 ("test/__init__", cwd, "test"),142 # nested package143 (144 test_path / "cliapp" / "inner1" / "__init__",145 test_path,146 "cliapp.inner1",147 ),148 (149 test_path / "cliapp" / "inner1" / "inner2",150 test_path,151 "cliapp.inner1.inner2",152 ),153 # dotted name154 ("test.a.b", cwd, "test.a.b"),155 (test_path / "cliapp.app", test_path, "cliapp.app"),156 # not a Python file, will be caught during import157 (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),158 ),159)160def test_prepare_import(request, value, path, result):161 """Expect the correct path to be set and the correct import and app names162 to be returned.163164 :func:`prepare_exec_for_file` has a side effect where the parent directory165 of the given import is added to :data:`sys.path`. This is reset after the166 test runs.167 """168 original_path = sys.path[:]169170 def reset_path():171 sys.path[:] = original_path172173 request.addfinalizer(reset_path)174175 assert prepare_import(value) == result176 assert sys.path[0] == str(path)177178179@pytest.mark.parametrize(180 "iname,aname,result",181 (182 ("cliapp.app", None, "testapp"),183 ("cliapp.app", "testapp", "testapp"),184 ("cliapp.factory", None, "app"),185 ("cliapp.factory", "create_app", "app"),186 ("cliapp.factory", "create_app()", "app"),187 ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),188 # trailing comma space189 ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),190 # strip whitespace191 ("cliapp.factory", " create_app () ", "app"),192 ),193)194def test_locate_app(test_apps, iname, aname, result):195 assert locate_app(iname, aname).name == result196197198@pytest.mark.parametrize(199 "iname,aname",200 (201 ("notanapp.py", None),202 ("cliapp/app", None),203 ("cliapp.app", "notanapp"),204 # not enough arguments205 ("cliapp.factory", 'create_app2("foo")'),206 # invalid identifier207 ("cliapp.factory", "create_app("),208 # no app returned209 ("cliapp.factory", "no_app"),210 # nested import error211 ("cliapp.importerrorapp", None),212 # not a Python file213 ("cliapp.message.txt", None),214 ),215)216def test_locate_app_raises(test_apps, iname, aname):217 with pytest.raises(NoAppException):218 locate_app(iname, aname)219220221def test_locate_app_suppress_raise(test_apps):222 app = locate_app("notanapp.py", None, raise_if_not_found=False)223 assert app is None224225 # only direct import error is suppressed226 with pytest.raises(NoAppException):227 locate_app("cliapp.importerrorapp", None, raise_if_not_found=False)228229230def test_get_version(test_apps, capsys):231 class MockCtx:232 resilient_parsing = False233 color = None234235 def exit(self):236 return237238 ctx = MockCtx()239 get_version(ctx, None, "test")240 out, err = capsys.readouterr()241 assert f"Python {platform.python_version()}" in out242 assert f"Flask {importlib.metadata.version('flask')}" in out243 assert f"Werkzeug {importlib.metadata.version('werkzeug')}" in out244245246def test_scriptinfo(test_apps, monkeypatch):247 obj = ScriptInfo(app_import_path="cliapp.app:testapp")248 app = obj.load_app()249 assert app.name == "testapp"250 assert obj.load_app() is app251252 # import app with module's absolute path253 cli_app_path = str(test_path / "cliapp" / "app.py")254255 obj = ScriptInfo(app_import_path=cli_app_path)256 app = obj.load_app()257 assert app.name == "testapp"258 assert obj.load_app() is app259 obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")260 app = obj.load_app()261 assert app.name == "testapp"262 assert obj.load_app() is app263264 def create_app():265 return Flask("createapp")266267 obj = ScriptInfo(create_app=create_app)268 app = obj.load_app()269 assert app.name == "createapp"270 assert obj.load_app() is app271272 obj = ScriptInfo()273 pytest.raises(NoAppException, obj.load_app)274275 # import app from wsgi.py in current directory276 monkeypatch.chdir(test_path / "helloworld")277 obj = ScriptInfo()278 app = obj.load_app()279 assert app.name == "hello"280281 # import app from app.py in current directory282 monkeypatch.chdir(test_path / "cliapp")283 obj = ScriptInfo()284 app = obj.load_app()285 assert app.name == "testapp"286287288def test_app_cli_has_app_context(app, runner):289 def _param_cb(ctx, param, value):290 # current_app should be available in parameter callbacks291 return bool(current_app)292293 @app.cli.command()294 @click.argument("value", callback=_param_cb)295 def check(value):296 app = click.get_current_context().obj.load_app()297 # the loaded app should be the same as current_app298 same_app = current_app._get_current_object() is app299 return same_app, value300301 cli = FlaskGroup(create_app=lambda: app)302 result = runner.invoke(cli, ["check", "x"], standalone_mode=False)303 assert result.return_value == (True, True)304305306def test_with_appcontext(runner):307 @click.command()308 @with_appcontext309 def testcmd():310 click.echo(current_app.name)311312 obj = ScriptInfo(create_app=lambda: Flask("testapp"))313314 result = runner.invoke(testcmd, obj=obj)315 assert result.exit_code == 0316 assert result.output == "testapp\n"317318319def test_appgroup_app_context(runner):320 @click.group(cls=AppGroup)321 def cli():322 pass323324 @cli.command()325 def test():326 click.echo(current_app.name)327328 @cli.group()329 def subgroup():330 pass331332 @subgroup.command()333 def test2():334 click.echo(current_app.name)335336 obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))337338 result = runner.invoke(cli, ["test"], obj=obj)339 assert result.exit_code == 0340 assert result.output == "testappgroup\n"341342 result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)343 assert result.exit_code == 0344 assert result.output == "testappgroup\n"345346347def test_flaskgroup_app_context(runner):348 def create_app():349 return Flask("flaskgroup")350351 @click.group(cls=FlaskGroup, create_app=create_app)352 def cli(**params):353 pass354355 @cli.command()356 def test():357 click.echo(current_app.name)358359 result = runner.invoke(cli, ["test"])360 assert result.exit_code == 0361 assert result.output == "flaskgroup\n"362363364@pytest.mark.parametrize("set_debug_flag", (True, False))365def test_flaskgroup_debug(runner, set_debug_flag):366 def create_app():367 app = Flask("flaskgroup")368 app.debug = True369 return app370371 @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)372 def cli(**params):373 pass374375 @cli.command()376 def test():377 click.echo(str(current_app.debug))378379 result = runner.invoke(cli, ["test"])380 assert result.exit_code == 0381 assert result.output == f"{not set_debug_flag}\n"382383384def test_flaskgroup_nested(app, runner):385 cli = click.Group("cli")386 flask_group = FlaskGroup(name="flask", create_app=lambda: app)387 cli.add_command(flask_group)388389 @flask_group.command()390 def show():391 click.echo(current_app.name)392393 result = runner.invoke(cli, ["flask", "show"])394 assert result.output == "flask_test\n"395396397def test_no_command_echo_loading_error():398 from flask.cli import cli399400 try:401 runner = CliRunner(mix_stderr=False)402 except (DeprecationWarning, TypeError):403 # Click >= 8.2404 runner = CliRunner()405406 result = runner.invoke(cli, ["missing"])407 assert result.exit_code == 2408 assert "FLASK_APP" in result.stderr409 assert "Usage:" in result.stderr410411412def test_help_echo_loading_error():413 from flask.cli import cli414415 try:416 runner = CliRunner(mix_stderr=False)417 except (DeprecationWarning, TypeError):418 # Click >= 8.2419 runner = CliRunner()420421 result = runner.invoke(cli, ["--help"])422 assert result.exit_code == 0423 assert "FLASK_APP" in result.stderr424 assert "Usage:" in result.stdout425426427def test_help_echo_exception():428 def create_app():429 raise Exception("oh no")430431 cli = FlaskGroup(create_app=create_app)432433 try:434 runner = CliRunner(mix_stderr=False)435 except (DeprecationWarning, TypeError):436 # Click >= 8.2437 runner = CliRunner()438439 result = runner.invoke(cli, ["--help"])440 assert result.exit_code == 0441 assert "Exception: oh no" in result.stderr442 assert "Usage:" in result.stdout443444445class TestRoutes:446 @pytest.fixture447 def app(self):448 app = Flask(__name__)449 app.add_url_rule(450 "/get_post/<int:x>/<int:y>",451 methods=["GET", "POST"],452 endpoint="yyy_get_post",453 )454 app.add_url_rule("/zzz_post", methods=["POST"], endpoint="aaa_post")455 return app456457 @pytest.fixture458 def invoke(self, app, runner):459 cli = FlaskGroup(create_app=lambda: 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:], strict=False):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, app, 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 match_order = [r.endpoint for r in app.url_map.iter_rules()]486 self.expect_order(match_order, invoke(["routes", "-s", "match"]).output)487488 def test_all_methods(self, invoke):489 output = invoke(["routes"]).output490 assert "GET, HEAD, OPTIONS, POST" not in output491492 output = invoke(["routes", "--all-methods"]).output493 assert "GET, HEAD, OPTIONS, POST" in output494495 def test_no_routes(self, runner):496 app = Flask(__name__, static_folder=None)497 cli = FlaskGroup(create_app=lambda: app)498 result = runner.invoke(cli, ["routes"])499 assert result.exit_code == 0500 assert "No routes were registered." in result.output501502 def test_subdomain(self, runner):503 app = Flask(__name__, static_folder=None)504 app.add_url_rule("/a", subdomain="a", endpoint="a")505 app.add_url_rule("/b", subdomain="b", endpoint="b")506 cli = FlaskGroup(create_app=lambda: app)507 result = runner.invoke(cli, ["routes"])508 assert result.exit_code == 0509 assert "Subdomain" in result.output510511 def test_host(self, runner):512 app = Flask(__name__, static_folder=None, host_matching=True)513 app.add_url_rule("/a", host="a", endpoint="a")514 app.add_url_rule("/b", host="b", endpoint="b")515 cli = FlaskGroup(create_app=lambda: app)516 result = runner.invoke(cli, ["routes"])517 assert result.exit_code == 0518 assert "Host" in result.output519520521def dotenv_not_available():522 try:523 import dotenv # noqa: F401524 except ImportError:525 return True526527 return False528529530need_dotenv = pytest.mark.skipif(531 dotenv_not_available(), reason="dotenv is not installed"532)533534535@need_dotenv536def test_load_dotenv(monkeypatch):537 for item in ("FOO", "BAR", "SPAM", "HAM"):538 monkeypatch.delenv(item, False)539540 monkeypatch.setenv("EGGS", "3")541 monkeypatch.chdir(test_path)542 assert load_dotenv()543 assert Path.cwd() == test_path544 # .flaskenv doesn't overwrite .env545 assert os.environ["FOO"] == "env"546 # set only in .flaskenv547 assert os.environ["BAR"] == "bar"548 # set only in .env549 assert os.environ["SPAM"] == "1"550 # set manually, files don't overwrite551 assert os.environ["EGGS"] == "3"552 # test env file encoding553 assert os.environ["HAM"] == "火腿"554 # Non existent file should not load555 assert not load_dotenv("non-existent-file", load_defaults=False)556557558@need_dotenv559def test_dotenv_path(monkeypatch):560 for item in ("FOO", "BAR", "EGGS"):561 monkeypatch.delenv(item, False)562563 load_dotenv(test_path / ".flaskenv")564 assert Path.cwd() == cwd565 assert "FOO" in os.environ566567568def test_dotenv_optional(monkeypatch):569 monkeypatch.delenv("FOO", False)570 monkeypatch.setitem(sys.modules, "dotenv", None)571 monkeypatch.chdir(test_path)572 load_dotenv()573 assert "FOO" not in os.environ574575576@need_dotenv577def test_disable_dotenv_from_env(monkeypatch, runner):578 monkeypatch.delenv("FOO", False)579 monkeypatch.chdir(test_path)580 monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")581 runner.invoke(FlaskGroup())582 assert "FOO" not in os.environ583584585def test_run_cert_path():586 # no key587 with pytest.raises(click.BadParameter):588 run_command.make_context("run", ["--cert", __file__])589590 # no cert591 with pytest.raises(click.BadParameter):592 run_command.make_context("run", ["--key", __file__])593594 # cert specified first595 ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])596 assert ctx.params["cert"] == (__file__, __file__)597598 # key specified first599 ctx = run_command.make_context("run", ["--key", __file__, "--cert", __file__])600 assert ctx.params["cert"] == (__file__, __file__)601602603def test_run_cert_adhoc(monkeypatch):604 monkeypatch.setitem(sys.modules, "cryptography", None)605606 # cryptography not installed607 with pytest.raises(click.BadParameter):608 run_command.make_context("run", ["--cert", "adhoc"])609610 # cryptography installed611 monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))612 ctx = run_command.make_context("run", ["--cert", "adhoc"])613 assert ctx.params["cert"] == "adhoc"614615 # no key with adhoc616 with pytest.raises(click.BadParameter):617 run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])618619620def test_run_cert_import(monkeypatch):621 monkeypatch.setitem(sys.modules, "not_here", None)622623 # ImportError624 with pytest.raises(click.BadParameter):625 run_command.make_context("run", ["--cert", "not_here"])626627 with pytest.raises(click.BadParameter):628 run_command.make_context("run", ["--cert", "flask"])629630 # SSLContext631 ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)632633 monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)634 ctx = run_command.make_context("run", ["--cert", "ssl_context"])635 assert ctx.params["cert"] is ssl_context636637 # no --key with SSLContext638 with pytest.raises(click.BadParameter):639 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])640641642def test_run_cert_no_ssl(monkeypatch):643 monkeypatch.setitem(sys.modules, "ssl", None)644645 with pytest.raises(click.BadParameter):646 run_command.make_context("run", ["--cert", "not_here"])647648649def test_cli_blueprints(app):650 """Test blueprint commands register correctly to the application"""651 custom = Blueprint("custom", __name__, cli_group="customized")652 nested = Blueprint("nested", __name__)653 merged = Blueprint("merged", __name__, cli_group=None)654 late = Blueprint("late", __name__)655656 @custom.cli.command("custom")657 def custom_command():658 click.echo("custom_result")659660 @nested.cli.command("nested")661 def nested_command():662 click.echo("nested_result")663664 @merged.cli.command("merged")665 def merged_command():666 click.echo("merged_result")667668 @late.cli.command("late")669 def late_command():670 click.echo("late_result")671672 app.register_blueprint(custom)673 app.register_blueprint(nested)674 app.register_blueprint(merged)675 app.register_blueprint(late, cli_group="late_registration")676677 app_runner = app.test_cli_runner()678679 result = app_runner.invoke(args=["customized", "custom"])680 assert "custom_result" in result.output681682 result = app_runner.invoke(args=["nested", "nested"])683 assert "nested_result" in result.output684685 result = app_runner.invoke(args=["merged"])686 assert "merged_result" in result.output687688 result = app_runner.invoke(args=["late_registration", "late"])689 assert "late_result" in result.output690691692def test_cli_empty(app):693 """If a Blueprint's CLI group is empty, do not register it."""694 bp = Blueprint("blue", __name__, cli_group="blue")695 app.register_blueprint(bp)696697 result = app.test_cli_runner().invoke(args=["blue", "--help"])698 assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"699700701def test_run_exclude_patterns():702 ctx = run_command.make_context("run", ["--exclude-patterns", __file__])703 assert ctx.params["exclude_patterns"] == [__file__]