Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

533 lines · 14.6 KiB · Python

Last changed by

Merge pull request #2624 from pallets/metadataDavid Lordbefore adoption4309c7c

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.test_cli4    ~~~~~~~~~~~~~~56    :copyright: © 2010 by the Pallets team.7    :license: BSD, see LICENSE for more details.8"""910# This file was part of Flask-CLI and was modified under the terms of11# its Revised BSD License. Copyright © 2015 CERN.1213from __future__ import absolute_import1415import os16import ssl17import sys18import types19from functools import partial2021import click22import pytest23from _pytest.monkeypatch import notset24from click.testing import CliRunner2526from flask import Flask, current_app27from flask.cli import (28    AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, find_best_app,29    get_version, load_dotenv, locate_app, prepare_import, run_command,30    with_appcontext31)3233cwd = os.getcwd()34test_path = os.path.abspath(os.path.join(35    os.path.dirname(__file__), 'test_apps'36))373839@pytest.fixture40def runner():41    return CliRunner()424344def test_cli_name(test_apps):45    """Make sure the CLI object's name is the app's name and not the app itself"""46    from cliapp.app import testapp47    assert testapp.cli.name == testapp.name484950def test_find_best_app(test_apps):51    """Test if `find_best_app` behaves as expected with different combinations of input."""52    script_info = ScriptInfo()5354    class Module:55        app = Flask('appname')5657    assert find_best_app(script_info, Module) == Module.app5859    class Module:60        application = Flask('appname')6162    assert find_best_app(script_info, Module) == Module.application6364    class Module:65        myapp = Flask('appname')6667    assert find_best_app(script_info, Module) == Module.myapp6869    class Module:70        @staticmethod71        def create_app():72            return Flask('appname')7374    assert isinstance(find_best_app(script_info, Module), Flask)75    assert find_best_app(script_info, Module).name == 'appname'7677    class Module:78        @staticmethod79        def create_app(foo):80            return Flask('appname')8182    assert isinstance(find_best_app(script_info, Module), Flask)83    assert find_best_app(script_info, Module).name == 'appname'8485    class Module:86        @staticmethod87        def create_app(foo=None, script_info=None):88            return Flask('appname')8990    assert isinstance(find_best_app(script_info, Module), Flask)91    assert find_best_app(script_info, Module).name == 'appname'9293    class Module:94        @staticmethod95        def make_app():96            return Flask('appname')9798    assert isinstance(find_best_app(script_info, Module), Flask)99    assert find_best_app(script_info, Module).name == 'appname'100101    class Module:102        myapp = Flask('appname1')103104        @staticmethod105        def create_app():106            return Flask('appname2')107108    assert find_best_app(script_info, Module) == Module.myapp109110    class Module:111        myapp = Flask('appname1')112113        @staticmethod114        def create_app():115            return Flask('appname2')116117    assert find_best_app(script_info, Module) == Module.myapp118119    class Module:120        pass121122    pytest.raises(NoAppException, find_best_app, script_info, Module)123124    class Module:125        myapp1 = Flask('appname1')126        myapp2 = Flask('appname2')127128    pytest.raises(NoAppException, find_best_app, script_info, Module)129130    class Module:131        @staticmethod132        def create_app(foo, bar):133            return Flask('appname2')134135    pytest.raises(NoAppException, find_best_app, script_info, Module)136137    class Module:138        @staticmethod139        def create_app():140            raise TypeError('bad bad factory!')141142    pytest.raises(TypeError, find_best_app, script_info, Module)143144145@pytest.mark.parametrize('value,path,result', (146    ('test', cwd, 'test'),147    ('test.py', cwd, 'test'),148    ('a/test', os.path.join(cwd, 'a'), 'test'),149    ('test/__init__.py', cwd, 'test'),150    ('test/__init__', cwd, 'test'),151    # nested package152    (153        os.path.join(test_path, 'cliapp', 'inner1', '__init__'),154        test_path, 'cliapp.inner1'155    ),156    (157        os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),158        test_path, 'cliapp.inner1.inner2'159    ),160    # dotted name161    ('test.a.b', cwd, 'test.a.b'),162    (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),163    # not a Python file, will be caught during import164    (165        os.path.join(test_path, 'cliapp', 'message.txt'),166        test_path, 'cliapp.message.txt'167    ),168))169def test_prepare_import(request, value, path, result):170    """Expect the correct path to be set and the correct import and app names171    to be returned.172173    :func:`prepare_exec_for_file` has a side effect where the parent directory174    of the given import is added to :data:`sys.path`. This is reset after the175    test runs.176    """177    original_path = sys.path[:]178179    def reset_path():180        sys.path[:] = original_path181182    request.addfinalizer(reset_path)183184    assert prepare_import(value) == result185    assert sys.path[0] == path186187188@pytest.mark.parametrize('iname,aname,result', (189    ('cliapp.app', None, 'testapp'),190    ('cliapp.app', 'testapp', 'testapp'),191    ('cliapp.factory', None, 'app'),192    ('cliapp.factory', 'create_app', 'app'),193    ('cliapp.factory', 'create_app()', 'app'),194    # no script_info195    ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),196    # trailing comma space197    ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),198    # takes script_info199    ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),200    # strip whitespace201    ('cliapp.factory', ' create_app () ', 'app'),202))203def test_locate_app(test_apps, iname, aname, result):204    info = ScriptInfo()205    info.data['test'] = 'spam'206    assert locate_app(info, iname, aname).name == result207208209@pytest.mark.parametrize('iname,aname', (210    ('notanapp.py', None),211    ('cliapp/app', None),212    ('cliapp.app', 'notanapp'),213    # not enough arguments214    ('cliapp.factory', 'create_app2("foo")'),215    # invalid identifier216    ('cliapp.factory', 'create_app('),217    # no app returned218    ('cliapp.factory', 'no_app'),219    # nested import error220    ('cliapp.importerrorapp', None),221    # not a Python file222    ('cliapp.message.txt', None),223))224def test_locate_app_raises(test_apps, iname, aname):225    info = ScriptInfo()226227    with pytest.raises(NoAppException):228        locate_app(info, iname, aname)229230231def test_locate_app_suppress_raise():232    info = ScriptInfo()233    app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)234    assert app is None235236    # only direct import error is suppressed237    with pytest.raises(NoAppException):238        locate_app(239            info, 'cliapp.importerrorapp', None, raise_if_not_found=False240        )241242243def test_get_version(test_apps, capsys):244    """Test of get_version."""245    from flask import __version__ as flask_ver246    from sys import version as py_ver247248    class MockCtx(object):249        resilient_parsing = False250        color = None251252        def exit(self): return253254    ctx = MockCtx()255    get_version(ctx, None, "test")256    out, err = capsys.readouterr()257    assert flask_ver in out258    assert py_ver in out259260261def test_scriptinfo(test_apps, monkeypatch):262    """Test of ScriptInfo."""263    obj = ScriptInfo(app_import_path="cliapp.app:testapp")264    assert obj.load_app().name == "testapp"265    assert obj.load_app().name == "testapp"266267    def create_app(info):268        return Flask("createapp")269270    obj = ScriptInfo(create_app=create_app)271    app = obj.load_app()272    assert app.name == "createapp"273    assert obj.load_app() == app274275    obj = ScriptInfo()276    pytest.raises(NoAppException, obj.load_app)277278    # import app from wsgi.py in current directory279    monkeypatch.chdir(os.path.abspath(os.path.join(280        os.path.dirname(__file__), 'test_apps', 'helloworld'281    )))282    obj = ScriptInfo()283    app = obj.load_app()284    assert app.name == 'hello'285286    # import app from app.py in current directory287    monkeypatch.chdir(os.path.abspath(os.path.join(288        os.path.dirname(__file__), 'test_apps', 'cliapp'289    )))290    obj = ScriptInfo()291    app = obj.load_app()292    assert app.name == 'testapp'293294295def test_with_appcontext(runner):296    """Test of with_appcontext."""297298    @click.command()299    @with_appcontext300    def testcmd():301        click.echo(current_app.name)302303    obj = ScriptInfo(create_app=lambda info: Flask("testapp"))304305    result = runner.invoke(testcmd, obj=obj)306    assert result.exit_code == 0307    assert result.output == 'testapp\n'308309310def test_appgroup(runner):311    """Test of with_appcontext."""312313    @click.group(cls=AppGroup)314    def cli():315        pass316317    @cli.command(with_appcontext=True)318    def test():319        click.echo(current_app.name)320321    @cli.group()322    def subgroup():323        pass324325    @subgroup.command(with_appcontext=True)326    def test2():327        click.echo(current_app.name)328329    obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))330331    result = runner.invoke(cli, ['test'], obj=obj)332    assert result.exit_code == 0333    assert result.output == 'testappgroup\n'334335    result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)336    assert result.exit_code == 0337    assert result.output == 'testappgroup\n'338339340def test_flaskgroup(runner):341    """Test FlaskGroup."""342343    def create_app(info):344        return Flask("flaskgroup")345346    @click.group(cls=FlaskGroup, create_app=create_app)347    def cli(**params):348        pass349350    @cli.command()351    def test():352        click.echo(current_app.name)353354    result = runner.invoke(cli, ['test'])355    assert result.exit_code == 0356    assert result.output == 'flaskgroup\n'357358359def test_print_exceptions(runner):360    """Print the stacktrace if the CLI."""361362    def create_app(info):363        raise Exception("oh no")364        return Flask("flaskgroup")365366    @click.group(cls=FlaskGroup, create_app=create_app)367    def cli(**params):368        pass369370    result = runner.invoke(cli, ['--help'])371    assert result.exit_code == 0372    assert 'Exception: oh no' in result.output373    assert 'Traceback' in result.output374375376class TestRoutes:377    @pytest.fixture378    def invoke(self, runner):379        def create_app(info):380            app = Flask(__name__)381            app.testing = True382383            @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])384            def yyy_get_post(x, y):385                pass386387            @app.route('/zzz_post', methods=['POST'])388            def aaa_post():389                pass390391            return app392393        cli = FlaskGroup(create_app=create_app)394        return partial(runner.invoke, cli)395396    def expect_order(self, order, output):397        # skip the header and match the start of each row398        for expect, line in zip(order, output.splitlines()[2:]):399            # do this instead of startswith for nicer pytest output400            assert line[:len(expect)] == expect401402    def test_simple(self, invoke):403        result = invoke(['routes'])404        assert result.exit_code == 0405        self.expect_order(406            ['aaa_post', 'static', 'yyy_get_post'],407            result.output408        )409410    def test_sort(self, invoke):411        default_output = invoke(['routes']).output412        endpoint_output = invoke(['routes', '-s', 'endpoint']).output413        assert default_output == endpoint_output414        self.expect_order(415            ['static', 'yyy_get_post', 'aaa_post'],416            invoke(['routes', '-s', 'methods']).output417        )418        self.expect_order(419            ['yyy_get_post', 'static', 'aaa_post'],420            invoke(['routes', '-s', 'rule']).output421        )422        self.expect_order(423            ['aaa_post', 'yyy_get_post', 'static'],424            invoke(['routes', '-s', 'match']).output425        )426427    def test_all_methods(self, invoke):428        output = invoke(['routes']).output429        assert 'GET, HEAD, OPTIONS, POST' not in output430        output = invoke(['routes', '--all-methods']).output431        assert 'GET, HEAD, OPTIONS, POST' in output432433434need_dotenv = pytest.mark.skipif(435    dotenv is None, reason='dotenv is not installed'436)437438439@need_dotenv440def test_load_dotenv(monkeypatch):441    # can't use monkeypatch.delitem since the keys don't exist yet442    for item in ('FOO', 'BAR', 'SPAM'):443        monkeypatch._setitem.append((os.environ, item, notset))444445    monkeypatch.setenv('EGGS', '3')446    monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))447    load_dotenv()448    assert os.getcwd() == test_path449    # .flaskenv doesn't overwrite .env450    assert os.environ['FOO'] == 'env'451    # set only in .flaskenv452    assert os.environ['BAR'] == 'bar'453    # set only in .env454    assert os.environ['SPAM'] == '1'455    # set manually, files don't overwrite456    assert os.environ['EGGS'] == '3'457458459@need_dotenv460def test_dotenv_path(monkeypatch):461    for item in ('FOO', 'BAR', 'EGGS'):462        monkeypatch._setitem.append((os.environ, item, notset))463464    cwd = os.getcwd()465    load_dotenv(os.path.join(test_path, '.flaskenv'))466    assert os.getcwd() == cwd467    assert 'FOO' in os.environ468469470def test_dotenv_optional(monkeypatch):471    monkeypatch.setattr('flask.cli.dotenv', None)472    monkeypatch.chdir(test_path)473    load_dotenv()474    assert 'FOO' not in os.environ475476477def test_run_cert_path():478    # no key479    with pytest.raises(click.BadParameter):480        run_command.make_context('run', ['--cert', __file__])481482    # no cert483    with pytest.raises(click.BadParameter):484        run_command.make_context('run', ['--key', __file__])485486    ctx = run_command.make_context(487        'run', ['--cert', __file__, '--key', __file__])488    assert ctx.params['cert'] == (__file__, __file__)489490491def test_run_cert_adhoc(monkeypatch):492    monkeypatch.setitem(sys.modules, 'OpenSSL', None)493494    # pyOpenSSL not installed495    with pytest.raises(click.BadParameter):496        run_command.make_context('run', ['--cert', 'adhoc'])497498    # pyOpenSSL installed499    monkeypatch.setitem(sys.modules, 'OpenSSL', types.ModuleType('OpenSSL'))500    ctx = run_command.make_context('run', ['--cert', 'adhoc'])501    assert ctx.params['cert'] == 'adhoc'502503    # no key with adhoc504    with pytest.raises(click.BadParameter):505        run_command.make_context('run', ['--cert', 'adhoc', '--key', __file__])506507508def test_run_cert_import(monkeypatch):509    monkeypatch.setitem(sys.modules, 'not_here', None)510511    # ImportError512    with pytest.raises(click.BadParameter):513        run_command.make_context('run', ['--cert', 'not_here'])514515    # not an SSLContext516    if sys.version_info >= (2, 7):517        with pytest.raises(click.BadParameter):518            run_command.make_context('run', ['--cert', 'flask'])519520    # SSLContext521    if sys.version_info < (2, 7):522        ssl_context = object()523    else:524        ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)525526    monkeypatch.setitem(sys.modules, 'ssl_context', ssl_context)527    ctx = run_command.make_context('run', ['--cert', 'ssl_context'])528    assert ctx.params['cert'] is ssl_context529530    # no --key with SSLContext531    with pytest.raises(click.BadParameter):532        run_command.make_context(533            'run', ['--cert', 'ssl_context', '--key', __file__])