test_cli.py
This file
Path
tests/test_cli.py
477 lines · 13.1 KiB · Python
Last changed by
Merge pull request #2490 from davidism/cli-reviewDavid Lordbefore adoption0932d8f
History of this fileTake it
resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 1–13why, one step back1# -*- coding: utf-8 -*-2"""3 tests.test_cli4 ~~~~~~~~~~~~~~56 :copyright: (c) 2016 by the Flask Team, see AUTHORS for more details.7 :license: BSD, see LICENSE for more details.8"""9#10# This file was part of Flask-CLI and was modified under the terms its license,11# the Revised BSD License.12# Copyright (C) 2015 CERN.13#Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 14–15why, one step back14from __future__ import absolute_import15resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 16–21why, one step back16import os17import sys18from functools import partial1920import click21import pytestMerge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
line 22why, one step back22from _pytest.monkeypatch import notsetresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 23why, one step back23from click.testing import CliRunnerMerge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
line 24why, one step back24resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 25why, one step back25from flask import Flask, current_appMerge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 26–28why, one step back26from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, \27 find_best_app, get_version, load_dotenv, locate_app, prepare_import, \28 with_appcontextresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 29why, one step back29Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 30–33why, one step back30cwd = os.getcwd()31test_path = os.path.abspath(os.path.join(32 os.path.dirname(__file__), 'test_apps'33))resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 34why, one step back34Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 35–48why, one step back3536@pytest.fixture(autouse=True)37def manage_os_environ(monkeypatch):38 # can't use monkeypatch.delitem since we don't want to restore a value39 os.environ.pop('FLASK_APP', None)40 os.environ.pop('FLASK_DEBUG', None)41 # use monkeypatch internals to force-delete environ keys42 monkeypatch._setitem.extend((43 (os.environ, 'FLASK_APP', notset),44 (os.environ, 'FLASK_DEBUG', notset),45 (os.environ, 'FLASK_RUN_FROM_CLI', notset),46 ))4748resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 49–147why, one step back49@pytest.fixture50def runner():51 return CliRunner()525354def test_cli_name(test_apps):55 """Make sure the CLI object's name is the app's name and not the app itself"""56 from cliapp.app import testapp57 assert testapp.cli.name == testapp.name585960def test_find_best_app(test_apps):61 """Test if `find_best_app` behaves as expected with different combinations of input."""62 script_info = ScriptInfo()6364 class Module:65 app = Flask('appname')6667 assert find_best_app(script_info, Module) == Module.app6869 class Module:70 application = Flask('appname')7172 assert find_best_app(script_info, Module) == Module.application7374 class Module:75 myapp = Flask('appname')7677 assert find_best_app(script_info, Module) == Module.myapp7879 class Module:80 @staticmethod81 def create_app():82 return Flask('appname')8384 assert isinstance(find_best_app(script_info, Module), Flask)85 assert find_best_app(script_info, Module).name == 'appname'8687 class Module:88 @staticmethod89 def create_app(foo):90 return Flask('appname')9192 assert isinstance(find_best_app(script_info, Module), Flask)93 assert find_best_app(script_info, Module).name == 'appname'9495 class Module:96 @staticmethod97 def create_app(foo=None, script_info=None):98 return Flask('appname')99100 assert isinstance(find_best_app(script_info, Module), Flask)101 assert find_best_app(script_info, Module).name == 'appname'102103 class Module:104 @staticmethod105 def make_app():106 return Flask('appname')107108 assert isinstance(find_best_app(script_info, Module), Flask)109 assert find_best_app(script_info, Module).name == 'appname'110111 class Module:112 myapp = Flask('appname1')113114 @staticmethod115 def create_app():116 return Flask('appname2')117118 assert find_best_app(script_info, Module) == Module.myapp119120 class Module:121 myapp = Flask('appname1')122123 @staticmethod124 def create_app():125 return Flask('appname2')126127 assert find_best_app(script_info, Module) == Module.myapp128129 class Module:130 pass131132 pytest.raises(NoAppException, find_best_app, script_info, Module)133134 class Module:135 myapp1 = Flask('appname1')136 myapp2 = Flask('appname2')137138 pytest.raises(NoAppException, find_best_app, script_info, Module)139140 class Module:141 @staticmethod142 def create_app(foo, bar):143 return Flask('appname2')144145 pytest.raises(NoAppException, find_best_app, script_info, Module)146147Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 148–178why, one step back148@pytest.mark.parametrize('value,path,result', (149 ('test', cwd, 'test'),150 ('test.py', cwd, 'test'),151 ('a/test', os.path.join(cwd, 'a'), 'test'),152 ('test/__init__.py', cwd, 'test'),153 ('test/__init__', cwd, 'test'),154 # nested package155 (156 os.path.join(test_path, 'cliapp', 'inner1', '__init__'),157 test_path, 'cliapp.inner1'158 ),159 (160 os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),161 test_path, 'cliapp.inner1.inner2'162 ),163 # dotted name164 ('test.a.b', cwd, 'test.a.b'),165 (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),166 # not a Python file, will be caught during import167 (168 os.path.join(test_path, 'cliapp', 'message.txt'),169 test_path, 'cliapp.message.txt'170 ),171))172def test_prepare_import(request, value, path, result):173 """Expect the correct path to be set and the correct import and app names174 to be returned.175176 :func:`prepare_exec_for_file` has a side effect where the parent directory177 of the given import is added to :data:`sys.path`. This is reset after the178 test runs.resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 179why, one step back179 """Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
line 180why, one step back180 original_path = sys.path[:]resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 181why, one step back181Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 182–183why, one step back182 def reset_path():183 sys.path[:] = original_pathresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 184why, one step back184Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
line 185why, one step back185 request.addfinalizer(reset_path)resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 186why, one step back186Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 187–188why, one step back187 assert prepare_import(value) == result188 assert sys.path[0] == pathresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 189–190why, one step back189190Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 191–202why, one step back191@pytest.mark.parametrize('iname,aname,result', (192 ('cliapp.app', None, 'testapp'),193 ('cliapp.app', 'testapp', 'testapp'),194 ('cliapp.factory', None, 'app'),195 ('cliapp.factory', 'create_app', 'app'),196 ('cliapp.factory', 'create_app()', 'app'),197 # no script_info198 ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),199 # trailing comma space200 ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),201 # takes script_info202 ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),Merge pull request #2490 from davidism/cli-reviewDavid Lordbefore adoption0932d8f
lines 203–204why, one step back203 # strip whitespace204 ('cliapp.factory', ' create_app () ', 'app'),Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 205–209why, one step back205))206def test_locate_app(test_apps, iname, aname, result):207 info = ScriptInfo()208 info.data['test'] = 'spam'209 assert locate_app(info, iname, aname).name == resultresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 210why, one step back210Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 211–217why, one step back211212@pytest.mark.parametrize('iname,aname', (213 ('notanapp.py', None),214 ('cliapp/app', None),215 ('cliapp.app', 'notanapp'),216 # not enough arguments217 ('cliapp.factory', 'create_app2("foo")'),Merge pull request #2490 from davidism/cli-reviewDavid Lordbefore adoption0932d8f
lines 218–221why, one step back218 # invalid identifier219 ('cliapp.factory', 'create_app('),220 # no app returned221 ('cliapp.factory', 'no_app'),Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 222–243why, one step back222 # nested import error223 ('cliapp.importerrorapp', None),224 # not a Python file225 ('cliapp.message.txt', None),226))227def test_locate_app_raises(test_apps, iname, aname):228 info = ScriptInfo()229230 with pytest.raises(NoAppException):231 locate_app(info, iname, aname)232233234def test_locate_app_suppress_raise():235 info = ScriptInfo()236 app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)237 assert app is None238239 # only direct import error is suppressed240 with pytest.raises(NoAppException):241 locate_app(242 info, 'cliapp.importerrorapp', None, raise_if_not_found=False243 )resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 244–263why, one step back244245246def test_get_version(test_apps, capsys):247 """Test of get_version."""248 from flask import __version__ as flask_ver249 from sys import version as py_ver250251 class MockCtx(object):252 resilient_parsing = False253 color = None254255 def exit(self): return256257 ctx = MockCtx()258 get_version(ctx, None, "test")259 out, err = capsys.readouterr()260 assert flask_ver in out261 assert py_ver in out262263Merge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a
line 264why, one step back264def test_scriptinfo(test_apps, monkeypatch):resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 265–276why, one step back265 """Test of ScriptInfo."""266 obj = ScriptInfo(app_import_path="cliapp.app:testapp")267 assert obj.load_app().name == "testapp"268 assert obj.load_app().name == "testapp"269270 def create_app(info):271 return Flask("createapp")272273 obj = ScriptInfo(create_app=create_app)274 app = obj.load_app()275 assert app.name == "createapp"276 assert obj.load_app() == appMerge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a
lines 277–295why, one step back277278 obj = ScriptInfo()279 pytest.raises(NoAppException, obj.load_app)280281 # import app from wsgi.py in current directory282 monkeypatch.chdir(os.path.abspath(os.path.join(283 os.path.dirname(__file__), 'test_apps', 'helloworld'284 )))285 obj = ScriptInfo()286 app = obj.load_app()287 assert app.name == 'hello'288289 # import app from app.py in current directory290 monkeypatch.chdir(os.path.abspath(os.path.join(291 os.path.dirname(__file__), 'test_apps', 'cliapp'292 )))293 obj = ScriptInfo()294 app = obj.load_app()295 assert app.name == 'testapp'resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 296–434why, one step back296297298def test_with_appcontext(runner):299 """Test of with_appcontext."""300301 @click.command()302 @with_appcontext303 def testcmd():304 click.echo(current_app.name)305306 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))307308 result = runner.invoke(testcmd, obj=obj)309 assert result.exit_code == 0310 assert result.output == 'testapp\n'311312313def test_appgroup(runner):314 """Test of with_appcontext."""315316 @click.group(cls=AppGroup)317 def cli():318 pass319320 @cli.command(with_appcontext=True)321 def test():322 click.echo(current_app.name)323324 @cli.group()325 def subgroup():326 pass327328 @subgroup.command(with_appcontext=True)329 def test2():330 click.echo(current_app.name)331332 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))333334 result = runner.invoke(cli, ['test'], obj=obj)335 assert result.exit_code == 0336 assert result.output == 'testappgroup\n'337338 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)339 assert result.exit_code == 0340 assert result.output == 'testappgroup\n'341342343def test_flaskgroup(runner):344 """Test FlaskGroup."""345346 def create_app(info):347 return Flask("flaskgroup")348349 @click.group(cls=FlaskGroup, create_app=create_app)350 def cli(**params):351 pass352353 @cli.command()354 def test():355 click.echo(current_app.name)356357 result = runner.invoke(cli, ['test'])358 assert result.exit_code == 0359 assert result.output == 'flaskgroup\n'360361362def test_print_exceptions(runner):363 """Print the stacktrace if the CLI."""364365 def create_app(info):366 raise Exception("oh no")367 return Flask("flaskgroup")368369 @click.group(cls=FlaskGroup, create_app=create_app)370 def cli(**params):371 pass372373 result = runner.invoke(cli, ['--help'])374 assert result.exit_code == 0375 assert 'Exception: oh no' in result.output376 assert 'Traceback' in result.output377378379class TestRoutes:380 @pytest.fixture381 def invoke(self, runner):382 def create_app(info):383 app = Flask(__name__)384 app.testing = True385386 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])387 def yyy_get_post(x, y):388 pass389390 @app.route('/zzz_post', methods=['POST'])391 def aaa_post():392 pass393394 return app395396 cli = FlaskGroup(create_app=create_app)397 return partial(runner.invoke, cli)398399 def expect_order(self, order, output):400 # skip the header and match the start of each row401 for expect, line in zip(order, output.splitlines()[2:]):402 # do this instead of startswith for nicer pytest output403 assert line[:len(expect)] == expect404405 def test_simple(self, invoke):406 result = invoke(['routes'])407 assert result.exit_code == 0408 self.expect_order(409 ['aaa_post', 'static', 'yyy_get_post'],410 result.output411 )412413 def test_sort(self, invoke):414 default_output = invoke(['routes']).output415 endpoint_output = invoke(['routes', '-s', 'endpoint']).output416 assert default_output == endpoint_output417 self.expect_order(418 ['static', 'yyy_get_post', 'aaa_post'],419 invoke(['routes', '-s', 'methods']).output420 )421 self.expect_order(422 ['yyy_get_post', 'static', 'aaa_post'],423 invoke(['routes', '-s', 'rule']).output424 )425 self.expect_order(426 ['aaa_post', 'yyy_get_post', 'static'],427 invoke(['routes', '-s', 'match']).output428 )429430 def test_all_methods(self, invoke):431 output = invoke(['routes']).output432 assert 'GET, HEAD, OPTIONS, POST' not in output433 output = invoke(['routes', '--all-methods']).output434 assert 'GET, HEAD, OPTIONS, POST' in outputMerge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 435–477why, one step back435436437need_dotenv = pytest.mark.skipif(438 dotenv is None, reason='dotenv is not installed'439)440441442@need_dotenv443def test_load_dotenv(monkeypatch):444 # can't use monkeypatch.delitem since the keys don't exist yet445 for item in ('FOO', 'BAR', 'SPAM'):446 monkeypatch._setitem.append((os.environ, item, notset))447448 monkeypatch.setenv('EGGS', '3')449 monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))450 load_dotenv()451 assert os.getcwd() == test_path452 # .flaskenv doesn't overwrite .env453 assert os.environ['FOO'] == 'env'454 # set only in .flaskenv455 assert os.environ['BAR'] == 'bar'456 # set only in .env457 assert os.environ['SPAM'] == '1'458 # set manually, files don't overwrite459 assert os.environ['EGGS'] == '3'460461462@need_dotenv463def test_dotenv_path(monkeypatch):464 for item in ('FOO', 'BAR', 'EGGS'):465 monkeypatch._setitem.append((os.environ, item, notset))466467 cwd = os.getcwd()468 load_dotenv(os.path.join(test_path, '.flaskenv'))469 assert os.getcwd() == cwd470 assert 'FOO' in os.environ471472473def test_dotenv_optional(monkeypatch):474 monkeypatch.setattr('flask.cli.dotenv', None)475 monkeypatch.chdir(test_path)476 load_dotenv()477 assert 'FOO' not in os.environ