Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

466 lines · 12.6 KiB · Python

Last changed by

Merge pull request #2592 from pallets/tests-envDavid Lordbefore adoption2949306

History of this file

Take it

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 1–13why, 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#

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

lines 14–15why, one step back
14from __future__ import absolute_import
15

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 16–21why, one step back
16import os
17import sys18from functools import partial1920import click21import pytest

Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4

line 22why, one step back
22from _pytest.monkeypatch import notset

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 23why, one step back
23from click.testing import CliRunner

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

line 24why, one step back
24

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 25why, one step back
25from flask import Flask, current_app

Merge pull request #2592 from pallets/tests-envDavid Lordbefore adoption2949306

lines 26–28why, one step back
26from flask.cli import (
27 AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv,28 find_best_app, get_version, load_dotenv, locate_app, prepare_import,

Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4

line 29why, one step back
29 with_appcontext

Merge pull request #2592 from pallets/tests-envDavid Lordbefore adoption2949306

line 30why, one step back
30)

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 31why, one step back
31

Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4

lines 32–37why, one step back
32cwd = os.getcwd()
33test_path = os.path.abspath(os.path.join(34 os.path.dirname(__file__), 'test_apps'35))3637

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 38–136why, one step back
38@pytest.fixture
39def runner():40 return CliRunner()414243def test_cli_name(test_apps):44 """Make sure the CLI object's name is the app's name and not the app itself"""45 from cliapp.app import testapp46 assert testapp.cli.name == testapp.name474849def test_find_best_app(test_apps):50 """Test if `find_best_app` behaves as expected with different combinations of input."""51 script_info = ScriptInfo()5253 class Module:54 app = Flask('appname')5556 assert find_best_app(script_info, Module) == Module.app5758 class Module:59 application = Flask('appname')6061 assert find_best_app(script_info, Module) == Module.application6263 class Module:64 myapp = Flask('appname')6566 assert find_best_app(script_info, Module) == Module.myapp6768 class Module:69 @staticmethod70 def create_app():71 return Flask('appname')7273 assert isinstance(find_best_app(script_info, Module), Flask)74 assert find_best_app(script_info, Module).name == 'appname'7576 class Module:77 @staticmethod78 def create_app(foo):79 return Flask('appname')8081 assert isinstance(find_best_app(script_info, Module), Flask)82 assert find_best_app(script_info, Module).name == 'appname'8384 class Module:85 @staticmethod86 def create_app(foo=None, script_info=None):87 return Flask('appname')8889 assert isinstance(find_best_app(script_info, Module), Flask)90 assert find_best_app(script_info, Module).name == 'appname'9192 class Module:93 @staticmethod94 def make_app():95 return Flask('appname')9697 assert isinstance(find_best_app(script_info, Module), Flask)98 assert find_best_app(script_info, Module).name == 'appname'99100 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 myapp = Flask('appname1')111112 @staticmethod113 def create_app():114 return Flask('appname2')115116 assert find_best_app(script_info, Module) == Module.myapp117118 class Module:119 pass120121 pytest.raises(NoAppException, find_best_app, script_info, Module)122123 class Module:124 myapp1 = Flask('appname1')125 myapp2 = Flask('appname2')126127 pytest.raises(NoAppException, find_best_app, script_info, Module)128129 class Module:130 @staticmethod131 def create_app(foo, bar):132 return Flask('appname2')133134 pytest.raises(NoAppException, find_best_app, script_info, Module)135136

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

