test_cli.py
This file
Path
tests/test_cli.py
672 lines · 18.9 KiB · Python
Last changed by
Merge pull request #3972 from ThiefMaster/click-7David Lordbefore adoption77db3d5
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 unittest.mock import patch910import 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 dotenv20from 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 main as cli_main26from flask.cli import NoAppException27from flask.cli import prepare_import28from flask.cli import run_command29from flask.cli import ScriptInfo30from flask.cli import with_appcontext3132cwd = os.getcwd()33test_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))343536@pytest.fixture37def runner():38 return CliRunner()394041def test_cli_name(test_apps):42 """Make sure the CLI object's name is the app's name and not the app itself"""43 from cliapp.app import testapp4445 assert testapp.cli.name == testapp.name464748def test_find_best_app(test_apps):49 script_info = ScriptInfo()5051 class Module:52 app = Flask("appname")5354 assert find_best_app(script_info, Module) == Module.app5556 class Module:57 application = Flask("appname")5859 assert find_best_app(script_info, Module) == Module.application6061 class Module:62 myapp = Flask("appname")6364 assert find_best_app(script_info, Module) == Module.myapp6566 class Module:67 @staticmethod68 def create_app():69 return Flask("appname")7071 app = find_best_app(script_info, Module)72 assert isinstance(app, Flask)73 assert app.name == "appname"7475 class Module:76 @staticmethod77 def create_app(foo):78 return Flask("appname")7980 with pytest.deprecated_call(match="Script info"):81 app = find_best_app(script_info, Module)8283 assert isinstance(app, Flask)84 assert app.name == "appname"8586 class Module:87 @staticmethod88 def create_app(foo=None, script_info=None):89 return Flask("appname")9091 with pytest.deprecated_call(match="script_info"):92 app = find_best_app(script_info, Module)9394 assert isinstance(app, Flask)95 assert app.name == "appname"9697 class Module:98 @staticmethod99 def make_app():100 return Flask("appname")101102 app = find_best_app(script_info, Module)103 assert isinstance(app, Flask)104 assert app.name == "appname"105106 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 myapp = Flask("appname1")117118 @staticmethod119 def create_app():120 return Flask("appname2")121122 assert find_best_app(script_info, Module) == Module.myapp123124 class Module:125 pass126127 pytest.raises(NoAppException, find_best_app, script_info, Module)128129 class Module:130 myapp1 = Flask("appname1")131 myapp2 = Flask("appname2")132133 pytest.raises(NoAppException, find_best_app, script_info, Module)134135 class Module:136 @staticmethod137 def create_app(foo, bar):138 return Flask("appname2")139140 pytest.raises(NoAppException, find_best_app, script_info, Module)141142 class Module:143 @staticmethod144 def create_app():145 raise TypeError("bad bad factory!")146147 pytest.raises(TypeError, find_best_app, script_info, Module)148149150@pytest.mark.parametrize(151 "value,path,result",152 (153 ("test", cwd, "test"),154 ("test.py", cwd, "test"),155 ("a/test", os.path.join(cwd, "a"), "test"),156 ("test/__init__.py", cwd, "test"),157 ("test/__init__", cwd, "test"),158 # nested package159 (160 os.path.join(test_path, "cliapp", "inner1", "__init__"),161 test_path,162 "cliapp.inner1",163 ),164 (165 os.path.join(test_path, "cliapp", "inner1", "inner2"),166 test_path,167 "cliapp.inner1.inner2",168 ),169 # dotted name170 ("test.a.b", cwd, "test.a.b"),171 (os.path.join(test_path, "cliapp.app"), test_path, "cliapp.app"),172 # not a Python file, will be caught during import173 (174 os.path.join(test_path, "cliapp", "message.txt"),175 test_path,176 "cliapp.message.txt",177 ),178 ),179)180def test_prepare_import(request, value, path, result):181 """Expect the correct path to be set and the correct import and app names182 to be returned.183184 :func:`prepare_exec_for_file` has a side effect where the parent directory185 of the given import is added to :data:`sys.path`. This is reset after the186 test runs.187 """188 original_path = sys.path[:]189190 def reset_path():191 sys.path[:] = original_path192193 request.addfinalizer(reset_path)194195 assert prepare_import(value) == result196 assert sys.path[0] == path197198199@pytest.mark.parametrize(200 "iname,aname,result",201 (202 ("cliapp.app", None, "testapp"),203 ("cliapp.app", "testapp", "testapp"),204 ("cliapp.factory", None, "app"),205 ("cliapp.factory", "create_app", "app"),206 ("cliapp.factory", "create_app()", "app"),207 ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),208 # trailing comma space209 ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),210 # strip whitespace211 ("cliapp.factory", " create_app () ", "app"),212 ),213)214def test_locate_app(test_apps, iname, aname, result):215 info = ScriptInfo()216 assert locate_app(info, iname, aname).name == result217218219@pytest.mark.parametrize(220 "iname,aname",221 (222 ("notanapp.py", None),223 ("cliapp/app", None),224 ("cliapp.app", "notanapp"),225 # not enough arguments226 ("cliapp.factory", 'create_app2("foo")'),227 # invalid identifier228 ("cliapp.factory", "create_app("),229 # no app returned230 ("cliapp.factory", "no_app"),231 # nested import error232 ("cliapp.importerrorapp", None),233 # not a Python file234 ("cliapp.message.txt", None),235 ),236)237def test_locate_app_raises(test_apps, iname, aname):238 info = ScriptInfo()239240 with pytest.raises(NoAppException):241 locate_app(info, iname, aname)242243244def test_locate_app_suppress_raise(test_apps):245 info = ScriptInfo()246 app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)247 assert app is None248249 # only direct import error is suppressed250 with pytest.raises(NoAppException):251 locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)252253254def test_get_version(test_apps, capsys):255 from flask import __version__ as flask_version256 from werkzeug import __version__ as werkzeug_version257 from platform import python_version258259 class MockCtx:260 resilient_parsing = False261 color = None262263 def exit(self):264 return265266 ctx = MockCtx()267 get_version(ctx, None, "test")268 out, err = capsys.readouterr()269 assert f"Python {python_version()}" in out270 assert f"Flask {flask_version}" in out271 assert f"Werkzeug {werkzeug_version}" in out272273274def test_scriptinfo(test_apps, monkeypatch):275 obj = ScriptInfo(app_import_path="cliapp.app:testapp")276 app = obj.load_app()277 assert app.name == "testapp"278 assert obj.load_app() is app279280 # import app with module's absolute path281 cli_app_path = os.path.abspath(282 os.path.join(os.path.dirname(__file__), "test_apps", "cliapp", "app.py")283 )284 obj = ScriptInfo(app_import_path=cli_app_path)285 app = obj.load_app()286 assert app.name == "testapp"287 assert obj.load_app() is app288 obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")289 app = obj.load_app()290 assert app.name == "testapp"291 assert obj.load_app() is app292293 def create_app():294 return Flask("createapp")295296 obj = ScriptInfo(create_app=create_app)297 app = obj.load_app()298 assert app.name == "createapp"299 assert obj.load_app() is app300301 obj = ScriptInfo()302 pytest.raises(NoAppException, obj.load_app)303304 # import app from wsgi.py in current directory305 monkeypatch.chdir(306 os.path.abspath(307 os.path.join(os.path.dirname(__file__), "test_apps", "helloworld")308 )309 )310 obj = ScriptInfo()311 app = obj.load_app()312 assert app.name == "hello"313314 # import app from app.py in current directory315 monkeypatch.chdir(316 os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps", "cliapp"))317 )318 obj = ScriptInfo()319 app = obj.load_app()320 assert app.name == "testapp"321322323def test_with_appcontext(runner):324 @click.command()325 @with_appcontext326 def testcmd():327 click.echo(current_app.name)328329 obj = ScriptInfo(create_app=lambda: Flask("testapp"))330331 result = runner.invoke(testcmd, obj=obj)332 assert result.exit_code == 0333 assert result.output == "testapp\n"334335336def test_appgroup(runner):337 @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: 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 def create_app():366 return Flask("flaskgroup")367368 @click.group(cls=FlaskGroup, create_app=create_app)369 def cli(**params):370 pass371372 @cli.command()373 def test():374 click.echo(current_app.name)375376 result = runner.invoke(cli, ["test"])377 assert result.exit_code == 0378 assert result.output == "flaskgroup\n"379380381@pytest.mark.parametrize("set_debug_flag", (True, False))382def test_flaskgroup_debug(runner, set_debug_flag):383 def create_app():384 app = Flask("flaskgroup")385 app.debug = True386 return app387388 @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)389 def cli(**params):390 pass391392 @cli.command()393 def test():394 click.echo(str(current_app.debug))395396 result = runner.invoke(cli, ["test"])397 assert result.exit_code == 0398 assert result.output == f"{not set_debug_flag}\n"399400401def test_no_command_echo_loading_error():402 from flask.cli import cli403404 runner = CliRunner(mix_stderr=False)405 result = runner.invoke(cli, ["missing"])406 assert result.exit_code == 2407 assert "FLASK_APP" in result.stderr408 assert "Usage:" in result.stderr409410411def test_help_echo_loading_error():412 from flask.cli import cli413414 runner = CliRunner(mix_stderr=False)415 result = runner.invoke(cli, ["--help"])416 assert result.exit_code == 0417 assert "FLASK_APP" in result.stderr418 assert "Usage:" in result.stdout419420421def test_help_echo_exception():422 def create_app():423 raise Exception("oh no")424425 cli = FlaskGroup(create_app=create_app)426 runner = CliRunner(mix_stderr=False)427 result = runner.invoke(cli, ["--help"])428 assert result.exit_code == 0429 assert "Exception: oh no" in result.stderr430 assert "Usage:" in result.stdout431432433class TestRoutes:434 @pytest.fixture435 def invoke(self, runner):436 def create_app():437 app = Flask(__name__)438 app.testing = True439440 @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])441 def yyy_get_post(x, y):442 pass443444 @app.route("/zzz_post", methods=["POST"])445 def aaa_post():446 pass447448 return app449450 cli = FlaskGroup(create_app=create_app)451 return partial(runner.invoke, cli)452453 @pytest.fixture454 def invoke_no_routes(self, runner):455 def create_app():456 app = Flask(__name__, static_folder=None)457 app.testing = True458459 return app460461 cli = FlaskGroup(create_app=create_app)462 return partial(runner.invoke, cli)463464 def expect_order(self, order, output):465 # skip the header and match the start of each row466 for expect, line in zip(order, output.splitlines()[2:]):467 # do this instead of startswith for nicer pytest output468 assert line[: len(expect)] == expect469470 def test_simple(self, invoke):471 result = invoke(["routes"])472 assert result.exit_code == 0473 self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)474475 def test_sort(self, invoke):476 default_output = invoke(["routes"]).output477 endpoint_output = invoke(["routes", "-s", "endpoint"]).output478 assert default_output == endpoint_output479 self.expect_order(480 ["static", "yyy_get_post", "aaa_post"],481 invoke(["routes", "-s", "methods"]).output,482 )483 self.expect_order(484 ["yyy_get_post", "static", "aaa_post"],485 invoke(["routes", "-s", "rule"]).output,486 )487 self.expect_order(488 ["aaa_post", "yyy_get_post", "static"],489 invoke(["routes", "-s", "match"]).output,490 )491492 def test_all_methods(self, invoke):493 output = invoke(["routes"]).output494 assert "GET, HEAD, OPTIONS, POST" not in output495 output = invoke(["routes", "--all-methods"]).output496 assert "GET, HEAD, OPTIONS, POST" in output497498 def test_no_routes(self, invoke_no_routes):499 result = invoke_no_routes(["routes"])500 assert result.exit_code == 0501 assert "No routes were registered." in result.output502503504need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")505506507@need_dotenv508def test_load_dotenv(monkeypatch):509 # can't use monkeypatch.delitem since the keys don't exist yet510 for item in ("FOO", "BAR", "SPAM", "HAM"):511 monkeypatch._setitem.append((os.environ, item, notset))512513 monkeypatch.setenv("EGGS", "3")514 monkeypatch.chdir(test_path)515 assert load_dotenv()516 assert os.getcwd() == test_path517 # .flaskenv doesn't overwrite .env518 assert os.environ["FOO"] == "env"519 # set only in .flaskenv520 assert os.environ["BAR"] == "bar"521 # set only in .env522 assert os.environ["SPAM"] == "1"523 # set manually, files don't overwrite524 assert os.environ["EGGS"] == "3"525 # test env file encoding526 assert os.environ["HAM"] == "火腿"527 # Non existent file should not load528 assert not load_dotenv("non-existent-file")529530531@need_dotenv532def test_dotenv_path(monkeypatch):533 for item in ("FOO", "BAR", "EGGS"):534 monkeypatch._setitem.append((os.environ, item, notset))535536 cwd = os.getcwd()537 load_dotenv(os.path.join(test_path, ".flaskenv"))538 assert os.getcwd() == cwd539 assert "FOO" in os.environ540541542def test_dotenv_optional(monkeypatch):543 monkeypatch.setattr("flask.cli.dotenv", None)544 monkeypatch.chdir(test_path)545 load_dotenv()546 assert "FOO" not in os.environ547548549@need_dotenv550def test_disable_dotenv_from_env(monkeypatch, runner):551 monkeypatch.chdir(test_path)552 monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")553 runner.invoke(FlaskGroup())554 assert "FOO" not in os.environ555556557def test_run_cert_path():558 # no key559 with pytest.raises(click.BadParameter):560 run_command.make_context("run", ["--cert", __file__])561562 # no cert563 with pytest.raises(click.BadParameter):564 run_command.make_context("run", ["--key", __file__])565566 ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])567 assert ctx.params["cert"] == (__file__, __file__)568569570def test_run_cert_adhoc(monkeypatch):571 monkeypatch.setitem(sys.modules, "cryptography", None)572573 # cryptography not installed574 with pytest.raises(click.BadParameter):575 run_command.make_context("run", ["--cert", "adhoc"])576577 # cryptography installed578 monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))579 ctx = run_command.make_context("run", ["--cert", "adhoc"])580 assert ctx.params["cert"] == "adhoc"581582 # no key with adhoc583 with pytest.raises(click.BadParameter):584 run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])585586587def test_run_cert_import(monkeypatch):588 monkeypatch.setitem(sys.modules, "not_here", None)589590 # ImportError591 with pytest.raises(click.BadParameter):592 run_command.make_context("run", ["--cert", "not_here"])593594 with pytest.raises(click.BadParameter):595 run_command.make_context("run", ["--cert", "flask"])596597 # SSLContext598 ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)599600 monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)601 ctx = run_command.make_context("run", ["--cert", "ssl_context"])602 assert ctx.params["cert"] is ssl_context603604 # no --key with SSLContext605 with pytest.raises(click.BadParameter):606 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])607608609def test_run_cert_no_ssl(monkeypatch):610 monkeypatch.setattr("flask.cli.ssl", None)611 with pytest.raises(click.BadParameter):612 run_command.make_context("run", ["--cert", "not_here"])613614615def test_cli_blueprints(app):616 """Test blueprint commands register correctly to the application"""617 custom = Blueprint("custom", __name__, cli_group="customized")618 nested = Blueprint("nested", __name__)619 merged = Blueprint("merged", __name__, cli_group=None)620 late = Blueprint("late", __name__)621622 @custom.cli.command("custom")623 def custom_command():624 click.echo("custom_result")625626 @nested.cli.command("nested")627 def nested_command():628 click.echo("nested_result")629630 @merged.cli.command("merged")631 def merged_command():632 click.echo("merged_result")633634 @late.cli.command("late")635 def late_command():636 click.echo("late_result")637638 app.register_blueprint(custom)639 app.register_blueprint(nested)640 app.register_blueprint(merged)641 app.register_blueprint(late, cli_group="late_registration")642643 app_runner = app.test_cli_runner()644645 result = app_runner.invoke(args=["customized", "custom"])646 assert "custom_result" in result.output647648 result = app_runner.invoke(args=["nested", "nested"])649 assert "nested_result" in result.output650651 result = app_runner.invoke(args=["merged"])652 assert "merged_result" in result.output653654 result = app_runner.invoke(args=["late_registration", "late"])655 assert "late_result" in result.output656657658def test_cli_empty(app):659 """If a Blueprint's CLI group is empty, do not register it."""660 bp = Blueprint("blue", __name__, cli_group="blue")661 app.register_blueprint(bp)662663 result = app.test_cli_runner().invoke(args=["blue", "--help"])664 assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"665666667def test_click_7_deprecated():668 with patch("flask.cli.cli"):669 if int(click.__version__[0]) < 8:670 pytest.deprecated_call(cli_main, match=".* Click 7 is deprecated")671 else:672 cli_main()