test_cli.py
This file
Path
tests/test_cli.py
576 lines · 15.9 KiB · Python
Last changed by
Merge pull request #2963 from garenchan/bugfix-#2961David Lordbefore adoption0038a67
History of this fileTake it
The walk stopped after 200 commits: lines older than d2a46dc point at it.
fix doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
line 15why, one step back15import osMerge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
line 16why, one step back16import sslfix doc build errorDavid Lordbefore adoptiond2a46dc
line 17why, one step back17import sysMerge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
line 18why, one step back18import typesfix doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
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 doc build errorDavid Lordbefore adoptiond2a46dc
lines 241–260why, one step back241242243def test_get_version(test_apps, capsys):244 """Test of get_version."""245 from flask import __version__ as flask_ver246 from sys import version as py_ver247248 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()257 assert flask_ver in out258 assert py_ver in out259260Merge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a
line 261why, one step back261def test_scriptinfo(test_apps, monkeypatch):fix doc build errorDavid Lordbefore adoptiond2a46dc
lines 262–263why, one step back262 """Test of ScriptInfo."""263 obj = ScriptInfo(app_import_path="cliapp.app:testapp")Merge pull request #2963 from garenchan/bugfix-#2961David Lordbefore adoption0038a67
lines 264–266why, one step back264 app = obj.load_app()265 assert app.name == "testapp"266 assert obj.load_app() is appfix doc build errorDavid Lordbefore adoptiond2a46dc
line 267why, one step back267Merge pull request #2963 from garenchan/bugfix-#2961David Lordbefore adoption0038a67
lines 268–279why, one step back268 # import app with module's absolute path269 cli_app_path = os.path.abspath(os.path.join(270 os.path.dirname(__file__), 'test_apps', 'cliapp', 'app.py'))271 obj = ScriptInfo(app_import_path=cli_app_path)272 app = obj.load_app()273 assert app.name == 'testapp'274 assert obj.load_app() is app275 obj = ScriptInfo(app_import_path=cli_app_path + ':testapp')276 app = obj.load_app()277 assert app.name == 'testapp'278 assert obj.load_app() is app279fix doc build errorDavid Lordbefore adoptiond2a46dc
lines 280–285why, one step back280 def create_app(info):281 return Flask("createapp")282283 obj = ScriptInfo(create_app=create_app)284 app = obj.load_app()285 assert app.name == "createapp"Merge pull request #2963 from garenchan/bugfix-#2961David Lordbefore adoption0038a67
line 286why, one step back286 assert obj.load_app() is appMerge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a
lines 287–305why, one step back287288 obj = ScriptInfo()289 pytest.raises(NoAppException, obj.load_app)290291 # import app from wsgi.py in current directory292 monkeypatch.chdir(os.path.abspath(os.path.join(293 os.path.dirname(__file__), 'test_apps', 'helloworld'294 )))295 obj = ScriptInfo()296 app = obj.load_app()297 assert app.name == 'hello'298299 # import app from app.py in current directory300 monkeypatch.chdir(os.path.abspath(os.path.join(301 os.path.dirname(__file__), 'test_apps', 'cliapp'302 )))303 obj = ScriptInfo()304 app = obj.load_app()305 assert app.name == 'testapp'fix doc build errorDavid Lordbefore adoptiond2a46dc
lines 306–371why, one step back306307308def test_with_appcontext(runner):309 """Test of with_appcontext."""310311 @click.command()312 @with_appcontext313 def testcmd():314 click.echo(current_app.name)315316 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))317318 result = runner.invoke(testcmd, obj=obj)319 assert result.exit_code == 0320 assert result.output == 'testapp\n'321322323def test_appgroup(runner):324 """Test of with_appcontext."""325326 @click.group(cls=AppGroup)327 def cli():328 pass329330 @cli.command(with_appcontext=True)331 def test():332 click.echo(current_app.name)333334 @cli.group()335 def subgroup():336 pass337338 @subgroup.command(with_appcontext=True)339 def test2():340 click.echo(current_app.name)341342 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))343344 result = runner.invoke(cli, ['test'], obj=obj)345 assert result.exit_code == 0346 assert result.output == 'testappgroup\n'347348 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)349 assert result.exit_code == 0350 assert result.output == 'testappgroup\n'351352353def test_flaskgroup(runner):354 """Test FlaskGroup."""355356 def create_app(info):357 return Flask("flaskgroup")358359 @click.group(cls=FlaskGroup, create_app=create_app)360 def cli(**params):361 pass362363 @cli.command()364 def test():365 click.echo(current_app.name)366367 result = runner.invoke(cli, ['test'])368 assert result.exit_code == 0369 assert result.output == 'flaskgroup\n'370371Merge pull request #2765 from ThiefMaster/custom-cli-ignore-debugAdrianbefore adoption1a9caed
lines 372–393why, one step back372@pytest.mark.parametrize('set_debug_flag', (True, False))373def test_flaskgroup_debug(runner, set_debug_flag):374 """Test FlaskGroup debug flag behavior."""375376 def create_app(info):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 == '%s\n' % str(not set_debug_flag)392393fix doc build errorDavid Lordbefore adoptiond2a46dc
lines 394–466why, one step back394def test_print_exceptions(runner):395 """Print the stacktrace if the CLI."""396397 def create_app(info):398 raise Exception("oh no")399 return Flask("flaskgroup")400401 @click.group(cls=FlaskGroup, create_app=create_app)402 def cli(**params):403 pass404405 result = runner.invoke(cli, ['--help'])406 assert result.exit_code == 0407 assert 'Exception: oh no' in result.output408 assert 'Traceback' in result.output409410411class TestRoutes:412 @pytest.fixture413 def invoke(self, runner):414 def create_app(info):415 app = Flask(__name__)416 app.testing = True417418 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])419 def yyy_get_post(x, y):420 pass421422 @app.route('/zzz_post', methods=['POST'])423 def aaa_post():424 pass425426 return app427428 cli = FlaskGroup(create_app=create_app)429 return partial(runner.invoke, cli)430431 def expect_order(self, order, output):432 # skip the header and match the start of each row433 for expect, line in zip(order, output.splitlines()[2:]):434 # do this instead of startswith for nicer pytest output435 assert line[:len(expect)] == expect436437 def test_simple(self, invoke):438 result = invoke(['routes'])439 assert result.exit_code == 0440 self.expect_order(441 ['aaa_post', 'static', 'yyy_get_post'],442 result.output443 )444445 def test_sort(self, invoke):446 default_output = invoke(['routes']).output447 endpoint_output = invoke(['routes', '-s', 'endpoint']).output448 assert default_output == endpoint_output449 self.expect_order(450 ['static', 'yyy_get_post', 'aaa_post'],451 invoke(['routes', '-s', 'methods']).output452 )453 self.expect_order(454 ['yyy_get_post', 'static', 'aaa_post'],455 invoke(['routes', '-s', 'rule']).output456 )457 self.expect_order(458 ['aaa_post', 'yyy_get_post', 'static'],459 invoke(['routes', '-s', 'match']).output460 )461462 def test_all_methods(self, invoke):463 output = invoke(['routes']).output464 assert 'GET, HEAD, OPTIONS, POST' not in output465 output = invoke(['routes', '--all-methods']).output466 assert 'GET, HEAD, OPTIONS, POST' in outputMerge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 467–509why, one step back467468469need_dotenv = pytest.mark.skipif(470 dotenv is None, reason='dotenv is not installed'471)472473474@need_dotenv475def test_load_dotenv(monkeypatch):476 # can't use monkeypatch.delitem since the keys don't exist yet477 for item in ('FOO', 'BAR', 'SPAM'):478 monkeypatch._setitem.append((os.environ, item, notset))479480 monkeypatch.setenv('EGGS', '3')481 monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))482 load_dotenv()483 assert os.getcwd() == test_path484 # .flaskenv doesn't overwrite .env485 assert os.environ['FOO'] == 'env'486 # set only in .flaskenv487 assert os.environ['BAR'] == 'bar'488 # set only in .env489 assert os.environ['SPAM'] == '1'490 # set manually, files don't overwrite491 assert os.environ['EGGS'] == '3'492493494@need_dotenv495def test_dotenv_path(monkeypatch):496 for item in ('FOO', 'BAR', 'EGGS'):497 monkeypatch._setitem.append((os.environ, item, notset))498499 cwd = os.getcwd()500 load_dotenv(os.path.join(test_path, '.flaskenv'))501 assert os.getcwd() == cwd502 assert 'FOO' in os.environ503504505def test_dotenv_optional(monkeypatch):506 monkeypatch.setattr('flask.cli.dotenv', None)507 monkeypatch.chdir(test_path)508 load_dotenv()509 assert 'FOO' not in os.environMerge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
lines 510–511why, one step back510511Merge pull request #2724 from pallets/issue-2722David Lordbefore adoption6f84cf4
lines 512–519why, one step back512@need_dotenv513def test_disable_dotenv_from_env(monkeypatch, runner):514 monkeypatch.chdir(test_path)515 monkeypatch.setitem(os.environ, 'FLASK_SKIP_DOTENV', '1')516 runner.invoke(FlaskGroup())517 assert 'FOO' not in os.environ518519Merge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
lines 520–558why, one step back520def test_run_cert_path():521 # no key522 with pytest.raises(click.BadParameter):523 run_command.make_context('run', ['--cert', __file__])524525 # no cert526 with pytest.raises(click.BadParameter):527 run_command.make_context('run', ['--key', __file__])528529 ctx = run_command.make_context(530 'run', ['--cert', __file__, '--key', __file__])531 assert ctx.params['cert'] == (__file__, __file__)532533534def test_run_cert_adhoc(monkeypatch):535 monkeypatch.setitem(sys.modules, 'OpenSSL', None)536537 # pyOpenSSL not installed538 with pytest.raises(click.BadParameter):539 run_command.make_context('run', ['--cert', 'adhoc'])540541 # pyOpenSSL installed542 monkeypatch.setitem(sys.modules, 'OpenSSL', types.ModuleType('OpenSSL'))543 ctx = run_command.make_context('run', ['--cert', 'adhoc'])544 assert ctx.params['cert'] == 'adhoc'545546 # no key with adhoc547 with pytest.raises(click.BadParameter):548 run_command.make_context('run', ['--cert', 'adhoc', '--key', __file__])549550551def test_run_cert_import(monkeypatch):552 monkeypatch.setitem(sys.modules, 'not_here', None)553554 # ImportError555 with pytest.raises(click.BadParameter):556 run_command.make_context('run', ['--cert', 'not_here'])557558 # not an SSLContextMerge pull request #2789 from briehanlombaard/fix-sslcontext-attribute-errorDavid Lordbefore adoption401d7f9
line 559why, one step back559 if sys.version_info >= (2, 7, 9):Merge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
lines 560–563why, one step back560 with pytest.raises(click.BadParameter):561 run_command.make_context('run', ['--cert', 'flask'])562563 # SSLContextMerge pull request #2789 from briehanlombaard/fix-sslcontext-attribute-errorDavid Lordbefore adoption401d7f9
line 564why, one step back564 if sys.version_info < (2, 7, 9):Merge pull request #2606 from pallets/run-sslDavid Lordbefore adoption8ff0cef
lines 565–576why, one step back565 ssl_context = object()566 else:567 ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)568569 monkeypatch.setitem(sys.modules, 'ssl_context', ssl_context)570 ctx = run_command.make_context('run', ['--cert', 'ssl_context'])571 assert ctx.params['cert'] is ssl_context572573 # no --key with SSLContext574 with pytest.raises(click.BadParameter):575 run_command.make_context(576 'run', ['--cert', 'ssl_context', '--key', __file__])