lines 137–167why, one step back
137@pytest.mark.parametrize('value,path,result', (
138 ('test', cwd, 'test'),139 ('test.py', cwd, 'test'),140 ('a/test', os.path.join(cwd, 'a'), 'test'),141 ('test/__init__.py', cwd, 'test'),142 ('test/__init__', cwd, 'test'),143 # nested package144 (145 os.path.join(test_path, 'cliapp', 'inner1', '__init__'),146 test_path, 'cliapp.inner1'147 ),148 (149 os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),150 test_path, 'cliapp.inner1.inner2'151 ),152 # dotted name153 ('test.a.b', cwd, 'test.a.b'),154 (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),155 # not a Python file, will be caught during import156 (157 os.path.join(test_path, 'cliapp', 'message.txt'),158 test_path, 'cliapp.message.txt'159 ),160))161def test_prepare_import(request, value, path, result):162 """Expect the correct path to be set and the correct import and app names163 to be returned.164165 :func:`prepare_exec_for_file` has a side effect where the parent directory166 of the given import is added to :data:`sys.path`. This is reset after the167 test runs.

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 168why, one step back
168 """

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

line 169why, one step back
169 original_path = sys.path[:]

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 170why, one step back
170

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

lines 171–172why, one step back
171 def reset_path():
172 sys.path[:] = original_path

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 173why, one step back
173

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

line 174why, one step back
174 request.addfinalizer(reset_path)

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 175why, one step back
175

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

lines 176–177why, one step back
176 assert prepare_import(value) == result
177 assert sys.path[0] == path

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 178–179why, one step back
178
179

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

lines 180–191why, one step back
180@pytest.mark.parametrize('iname,aname,result', (
181 ('cliapp.app', None, 'testapp'),182 ('cliapp.app', 'testapp', 'testapp'),183 ('cliapp.factory', None, 'app'),184 ('cliapp.factory', 'create_app', 'app'),185 ('cliapp.factory', 'create_app()', 'app'),186 # no script_info187 ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),188 # trailing comma space189 ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),190 # takes script_info191 ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),

Merge pull request #2490 from davidism/cli-reviewDavid Lordbefore adoption0932d8f

lines 192–193why, one step back
192 # strip whitespace
193 ('cliapp.factory', ' create_app () ', 'app'),

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

lines 194–198why, one step back
194))
195def test_locate_app(test_apps, iname, aname, result):196 info = ScriptInfo()197 info.data['test'] = 'spam'198 assert locate_app(info, iname, aname).name == result

resolve merge conflictsKenneth Reitzbefore adoption31174fe

line 199why, one step back
199

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

lines 200–206why, one step back
200
201@pytest.mark.parametrize('iname,aname', (202 ('notanapp.py', None),203 ('cliapp/app', None),204 ('cliapp.app', 'notanapp'),205 # not enough arguments206 ('cliapp.factory', 'create_app2("foo")'),

Merge pull request #2490 from davidism/cli-reviewDavid Lordbefore adoption0932d8f

lines 207–210why, one step back
207 # invalid identifier
208 ('cliapp.factory', 'create_app('),209 # no app returned210 ('cliapp.factory', 'no_app'),

Merge pull request #2414 from davidism/cli-load-local-packageDavid Lordbefore adoption77b98a2

lines 211–232why, one step back
211 # nested import error
212 ('cliapp.importerrorapp', None),213 # not a Python file214 ('cliapp.message.txt', None),215))216def test_locate_app_raises(test_apps, iname, aname):217 info = ScriptInfo()218219 with pytest.raises(NoAppException):220 locate_app(info, iname, aname)221222223def test_locate_app_suppress_raise():224 info = ScriptInfo()225 app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)226 assert app is None227228 # only direct import error is suppressed229 with pytest.raises(NoAppException):230 locate_app(231 info, 'cliapp.importerrorapp', None, raise_if_not_found=False232 )

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 233–252why, one step back
233
234235def test_get_version(test_apps, capsys):236 """Test of get_version."""237 from flask import __version__ as flask_ver238 from sys import version as py_ver239240 class MockCtx(object):241 resilient_parsing = False242 color = None243244 def exit(self): return245246 ctx = MockCtx()247 get_version(ctx, None, "test")248 out, err = capsys.readouterr()249 assert flask_ver in out250 assert py_ver in out251252

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

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

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 254–265why, one step back
254 """Test of ScriptInfo."""
255 obj = ScriptInfo(app_import_path="cliapp.app:testapp")256 assert obj.load_app().name == "testapp"257 assert obj.load_app().name == "testapp"258259 def create_app(info):260 return Flask("createapp")261262 obj = ScriptInfo(create_app=create_app)263 app = obj.load_app()264 assert app.name == "createapp"265 assert obj.load_app() == app

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

lines 266–284why, one step back
266
267 obj = ScriptInfo()268 pytest.raises(NoAppException, obj.load_app)269270 # import app from wsgi.py in current directory271 monkeypatch.chdir(os.path.abspath(os.path.join(272 os.path.dirname(__file__), 'test_apps', 'helloworld'273 )))274 obj = ScriptInfo()275 app = obj.load_app()276 assert app.name == 'hello'277278 # import app from app.py in current directory279 monkeypatch.chdir(os.path.abspath(os.path.join(280 os.path.dirname(__file__), 'test_apps', 'cliapp'281 )))282 obj = ScriptInfo()283 app = obj.load_app()284 assert app.name == 'testapp'

resolve merge conflictsKenneth Reitzbefore adoption31174fe

lines 285–423why, one step back
285
286287def test_with_appcontext(runner):288 """Test of with_appcontext."""289290 @click.command()291 @with_appcontext292 def testcmd():293 click.echo(current_app.name)294295 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))296297 result = runner.invoke(testcmd, obj=obj)298 assert result.exit_code == 0299 assert result.output == 'testapp\n'300301302def test_appgroup(runner):303 """Test of with_appcontext."""304305 @click.group(cls=AppGroup)306 def cli():307 pass308309 @cli.command(with_appcontext=True)310 def test():311 click.echo(current_app.name)312313 @cli.group()314 def subgroup():315 pass316317 @subgroup.command(with_appcontext=True)318 def test2():319 click.echo(current_app.name)320321 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))322323 result = runner.invoke(cli, ['test'], obj=obj)324 assert result.exit_code == 0325 assert result.output == 'testappgroup\n'326327 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)328 assert result.exit_code == 0329 assert result.output == 'testappgroup\n'330331332def test_flaskgroup(runner):333 """Test FlaskGroup."""334335 def create_app(info):336 return Flask("flaskgroup")337338 @click.group(cls=FlaskGroup, create_app=create_app)339 def cli(**params):340 pass341342 @cli.command()343 def test():344 click.echo(current_app.name)345346 result = runner.invoke(cli, ['test'])347 assert result.exit_code == 0348 assert result.output == 'flaskgroup\n'349350351def test_print_exceptions(runner):352 """Print the stacktrace if the CLI."""353354 def create_app(info):355 raise Exception("oh no")356 return Flask("flaskgroup")357358 @click.group(cls=FlaskGroup, create_app=create_app)359 def cli(**params):360 pass361362 result = runner.invoke(cli, ['--help'])363 assert result.exit_code == 0364 assert 'Exception: oh no' in result.output365 assert 'Traceback' in result.output366367368class TestRoutes:369 @pytest.fixture370 def invoke(self, runner):371 def create_app(info):372 app = Flask(__name__)373 app.testing = True374375 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])376 def yyy_get_post(x, y):377 pass378379 @app.route('/zzz_post', methods=['POST'])380 def aaa_post():381 pass382383 return app384385 cli = FlaskGroup(create_app=create_app)386 return partial(runner.invoke, cli)387388 def expect_order(self, order, output):389 # skip the header and match the start of each row390 for expect, line in zip(order, output.splitlines()[2:]):391 # do this instead of startswith for nicer pytest output392 assert line[:len(expect)] == expect393394 def test_simple(self, invoke):395 result = invoke(['routes'])396 assert result.exit_code == 0397 self.expect_order(398 ['aaa_post', 'static', 'yyy_get_post'],399 result.output400 )401402 def test_sort(self, invoke):403 default_output = invoke(['routes']).output404 endpoint_output = invoke(['routes', '-s', 'endpoint']).output405 assert default_output == endpoint_output406 self.expect_order(407 ['static', 'yyy_get_post', 'aaa_post'],408 invoke(['routes', '-s', 'methods']).output409 )410 self.expect_order(411 ['yyy_get_post', 'static', 'aaa_post'],412 invoke(['routes', '-s', 'rule']).output413 )414 self.expect_order(415 ['aaa_post', 'yyy_get_post', 'static'],416 invoke(['routes', '-s', 'match']).output417 )418419 def test_all_methods(self, invoke):420 output = invoke(['routes']).output421 assert 'GET, HEAD, OPTIONS, POST' not in output422 output = invoke(['routes', '--all-methods']).output423 assert 'GET, HEAD, OPTIONS, POST' in output

Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4

lines 424–466why, one step back
424
425426need_dotenv = pytest.mark.skipif(427 dotenv is None, reason='dotenv is not installed'428)429430431@need_dotenv432def test_load_dotenv(monkeypatch):433 # can't use monkeypatch.delitem since the keys don't exist yet434 for item in ('FOO', 'BAR', 'SPAM'):435 monkeypatch._setitem.append((os.environ, item, notset))436437 monkeypatch.setenv('EGGS', '3')438 monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))439 load_dotenv()440 assert os.getcwd() == test_path441 # .flaskenv doesn't overwrite .env442 assert os.environ['FOO'] == 'env'443 # set only in .flaskenv444 assert os.environ['BAR'] == 'bar'445 # set only in .env446 assert os.environ['SPAM'] == '1'447 # set manually, files don't overwrite448 assert os.environ['EGGS'] == '3'449450451@need_dotenv452def test_dotenv_path(monkeypatch):453 for item in ('FOO', 'BAR', 'EGGS'):454 monkeypatch._setitem.append((os.environ, item, notset))455456 cwd = os.getcwd()457 load_dotenv(os.path.join(test_path, '.flaskenv'))458 assert os.getcwd() == cwd459 assert 'FOO' in os.environ460461462def test_dotenv_optional(monkeypatch):463 monkeypatch.setattr('flask.cli.dotenv', None)464 monkeypatch.chdir(test_path)465 load_dotenv()466 assert 'FOO' not in os.environ