test_cli.py
This file
Path
tests/test_cli.py
368 lines · 10.6 KiB · Python
Last changed by
Merge branch 'master' into json-object-hookDavid Lordbefore adoptionea2e960
History of this fileTake it
1# -*- 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#14from __future__ import absolute_import, print_function15import os16import sys17from functools import partial1819import click20import pytest21from click.testing import CliRunner22from flask import Flask, current_app2324from flask.cli import cli, AppGroup, FlaskGroup, NoAppException, ScriptInfo, \25 find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \26 find_default_import_path, get_version272829@pytest.fixture30def runner():31 return CliRunner()323334def test_cli_name(test_apps):35 """Make sure the CLI object's name is the app's name and not the app itself"""36 from cliapp.app import testapp37 assert testapp.cli.name == testapp.name383940def test_find_best_app(test_apps):41 """Test if `find_best_app` behaves as expected with different combinations of input."""42 script_info = ScriptInfo()4344 class Module:45 app = Flask('appname')4647 assert find_best_app(script_info, Module) == Module.app4849 class Module:50 application = Flask('appname')5152 assert find_best_app(script_info, Module) == Module.application5354 class Module:55 myapp = Flask('appname')5657 assert find_best_app(script_info, Module) == Module.myapp5859 class Module:60 @staticmethod61 def create_app():62 return Flask('appname')6364 assert isinstance(find_best_app(script_info, Module), Flask)65 assert find_best_app(script_info, Module).name == 'appname'6667 class Module:68 @staticmethod69 def create_app(foo):70 return Flask('appname')7172 assert isinstance(find_best_app(script_info, Module), Flask)73 assert find_best_app(script_info, Module).name == 'appname'7475 class Module:76 @staticmethod77 def create_app(foo=None, script_info=None):78 return Flask('appname')7980 assert isinstance(find_best_app(script_info, Module), Flask)81 assert find_best_app(script_info, Module).name == 'appname'8283 class Module:84 @staticmethod85 def make_app():86 return Flask('appname')8788 assert isinstance(find_best_app(script_info, Module), Flask)89 assert find_best_app(script_info, Module).name == 'appname'9091 class Module:92 myapp = Flask('appname1')9394 @staticmethod95 def create_app():96 return Flask('appname2')9798 assert find_best_app(script_info, Module) == Module.myapp99100 class Module:101 myapp = Flask('appname1')102103 @staticmethod104 def create_app():105 return Flask('appname2')106107 assert find_best_app(script_info, Module) == Module.myapp108109 class Module:110 pass111112 pytest.raises(NoAppException, find_best_app, script_info, Module)113114 class Module:115 myapp1 = Flask('appname1')116 myapp2 = Flask('appname2')117118 pytest.raises(NoAppException, find_best_app, script_info, Module)119120 class Module:121 @staticmethod122 def create_app(foo, bar):123 return Flask('appname2')124125 pytest.raises(NoAppException, find_best_app, script_info, Module)126127128def test_prepare_exec_for_file(test_apps):129 """Expect the correct path to be set and the correct module name to be returned.130131 :func:`prepare_exec_for_file` has a side effect, where132 the parent directory of given file is added to `sys.path`.133 """134 realpath = os.path.realpath('/tmp/share/test.py')135 dirname = os.path.dirname(realpath)136 assert prepare_exec_for_file('/tmp/share/test.py') == 'test'137 assert dirname in sys.path138139 realpath = os.path.realpath('/tmp/share/__init__.py')140 dirname = os.path.dirname(os.path.dirname(realpath))141 assert prepare_exec_for_file('/tmp/share/__init__.py') == 'share'142 assert dirname in sys.path143144 with pytest.raises(NoAppException):145 prepare_exec_for_file('/tmp/share/test.txt')146147148def test_locate_app(test_apps):149 """Test of locate_app."""150 script_info = ScriptInfo()151 assert locate_app(script_info, "cliapp.app").name == "testapp"152 assert locate_app(script_info, "cliapp.app:testapp").name == "testapp"153 assert locate_app(script_info, "cliapp.factory").name == "create_app"154 assert locate_app(155 script_info, "cliapp.factory").name == "create_app"156 assert locate_app(157 script_info, "cliapp.factory:create_app").name == "create_app"158 assert locate_app(159 script_info, "cliapp.factory:create_app()").name == "create_app"160 assert locate_app(161 script_info, "cliapp.factory:create_app2('foo', 'bar')"162 ).name == "create_app2_foo_bar"163 assert locate_app(164 script_info, "cliapp.factory:create_app2('foo', 'bar', )"165 ).name == "create_app2_foo_bar"166 assert locate_app(167 script_info, "cliapp.factory:create_app3('baz', 'qux')"168 ).name == "create_app3_baz_qux"169 assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1"170 pytest.raises(171 NoAppException, locate_app, script_info, "notanpp.py")172 pytest.raises(173 NoAppException, locate_app, script_info, "cliapp/app")174 pytest.raises(175 RuntimeError, locate_app, script_info, "cliapp.app:notanapp")176 pytest.raises(177 NoAppException, locate_app,178 script_info, "cliapp.factory:create_app2('foo')")179 pytest.raises(180 NoAppException, locate_app,181 script_info, "cliapp.factory:create_app ()")182 pytest.raises(183 NoAppException, locate_app, script_info, "cliapp.importerrorapp")184185186def test_find_default_import_path(test_apps, monkeypatch, tmpdir):187 """Test of find_default_import_path."""188 monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)189 assert find_default_import_path() == None190 monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')191 assert find_default_import_path() == 'notanapp'192 tmpfile = tmpdir.join('testapp.py')193 tmpfile.write('')194 monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))195 expect_rv = prepare_exec_for_file(str(tmpfile))196 assert find_default_import_path() == expect_rv197198199def test_get_version(test_apps, capsys):200 """Test of get_version."""201 from flask import __version__ as flask_ver202 from sys import version as py_ver203204 class MockCtx(object):205 resilient_parsing = False206 color = None207208 def exit(self): return209210 ctx = MockCtx()211 get_version(ctx, None, "test")212 out, err = capsys.readouterr()213 assert flask_ver in out214 assert py_ver in out215216217def test_scriptinfo(test_apps):218 """Test of ScriptInfo."""219 obj = ScriptInfo(app_import_path="cliapp.app:testapp")220 assert obj.load_app().name == "testapp"221 assert obj.load_app().name == "testapp"222223 def create_app(info):224 return Flask("createapp")225226 obj = ScriptInfo(create_app=create_app)227 app = obj.load_app()228 assert app.name == "createapp"229 assert obj.load_app() == app230231232def test_with_appcontext(runner):233 """Test of with_appcontext."""234235 @click.command()236 @with_appcontext237 def testcmd():238 click.echo(current_app.name)239240 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))241242 result = runner.invoke(testcmd, obj=obj)243 assert result.exit_code == 0244 assert result.output == 'testapp\n'245246247def test_appgroup(runner):248 """Test of with_appcontext."""249250 @click.group(cls=AppGroup)251 def cli():252 pass253254 @cli.command(with_appcontext=True)255 def test():256 click.echo(current_app.name)257258 @cli.group()259 def subgroup():260 pass261262 @subgroup.command(with_appcontext=True)263 def test2():264 click.echo(current_app.name)265266 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))267268 result = runner.invoke(cli, ['test'], obj=obj)269 assert result.exit_code == 0270 assert result.output == 'testappgroup\n'271272 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)273 assert result.exit_code == 0274 assert result.output == 'testappgroup\n'275276277def test_flaskgroup(runner):278 """Test FlaskGroup."""279280 def create_app(info):281 return Flask("flaskgroup")282283 @click.group(cls=FlaskGroup, create_app=create_app)284 def cli(**params):285 pass286287 @cli.command()288 def test():289 click.echo(current_app.name)290291 result = runner.invoke(cli, ['test'])292 assert result.exit_code == 0293 assert result.output == 'flaskgroup\n'294295296def test_print_exceptions(runner):297 """Print the stacktrace if the CLI."""298299 def create_app(info):300 raise Exception("oh no")301 return Flask("flaskgroup")302303 @click.group(cls=FlaskGroup, create_app=create_app)304 def cli(**params):305 pass306307 result = runner.invoke(cli, ['--help'])308 assert result.exit_code == 0309 assert 'Exception: oh no' in result.output310 assert 'Traceback' in result.output311312313class TestRoutes:314 @pytest.fixture315 def invoke(self, runner):316 def create_app(info):317 app = Flask(__name__)318 app.testing = True319320 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])321 def yyy_get_post(x, y):322 pass323324 @app.route('/zzz_post', methods=['POST'])325 def aaa_post():326 pass327328 return app329330 cli = FlaskGroup(create_app=create_app)331 return partial(runner.invoke, cli)332333 def expect_order(self, order, output):334 # skip the header and match the start of each row335 for expect, line in zip(order, output.splitlines()[2:]):336 # do this instead of startswith for nicer pytest output337 assert line[:len(expect)] == expect338339 def test_simple(self, invoke):340 result = invoke(['routes'])341 assert result.exit_code == 0342 self.expect_order(343 ['aaa_post', 'static', 'yyy_get_post'],344 result.output345 )346347 def test_sort(self, invoke):348 default_output = invoke(['routes']).output349 endpoint_output = invoke(['routes', '-s', 'endpoint']).output350 assert default_output == endpoint_output351 self.expect_order(352 ['static', 'yyy_get_post', 'aaa_post'],353 invoke(['routes', '-s', 'methods']).output354 )355 self.expect_order(356 ['yyy_get_post', 'static', 'aaa_post'],357 invoke(['routes', '-s', 'rule']).output358 )359 self.expect_order(360 ['aaa_post', 'yyy_get_post', 'static'],361 invoke(['routes', '-s', 'match']).output362 )363364 def test_all_methods(self, invoke):365 output = invoke(['routes']).output366 assert 'GET, HEAD, OPTIONS, POST' not in output367 output = invoke(['routes', '--all-methods']).output368 assert 'GET, HEAD, OPTIONS, POST' in output