Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

324 lines · 9.7 KiB · Python

Last changed by

Merge pull request #2319 from HndrkMkt/#2266-support-create-app-without-script-infoDavid Lordbefore adoption39f7aaa

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()43    class Module:44        app = Flask('appname')45    assert find_best_app(script_info, Module) == Module.app4647    class Module:48        application = Flask('appname')49    assert find_best_app(script_info, Module) == Module.application5051    class Module:52        myapp = Flask('appname')53    assert find_best_app(script_info, Module) == Module.myapp5455    class Module:56        @staticmethod57        def create_app():58            return Flask('appname')59    assert isinstance(find_best_app(script_info, Module), Flask)60    assert find_best_app(script_info, Module).name == 'appname'6162    class Module:63        @staticmethod64        def create_app(foo):65            return Flask('appname')66    assert isinstance(find_best_app(script_info, Module), Flask)67    assert find_best_app(script_info, Module).name == 'appname'6869    class Module:70        @staticmethod71        def create_app(foo=None, script_info=None):72            return Flask('appname')73    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 make_app():79            return Flask('appname')80    assert isinstance(find_best_app(script_info, Module), Flask)81    assert find_best_app(script_info, Module).name == 'appname'8283    class Module:84        myapp = Flask('appname1')85        @staticmethod86        def create_app():87            return Flask('appname2')88    assert find_best_app(script_info, Module) == Module.myapp8990    class Module:91        myapp = Flask('appname1')92        @staticmethod93        def create_app():94            return Flask('appname2')95    assert find_best_app(script_info, Module) == Module.myapp9697    class Module:98        pass99    pytest.raises(NoAppException, find_best_app, script_info, Module)100101    class Module:102        myapp1 = Flask('appname1')103        myapp2 = Flask('appname2')104    pytest.raises(NoAppException, find_best_app, script_info, Module)105106    class Module:107        @staticmethod108        def create_app(foo, bar):109            return Flask('appname2')110    pytest.raises(NoAppException, find_best_app, script_info, Module)111112113def test_prepare_exec_for_file(test_apps):114    """Expect the correct path to be set and the correct module name to be returned.115116    :func:`prepare_exec_for_file` has a side effect, where117    the parent directory of given file is added to `sys.path`.118    """119    realpath = os.path.realpath('/tmp/share/test.py')120    dirname = os.path.dirname(realpath)121    assert prepare_exec_for_file('/tmp/share/test.py') == 'test'122    assert dirname in sys.path123124    realpath = os.path.realpath('/tmp/share/__init__.py')125    dirname = os.path.dirname(os.path.dirname(realpath))126    assert prepare_exec_for_file('/tmp/share/__init__.py') == 'share'127    assert dirname in sys.path128129    with pytest.raises(NoAppException):130        prepare_exec_for_file('/tmp/share/test.txt')131132133def test_locate_app(test_apps):134    """Test of locate_app."""135    script_info = ScriptInfo()136    assert locate_app(script_info, "cliapp.app").name == "testapp"137    assert locate_app(script_info, "cliapp.app:testapp").name == "testapp"138    assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1"139    pytest.raises(NoAppException, locate_app,140                  script_info, "notanpp.py")141    pytest.raises(NoAppException, locate_app,142                  script_info, "cliapp/app")143    pytest.raises(RuntimeError, locate_app,144                  script_info, "cliapp.app:notanapp")145    pytest.raises(NoAppException, locate_app,146                  script_info, "cliapp.importerrorapp")147148149def test_find_default_import_path(test_apps, monkeypatch, tmpdir):150    """Test of find_default_import_path."""151    monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)152    assert find_default_import_path() == None153    monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')154    assert find_default_import_path() == 'notanapp'155    tmpfile = tmpdir.join('testapp.py')156    tmpfile.write('')157    monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))158    expect_rv = prepare_exec_for_file(str(tmpfile))159    assert find_default_import_path() == expect_rv160161162def test_get_version(test_apps, capsys):163    """Test of get_version."""164    from flask import __version__ as flask_ver165    from sys import version as py_ver166    class MockCtx(object):167        resilient_parsing = False168        color = None169        def exit(self): return170    ctx = MockCtx()171    get_version(ctx, None, "test")172    out, err = capsys.readouterr()173    assert flask_ver in out174    assert py_ver in out175176177def test_scriptinfo(test_apps):178    """Test of ScriptInfo."""179    obj = ScriptInfo(app_import_path="cliapp.app:testapp")180    assert obj.load_app().name == "testapp"181    assert obj.load_app().name == "testapp"182183    def create_app(info):184        return Flask("createapp")185186    obj = ScriptInfo(create_app=create_app)187    app = obj.load_app()188    assert app.name == "createapp"189    assert obj.load_app() == app190191192def test_with_appcontext(runner):193    """Test of with_appcontext."""194    @click.command()195    @with_appcontext196    def testcmd():197        click.echo(current_app.name)198199    obj = ScriptInfo(create_app=lambda info: Flask("testapp"))200201    result = runner.invoke(testcmd, obj=obj)202    assert result.exit_code == 0203    assert result.output == 'testapp\n'204205206def test_appgroup(runner):207    """Test of with_appcontext."""208    @click.group(cls=AppGroup)209    def cli():210        pass211212    @cli.command(with_appcontext=True)213    def test():214        click.echo(current_app.name)215216    @cli.group()217    def subgroup():218        pass219220    @subgroup.command(with_appcontext=True)221    def test2():222        click.echo(current_app.name)223224    obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))225226    result = runner.invoke(cli, ['test'], obj=obj)227    assert result.exit_code == 0228    assert result.output == 'testappgroup\n'229230    result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)231    assert result.exit_code == 0232    assert result.output == 'testappgroup\n'233234235def test_flaskgroup(runner):236    """Test FlaskGroup."""237    def create_app(info):238        return Flask("flaskgroup")239240    @click.group(cls=FlaskGroup, create_app=create_app)241    def cli(**params):242        pass243244    @cli.command()245    def test():246        click.echo(current_app.name)247248    result = runner.invoke(cli, ['test'])249    assert result.exit_code == 0250    assert result.output == 'flaskgroup\n'251252253def test_print_exceptions(runner):254    """Print the stacktrace if the CLI."""255    def create_app(info):256        raise Exception("oh no")257        return Flask("flaskgroup")258259    @click.group(cls=FlaskGroup, create_app=create_app)260    def cli(**params):261        pass262263    result = runner.invoke(cli, ['--help'])264    assert result.exit_code == 0265    assert 'Exception: oh no' in result.output266    assert 'Traceback' in result.output267268269class TestRoutes:270    @pytest.fixture271    def invoke(self, runner):272        def create_app(info):273            app = Flask(__name__)274            app.testing = True275276            @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])277            def yyy_get_post(x, y):278                pass279280            @app.route('/zzz_post', methods=['POST'])281            def aaa_post():282                pass283284            return app285286        cli = FlaskGroup(create_app=create_app)287        return partial(runner.invoke, cli)288289    def expect_order(self, order, output):290        # skip the header and match the start of each row291        for expect, line in zip(order, output.splitlines()[2:]):292            # do this instead of startswith for nicer pytest output293            assert line[:len(expect)] == expect294295    def test_simple(self, invoke):296        result = invoke(['routes'])297        assert result.exit_code == 0298        self.expect_order(299            ['aaa_post', 'static', 'yyy_get_post'],300            result.output301        )302303    def test_sort(self, invoke):304        default_output = invoke(['routes']).output305        endpoint_output = invoke(['routes', '-s', 'endpoint']).output306        assert default_output == endpoint_output307        self.expect_order(308            ['static', 'yyy_get_post', 'aaa_post'],309            invoke(['routes', '-s', 'methods']).output310        )311        self.expect_order(312            ['yyy_get_post', 'static', 'aaa_post'],313            invoke(['routes', '-s', 'rule']).output314        )315        self.expect_order(316            ['aaa_post', 'yyy_get_post', 'static'],317            invoke(['routes', '-s', 'match']).output318        )319320    def test_all_methods(self, invoke):321        output = invoke(['routes']).output322        assert 'GET, HEAD, OPTIONS, POST' not in output323        output = invoke(['routes', '--all-methods']).output324        assert 'GET, HEAD, OPTIONS, POST' in output