test_cli.py
This file
Path
tests/test_cli.py
416 lines · 11.2 KiB · Python
Last changed by
Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
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–22why, one step back16import os17import sys18from functools import partial1920import click21import pytest22from click.testing import CliRunnerMerge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
line 23why, one step back23resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 24why, one step back24from flask import Flask, current_appMerge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 25–26why, one step back25from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \26 find_best_app, get_version, locate_app, prepare_import, with_appcontextresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 27–127why, one step back272829@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)126127Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 128–131why, one step back128cwd = os.getcwd()129test_path = os.path.abspath(os.path.join(130 os.path.dirname(__file__), 'test_apps'131))resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 132why, one step back132Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 133–164why, one step back133134@pytest.mark.parametrize('value,path,result', (135 ('test', cwd, 'test'),136 ('test.py', cwd, 'test'),137 ('a/test', os.path.join(cwd, 'a'), 'test'),138 ('test/__init__.py', cwd, 'test'),139 ('test/__init__', cwd, 'test'),140 # nested package141 (142 os.path.join(test_path, 'cliapp', 'inner1', '__init__'),143 test_path, 'cliapp.inner1'144 ),145 (146 os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),147 test_path, 'cliapp.inner1.inner2'148 ),149 # dotted name150 ('test.a.b', cwd, 'test.a.b'),151 (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),152 # not a Python file, will be caught during import153 (154 os.path.join(test_path, 'cliapp', 'message.txt'),155 test_path, 'cliapp.message.txt'156 ),157))158def test_prepare_import(request, value, path, result):159 """Expect the correct path to be set and the correct import and app names160 to be returned.161162 :func:`prepare_exec_for_file` has a side effect where the parent directory163 of the given import is added to :data:`sys.path`. This is reset after the164 test runs.resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 165why, one step back165 """Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
line 166why, one step back166 original_path = sys.path[:]resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 167why, one step back167Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 168–169why, one step back168 def reset_path():169 sys.path[:] = original_pathresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 170why, one step back170Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
line 171why, one step back171 request.addfinalizer(reset_path)resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 172why, one step back172Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 173–174why, one step back173 assert prepare_import(value) == result174 assert sys.path[0] == pathresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 175–176why, one step back175176Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 177–193why, one step back177@pytest.mark.parametrize('iname,aname,result', (178 ('cliapp.app', None, 'testapp'),179 ('cliapp.app', 'testapp', 'testapp'),180 ('cliapp.factory', None, 'app'),181 ('cliapp.factory', 'create_app', 'app'),182 ('cliapp.factory', 'create_app()', 'app'),183 # no script_info184 ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),185 # trailing comma space186 ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),187 # takes script_info188 ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),189))190def test_locate_app(test_apps, iname, aname, result):191 info = ScriptInfo()192 info.data['test'] = 'spam'193 assert locate_app(info, iname, aname).name == resultresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 194why, one step back194Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2
lines 195–225why, one step back195196@pytest.mark.parametrize('iname,aname', (197 ('notanapp.py', None),198 ('cliapp/app', None),199 ('cliapp.app', 'notanapp'),200 # not enough arguments201 ('cliapp.factory', 'create_app2("foo")'),202 # nested import error203 ('cliapp.importerrorapp', None),204 # not a Python file205 ('cliapp.message.txt', None),206 # space before arg list207 ('cliapp.factory', 'create_app ()'),208))209def test_locate_app_raises(test_apps, iname, aname):210 info = ScriptInfo()211212 with pytest.raises(NoAppException):213 locate_app(info, iname, aname)214215216def test_locate_app_suppress_raise():217 info = ScriptInfo()218 app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)219 assert app is None220221 # only direct import error is suppressed222 with pytest.raises(NoAppException):223 locate_app(224 info, 'cliapp.importerrorapp', None, raise_if_not_found=False225 )resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 226–245why, one step back226227228def test_get_version(test_apps, capsys):229 """Test of get_version."""230 from flask import __version__ as flask_ver231 from sys import version as py_ver232233 class MockCtx(object):234 resilient_parsing = False235 color = None236237 def exit(self): return238239 ctx = MockCtx()240 get_version(ctx, None, "test")241 out, err = capsys.readouterr()242 assert flask_ver in out243 assert py_ver in out244245Merge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a
line 246why, one step back246def test_scriptinfo(test_apps, monkeypatch):resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 247–258why, one step back247 """Test of ScriptInfo."""248 obj = ScriptInfo(app_import_path="cliapp.app:testapp")249 assert obj.load_app().name == "testapp"250 assert obj.load_app().name == "testapp"251252 def create_app(info):253 return Flask("createapp")254255 obj = ScriptInfo(create_app=create_app)256 app = obj.load_app()257 assert app.name == "createapp"258 assert obj.load_app() == appMerge pull request #2378 from miguelgrinberg/default-flask-appDavid Lordbefore adoption29c055a
lines 259–277why, one step back259260 obj = ScriptInfo()261 pytest.raises(NoAppException, obj.load_app)262263 # import app from wsgi.py in current directory264 monkeypatch.chdir(os.path.abspath(os.path.join(265 os.path.dirname(__file__), 'test_apps', 'helloworld'266 )))267 obj = ScriptInfo()268 app = obj.load_app()269 assert app.name == 'hello'270271 # import app from app.py in current directory272 monkeypatch.chdir(os.path.abspath(os.path.join(273 os.path.dirname(__file__), 'test_apps', 'cliapp'274 )))275 obj = ScriptInfo()276 app = obj.load_app()277 assert app.name == 'testapp'resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 278–416why, one step back278279280def test_with_appcontext(runner):281 """Test of with_appcontext."""282283 @click.command()284 @with_appcontext285 def testcmd():286 click.echo(current_app.name)287288 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))289290 result = runner.invoke(testcmd, obj=obj)291 assert result.exit_code == 0292 assert result.output == 'testapp\n'293294295def test_appgroup(runner):296 """Test of with_appcontext."""297298 @click.group(cls=AppGroup)299 def cli():300 pass301302 @cli.command(with_appcontext=True)303 def test():304 click.echo(current_app.name)305306 @cli.group()307 def subgroup():308 pass309310 @subgroup.command(with_appcontext=True)311 def test2():312 click.echo(current_app.name)313314 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))315316 result = runner.invoke(cli, ['test'], obj=obj)317 assert result.exit_code == 0318 assert result.output == 'testappgroup\n'319320 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)321 assert result.exit_code == 0322 assert result.output == 'testappgroup\n'323324325def test_flaskgroup(runner):326 """Test FlaskGroup."""327328 def create_app(info):329 return Flask("flaskgroup")330331 @click.group(cls=FlaskGroup, create_app=create_app)332 def cli(**params):333 pass334335 @cli.command()336 def test():337 click.echo(current_app.name)338339 result = runner.invoke(cli, ['test'])340 assert result.exit_code == 0341 assert result.output == 'flaskgroup\n'342343344def test_print_exceptions(runner):345 """Print the stacktrace if the CLI."""346347 def create_app(info):348 raise Exception("oh no")349 return Flask("flaskgroup")350351 @click.group(cls=FlaskGroup, create_app=create_app)352 def cli(**params):353 pass354355 result = runner.invoke(cli, ['--help'])356 assert result.exit_code == 0357 assert 'Exception: oh no' in result.output358 assert 'Traceback' in result.output359360361class TestRoutes:362 @pytest.fixture363 def invoke(self, runner):364 def create_app(info):365 app = Flask(__name__)366 app.testing = True367368 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])369 def yyy_get_post(x, y):370 pass371372 @app.route('/zzz_post', methods=['POST'])373 def aaa_post():374 pass375376 return app377378 cli = FlaskGroup(create_app=create_app)379 return partial(runner.invoke, cli)380381 def expect_order(self, order, output):382 # skip the header and match the start of each row383 for expect, line in zip(order, output.splitlines()[2:]):384 # do this instead of startswith for nicer pytest output385 assert line[:len(expect)] == expect386387 def test_simple(self, invoke):388 result = invoke(['routes'])389 assert result.exit_code == 0390 self.expect_order(391 ['aaa_post', 'static', 'yyy_get_post'],392 result.output393 )394395 def test_sort(self, invoke):396 default_output = invoke(['routes']).output397 endpoint_output = invoke(['routes', '-s', 'endpoint']).output398 assert default_output == endpoint_output399 self.expect_order(400 ['static', 'yyy_get_post', 'aaa_post'],401 invoke(['routes', '-s', 'methods']).output402 )403 self.expect_order(404 ['yyy_get_post', 'static', 'aaa_post'],405 invoke(['routes', '-s', 'rule']).output406 )407 self.expect_order(408 ['aaa_post', 'yyy_get_post', 'static'],409 invoke(['routes', '-s', 'match']).output410 )411412 def test_all_methods(self, invoke):413 output = invoke(['routes']).output414 assert 'GET, HEAD, OPTIONS, POST' not in output415 output = invoke(['routes', '--all-methods']).output416 assert 'GET, HEAD, OPTIONS, POST' in output