test_cli.py
This file
Path
tests/test_cli.py
270 lines · 7.9 KiB · Python
Last changed by
Merge pull request #2259 from davidism/routes-commandDavid Lordbefore adoption39d5552
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 class Module:43 app = Flask('appname')44 assert find_best_app(Module) == Module.app4546 class Module:47 application = Flask('appname')48 assert find_best_app(Module) == Module.application4950 class Module:51 myapp = Flask('appname')52 assert find_best_app(Module) == Module.myapp5354 class Module:55 pass56 pytest.raises(NoAppException, find_best_app, Module)5758 class Module:59 myapp1 = Flask('appname1')60 myapp2 = Flask('appname2')61 pytest.raises(NoAppException, find_best_app, Module)626364def test_prepare_exec_for_file(test_apps):65 """Expect the correct path to be set and the correct module name to be returned.6667 :func:`prepare_exec_for_file` has a side effect, where68 the parent directory of given file is added to `sys.path`.69 """70 realpath = os.path.realpath('/tmp/share/test.py')71 dirname = os.path.dirname(realpath)72 assert prepare_exec_for_file('/tmp/share/test.py') == 'test'73 assert dirname in sys.path7475 realpath = os.path.realpath('/tmp/share/__init__.py')76 dirname = os.path.dirname(os.path.dirname(realpath))77 assert prepare_exec_for_file('/tmp/share/__init__.py') == 'share'78 assert dirname in sys.path7980 with pytest.raises(NoAppException):81 prepare_exec_for_file('/tmp/share/test.txt')828384def test_locate_app(test_apps):85 """Test of locate_app."""86 assert locate_app("cliapp.app").name == "testapp"87 assert locate_app("cliapp.app:testapp").name == "testapp"88 assert locate_app("cliapp.multiapp:app1").name == "app1"89 pytest.raises(NoAppException, locate_app, "notanpp.py")90 pytest.raises(NoAppException, locate_app, "cliapp/app")91 pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")92 pytest.raises(NoAppException, locate_app, "cliapp.importerrorapp")939495def test_find_default_import_path(test_apps, monkeypatch, tmpdir):96 """Test of find_default_import_path."""97 monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)98 assert find_default_import_path() == None99 monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')100 assert find_default_import_path() == 'notanapp'101 tmpfile = tmpdir.join('testapp.py')102 tmpfile.write('')103 monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))104 expect_rv = prepare_exec_for_file(str(tmpfile))105 assert find_default_import_path() == expect_rv106107108def test_get_version(test_apps, capsys):109 """Test of get_version."""110 from flask import __version__ as flask_ver111 from sys import version as py_ver112 class MockCtx(object):113 resilient_parsing = False114 color = None115 def exit(self): return116 ctx = MockCtx()117 get_version(ctx, None, "test")118 out, err = capsys.readouterr()119 assert flask_ver in out120 assert py_ver in out121122123def test_scriptinfo(test_apps):124 """Test of ScriptInfo."""125 obj = ScriptInfo(app_import_path="cliapp.app:testapp")126 assert obj.load_app().name == "testapp"127 assert obj.load_app().name == "testapp"128129 def create_app(info):130 return Flask("createapp")131132 obj = ScriptInfo(create_app=create_app)133 app = obj.load_app()134 assert app.name == "createapp"135 assert obj.load_app() == app136137138def test_with_appcontext(runner):139 """Test of with_appcontext."""140 @click.command()141 @with_appcontext142 def testcmd():143 click.echo(current_app.name)144145 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))146147 result = runner.invoke(testcmd, obj=obj)148 assert result.exit_code == 0149 assert result.output == 'testapp\n'150151152def test_appgroup(runner):153 """Test of with_appcontext."""154 @click.group(cls=AppGroup)155 def cli():156 pass157158 @cli.command(with_appcontext=True)159 def test():160 click.echo(current_app.name)161162 @cli.group()163 def subgroup():164 pass165166 @subgroup.command(with_appcontext=True)167 def test2():168 click.echo(current_app.name)169170 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))171172 result = runner.invoke(cli, ['test'], obj=obj)173 assert result.exit_code == 0174 assert result.output == 'testappgroup\n'175176 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)177 assert result.exit_code == 0178 assert result.output == 'testappgroup\n'179180181def test_flaskgroup(runner):182 """Test FlaskGroup."""183 def create_app(info):184 return Flask("flaskgroup")185186 @click.group(cls=FlaskGroup, create_app=create_app)187 def cli(**params):188 pass189190 @cli.command()191 def test():192 click.echo(current_app.name)193194 result = runner.invoke(cli, ['test'])195 assert result.exit_code == 0196 assert result.output == 'flaskgroup\n'197198199def test_print_exceptions(runner):200 """Print the stacktrace if the CLI."""201 def create_app(info):202 raise Exception("oh no")203 return Flask("flaskgroup")204205 @click.group(cls=FlaskGroup, create_app=create_app)206 def cli(**params):207 pass208209 result = runner.invoke(cli, ['--help'])210 assert result.exit_code == 0211 assert 'Exception: oh no' in result.output212 assert 'Traceback' in result.output213214215class TestRoutes:216 @pytest.fixture217 def invoke(self, runner):218 def create_app(info):219 app = Flask(__name__)220 app.testing = True221222 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])223 def yyy_get_post(x, y):224 pass225226 @app.route('/zzz_post', methods=['POST'])227 def aaa_post():228 pass229230 return app231232 cli = FlaskGroup(create_app=create_app)233 return partial(runner.invoke, cli)234235 def expect_order(self, order, output):236 # skip the header and match the start of each row237 for expect, line in zip(order, output.splitlines()[2:]):238 # do this instead of startswith for nicer pytest output239 assert line[:len(expect)] == expect240241 def test_simple(self, invoke):242 result = invoke(['routes'])243 assert result.exit_code == 0244 self.expect_order(245 ['aaa_post', 'static', 'yyy_get_post'],246 result.output247 )248249 def test_sort(self, invoke):250 default_output = invoke(['routes']).output251 endpoint_output = invoke(['routes', '-s', 'endpoint']).output252 assert default_output == endpoint_output253 self.expect_order(254 ['static', 'yyy_get_post', 'aaa_post'],255 invoke(['routes', '-s', 'methods']).output256 )257 self.expect_order(258 ['yyy_get_post', 'static', 'aaa_post'],259 invoke(['routes', '-s', 'rule']).output260 )261 self.expect_order(262 ['aaa_post', 'yyy_get_post', 'static'],263 invoke(['routes', '-s', 'match']).output264 )265266 def test_all_methods(self, invoke):267 output = invoke(['routes']).output268 assert 'GET, HEAD, OPTIONS, POST' not in output269 output = invoke(['routes', '--all-methods']).output270 assert 'GET, HEAD, OPTIONS, POST' in output