test_cli.py
This file
Path
tests/test_cli.py
608 lines · 16.8 KiB · Python
Last changed by
Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 tests.test_cli4 ~~~~~~~~~~~~~~56 :copyright: © 2010 by the Pallets team.7 :license: BSD, see LICENSE for more details.8"""910# This file was part of Flask-CLI and was modified under the terms of11# its Revised BSD License. Copyright © 2015 CERN.1213from __future__ import absolute_import1415import os16import ssl17import sys18import types19from functools import partial2021import click22import pytest23from _pytest.monkeypatch import notset24from click.testing import CliRunner2526from flask import Flask, current_app27from flask.cli import (28 AppGroup,29 FlaskGroup,30 NoAppException,31 ScriptInfo,32 dotenv,33 find_best_app,34 get_version,35 load_dotenv,36 locate_app,37 prepare_import,38 run_command,39 with_appcontext,40)4142cwd = os.getcwd()43test_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))444546@pytest.fixture47def runner():48 return CliRunner()495051def test_cli_name(test_apps):52 """Make sure the CLI object's name is the app's name and not the app itself"""53 from cliapp.app import testapp5455 assert testapp.cli.name == testapp.name565758def test_find_best_app(test_apps):59 """Test if `find_best_app` behaves as expected with different combinations of input."""60 script_info = ScriptInfo()6162 class Module:63 app = Flask("appname")6465 assert find_best_app(script_info, Module) == Module.app6667 class Module:68 application = Flask("appname")6970 assert find_best_app(script_info, Module) == Module.application7172 class Module:73 myapp = Flask("appname")7475 assert find_best_app(script_info, Module) == Module.myapp7677 class Module:78 @staticmethod79 def create_app():80 return Flask("appname")8182 assert isinstance(find_best_app(script_info, Module), Flask)83 assert find_best_app(script_info, Module).name == "appname"8485 class Module:86 @staticmethod87 def create_app(foo):88 return Flask("appname")8990 assert isinstance(find_best_app(script_info, Module), Flask)91 assert find_best_app(script_info, Module).name == "appname"9293 class Module:94 @staticmethod95 def create_app(foo=None, script_info=None):96 return Flask("appname")9798 assert isinstance(find_best_app(script_info, Module), Flask)99 assert find_best_app(script_info, Module).name == "appname"100101 class Module:102 @staticmethod103 def make_app():104 return Flask("appname")105106 assert isinstance(find_best_app(script_info, Module), Flask)107 assert find_best_app(script_info, Module).name == "appname"108109 class Module:110 myapp = Flask("appname1")111112 @staticmethod113 def create_app():114 return Flask("appname2")115116 assert find_best_app(script_info, Module) == Module.myapp117118 class Module:119 myapp = Flask("appname1")120121 @staticmethod122 def create_app():123 return Flask("appname2")124125 assert find_best_app(script_info, Module) == Module.myapp126127 class Module:128 pass129130 pytest.raises(NoAppException, find_best_app, script_info, Module)131132 class Module:133 myapp1 = Flask("appname1")134 myapp2 = Flask("appname2")135136 pytest.raises(NoAppException, find_best_app, script_info, Module)137138 class Module:139 @staticmethod140 def create_app(foo, bar):141 return Flask("appname2")142143 pytest.raises(NoAppException, find_best_app, script_info, Module)144145 class Module:146 @staticmethod147 def create_app():148 raise TypeError("bad bad factory!")149150 pytest.raises(TypeError, find_best_app, script_info, Module)151152153@pytest.mark.parametrize(154 "value,path,result",155 (156 ("test", cwd, "test"),157 ("test.py", cwd, "test"),158 ("a/test", os.path.join(cwd, "a"), "test"),159 ("test/__init__.py", cwd, "test"),160 ("test/__init__", cwd, "test"),161 # nested package162 (163 os.path.join(test_path, "cliapp", "inner1", "__init__"),164 test_path,165 "cliapp.inner1",166 ),167 (168 os.path.join(test_path, "cliapp", "inner1", "inner2"),169 test_path,170 "cliapp.inner1.inner2",171 ),172 # dotted name173 ("test.a.b", cwd, "test.a.b"),174 (os.path.join(test_path, "cliapp.app"), test_path, "cliapp.app"),175 # not a Python file, will be caught during import176 (177 os.path.join(test_path, "cliapp", "message.txt"),178 test_path,179 "cliapp.message.txt",180 ),181 ),182)183def test_prepare_import(request, value, path, result):184 """Expect the correct path to be set and the correct import and app names185 to be returned.186187 :func:`prepare_exec_for_file` has a side effect where the parent directory188 of the given import is added to :data:`sys.path`. This is reset after the189 test runs.190 """191 original_path = sys.path[:]192193 def reset_path():194 sys.path[:] = original_path195196 request.addfinalizer(reset_path)197198 assert prepare_import(value) == result199 assert sys.path[0] == path200201202@pytest.mark.parametrize(203 "iname,aname,result",204 (205 ("cliapp.app", None, "testapp"),206 ("cliapp.app", "testapp", "testapp"),207 ("cliapp.factory", None, "app"),208 ("cliapp.factory", "create_app", "app"),209 ("cliapp.factory", "create_app()", "app"),210 # no script_info211 ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),212 # trailing comma space213 ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),214 # takes script_info215 ("cliapp.factory", 'create_app3("foo")', "app3_foo_spam"),216 # strip whitespace217 ("cliapp.factory", " create_app () ", "app"),218 ),219)220def test_locate_app(test_apps, iname, aname, result):221 info = ScriptInfo()222 info.data["test"] = "spam"223 assert locate_app(info, iname, aname).name == result224225226@pytest.mark.parametrize(227 "iname,aname",228 (229 ("notanapp.py", None),230 ("cliapp/app", None),231 ("cliapp.app", "notanapp"),232 # not enough arguments233 ("cliapp.factory", 'create_app2("foo")'),234 # invalid identifier235 ("cliapp.factory", "create_app("),236 # no app returned237 ("cliapp.factory", "no_app"),238 # nested import error239 ("cliapp.importerrorapp", None),240 # not a Python file241 ("cliapp.message.txt", None),242 ),243)244def test_locate_app_raises(test_apps, iname, aname):245 info = ScriptInfo()246247 with pytest.raises(NoAppException):248 locate_app(info, iname, aname)249250251def test_locate_app_suppress_raise():252 info = ScriptInfo()253 app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)254 assert app is None255256 # only direct import error is suppressed257 with pytest.raises(NoAppException):258 locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)259260261def test_get_version(test_apps, capsys):262 from flask import __version__ as flask_version263 from werkzeug import __version__ as werkzeug_version264 from platform import python_version265266 class MockCtx(object):267 resilient_parsing = False268 color = None269270 def exit(self):271 return272273 ctx = MockCtx()274 get_version(ctx, None, "test")275 out, err = capsys.readouterr()276 assert "Python " + python_version() in out277 assert "Flask " + flask_version in out278 assert "Werkzeug " + werkzeug_version in out279280281def test_scriptinfo(test_apps, monkeypatch):282 """Test of ScriptInfo."""283 obj = ScriptInfo(app_import_path="cliapp.app:testapp")284 app = obj.load_app()285 assert app.name == "testapp"286 assert obj.load_app() is app287288 # import app with module's absolute path289 cli_app_path = os.path.abspath(290 os.path.join(os.path.dirname(__file__), "test_apps", "cliapp", "app.py")291 )292 obj = ScriptInfo(app_import_path=cli_app_path)293 app = obj.load_app()294 assert app.name == "testapp"295 assert obj.load_app() is app296 obj = ScriptInfo(app_import_path=cli_app_path + ":testapp")297 app = obj.load_app()298 assert app.name == "testapp"299 assert obj.load_app() is app300301 def create_app(info):302 return Flask("createapp")303304 obj = ScriptInfo(create_app=create_app)305 app = obj.load_app()306 assert app.name == "createapp"307 assert obj.load_app() is app308309 obj = ScriptInfo()310 pytest.raises(NoAppException, obj.load_app)311312 # import app from wsgi.py in current directory313 monkeypatch.chdir(314 os.path.abspath(315 os.path.join(os.path.dirname(__file__), "test_apps", "helloworld")316 )317 )318 obj = ScriptInfo()319 app = obj.load_app()320 assert app.name == "hello"321322 # import app from app.py in current directory323 monkeypatch.chdir(324 os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps", "cliapp"))325 )326 obj = ScriptInfo()327 app = obj.load_app()328 assert app.name == "testapp"329330331def test_with_appcontext(runner):332 """Test of with_appcontext."""333334 @click.command()335 @with_appcontext336 def testcmd():337 click.echo(current_app.name)338339 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))340341 result = runner.invoke(testcmd, obj=obj)342 assert result.exit_code == 0343 assert result.output == "testapp\n"344345346def test_appgroup(runner):347 """Test of with_appcontext."""348349 @click.group(cls=AppGroup)350 def cli():351 pass352353 @cli.command(with_appcontext=True)354 def test():355 click.echo(current_app.name)356357 @cli.group()358 def subgroup():359 pass360361 @subgroup.command(with_appcontext=True)362 def test2():363 click.echo(current_app.name)364365 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))366367 result = runner.invoke(cli, ["test"], obj=obj)368 assert result.exit_code == 0369 assert result.output == "testappgroup\n"370371 result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)372 assert result.exit_code == 0373 assert result.output == "testappgroup\n"374375376def test_flaskgroup(runner):377 """Test FlaskGroup."""378379 def create_app(info):380 return Flask("flaskgroup")381382 @click.group(cls=FlaskGroup, create_app=create_app)383 def cli(**params):384 pass385386 @cli.command()387 def test():388 click.echo(current_app.name)389390 result = runner.invoke(cli, ["test"])391 assert result.exit_code == 0392 assert result.output == "flaskgroup\n"393394395@pytest.mark.parametrize("set_debug_flag", (True, False))396def test_flaskgroup_debug(runner, set_debug_flag):397 """Test FlaskGroup debug flag behavior."""398399 def create_app(info):400 app = Flask("flaskgroup")401 app.debug = True402 return app403404 @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)405 def cli(**params):406 pass407408 @cli.command()409 def test():410 click.echo(str(current_app.debug))411412 result = runner.invoke(cli, ["test"])413 assert result.exit_code == 0414 assert result.output == "%s\n" % str(not set_debug_flag)415416417def test_print_exceptions(runner):418 """Print the stacktrace if the CLI."""419420 def create_app(info):421 raise Exception("oh no")422 return Flask("flaskgroup")423424 @click.group(cls=FlaskGroup, create_app=create_app)425 def cli(**params):426 pass427428 result = runner.invoke(cli, ["--help"])429 assert result.exit_code == 0430 assert "Exception: oh no" in result.output431 assert "Traceback" in result.output432433434class TestRoutes:435 @pytest.fixture436 def invoke(self, runner):437 def create_app(info):438 app = Flask(__name__)439 app.testing = True440441 @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])442 def yyy_get_post(x, y):443 pass444445 @app.route("/zzz_post", methods=["POST"])446 def aaa_post():447 pass448449 return app450451 cli = FlaskGroup(create_app=create_app)452 return partial(runner.invoke, cli)453454 @pytest.fixture455 def invoke_no_routes(self, runner):456 def create_app(info):457 app = Flask(__name__, static_folder=None)458 app.testing = True459460 return app461462 cli = FlaskGroup(create_app=create_app)463 return partial(runner.invoke, cli)464465 def expect_order(self, order, output):466 # skip the header and match the start of each row467 for expect, line in zip(order, output.splitlines()[2:]):468 # do this instead of startswith for nicer pytest output469 assert line[: len(expect)] == expect470471 def test_simple(self, invoke):472 result = invoke(["routes"])473 assert result.exit_code == 0474 self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)475476 def test_sort(self, invoke):477 default_output = invoke(["routes"]).output478 endpoint_output = invoke(["routes", "-s", "endpoint"]).output479 assert default_output == endpoint_output480 self.expect_order(481 ["static", "yyy_get_post", "aaa_post"],482 invoke(["routes", "-s", "methods"]).output,483 )484 self.expect_order(485 ["yyy_get_post", "static", "aaa_post"],486 invoke(["routes", "-s", "rule"]).output,487 )488 self.expect_order(489 ["aaa_post", "yyy_get_post", "static"],490 invoke(["routes", "-s", "match"]).output,491 )492493 def test_all_methods(self, invoke):494 output = invoke(["routes"]).output495 assert "GET, HEAD, OPTIONS, POST" not in output496 output = invoke(["routes", "--all-methods"]).output497 assert "GET, HEAD, OPTIONS, POST" in output498499 def test_no_routes(self, invoke_no_routes):500 result = invoke_no_routes(["routes"])501 assert result.exit_code == 0502 assert "No routes were registered." in result.output503504505need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")506507508@need_dotenv509def test_load_dotenv(monkeypatch):510 # can't use monkeypatch.delitem since the keys don't exist yet511 for item in ("FOO", "BAR", "SPAM"):512 monkeypatch._setitem.append((os.environ, item, notset))513514 monkeypatch.setenv("EGGS", "3")515 monkeypatch.chdir(os.path.join(test_path, "cliapp", "inner1"))516 load_dotenv()517 assert os.getcwd() == test_path518 # .flaskenv doesn't overwrite .env519 assert os.environ["FOO"] == "env"520 # set only in .flaskenv521 assert os.environ["BAR"] == "bar"522 # set only in .env523 assert os.environ["SPAM"] == "1"524 # set manually, files don't overwrite525 assert os.environ["EGGS"] == "3"526527528@need_dotenv529def test_dotenv_path(monkeypatch):530 for item in ("FOO", "BAR", "EGGS"):531 monkeypatch._setitem.append((os.environ, item, notset))532533 cwd = os.getcwd()534 load_dotenv(os.path.join(test_path, ".flaskenv"))535 assert os.getcwd() == cwd536 assert "FOO" in os.environ537538539def test_dotenv_optional(monkeypatch):540 monkeypatch.setattr("flask.cli.dotenv", None)541 monkeypatch.chdir(test_path)542 load_dotenv()543 assert "FOO" not in os.environ544545546@need_dotenv547def test_disable_dotenv_from_env(monkeypatch, runner):548 monkeypatch.chdir(test_path)549 monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")550 runner.invoke(FlaskGroup())551 assert "FOO" not in os.environ552553554def test_run_cert_path():555 # no key556 with pytest.raises(click.BadParameter):557 run_command.make_context("run", ["--cert", __file__])558559 # no cert560 with pytest.raises(click.BadParameter):561 run_command.make_context("run", ["--key", __file__])562563 ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])564 assert ctx.params["cert"] == (__file__, __file__)565566567def test_run_cert_adhoc(monkeypatch):568 monkeypatch.setitem(sys.modules, "OpenSSL", None)569570 # pyOpenSSL not installed571 with pytest.raises(click.BadParameter):572 run_command.make_context("run", ["--cert", "adhoc"])573574 # pyOpenSSL installed575 monkeypatch.setitem(sys.modules, "OpenSSL", types.ModuleType("OpenSSL"))576 ctx = run_command.make_context("run", ["--cert", "adhoc"])577 assert ctx.params["cert"] == "adhoc"578579 # no key with adhoc580 with pytest.raises(click.BadParameter):581 run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])582583584def test_run_cert_import(monkeypatch):585 monkeypatch.setitem(sys.modules, "not_here", None)586587 # ImportError588 with pytest.raises(click.BadParameter):589 run_command.make_context("run", ["--cert", "not_here"])590591 # not an SSLContext592 if sys.version_info >= (2, 7, 9):593 with pytest.raises(click.BadParameter):594 run_command.make_context("run", ["--cert", "flask"])595596 # SSLContext597 if sys.version_info < (2, 7, 9):598 ssl_context = object()599 else:600 ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)601602 monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)603 ctx = run_command.make_context("run", ["--cert", "ssl_context"])604 assert ctx.params["cert"] is ssl_context605606 # no --key with SSLContext607 with pytest.raises(click.BadParameter):608 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])