test_cli.py
This file
Path
tests/test_cli.py
577 lines · 16.0 KiB · Python
Last changed by
Merge pull request #2825 from eso31/fix-2824-issueDavid Lordbefore adoption232e5c8
History of this fileTake it
The walk stopped after 200 commits: lines older than 8207b15 point at it.
fix formattingDavid Lordbefore adoption8207b15
lines 1–5why, one step back1# -*- coding: utf-8 -*-2"""3 tests.test_cli4 ~~~~~~~~~~~~~~5Merge pull request #2624 from pallets/metadataDavid Lordbefore adoption4309c7c
line 6why, one step back6 :copyright: © 2010 by the Pallets team.fix formattingDavid Lordbefore adoption8207b15
lines 7–8why, one step back7 :license: BSD, see LICENSE for more details.8"""Merge pull request #2624 from pallets/metadataDavid Lordbefore adoption4309c7c
lines 9–12why, one step back910# This file was part of Flask-CLI and was modified under the terms of11# its Revised BSD License. Copyright © 2015 CERN.12Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 13–14why, one step back13from __future__ import absolute_import14fix formattingDavid Lordbefore adoption8207b15
line 15why, one step back15import osMerge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
line 16why, one step back16import sslfix formattingDavid Lordbefore adoption8207b15
line 17why, one step back17import sysMerge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
line 18why, one step back18import typesfix formattingDavid Lordbefore adoption8207b15
lines 19–22why, one step back19from functools import partial2021import click22import pytestMerge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
line 23why, one step back23from _pytest.monkeypatch import notsetfix formattingDavid Lordbefore adoption8207b15
line 24why, one step back24from click.testing import CliRunnerMerge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
line 25why, one step back25fix formattingDavid Lordbefore adoption8207b15
line 26why, one step back26from flask import Flask, current_appMerge pull request #2592 from pallets/tests-envDavid Lordbefore adoption2949306
line 27why, one step back27from flask.cli import (Merge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
lines 28–29why, one step back28 AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, find_best_app,29 get_version, load_dotenv, locate_app, prepare_import, run_command,Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
line 30why, one step back30 with_appcontextMerge pull request #2592 from pallets/tests-envDavid Lordbefore adoption2949306
line 31why, one step back31)fix formattingDavid Lordbefore adoption8207b15
line 32why, one step back32Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 33–38why, one step back33cwd = os.getcwd()34test_path = os.path.abspath(os.path.join(35 os.path.dirname(__file__), 'test_apps'36))3738fix formattingDavid Lordbefore adoption8207b15
lines 39–136why, one step back39@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 testapp47 assert testapp.cli.name == testapp.name484950def test_find_best_app(test_apps):51 """Test if `find_best_app` behaves as expected with different combinations of input."""52 script_info = ScriptInfo()5354 class Module:55 app = Flask('appname')5657 assert find_best_app(script_info, Module) == Module.app5859 class Module:60 application = Flask('appname')6162 assert find_best_app(script_info, Module) == Module.application6364 class Module:65 myapp = Flask('appname')6667 assert find_best_app(script_info, Module) == Module.myapp6869 class Module:70 @staticmethod71 def create_app():72 return Flask('appname')7374 assert isinstance(find_best_app(script_info, Module), Flask)75 assert find_best_app(script_info, Module).name == 'appname'7677 class Module:78 @staticmethod79 def create_app(foo):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=None, script_info=None):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 make_app():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 myapp = Flask('appname1')103104 @staticmethod105 def create_app():106 return Flask('appname2')107108 assert find_best_app(script_info, Module) == Module.myapp109110 class Module:111 myapp = Flask('appname1')112113 @staticmethod114 def create_app():115 return Flask('appname2')116117 assert find_best_app(script_info, Module) == Module.myapp118119 class Module:120 pass121122 pytest.raises(NoAppException, find_best_app, script_info, Module)123124 class Module:125 myapp1 = Flask('appname1')126 myapp2 = Flask('appname2')127128 pytest.raises(NoAppException, find_best_app, script_info, Module)129130 class Module:131 @staticmethod132 def create_app(foo, bar):133 return Flask('appname2')134135 pytest.raises(NoAppException, find_best_app, script_info, Module)136Merge pull request #2530 from pallets/feature/factory-detectionDavid Lordbefore adoption03a2996
lines 137–143why, one step back137 class Module:138 @staticmethod139 def create_app():140 raise TypeError('bad bad factory!')141142 pytest.raises(TypeError, find_best_app, script_info, Module)143fix formattingDavid Lordbefore adoption8207b15
line 144why, one step back144Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 145–175why, one step back145@pytest.mark.parametrize('value,path,result', (146 ('test', cwd, 'test'),147 ('test.py', cwd, 'test'),148 ('a/test', os.path.join(cwd, 'a'), 'test'),149 ('test/__init__.py', cwd, 'test'),150 ('test/__init__', cwd, 'test'),151 # nested package152 (153 os.path.join(test_path, 'cliapp', 'inner1', '__init__'),154 test_path, 'cliapp.inner1'155 ),156 (157 os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),158 test_path, 'cliapp.inner1.inner2'159 ),160 # dotted name161 ('test.a.b', cwd, 'test.a.b'),162 (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),163 # not a Python file, will be caught during import164 (165 os.path.join(test_path, 'cliapp', 'message.txt'),166 test_path, 'cliapp.message.txt'167 ),168))169def test_prepare_import(request, value, path, result):170 """Expect the correct path to be set and the correct import and app names171 to be returned.172173 :func:`prepare_exec_for_file` has a side effect where the parent directory174 of the given import is added to :data:`sys.path`. This is reset after the175 test runs.fix formattingDavid Lordbefore adoption8207b15
line 176why, one step back176 """Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
line 177why, one step back177 original_path = sys.path[:]fix formattingDavid Lordbefore adoption8207b15
line 178why, one step back178Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 179–180why, one step back179 def reset_path():180 sys.path[:] = original_pathfix formattingDavid Lordbefore adoption8207b15
line 181why, one step back181Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
line 182why, one step back182 request.addfinalizer(reset_path)fix formattingDavid Lordbefore adoption8207b15
line 183why, one step back183Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 184–185why, one step back184 assert prepare_import(value) == result185 assert sys.path[0] == pathfix formattingDavid Lordbefore adoption8207b15
lines 186–187why, one step back186187Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 188–199why, one step back188@pytest.mark.parametrize('iname,aname,result', (189 ('cliapp.app', None, 'testapp'),190 ('cliapp.app', 'testapp', 'testapp'),191 ('cliapp.factory', None, 'app'),192 ('cliapp.factory', 'create_app', 'app'),193 ('cliapp.factory', 'create_app()', 'app'),194 # no script_info195 ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),196 # trailing comma space197 ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),198 # takes script_info199 ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),Merge pull request #2490 from davidism/cli-reviewDavid Lordbefore adoption0932d8f
lines 200–201why, one step back200 # strip whitespace201 ('cliapp.factory', ' create_app () ', 'app'),Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 202–206why, one step back202))203def test_locate_app(test_apps, iname, aname, result):204 info = ScriptInfo()205 info.data['test'] = 'spam'206 assert locate_app(info, iname, aname).name == resultfix formattingDavid Lordbefore adoption8207b15
line 207why, one step back207Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 208–214why, one step back208209@pytest.mark.parametrize('iname,aname', (210 ('notanapp.py', None),211 ('cliapp/app', None),212 ('cliapp.app', 'notanapp'),213 # not enough arguments214 ('cliapp.factory', 'create_app2("foo")'),Merge pull request #2490 from davidism/cli-reviewDavid Lordbefore adoption0932d8f
lines 215–218why, one step back215 # invalid identifier216 ('cliapp.factory', 'create_app('),217 # no app returned218 ('cliapp.factory', 'no_app'),Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 219–240why, one step back219 # nested import error220 ('cliapp.importerrorapp', None),221 # not a Python file222 ('cliapp.message.txt', None),223))224def test_locate_app_raises(test_apps, iname, aname):225 info = ScriptInfo()226227 with pytest.raises(NoAppException):228 locate_app(info, iname, aname)229230231def test_locate_app_suppress_raise():232 info = ScriptInfo()233 app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)234 assert app is None235236 # only direct import error is suppressed237 with pytest.raises(NoAppException):238 locate_app(239 info, 'cliapp.importerrorapp', None, raise_if_not_found=False240 )fix formattingDavid Lordbefore adoption8207b15
lines 241–243why, one step back241242243def test_get_version(test_apps, capsys):Merge pull request #2825 from eso31/fix-2824-issueDavid Lordbefore adoption232e5c8
lines 244–246why, one step back244 from flask import __version__ as flask_version245 from werkzeug import __version__ as werkzeug_version246 from platform import python_versionfix formattingDavid Lordbefore adoption8207b15
lines 247–256why, one step back247248 class MockCtx(object):249 resilient_parsing = False250 color = None251252 def exit(self): return253254 ctx = MockCtx()255 get_version(ctx, None, "test")256 out, err = capsys.readouterr()Merge pull request #2825 from eso31/fix-2824-issueDavid Lordbefore adoption232e5c8
lines 257–259why, one step back257 assert "Python " + python_version() in out258 assert "Flask " + flask_version in out259 assert "Werkzeug " + werkzeug_version in outfix formattingDavid Lordbefore adoption8207b15
lines 260–264why, one step back260261262def test_scriptinfo(test_apps, monkeypatch):263 """Test of ScriptInfo."""264 obj = ScriptInfo(app_import_path="cliapp.app:testapp")Merge pull request #2963 from garenchan/bugfix-#2961David Lordbefore adoption0038a67
lines 265–267why, one step back265 app = obj.load_app()266 assert app.name == "testapp"267 assert obj.load_app() is appfix formattingDavid Lordbefore adoption8207b15
line 268why, one step back268Merge pull request #2963 from garenchan/bugfix-#2961David Lordbefore adoption0038a67
lines 269–280why, one step back269 # import app with module's absolute path270 cli_app_path = os.path.abspath(os.path.join(271 os.path.dirname(__file__), 'test_apps', 'cliapp', 'app.py'))272 obj = ScriptInfo(app_import_path=cli_app_path)273 app = obj.load_app()274 assert app.name == 'testapp'275 assert obj.load_app() is app276 obj = ScriptInfo(app_import_path=cli_app_path + ':testapp')277 app = obj.load_app()278 assert app.name == 'testapp'279 assert obj.load_app() is app280fix formattingDavid Lordbefore adoption8207b15
lines 281–286why, one step back281 def create_app(info):282 return Flask("createapp")283284 obj = ScriptInfo(create_app=create_app)285 app = obj.load_app()286 assert app.name == "createapp"Merge pull request #2963 from garenchan/bugfix-#2961David Lordbefore adoption0038a67
line 287why, one step back287 assert obj.load_app() is appfix formattingDavid Lordbefore adoption8207b15
lines 288–372why, one step back288289 obj = ScriptInfo()290 pytest.raises(NoAppException, obj.load_app)291292 # import app from wsgi.py in current directory293 monkeypatch.chdir(os.path.abspath(os.path.join(294 os.path.dirname(__file__), 'test_apps', 'helloworld'295 )))296 obj = ScriptInfo()297 app = obj.load_app()298 assert app.name == 'hello'299300 # import app from app.py in current directory301 monkeypatch.chdir(os.path.abspath(os.path.join(302 os.path.dirname(__file__), 'test_apps', 'cliapp'303 )))304 obj = ScriptInfo()305 app = obj.load_app()306 assert app.name == 'testapp'307308309def test_with_appcontext(runner):310 """Test of with_appcontext."""311312 @click.command()313 @with_appcontext314 def testcmd():315 click.echo(current_app.name)316317 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))318319 result = runner.invoke(testcmd, obj=obj)320 assert result.exit_code == 0321 assert result.output == 'testapp\n'322323324def test_appgroup(runner):325 """Test of with_appcontext."""326327 @click.group(cls=AppGroup)328 def cli():329 pass330331 @cli.command(with_appcontext=True)332 def test():333 click.echo(current_app.name)334335 @cli.group()336 def subgroup():337 pass338339 @subgroup.command(with_appcontext=True)340 def test2():341 click.echo(current_app.name)342343 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))344345 result = runner.invoke(cli, ['test'], obj=obj)346 assert result.exit_code == 0347 assert result.output == 'testappgroup\n'348349 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)350 assert result.exit_code == 0351 assert result.output == 'testappgroup\n'352353354def test_flaskgroup(runner):355 """Test FlaskGroup."""356357 def create_app(info):358 return Flask("flaskgroup")359360 @click.group(cls=FlaskGroup, create_app=create_app)361 def cli(**params):362 pass363364 @cli.command()365 def test():366 click.echo(current_app.name)367368 result = runner.invoke(cli, ['test'])369 assert result.exit_code == 0370 assert result.output == 'flaskgroup\n'371372Merge pull request #2765 from ThiefMaster/custom-cli-ignore-debugAdrianbefore adoption1a9caed
lines 373–394why, one step back373@pytest.mark.parametrize('set_debug_flag', (True, False))374def test_flaskgroup_debug(runner, set_debug_flag):375 """Test FlaskGroup debug flag behavior."""376377 def create_app(info):378 app = Flask("flaskgroup")379 app.debug = True380 return app381382 @click.group(cls=FlaskGroup, create_app=create_app, set_debug_flag=set_debug_flag)383 def cli(**params):384 pass385386 @cli.command()387 def test():388 click.echo(str(current_app.debug))389390 result = runner.invoke(cli, ['test'])391 assert result.exit_code == 0392 assert result.output == '%s\n' % str(not set_debug_flag)393394fix formattingDavid Lordbefore adoption8207b15
lines 395–467why, one step back395def test_print_exceptions(runner):396 """Print the stacktrace if the CLI."""397398 def create_app(info):399 raise Exception("oh no")400 return Flask("flaskgroup")401402 @click.group(cls=FlaskGroup, create_app=create_app)403 def cli(**params):404 pass405406 result = runner.invoke(cli, ['--help'])407 assert result.exit_code == 0408 assert 'Exception: oh no' in result.output409 assert 'Traceback' in result.output410411412class TestRoutes:413 @pytest.fixture414 def invoke(self, runner):415 def create_app(info):416 app = Flask(__name__)417 app.testing = True418419 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])420 def yyy_get_post(x, y):421 pass422423 @app.route('/zzz_post', methods=['POST'])424 def aaa_post():425 pass426427 return app428429 cli = FlaskGroup(create_app=create_app)430 return partial(runner.invoke, cli)431432 def expect_order(self, order, output):433 # skip the header and match the start of each row434 for expect, line in zip(order, output.splitlines()[2:]):435 # do this instead of startswith for nicer pytest output436 assert line[:len(expect)] == expect437438 def test_simple(self, invoke):439 result = invoke(['routes'])440 assert result.exit_code == 0441 self.expect_order(442 ['aaa_post', 'static', 'yyy_get_post'],443 result.output444 )445446 def test_sort(self, invoke):447 default_output = invoke(['routes']).output448 endpoint_output = invoke(['routes', '-s', 'endpoint']).output449 assert default_output == endpoint_output450 self.expect_order(451 ['static', 'yyy_get_post', 'aaa_post'],452 invoke(['routes', '-s', 'methods']).output453 )454 self.expect_order(455 ['yyy_get_post', 'static', 'aaa_post'],456 invoke(['routes', '-s', 'rule']).output457 )458 self.expect_order(459 ['aaa_post', 'yyy_get_post', 'static'],460 invoke(['routes', '-s', 'match']).output461 )462463 def test_all_methods(self, invoke):464 output = invoke(['routes']).output465 assert 'GET, HEAD, OPTIONS, POST' not in output466 output = invoke(['routes', '--all-methods']).output467 assert 'GET, HEAD, OPTIONS, POST' in outputMerge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 468–510why, one step back468469470need_dotenv = pytest.mark.skipif(471 dotenv is None, reason='dotenv is not installed'472)473474475@need_dotenv476def test_load_dotenv(monkeypatch):477 # can't use monkeypatch.delitem since the keys don't exist yet478 for item in ('FOO', 'BAR', 'SPAM'):479 monkeypatch._setitem.append((os.environ, item, notset))480481 monkeypatch.setenv('EGGS', '3')482 monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))483 load_dotenv()484 assert os.getcwd() == test_path485 # .flaskenv doesn't overwrite .env486 assert os.environ['FOO'] == 'env'487 # set only in .flaskenv488 assert os.environ['BAR'] == 'bar'489 # set only in .env490 assert os.environ['SPAM'] == '1'491 # set manually, files don't overwrite492 assert os.environ['EGGS'] == '3'493494495@need_dotenv496def test_dotenv_path(monkeypatch):497 for item in ('FOO', 'BAR', 'EGGS'):498 monkeypatch._setitem.append((os.environ, item, notset))499500 cwd = os.getcwd()501 load_dotenv(os.path.join(test_path, '.flaskenv'))502 assert os.getcwd() == cwd503 assert 'FOO' in os.environ504505506def test_dotenv_optional(monkeypatch):507 monkeypatch.setattr('flask.cli.dotenv', None)508 monkeypatch.chdir(test_path)509 load_dotenv()510 assert 'FOO' not in os.environMerge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
lines 511–512why, one step back511512Merge pull request #2724 from pallets/issue-2722David Lordbefore adoption6f84cf4
lines 513–520why, one step back513@need_dotenv514def test_disable_dotenv_from_env(monkeypatch, runner):515 monkeypatch.chdir(test_path)516 monkeypatch.setitem(os.environ, 'FLASK_SKIP_DOTENV', '1')517 runner.invoke(FlaskGroup())518 assert 'FOO' not in os.environ519520Merge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
lines 521–559why, one step back521def test_run_cert_path():522 # no key523 with pytest.raises(click.BadParameter):524 run_command.make_context('run', ['--cert', __file__])525526 # no cert527 with pytest.raises(click.BadParameter):528 run_command.make_context('run', ['--key', __file__])529530 ctx = run_command.make_context(531 'run', ['--cert', __file__, '--key', __file__])532 assert ctx.params['cert'] == (__file__, __file__)533534535def test_run_cert_adhoc(monkeypatch):536 monkeypatch.setitem(sys.modules, 'OpenSSL', None)537538 # pyOpenSSL not installed539 with pytest.raises(click.BadParameter):540 run_command.make_context('run', ['--cert', 'adhoc'])541542 # pyOpenSSL installed543 monkeypatch.setitem(sys.modules, 'OpenSSL', types.ModuleType('OpenSSL'))544 ctx = run_command.make_context('run', ['--cert', 'adhoc'])545 assert ctx.params['cert'] == 'adhoc'546547 # no key with adhoc548 with pytest.raises(click.BadParameter):549 run_command.make_context('run', ['--cert', 'adhoc', '--key', __file__])550551552def test_run_cert_import(monkeypatch):553 monkeypatch.setitem(sys.modules, 'not_here', None)554555 # ImportError556 with pytest.raises(click.BadParameter):557 run_command.make_context('run', ['--cert', 'not_here'])558559 # not an SSLContextMerge pull request #2789 from briehanlombaard/fix-sslcontext-attribute-errorDavid Lordbefore adoption401d7f9
line 560why, one step back560 if sys.version_info >= (2, 7, 9):Merge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
lines 561–564why, one step back561 with pytest.raises(click.BadParameter):562 run_command.make_context('run', ['--cert', 'flask'])563564 # SSLContextMerge pull request #2789 from briehanlombaard/fix-sslcontext-attribute-errorDavid Lordbefore adoption401d7f9
line 565why, one step back565 if sys.version_info < (2, 7, 9):Merge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
lines 566–577why, one step back566 ssl_context = object()567 else:568 ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)569570 monkeypatch.setitem(sys.modules, 'ssl_context', ssl_context)571 ctx = run_command.make_context('run', ['--cert', 'ssl_context'])572 assert ctx.params['cert'] is ssl_context573574 # no --key with SSLContext575 with pytest.raises(click.BadParameter):576 run_command.make_context(577 'run', ['--cert', 'ssl_context', '--key', __file__])