test_cli.py
This file
Path
tests/test_cli.py
667 lines · 18.8 KiB · Python
Last changed by
Merge branch '1.0.x'David Lordbefore adoption1351d0a
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.test_cli4 ~~~~~~~~~~~~~~56 :copyright: 2010 Pallets7 :license: BSD-3-Clause8"""9# This file was part of Flask-CLI and was modified under the terms of10# its Revised BSD License. Copyright © 2015 CERN.11from __future__ import absolute_import1213import os14import ssl15import sys16import types17from functools import partial1819import click20import pytest21from _pytest.monkeypatch import notset22from click.testing import CliRunner2324from flask import Blueprint25from flask import current_app26from flask import Flask27from flask.cli import AppGroup28from flask.cli import dotenv29from flask.cli import find_best_app30from flask.cli import FlaskGroup31from flask.cli import get_version32from flask.cli import load_dotenv33from flask.cli import locate_app34from flask.cli import NoAppException35from flask.cli import prepare_import36from flask.cli import run_command37from flask.cli import ScriptInfo38from flask.cli import with_appcontext3940cwd = os.getcwd()41test_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))424344@pytest.fixture45def runner():46 return CliRunner()474849def test_cli_name(test_apps):50 """Make sure the CLI object's name is the app's name and not the app itself"""51 from cliapp.app import testapp5253 assert testapp.cli.name == testapp.name545556def test_find_best_app(test_apps):57 """Test if `find_best_app` behaves as expected with different combinations of input.""" # noqa: B95058 script_info = ScriptInfo()5960 class Module:61 app = Flask("appname")6263 assert find_best_app(script_info, Module) == Module.app6465 class Module:66 application = Flask("appname")6768 assert find_best_app(script_info, Module) == Module.application6970 class Module:71 myapp = Flask("appname")7273 assert find_best_app(script_info, Module) == Module.myapp7475 class Module:76 @staticmethod77 def create_app():78 return Flask("appname")7980 assert isinstance(find_best_app(script_info, Module), Flask)81 assert find_best_app(script_info, Module).name == "appname"8283 class Module:84 @staticmethod85 def create_app(foo):86 return Flask("appname")8788 assert isinstance(find_best_app(script_info, Module), Flask)89 assert find_best_app(script_info, Module).name == "appname"9091 class Module:92 @staticmethod93 def create_app(foo=None, script_info=None):94 return Flask("appname")9596 assert isinstance(find_best_app(script_info, Module), Flask)97 assert find_best_app(script_info, Module).name == "appname"9899 class Module:100 @staticmethod101 def make_app():102 return Flask("appname")103104 assert isinstance(find_best_app(script_info, Module), Flask)105 assert find_best_app(script_info, Module).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", os.path.join(cwd, "a"), "test"),157 ("test/__init__.py", cwd, "test"),158 ("test/__init__", cwd, "test"),159 # nested package160 (161 os.path.join(test_path, "cliapp", "inner1", "__init__"),162 test_path,163 "cliapp.inner1",164 ),165 (166 os.path.join(test_path, "cliapp", "inner1", "inner2"),167 test_path,168 "cliapp.inner1.inner2",169 ),170 # dotted name171 ("test.a.b", cwd, "test.a.b"),172 (os.path.join(test_path, "cliapp.app"), test_path, "cliapp.app"),173 # not a Python file, will be caught during import174 (175 os.path.join(test_path, "cliapp", "message.txt"),176 test_path,177 "cliapp.message.txt",178 ),179 ),180)181def test_prepare_import(request, value, path, result):182 """Expect the correct path to be set and the correct import and app names183 to be returned.184185 :func:`prepare_exec_for_file` has a side effect where the parent directory186 of the given import is added to :data:`sys.path`. This is reset after the187 test runs.188 """189 original_path = sys.path[:]190191 def reset_path():192 sys.path[:] = original_path193194 request.addfinalizer(reset_path)195196 assert prepare_import(value) == result197 assert sys.path[0] == path198199200@pytest.mark.parametrize(201 "iname,aname,result",202 (203 ("cliapp.app", None, "testapp"),204 ("cliapp.app", "testapp", "testapp"),205 ("cliapp.factory", None, "app"),206 ("cliapp.factory", "create_app", "app"),207 ("cliapp.factory", "create_app()", "app"),208 # no script_info209 ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),210 # trailing comma space211 ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),212 # takes script_info213 ("cliapp.factory", 'create_app3("foo")', "app3_foo_spam"),214 # strip whitespace215 ("cliapp.factory", " create_app () ", "app"),216 ),217)218def test_locate_app(test_apps, iname, aname, result):219 info = ScriptInfo()220 info.data["test"] = "spam"221 assert locate_app(info, iname, aname).name == result222223224@pytest.mark.parametrize(225 "iname,aname",226 (227 ("notanapp.py", None),228 ("cliapp/app", None),229 ("cliapp.app", "notanapp"),230 # not enough arguments231 ("cliapp.factory", 'create_app2("foo")'),232 # invalid identifier233 ("cliapp.factory", "create_app("),234 # no app returned235 ("cliapp.factory", "no_app"),236 # nested import error237 ("cliapp.importerrorapp", None),238 # not a Python file239 ("cliapp.message.txt", None),240 ),241)242def test_locate_app_raises(test_apps, iname, aname):243 info = ScriptInfo()244245 with pytest.raises(NoAppException):246 locate_app(info, iname, aname)247248249def test_locate_app_suppress_raise():250 info = ScriptInfo()251 app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)252 assert app is None253254 # only direct import error is suppressed255 with pytest.raises(NoAppException):256 locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)257258259def test_get_version(test_apps, capsys):260 from flask import __version__ as flask_version261 from werkzeug import __version__ as werkzeug_version262 from platform import python_version263264 class MockCtx(object):265 resilient_parsing = False266 color = None267268 def exit(self):269 return270271 ctx = MockCtx()272 get_version(ctx, None, "test")273 out, err = capsys.readouterr()274 assert "Python " + python_version() in out275 assert "Flask " + flask_version in out276 assert "Werkzeug " + werkzeug_version in out277278279def test_scriptinfo(test_apps, monkeypatch):280 """Test of ScriptInfo."""281 obj = ScriptInfo(app_import_path="cliapp.app:testapp")282 app = obj.load_app()283 assert app.name == "testapp"284 assert obj.load_app() is app285286 # import app with module's absolute path287 cli_app_path = os.path.abspath(288 os.path.join(os.path.dirname(__file__), "test_apps", "cliapp", "app.py")289 )290 obj = ScriptInfo(app_import_path=cli_app_path)291 app = obj.load_app()292 assert app.name == "testapp"293 assert obj.load_app() is app294 obj = ScriptInfo(app_import_path=cli_app_path + ":testapp")295 app = obj.load_app()296 assert app.name == "testapp"297 assert obj.load_app() is app298299 def create_app(info):300 return Flask("createapp")301302 obj = ScriptInfo(create_app=create_app)303 app = obj.load_app()304 assert app.name == "createapp"305 assert obj.load_app() is app306307 obj = ScriptInfo()308 pytest.raises(NoAppException, obj.load_app)309310 # import app from wsgi.py in current directory311 monkeypatch.chdir(312 os.path.abspath(313 os.path.join(os.path.dirname(__file__), "test_apps", "helloworld")314 )315 )316 obj = ScriptInfo()317 app = obj.load_app()318 assert app.name == "hello"319320 # import app from app.py in current directory321 monkeypatch.chdir(322 os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps", "cliapp"))323 )324 obj = ScriptInfo()325 app = obj.load_app()326 assert app.name == "testapp"327328329def test_with_appcontext(runner):330 """Test of with_appcontext."""331332 @click.command()333 @with_appcontext334 def testcmd():335 click.echo(current_app.name)336337 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))338339 result = runner.invoke(testcmd, obj=obj)340 assert result.exit_code == 0341 assert result.output == "testapp\n"342343344def test_appgroup(runner):345 """Test of with_appcontext."""346347 @click.group(cls=AppGroup)348 def cli():349 pass350351 @cli.command(with_appcontext=True)352 def test():353 click.echo(current_app.name)354355 @cli.group()356 def subgroup():357 pass358359 @subgroup.command(with_appcontext=True)360 def test2():361 click.echo(current_app.name)362363 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))364365 result = runner.invoke(cli, ["test"], obj=obj)366 assert result.exit_code == 0367 assert result.output == "testappgroup\n"368369 result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)370 assert result.exit_code == 0371 assert result.output == "testappgroup\n"372373374def test_flaskgroup(runner):375 """Test FlaskGroup."""376377 def create_app(info):378 return Flask("flaskgroup")379380 @click.group(cls=FlaskGroup, create_app=create_app)381 def cli(**params):382 pass383384 @cli.command()385 def test():386 click.echo(current_app.name)387388 result = runner.invoke(cli, ["test"])389 assert result.exit_code == 0390 assert result.output == "flaskgroup\n"391392393@pytest.mark.parametrize("set_debug_flag", (True, False))394def test_flaskgroup_debug(runner, set_debug_flag):395 """Test FlaskGroup debug flag behavior."""396397 def create_app(info):398 app = Flask("flaskgroup")399 app.debug = True400 return app401402 @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)403 def cli(**params):404 pass405406 @cli.command()407 def test():408 click.echo(str(current_app.debug))409410 result = runner.invoke(cli, ["test"])411 assert result.exit_code == 0412 assert result.output == "%s\n" % str(not set_debug_flag)413414415def test_print_exceptions(runner):416 """Print the stacktrace if the CLI."""417418 def create_app(info):419 raise Exception("oh no")420 return Flask("flaskgroup")421422 @click.group(cls=FlaskGroup, create_app=create_app)423 def cli(**params):424 pass425426 result = runner.invoke(cli, ["--help"])427 assert result.exit_code == 0428 assert "Exception: oh no" in result.output429 assert "Traceback" in result.output430431432class TestRoutes:433 @pytest.fixture434 def invoke(self, runner):435 def create_app(info):436 app = Flask(__name__)437 app.testing = True438439 @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])440 def yyy_get_post(x, y):441 pass442443 @app.route("/zzz_post", methods=["POST"])444 def aaa_post():445 pass446447 return app448449 cli = FlaskGroup(create_app=create_app)450 return partial(runner.invoke, cli)451452 @pytest.fixture453 def invoke_no_routes(self, runner):454 def create_app(info):455 app = Flask(__name__, static_folder=None)456 app.testing = True457458 return app459460 cli = FlaskGroup(create_app=create_app)461 return partial(runner.invoke, cli)462463 def expect_order(self, order, output):464 # skip the header and match the start of each row465 for expect, line in zip(order, output.splitlines()[2:]):466 # do this instead of startswith for nicer pytest output467 assert line[: len(expect)] == expect468469 def test_simple(self, invoke):470 result = invoke(["routes"])471 assert result.exit_code == 0472 self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)473474 def test_sort(self, invoke):475 default_output = invoke(["routes"]).output476 endpoint_output = invoke(["routes", "-s", "endpoint"]).output477 assert default_output == endpoint_output478 self.expect_order(479 ["static", "yyy_get_post", "aaa_post"],480 invoke(["routes", "-s", "methods"]).output,481 )482 self.expect_order(483 ["yyy_get_post", "static", "aaa_post"],484 invoke(["routes", "-s", "rule"]).output,485 )486 self.expect_order(487 ["aaa_post", "yyy_get_post", "static"],488 invoke(["routes", "-s", "match"]).output,489 )490491 def test_all_methods(self, invoke):492 output = invoke(["routes"]).output493 assert "GET, HEAD, OPTIONS, POST" not in output494 output = invoke(["routes", "--all-methods"]).output495 assert "GET, HEAD, OPTIONS, POST" in output496497 def test_no_routes(self, invoke_no_routes):498 result = invoke_no_routes(["routes"])499 assert result.exit_code == 0500 assert "No routes were registered." in result.output501502503need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")504505506@need_dotenv507def test_load_dotenv(monkeypatch):508 # can't use monkeypatch.delitem since the keys don't exist yet509 for item in ("FOO", "BAR", "SPAM"):510 monkeypatch._setitem.append((os.environ, item, notset))511512 monkeypatch.setenv("EGGS", "3")513 monkeypatch.chdir(os.path.join(test_path, "cliapp", "inner1"))514 assert load_dotenv()515 assert os.getcwd() == test_path516 # .flaskenv doesn't overwrite .env517 assert os.environ["FOO"] == "env"518 # set only in .flaskenv519 assert os.environ["BAR"] == "bar"520 # set only in .env521 assert os.environ["SPAM"] == "1"522 # set manually, files don't overwrite523 assert os.environ["EGGS"] == "3"524525 # 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, "OpenSSL", None)570571 # pyOpenSSL not installed572 with pytest.raises(click.BadParameter):573 run_command.make_context("run", ["--cert", "adhoc"])574575 # pyOpenSSL installed576 monkeypatch.setitem(sys.modules, "OpenSSL", types.ModuleType("OpenSSL"))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 # not an SSLContext593 if sys.version_info >= (2, 7, 9):594 with pytest.raises(click.BadParameter):595 run_command.make_context("run", ["--cert", "flask"])596597 # SSLContext598 if sys.version_info < (2, 7, 9):599 ssl_context = object()600 else:601 ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)602603 monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)604 ctx = run_command.make_context("run", ["--cert", "ssl_context"])605 assert ctx.params["cert"] is ssl_context606607 # no --key with SSLContext608 with pytest.raises(click.BadParameter):609 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])610611612def test_run_cert_no_ssl(monkeypatch):613 monkeypatch.setattr("flask.cli.ssl", None)614 with pytest.raises(click.BadParameter):615 run_command.make_context("run", ["--cert", "not_here"])616617618def test_cli_blueprints(app):619 """Test blueprint commands register correctly to the application"""620 custom = Blueprint("custom", __name__, cli_group="customized")621 nested = Blueprint("nested", __name__)622 merged = Blueprint("merged", __name__, cli_group=None)623 late = Blueprint("late", __name__)624625 @custom.cli.command("custom")626 def custom_command():627 click.echo("custom_result")628629 @nested.cli.command("nested")630 def nested_command():631 click.echo("nested_result")632633 @merged.cli.command("merged")634 def merged_command():635 click.echo("merged_result")636637 @late.cli.command("late")638 def late_command():639 click.echo("late_result")640641 app.register_blueprint(custom)642 app.register_blueprint(nested)643 app.register_blueprint(merged)644 app.register_blueprint(late, cli_group="late_registration")645646 app_runner = app.test_cli_runner()647648 result = app_runner.invoke(args=["customized", "custom"])649 assert "custom_result" in result.output650651 result = app_runner.invoke(args=["nested", "nested"])652 assert "nested_result" in result.output653654 result = app_runner.invoke(args=["merged"])655 assert "merged_result" in result.output656657 result = app_runner.invoke(args=["late_registration", "late"])658 assert "late_result" in result.output659660661def test_cli_empty(app):662 """If a Blueprint's CLI group is empty, do not register it."""663 bp = Blueprint("blue", __name__, cli_group="blue")664 app.register_blueprint(bp)665666 result = app.test_cli_runner().invoke(args=["blue", "--help"])667 assert result.exit_code == 2, "Unexpected success:\n\n" + result.output