test_cli.py
This file
Path
tests/test_cli.py
664 lines · 18.5 KiB · Python
Last changed by
Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
History of this fileTake it
The walk stopped after 200 commits: lines older than eec29a8 point at it.
Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 1–3why, one step back1# This file was part of Flask-CLI and was modified under the terms of2# its Revised BSD License. Copyright © 2015 CERN.3import osMerge branch '2.0.x'David Lordbefore adoption44bc286
line 4why, one step back4import platformMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 5–8why, one step back5import ssl6import sys7import types8from functools import partialMerge branch '2.0.x'David Lordbefore adoption83f7efa
line 9why, one step back9from pathlib import PathMerge pull request #3972 from ThiefMaster/click-7David Lordbefore adoption77db3d5
line 10why, one step back10from unittest.mock import patchMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 11–20why, one step back1112import click13import pytest14from _pytest.monkeypatch import notset15from click.testing import CliRunner1617from flask import Blueprint18from flask import current_app19from flask import Flask20from flask.cli import AppGroupMerge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9
line 21why, one step back21from flask.cli import DispatchingAppMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 22–27why, one step back22from flask.cli import dotenv23from flask.cli import find_best_app24from flask.cli import FlaskGroup25from flask.cli import get_version26from flask.cli import load_dotenv27from flask.cli import locate_appMerge pull request #3972 from ThiefMaster/click-7David Lordbefore adoption77db3d5
line 28why, one step back28from flask.cli import main as cli_mainMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 29–34why, one step back29from flask.cli import NoAppException30from flask.cli import prepare_import31from flask.cli import run_command32from flask.cli import ScriptInfo33from flask.cli import with_appcontext34Merge branch '2.0.x'David Lordbefore adoption83f7efa
lines 35–36why, one step back35cwd = Path.cwd()36test_path = (Path(__file__) / ".." / "test_apps").resolve()Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 37–54why, one step back373839@pytest.fixture40def runner():41 return CliRunner()424344def test_cli_name(test_apps):45 """Make sure the CLI object's name is the app's name and not the app itself"""46 from cliapp.app import testapp4748 assert testapp.cli.name == testapp.name495051def test_find_best_app(test_apps):52 class Module:53 app = Flask("appname")54Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 55why, one step back55 assert find_best_app(Module) == Module.appMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 56–59why, one step back5657 class Module:58 application = Flask("appname")59Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 60why, one step back60 assert find_best_app(Module) == Module.applicationMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 61–64why, one step back6162 class Module:63 myapp = Flask("appname")64Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 65why, one step back65 assert find_best_app(Module) == Module.myappMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 66–71why, one step back6667 class Module:68 @staticmethod69 def create_app():70 return Flask("appname")71Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 72why, one step back72 app = find_best_app(Module)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 73–77why, one step back73 assert isinstance(app, Flask)74 assert app.name == "appname"7576 class Module:77 @staticmethodMerge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9
lines 78–80why, one step back78 def create_app(**kwargs):79 return Flask("appname")80Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 81why, one step back81 app = find_best_app(Module)Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9
lines 82–86why, one step back82 assert isinstance(app, Flask)83 assert app.name == "appname"8485 class Module:86 @staticmethodMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 87–89why, one step back87 def make_app():88 return Flask("appname")89Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 90why, one step back90 app = find_best_app(Module)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 91–100why, one step back91 assert isinstance(app, Flask)92 assert app.name == "appname"9394 class Module:95 myapp = Flask("appname1")9697 @staticmethod98 def create_app():99 return Flask("appname2")100Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 101why, one step back101 assert find_best_app(Module) == Module.myappMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 102–109why, one step back102103 class Module:104 myapp = Flask("appname1")105106 @staticmethod107 def create_app():108 return Flask("appname2")109Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 110why, one step back110 assert find_best_app(Module) == Module.myappMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 111–114why, one step back111112 class Module:113 pass114Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 115why, one step back115 pytest.raises(NoAppException, find_best_app, Module)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 116–120why, one step back116117 class Module:118 myapp1 = Flask("appname1")119 myapp2 = Flask("appname2")120Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 121why, one step back121 pytest.raises(NoAppException, find_best_app, Module)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 122–127why, one step back122123 class Module:124 @staticmethod125 def create_app(foo, bar):126 return Flask("appname2")127Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 128why, one step back128 pytest.raises(NoAppException, find_best_app, Module)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 129–134why, one step back129130 class Module:131 @staticmethod132 def create_app():133 raise TypeError("bad bad factory!")134Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 135why, one step back135 pytest.raises(TypeError, find_best_app, Module)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 136–142why, one step back136137138@pytest.mark.parametrize(139 "value,path,result",140 (141 ("test", cwd, "test"),142 ("test.py", cwd, "test"),Merge branch '2.0.x'David Lordbefore adoption83f7efa
line 143why, one step back143 ("a/test", cwd / "a", "test"),Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 144–147why, one step back144 ("test/__init__.py", cwd, "test"),145 ("test/__init__", cwd, "test"),146 # nested package147 (Merge branch '2.0.x'David Lordbefore adoption83f7efa
line 148why, one step back148 test_path / "cliapp" / "inner1" / "__init__",Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 149–152why, one step back149 test_path,150 "cliapp.inner1",151 ),152 (Merge branch '2.0.x'David Lordbefore adoption83f7efa
line 153why, one step back153 test_path / "cliapp" / "inner1" / "inner2",Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 154–158why, one step back154 test_path,155 "cliapp.inner1.inner2",156 ),157 # dotted name158 ("test.a.b", cwd, "test.a.b"),Merge branch '2.0.x'David Lordbefore adoption83f7efa
line 159why, one step back159 (test_path / "cliapp.app", test_path, "cliapp.app"),Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
line 160why, one step back160 # not a Python file, will be caught during importMerge branch '2.0.x'David Lordbefore adoption83f7efa
line 161why, one step back161 (test_path / "cliapp" / "message.txt", test_path, "cliapp.message.txt"),Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 162–179why, one step back162 ),163)164def test_prepare_import(request, value, path, result):165 """Expect the correct path to be set and the correct import and app names166 to be returned.167168 :func:`prepare_exec_for_file` has a side effect where the parent directory169 of the given import is added to :data:`sys.path`. This is reset after the170 test runs.171 """172 original_path = sys.path[:]173174 def reset_path():175 sys.path[:] = original_path176177 request.addfinalizer(reset_path)178179 assert prepare_import(value) == resultMerge branch '2.0.x'David Lordbefore adoption83f7efa
line 180why, one step back180 assert sys.path[0] == str(path)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 181–198why, one step back181182183@pytest.mark.parametrize(184 "iname,aname,result",185 (186 ("cliapp.app", None, "testapp"),187 ("cliapp.app", "testapp", "testapp"),188 ("cliapp.factory", None, "app"),189 ("cliapp.factory", "create_app", "app"),190 ("cliapp.factory", "create_app()", "app"),191 ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),192 # trailing comma space193 ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),194 # strip whitespace195 ("cliapp.factory", " create_app () ", "app"),196 ),197)198def test_locate_app(test_apps, iname, aname, result):Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 199why, one step back199 assert locate_app(iname, aname).name == resultMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 200–221why, one step back200201202@pytest.mark.parametrize(203 "iname,aname",204 (205 ("notanapp.py", None),206 ("cliapp/app", None),207 ("cliapp.app", "notanapp"),208 # not enough arguments209 ("cliapp.factory", 'create_app2("foo")'),210 # invalid identifier211 ("cliapp.factory", "create_app("),212 # no app returned213 ("cliapp.factory", "no_app"),214 # nested import error215 ("cliapp.importerrorapp", None),216 # not a Python file217 ("cliapp.message.txt", None),218 ),219)220def test_locate_app_raises(test_apps, iname, aname):221 with pytest.raises(NoAppException):Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 222why, one step back222 locate_app(iname, aname)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 223–224why, one step back223224Merge pull request #3711 from pallets/cli-loading-errorDavid Lordbefore adoption6638432
line 225why, one step back225def test_locate_app_suppress_raise(test_apps):Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 226why, one step back226 app = locate_app("notanapp.py", None, raise_if_not_found=False)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 227–230why, one step back227 assert app is None228229 # only direct import error is suppressed230 with pytest.raises(NoAppException):Merge pull request #4337 from pallets/remove-deprecated-codeDavid Lordbefore adoption7620cb7
line 231why, one step back231 locate_app("cliapp.importerrorapp", None, raise_if_not_found=False)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 232–260why, one step back232233234def test_get_version(test_apps, capsys):235 from flask import __version__ as flask_version236 from werkzeug import __version__ as werkzeug_version237 from platform import python_version238239 class MockCtx:240 resilient_parsing = False241 color = None242243 def exit(self):244 return245246 ctx = MockCtx()247 get_version(ctx, None, "test")248 out, err = capsys.readouterr()249 assert f"Python {python_version()}" in out250 assert f"Flask {flask_version}" in out251 assert f"Werkzeug {werkzeug_version}" in out252253254def test_scriptinfo(test_apps, monkeypatch):255 obj = ScriptInfo(app_import_path="cliapp.app:testapp")256 app = obj.load_app()257 assert app.name == "testapp"258 assert obj.load_app() is app259260 # import app with module's absolute pathMerge branch '2.0.x'David Lordbefore adoption83f7efa
lines 261–262why, one step back261 cli_app_path = str(test_path / "cliapp" / "app.py")262Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 263–283why, one step back263 obj = ScriptInfo(app_import_path=cli_app_path)264 app = obj.load_app()265 assert app.name == "testapp"266 assert obj.load_app() is app267 obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")268 app = obj.load_app()269 assert app.name == "testapp"270 assert obj.load_app() is app271272 def create_app():273 return Flask("createapp")274275 obj = ScriptInfo(create_app=create_app)276 app = obj.load_app()277 assert app.name == "createapp"278 assert obj.load_app() is app279280 obj = ScriptInfo()281 pytest.raises(NoAppException, obj.load_app)282283 # import app from wsgi.py in current directoryMerge branch '2.0.x'David Lordbefore adoption83f7efa
line 284why, one step back284 monkeypatch.chdir(test_path / "helloworld")Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 285–289why, one step back285 obj = ScriptInfo()286 app = obj.load_app()287 assert app.name == "hello"288289 # import app from app.py in current directoryMerge branch '2.0.x'David Lordbefore adoption83f7efa
line 290why, one step back290 monkeypatch.chdir(test_path / "cliapp")Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 291–293why, one step back291 obj = ScriptInfo()292 app = obj.load_app()293 assert app.name == "testapp"Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9
lines 294–295why, one step back294295Merge branch '2.0.x'David Lordbefore adoption44bc286
line 296why, one step back296@pytest.mark.xfail(platform.python_implementation() == "PyPy", reason="flaky on pypy")Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoptionafc13b9
lines 297–310why, one step back297def test_lazy_load_error(monkeypatch):298 """When using lazy loading, the correct exception should be299 re-raised.300 """301302 class BadExc(Exception):303 pass304305 def bad_load():306 raise BadExc307308 lazy = DispatchingApp(bad_load, use_eager_loading=False)309310 with pytest.raises(BadExc):Merge branch '2.0.x'David Lordbefore adoptionfb82e3c
lines 311–313why, one step back311 # reduce flakiness by waiting for the internal loading lock312 with lazy._lock:313 lazy._flush_bg_loading_exception()Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 314–393why, one step back314315316def test_with_appcontext(runner):317 @click.command()318 @with_appcontext319 def testcmd():320 click.echo(current_app.name)321322 obj = ScriptInfo(create_app=lambda: Flask("testapp"))323324 result = runner.invoke(testcmd, obj=obj)325 assert result.exit_code == 0326 assert result.output == "testapp\n"327328329def test_appgroup(runner):330 @click.group(cls=AppGroup)331 def cli():332 pass333334 @cli.command(with_appcontext=True)335 def test():336 click.echo(current_app.name)337338 @cli.group()339 def subgroup():340 pass341342 @subgroup.command(with_appcontext=True)343 def test2():344 click.echo(current_app.name)345346 obj = ScriptInfo(create_app=lambda: Flask("testappgroup"))347348 result = runner.invoke(cli, ["test"], obj=obj)349 assert result.exit_code == 0350 assert result.output == "testappgroup\n"351352 result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)353 assert result.exit_code == 0354 assert result.output == "testappgroup\n"355356357def test_flaskgroup(runner):358 def create_app():359 return Flask("flaskgroup")360361 @click.group(cls=FlaskGroup, create_app=create_app)362 def cli(**params):363 pass364365 @cli.command()366 def test():367 click.echo(current_app.name)368369 result = runner.invoke(cli, ["test"])370 assert result.exit_code == 0371 assert result.output == "flaskgroup\n"372373374@pytest.mark.parametrize("set_debug_flag", (True, False))375def test_flaskgroup_debug(runner, set_debug_flag):376 def create_app():377 app = Flask("flaskgroup")378 app.debug = True379 return app380381 @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)382 def cli(**params):383 pass384385 @cli.command()386 def test():387 click.echo(str(current_app.debug))388389 result = runner.invoke(cli, ["test"])390 assert result.exit_code == 0391 assert result.output == f"{not set_debug_flag}\n"392393Merge pull request #3711 from pallets/cli-loading-errorDavid Lordbefore adoption6638432
lines 394–395why, one step back394def test_no_command_echo_loading_error():395 from flask.cli import cliMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
line 396why, one step back396Merge pull request #3711 from pallets/cli-loading-errorDavid Lordbefore adoption6638432
lines 397–414why, one step back397 runner = CliRunner(mix_stderr=False)398 result = runner.invoke(cli, ["missing"])399 assert result.exit_code == 2400 assert "FLASK_APP" in result.stderr401 assert "Usage:" in result.stderr402403404def test_help_echo_loading_error():405 from flask.cli import cli406407 runner = CliRunner(mix_stderr=False)408 result = runner.invoke(cli, ["--help"])409 assert result.exit_code == 0410 assert "FLASK_APP" in result.stderr411 assert "Usage:" in result.stdout412413414def test_help_echo_exception():Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 415–417why, one step back415 def create_app():416 raise Exception("oh no")417Merge pull request #3711 from pallets/cli-loading-errorDavid Lordbefore adoption6638432
lines 418–419why, one step back418 cli = FlaskGroup(create_app=create_app)419 runner = CliRunner(mix_stderr=False)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 420–421why, one step back420 result = runner.invoke(cli, ["--help"])421 assert result.exit_code == 0Merge pull request #3711 from pallets/cli-loading-errorDavid Lordbefore adoption6638432
lines 422–423why, one step back422 assert "Exception: oh no" in result.stderr423 assert "Usage:" in result.stdoutMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 424–502why, one step back424425426class TestRoutes:427 @pytest.fixture428 def invoke(self, runner):429 def create_app():430 app = Flask(__name__)431 app.testing = True432433 @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])434 def yyy_get_post(x, y):435 pass436437 @app.route("/zzz_post", methods=["POST"])438 def aaa_post():439 pass440441 return app442443 cli = FlaskGroup(create_app=create_app)444 return partial(runner.invoke, cli)445446 @pytest.fixture447 def invoke_no_routes(self, runner):448 def create_app():449 app = Flask(__name__, static_folder=None)450 app.testing = True451452 return app453454 cli = FlaskGroup(create_app=create_app)455 return partial(runner.invoke, cli)456457 def expect_order(self, order, output):458 # skip the header and match the start of each row459 for expect, line in zip(order, output.splitlines()[2:]):460 # do this instead of startswith for nicer pytest output461 assert line[: len(expect)] == expect462463 def test_simple(self, invoke):464 result = invoke(["routes"])465 assert result.exit_code == 0466 self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)467468 def test_sort(self, invoke):469 default_output = invoke(["routes"]).output470 endpoint_output = invoke(["routes", "-s", "endpoint"]).output471 assert default_output == endpoint_output472 self.expect_order(473 ["static", "yyy_get_post", "aaa_post"],474 invoke(["routes", "-s", "methods"]).output,475 )476 self.expect_order(477 ["yyy_get_post", "static", "aaa_post"],478 invoke(["routes", "-s", "rule"]).output,479 )480 self.expect_order(481 ["aaa_post", "yyy_get_post", "static"],482 invoke(["routes", "-s", "match"]).output,483 )484485 def test_all_methods(self, invoke):486 output = invoke(["routes"]).output487 assert "GET, HEAD, OPTIONS, POST" not in output488 output = invoke(["routes", "--all-methods"]).output489 assert "GET, HEAD, OPTIONS, POST" in output490491 def test_no_routes(self, invoke_no_routes):492 result = invoke_no_routes(["routes"])493 assert result.exit_code == 0494 assert "No routes were registered." in result.output495496497need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")498499500@need_dotenv501def test_load_dotenv(monkeypatch):502 # can't use monkeypatch.delitem since the keys don't exist yetMerge pull request #3932 from greyli/set-encodingDavid Lordbefore adoption3316604
line 503why, one step back503 for item in ("FOO", "BAR", "SPAM", "HAM"):Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 504–506why, one step back504 monkeypatch._setitem.append((os.environ, item, notset))505506 monkeypatch.setenv("EGGS", "3")Merge pull request #3560 from greyli/fix-env-chdirJoshua Bronsonbefore adoptiona40c381
line 507why, one step back507 monkeypatch.chdir(test_path)Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
line 508why, one step back508 assert load_dotenv()Merge branch '2.0.x'David Lordbefore adoption83f7efa
line 509why, one step back509 assert Path.cwd() == test_pathMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 510–517why, one step back510 # .flaskenv doesn't overwrite .env511 assert os.environ["FOO"] == "env"512 # set only in .flaskenv513 assert os.environ["BAR"] == "bar"514 # set only in .env515 assert os.environ["SPAM"] == "1"516 # set manually, files don't overwrite517 assert os.environ["EGGS"] == "3"Merge pull request #3932 from greyli/set-encodingDavid Lordbefore adoption3316604
lines 518–519why, one step back518 # test env file encoding519 assert os.environ["HAM"] == "火腿"Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 520–528why, one step back520 # Non existent file should not load521 assert not load_dotenv("non-existent-file")522523524@need_dotenv525def test_dotenv_path(monkeypatch):526 for item in ("FOO", "BAR", "EGGS"):527 monkeypatch._setitem.append((os.environ, item, notset))528Merge branch '2.0.x'David Lordbefore adoption83f7efa
lines 529–530why, one step back529 load_dotenv(test_path / ".flaskenv")530 assert Path.cwd() == cwdMerge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
lines 531–656why, one step back531 assert "FOO" in os.environ532533534def test_dotenv_optional(monkeypatch):535 monkeypatch.setattr("flask.cli.dotenv", None)536 monkeypatch.chdir(test_path)537 load_dotenv()538 assert "FOO" not in os.environ539540541@need_dotenv542def test_disable_dotenv_from_env(monkeypatch, runner):543 monkeypatch.chdir(test_path)544 monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")545 runner.invoke(FlaskGroup())546 assert "FOO" not in os.environ547548549def test_run_cert_path():550 # no key551 with pytest.raises(click.BadParameter):552 run_command.make_context("run", ["--cert", __file__])553554 # no cert555 with pytest.raises(click.BadParameter):556 run_command.make_context("run", ["--key", __file__])557558 ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])559 assert ctx.params["cert"] == (__file__, __file__)560561562def test_run_cert_adhoc(monkeypatch):563 monkeypatch.setitem(sys.modules, "cryptography", None)564565 # cryptography not installed566 with pytest.raises(click.BadParameter):567 run_command.make_context("run", ["--cert", "adhoc"])568569 # cryptography installed570 monkeypatch.setitem(sys.modules, "cryptography", types.ModuleType("cryptography"))571 ctx = run_command.make_context("run", ["--cert", "adhoc"])572 assert ctx.params["cert"] == "adhoc"573574 # no key with adhoc575 with pytest.raises(click.BadParameter):576 run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])577578579def test_run_cert_import(monkeypatch):580 monkeypatch.setitem(sys.modules, "not_here", None)581582 # ImportError583 with pytest.raises(click.BadParameter):584 run_command.make_context("run", ["--cert", "not_here"])585586 with pytest.raises(click.BadParameter):587 run_command.make_context("run", ["--cert", "flask"])588589 # SSLContext590 ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)591592 monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)593 ctx = run_command.make_context("run", ["--cert", "ssl_context"])594 assert ctx.params["cert"] is ssl_context595596 # no --key with SSLContext597 with pytest.raises(click.BadParameter):598 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])599600601def test_run_cert_no_ssl(monkeypatch):602 monkeypatch.setattr("flask.cli.ssl", None)603 with pytest.raises(click.BadParameter):604 run_command.make_context("run", ["--cert", "not_here"])605606607def test_cli_blueprints(app):608 """Test blueprint commands register correctly to the application"""609 custom = Blueprint("custom", __name__, cli_group="customized")610 nested = Blueprint("nested", __name__)611 merged = Blueprint("merged", __name__, cli_group=None)612 late = Blueprint("late", __name__)613614 @custom.cli.command("custom")615 def custom_command():616 click.echo("custom_result")617618 @nested.cli.command("nested")619 def nested_command():620 click.echo("nested_result")621622 @merged.cli.command("merged")623 def merged_command():624 click.echo("merged_result")625626 @late.cli.command("late")627 def late_command():628 click.echo("late_result")629630 app.register_blueprint(custom)631 app.register_blueprint(nested)632 app.register_blueprint(merged)633 app.register_blueprint(late, cli_group="late_registration")634635 app_runner = app.test_cli_runner()636637 result = app_runner.invoke(args=["customized", "custom"])638 assert "custom_result" in result.output639640 result = app_runner.invoke(args=["nested", "nested"])641 assert "nested_result" in result.output642643 result = app_runner.invoke(args=["merged"])644 assert "merged_result" in result.output645646 result = app_runner.invoke(args=["late_registration", "late"])647 assert "late_result" in result.output648649650def test_cli_empty(app):651 """If a Blueprint's CLI group is empty, do not register it."""652 bp = Blueprint("blue", __name__, cli_group="blue")653 app.register_blueprint(bp)654655 result = app.test_cli_runner().invoke(args=["blue", "--help"])656 assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"Merge pull request #3972 from ThiefMaster/click-7David Lordbefore adoption77db3d5
lines 657–664why, one step back657658659def test_click_7_deprecated():660 with patch("flask.cli.cli"):661 if int(click.__version__[0]) < 8:662 pytest.deprecated_call(cli_main, match=".* Click 7 is deprecated")663 else:664 cli_main()