Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

304 lines · 8.9 KiB · Python

Last changed by

Merge pull request #2297 from HndrkMkt/#2265-auto-detect-create-app-functionDavid Lordbefore adoption0c94908

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    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        @staticmethod56        def create_app():57            return Flask('appname')58    assert isinstance(find_best_app(Module), Flask)59    assert find_best_app(Module).name == 'appname'6061    class Module:62        @staticmethod63        def make_app():64            return Flask('appname')65    assert isinstance(find_best_app(Module), Flask)66    assert find_best_app(Module).name == 'appname'6768    class Module:69        myapp = Flask('appname1')70        @staticmethod71        def create_app():72            return Flask('appname2')73    assert find_best_app(Module) == Module.myapp7475    class Module:76        myapp = Flask('appname1')77        @staticmethod78        def create_app(foo):79            return Flask('appname2')80    assert find_best_app(Module) == Module.myapp8182    class Module:83        pass84    pytest.raises(NoAppException, find_best_app, Module)8586    class Module:87        myapp1 = Flask('appname1')88        myapp2 = Flask('appname2')89    pytest.raises(NoAppException, find_best_app, Module)9091    class Module:92        @staticmethod93        def create_app(foo):94            return Flask('appname2')95    pytest.raises(NoAppException, find_best_app, Module)969798def test_prepare_exec_for_file(test_apps):99    """Expect the correct path to be set and the correct module name to be returned.100101    :func:`prepare_exec_for_file` has a side effect, where102    the parent directory of given file is added to `sys.path`.103    """104    realpath = os.path.realpath('/tmp/share/test.py')105    dirname = os.path.dirname(realpath)106    assert prepare_exec_for_file('/tmp/share/test.py') == 'test'107    assert dirname in sys.path108109    realpath = os.path.realpath('/tmp/share/__init__.py')110    dirname = os.path.dirname(os.path.dirname(realpath))111    assert prepare_exec_for_file('/tmp/share/__init__.py') == 'share'112    assert dirname in sys.path113114    with pytest.raises(NoAppException):115        prepare_exec_for_file('/tmp/share/test.txt')116117118def test_locate_app(test_apps):119    """Test of locate_app."""120    assert locate_app("cliapp.app").name == "testapp"121    assert locate_app("cliapp.app:testapp").name == "testapp"122    assert locate_app("cliapp.multiapp:app1").name == "app1"123    pytest.raises(NoAppException, locate_app, "notanpp.py")124    pytest.raises(NoAppException, locate_app, "cliapp/app")125    pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")126    pytest.raises(NoAppException, locate_app, "cliapp.importerrorapp")127128129def test_find_default_import_path(test_apps, monkeypatch, tmpdir):130    """Test of find_default_import_path."""131    monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)132    assert find_default_import_path() == None133    monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')134    assert find_default_import_path() == 'notanapp'135    tmpfile = tmpdir.join('testapp.py')136    tmpfile.write('')137    monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))138    expect_rv = prepare_exec_for_file(str(tmpfile))139    assert find_default_import_path() == expect_rv140141142def test_get_version(test_apps, capsys):143    """Test of get_version."""144    from flask import __version__ as flask_ver145    from sys import version as py_ver146    class MockCtx(object):147        resilient_parsing = False148        color = None149        def exit(self): return150    ctx = MockCtx()151    get_version(ctx, None, "test")152    out, err = capsys.readouterr()153    assert flask_ver in out154    assert py_ver in out155156157def test_scriptinfo(test_apps):158    """Test of ScriptInfo."""159    obj = ScriptInfo(app_import_path="cliapp.app:testapp")160    assert obj.load_app().name == "testapp"161    assert obj.load_app().name == "testapp"162163    def create_app(info):164        return Flask("createapp")165166    obj = ScriptInfo(create_app=create_app)167    app = obj.load_app()168    assert app.name == "createapp"169    assert obj.load_app() == app170171172def test_with_appcontext(runner):173    """Test of with_appcontext."""174    @click.command()175    @with_appcontext176    def testcmd():177        click.echo(current_app.name)178179    obj = ScriptInfo(create_app=lambda info: Flask("testapp"))180181    result = runner.invoke(testcmd, obj=obj)182    assert result.exit_code == 0183    assert result.output == 'testapp\n'184185186def test_appgroup(runner):187    """Test of with_appcontext."""188    @click.group(cls=AppGroup)189    def cli():190        pass191192    @cli.command(with_appcontext=True)193    def test():194        click.echo(current_app.name)195196    @cli.group()197    def subgroup():198        pass199200    @subgroup.command(with_appcontext=True)201    def test2():202        click.echo(current_app.name)203204    obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))205206    result = runner.invoke(cli, ['test'], obj=obj)207    assert result.exit_code == 0208    assert result.output == 'testappgroup\n'209210    result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)211    assert result.exit_code == 0212    assert result.output == 'testappgroup\n'213214215def test_flaskgroup(runner):216    """Test FlaskGroup."""217    def create_app(info):218        return Flask("flaskgroup")219220    @click.group(cls=FlaskGroup, create_app=create_app)221    def cli(**params):222        pass223224    @cli.command()225    def test():226        click.echo(current_app.name)227228    result = runner.invoke(cli, ['test'])229    assert result.exit_code == 0230    assert result.output == 'flaskgroup\n'231232233def test_print_exceptions(runner):234    """Print the stacktrace if the CLI."""235    def create_app(info):236        raise Exception("oh no")237        return Flask("flaskgroup")238239    @click.group(cls=FlaskGroup, create_app=create_app)240    def cli(**params):241        pass242243    result = runner.invoke(cli, ['--help'])244    assert result.exit_code == 0245    assert 'Exception: oh no' in result.output246    assert 'Traceback' in result.output247248249class TestRoutes:250    @pytest.fixture251    def invoke(self, runner):252        def create_app(info):253            app = Flask(__name__)254            app.testing = True255256            @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])257            def yyy_get_post(x, y):258                pass259260            @app.route('/zzz_post', methods=['POST'])261            def aaa_post():262                pass263264            return app265266        cli = FlaskGroup(create_app=create_app)267        return partial(runner.invoke, cli)268269    def expect_order(self, order, output):270        # skip the header and match the start of each row271        for expect, line in zip(order, output.splitlines()[2:]):272            # do this instead of startswith for nicer pytest output273            assert line[:len(expect)] == expect274275    def test_simple(self, invoke):276        result = invoke(['routes'])277        assert result.exit_code == 0278        self.expect_order(279            ['aaa_post', 'static', 'yyy_get_post'],280            result.output281        )282283    def test_sort(self, invoke):284        default_output = invoke(['routes']).output285        endpoint_output = invoke(['routes', '-s', 'endpoint']).output286        assert default_output == endpoint_output287        self.expect_order(288            ['static', 'yyy_get_post', 'aaa_post'],289            invoke(['routes', '-s', 'methods']).output290        )291        self.expect_order(292            ['yyy_get_post', 'static', 'aaa_post'],293            invoke(['routes', '-s', 'rule']).output294        )295        self.expect_order(296            ['aaa_post', 'yyy_get_post', 'static'],297            invoke(['routes', '-s', 'match']).output298        )299300    def test_all_methods(self, invoke):301        output = invoke(['routes']).output302        assert 'GET, HEAD, OPTIONS, POST' not in output303        output = invoke(['routes', '--all-methods']).output304        assert 'GET, HEAD, OPTIONS, POST' in output