Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

390 lines · 11.3 KiB · Python

Last changed by

Merge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a

History of this file

Take it

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 1–152why, one step back
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"

Merge pull request #2326 from HndrkMkt/#2264-handle-app-factory-in-FLASK_APPKenneth Reitzbefore adoption090109b

lines 153–168why, one step back
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"

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 169why, one step back
169 assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1"

Merge pull request #2326 from HndrkMkt/#2264-handle-app-factory-in-FLASK_APPKenneth Reitzbefore adoption090109b

lines 170–183why, one step back
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")

Merge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a

lines 184–186why, one step back
184 assert locate_app(
185 script_info, "notanpp.py", raise_if_not_found=False186 ) is None

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 187–219why, one step back
187
188189def test_find_default_import_path(test_apps, monkeypatch, tmpdir):190 """Test of find_default_import_path."""191 monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)192 assert find_default_import_path() == None193 monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')194 assert find_default_import_path() == 'notanapp'195 tmpfile = tmpdir.join('testapp.py')196 tmpfile.write('')197 monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))198 expect_rv = prepare_exec_for_file(str(tmpfile))199 assert find_default_import_path() == expect_rv200201202def test_get_version(test_apps, capsys):203 """Test of get_version."""204 from flask import __version__ as flask_ver205 from sys import version as py_ver206207 class MockCtx(object):208 resilient_parsing = False209 color = None210211 def exit(self): return212213 ctx = MockCtx()214 get_version(ctx, None, "test")215 out, err = capsys.readouterr()216 assert flask_ver in out217 assert py_ver in out218219

Merge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a

line 220why, one step back
220def test_scriptinfo(test_apps, monkeypatch):

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 221–232why, one step back
221 """Test of ScriptInfo."""
222 obj = ScriptInfo(app_import_path="cliapp.app:testapp")223 assert obj.load_app().name == "testapp"224 assert obj.load_app().name == "testapp"225226 def create_app(info):227 return Flask("createapp")228229 obj = ScriptInfo(create_app=create_app)230 app = obj.load_app()231 assert app.name == "createapp"232 assert obj.load_app() == app

Merge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a

lines 233–251why, one step back
233
234 obj = ScriptInfo()235 pytest.raises(NoAppException, obj.load_app)236237 # import app from wsgi.py in current directory238 monkeypatch.chdir(os.path.abspath(os.path.join(239 os.path.dirname(__file__), 'test_apps', 'helloworld'240 )))241 obj = ScriptInfo()242 app = obj.load_app()243 assert app.name == 'hello'244245 # import app from app.py in current directory246 monkeypatch.chdir(os.path.abspath(os.path.join(247 os.path.dirname(__file__), 'test_apps', 'cliapp'248 )))249 obj = ScriptInfo()250 app = obj.load_app()251 assert app.name == 'testapp'

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 252–390why, one step back
252
253254def test_with_appcontext(runner):255 """Test of with_appcontext."""256257 @click.command()258 @with_appcontext259 def testcmd():260 click.echo(current_app.name)261262 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))263264 result = runner.invoke(testcmd, obj=obj)265 assert result.exit_code == 0266 assert result.output == 'testapp\n'267268269def test_appgroup(runner):270 """Test of with_appcontext."""271272 @click.group(cls=AppGroup)273 def cli():274 pass275276 @cli.command(with_appcontext=True)277 def test():278 click.echo(current_app.name)279280 @cli.group()281 def subgroup():282 pass283284 @subgroup.command(with_appcontext=True)285 def test2():286 click.echo(current_app.name)287288 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))289290 result = runner.invoke(cli, ['test'], obj=obj)291 assert result.exit_code == 0292 assert result.output == 'testappgroup\n'293294 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)295 assert result.exit_code == 0296 assert result.output == 'testappgroup\n'297298299def test_flaskgroup(runner):300 """Test FlaskGroup."""301302 def create_app(info):303 return Flask("flaskgroup")304305 @click.group(cls=FlaskGroup, create_app=create_app)306 def cli(**params):307 pass308309 @cli.command()310 def test():311 click.echo(current_app.name)312313 result = runner.invoke(cli, ['test'])314 assert result.exit_code == 0315 assert result.output == 'flaskgroup\n'316317318def test_print_exceptions(runner):319 """Print the stacktrace if the CLI."""320321 def create_app(info):322 raise Exception("oh no")323 return Flask("flaskgroup")324325 @click.group(cls=FlaskGroup, create_app=create_app)326 def cli(**params):327 pass328329 result = runner.invoke(cli, ['--help'])330 assert result.exit_code == 0331 assert 'Exception: oh no' in result.output332 assert 'Traceback' in result.output333334335class TestRoutes:336 @pytest.fixture337 def invoke(self, runner):338 def create_app(info):339 app = Flask(__name__)340 app.testing = True341342 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])343 def yyy_get_post(x, y):344 pass345346 @app.route('/zzz_post', methods=['POST'])347 def aaa_post():348 pass349350 return app351352 cli = FlaskGroup(create_app=create_app)353 return partial(runner.invoke, cli)354355 def expect_order(self, order, output):356 # skip the header and match the start of each row357 for expect, line in zip(order, output.splitlines()[2:]):358 # do this instead of startswith for nicer pytest output359 assert line[:len(expect)] == expect360361 def test_simple(self, invoke):362 result = invoke(['routes'])363 assert result.exit_code == 0364 self.expect_order(365 ['aaa_post', 'static', 'yyy_get_post'],366 result.output367 )368369 def test_sort(self, invoke):370 default_output = invoke(['routes']).output371 endpoint_output = invoke(['routes', '-s', 'endpoint']).output372 assert default_output == endpoint_output373 self.expect_order(374 ['static', 'yyy_get_post', 'aaa_post'],375 invoke(['routes', '-s', 'methods']).output376 )377 self.expect_order(378 ['yyy_get_post', 'static', 'aaa_post'],379 invoke(['routes', '-s', 'rule']).output380 )381 self.expect_order(382 ['aaa_post', 'yyy_get_post', 'static'],383 invoke(['routes', '-s', 'match']).output384 )385386 def test_all_methods(self, invoke):387 output = invoke(['routes']).output388 assert 'GET, HEAD, OPTIONS, POST' not in output389 output = invoke(['routes', '--all-methods']).output390 assert 'GET, HEAD, OPTIONS, POST' in output