Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

346 lines · 9.7 KiB · Python

Last changed by

resolve merge conflictsKenneth Reitzbefore adoption31174fe

History of this file

Take 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.multiapp:app1").name == "app1"154    pytest.raises(NoAppException, locate_app,155                  script_info, "notanpp.py")156    pytest.raises(NoAppException, locate_app,157                  script_info, "cliapp/app")158    pytest.raises(RuntimeError, locate_app,159                  script_info, "cliapp.app:notanapp")160    pytest.raises(NoAppException, locate_app,161                  script_info, "cliapp.importerrorapp")162163164def test_find_default_import_path(test_apps, monkeypatch, tmpdir):165    """Test of find_default_import_path."""166    monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)167    assert find_default_import_path() == None168    monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')169    assert find_default_import_path() == 'notanapp'170    tmpfile = tmpdir.join('testapp.py')171    tmpfile.write('')172    monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))173    expect_rv = prepare_exec_for_file(str(tmpfile))174    assert find_default_import_path() == expect_rv175176177def test_get_version(test_apps, capsys):178    """Test of get_version."""179    from flask import __version__ as flask_ver180    from sys import version as py_ver181182    class MockCtx(object):183        resilient_parsing = False184        color = None185186        def exit(self): return187188    ctx = MockCtx()189    get_version(ctx, None, "test")190    out, err = capsys.readouterr()191    assert flask_ver in out192    assert py_ver in out193194195def test_scriptinfo(test_apps):196    """Test of ScriptInfo."""197    obj = ScriptInfo(app_import_path="cliapp.app:testapp")198    assert obj.load_app().name == "testapp"199    assert obj.load_app().name == "testapp"200201    def create_app(info):202        return Flask("createapp")203204    obj = ScriptInfo(create_app=create_app)205    app = obj.load_app()206    assert app.name == "createapp"207    assert obj.load_app() == app208209210def test_with_appcontext(runner):211    """Test of with_appcontext."""212213    @click.command()214    @with_appcontext215    def testcmd():216        click.echo(current_app.name)217218    obj = ScriptInfo(create_app=lambda info: Flask("testapp"))219220    result = runner.invoke(testcmd, obj=obj)221    assert result.exit_code == 0222    assert result.output == 'testapp\n'223224225def test_appgroup(runner):226    """Test of with_appcontext."""227228    @click.group(cls=AppGroup)229    def cli():230        pass231232    @cli.command(with_appcontext=True)233    def test():234        click.echo(current_app.name)235236    @cli.group()237    def subgroup():238        pass239240    @subgroup.command(with_appcontext=True)241    def test2():242        click.echo(current_app.name)243244    obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))245246    result = runner.invoke(cli, ['test'], obj=obj)247    assert result.exit_code == 0248    assert result.output == 'testappgroup\n'249250    result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)251    assert result.exit_code == 0252    assert result.output == 'testappgroup\n'253254255def test_flaskgroup(runner):256    """Test FlaskGroup."""257258    def create_app(info):259        return Flask("flaskgroup")260261    @click.group(cls=FlaskGroup, create_app=create_app)262    def cli(**params):263        pass264265    @cli.command()266    def test():267        click.echo(current_app.name)268269    result = runner.invoke(cli, ['test'])270    assert result.exit_code == 0271    assert result.output == 'flaskgroup\n'272273274def test_print_exceptions(runner):275    """Print the stacktrace if the CLI."""276277    def create_app(info):278        raise Exception("oh no")279        return Flask("flaskgroup")280281    @click.group(cls=FlaskGroup, create_app=create_app)282    def cli(**params):283        pass284285    result = runner.invoke(cli, ['--help'])286    assert result.exit_code == 0287    assert 'Exception: oh no' in result.output288    assert 'Traceback' in result.output289290291class TestRoutes:292    @pytest.fixture293    def invoke(self, runner):294        def create_app(info):295            app = Flask(__name__)296            app.testing = True297298            @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])299            def yyy_get_post(x, y):300                pass301302            @app.route('/zzz_post', methods=['POST'])303            def aaa_post():304                pass305306            return app307308        cli = FlaskGroup(create_app=create_app)309        return partial(runner.invoke, cli)310311    def expect_order(self, order, output):312        # skip the header and match the start of each row313        for expect, line in zip(order, output.splitlines()[2:]):314            # do this instead of startswith for nicer pytest output315            assert line[:len(expect)] == expect316317    def test_simple(self, invoke):318        result = invoke(['routes'])319        assert result.exit_code == 0320        self.expect_order(321            ['aaa_post', 'static', 'yyy_get_post'],322            result.output323        )324325    def test_sort(self, invoke):326        default_output = invoke(['routes']).output327        endpoint_output = invoke(['routes', '-s', 'endpoint']).output328        assert default_output == endpoint_output329        self.expect_order(330            ['static', 'yyy_get_post', 'aaa_post'],331            invoke(['routes', '-s', 'methods']).output332        )333        self.expect_order(334            ['yyy_get_post', 'static', 'aaa_post'],335            invoke(['routes', '-s', 'rule']).output336        )337        self.expect_order(338            ['aaa_post', 'yyy_get_post', 'static'],339            invoke(['routes', '-s', 'match']).output340        )341342    def test_all_methods(self, invoke):343        output = invoke(['routes']).output344        assert 'GET, HEAD, OPTIONS, POST' not in output345        output = invoke(['routes', '--all-methods']).output346        assert 'GET, HEAD, OPTIONS, POST' in output