Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

534 lines · 14.7 KiB · Python

Last changed by

Merge pull request #2530 from pallets/feature/factory-detectionDavid Lordbefore adoption03a2996

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_import1516import os17import ssl18import sys19import types20from functools import partial2122import click23import pytest24from _pytest.monkeypatch import notset25from click.testing import CliRunner2627from flask import Flask, current_app28from flask.cli import (29    AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, find_best_app,30    get_version, load_dotenv, locate_app, prepare_import, run_command,31    with_appcontext32)3334cwd = os.getcwd()35test_path = os.path.abspath(os.path.join(36    os.path.dirname(__file__), 'test_apps'37))383940@pytest.fixture41def runner():42    return CliRunner()434445def test_cli_name(test_apps):46    """Make sure the CLI object's name is the app's name and not the app itself"""47    from cliapp.app import testapp48    assert testapp.cli.name == testapp.name495051def test_find_best_app(test_apps):52    """Test if `find_best_app` behaves as expected with different combinations of input."""53    script_info = ScriptInfo()5455    class Module:56        app = Flask('appname')5758    assert find_best_app(script_info, Module) == Module.app5960    class Module:61        application = Flask('appname')6263    assert find_best_app(script_info, Module) == Module.application6465    class Module:66        myapp = Flask('appname')6768    assert find_best_app(script_info, Module) == Module.myapp6970    class Module:71        @staticmethod72        def create_app():73            return Flask('appname')7475    assert isinstance(find_best_app(script_info, Module), Flask)76    assert find_best_app(script_info, Module).name == 'appname'7778    class Module:79        @staticmethod80        def create_app(foo):81            return Flask('appname')8283    assert isinstance(find_best_app(script_info, Module), Flask)84    assert find_best_app(script_info, Module).name == 'appname'8586    class Module:87        @staticmethod88        def create_app(foo=None, script_info=None):89            return Flask('appname')9091    assert isinstance(find_best_app(script_info, Module), Flask)92    assert find_best_app(script_info, Module).name == 'appname'9394    class Module:95        @staticmethod96        def make_app():97            return Flask('appname')9899    assert isinstance(find_best_app(script_info, Module), Flask)100    assert find_best_app(script_info, Module).name == 'appname'101102    class Module:103        myapp = Flask('appname1')104105        @staticmethod106        def create_app():107            return Flask('appname2')108109    assert find_best_app(script_info, Module) == Module.myapp110111    class Module:112        myapp = Flask('appname1')113114        @staticmethod115        def create_app():116            return Flask('appname2')117118    assert find_best_app(script_info, Module) == Module.myapp119120    class Module:121        pass122123    pytest.raises(NoAppException, find_best_app, script_info, Module)124125    class Module:126        myapp1 = Flask('appname1')127        myapp2 = Flask('appname2')128129    pytest.raises(NoAppException, find_best_app, script_info, Module)130131    class Module:132        @staticmethod133        def create_app(foo, bar):134            return Flask('appname2')135136    pytest.raises(NoAppException, find_best_app, script_info, Module)137138    class Module:139        @staticmethod140        def create_app():141            raise TypeError('bad bad factory!')142143    pytest.raises(TypeError, find_best_app, script_info, Module)144145146@pytest.mark.parametrize('value,path,result', (147    ('test', cwd, 'test'),148    ('test.py', cwd, 'test'),149    ('a/test', os.path.join(cwd, 'a'), 'test'),150    ('test/__init__.py', cwd, 'test'),151    ('test/__init__', cwd, 'test'),152    # nested package153    (154        os.path.join(test_path, 'cliapp', 'inner1', '__init__'),155        test_path, 'cliapp.inner1'156    ),157    (158        os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),159        test_path, 'cliapp.inner1.inner2'160    ),161    # dotted name162    ('test.a.b', cwd, 'test.a.b'),163    (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),164    # not a Python file, will be caught during import165    (166        os.path.join(test_path, 'cliapp', 'message.txt'),167        test_path, 'cliapp.message.txt'168    ),169))170def test_prepare_import(request, value, path, result):171    """Expect the correct path to be set and the correct import and app names172    to be returned.173174    :func:`prepare_exec_for_file` has a side effect where the parent directory175    of the given import is added to :data:`sys.path`. This is reset after the176    test runs.177    """178    original_path = sys.path[:]179180    def reset_path():181        sys.path[:] = original_path182183    request.addfinalizer(reset_path)184185    assert prepare_import(value) == result186    assert sys.path[0] == path187188189@pytest.mark.parametrize('iname,aname,result', (190    ('cliapp.app', None, 'testapp'),191    ('cliapp.app', 'testapp', 'testapp'),192    ('cliapp.factory', None, 'app'),193    ('cliapp.factory', 'create_app', 'app'),194    ('cliapp.factory', 'create_app()', 'app'),195    # no script_info196    ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),197    # trailing comma space198    ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),199    # takes script_info200    ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),201    # strip whitespace202    ('cliapp.factory', ' create_app () ', 'app'),203))204def test_locate_app(test_apps, iname, aname, result):205    info = ScriptInfo()206    info.data['test'] = 'spam'207    assert locate_app(info, iname, aname).name == result208209210@pytest.mark.parametrize('iname,aname', (211    ('notanapp.py', None),212    ('cliapp/app', None),213    ('cliapp.app', 'notanapp'),214    # not enough arguments215    ('cliapp.factory', 'create_app2("foo")'),216    # invalid identifier217    ('cliapp.factory', 'create_app('),218    # no app returned219    ('cliapp.factory', 'no_app'),220    # nested import error221    ('cliapp.importerrorapp', None),222    # not a Python file223    ('cliapp.message.txt', None),224))225def test_locate_app_raises(test_apps, iname, aname):226    info = ScriptInfo()227228    with pytest.raises(NoAppException):229        locate_app(info, iname, aname)230231232def test_locate_app_suppress_raise():233    info = ScriptInfo()234    app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)235    assert app is None236237    # only direct import error is suppressed238    with pytest.raises(NoAppException):239        locate_app(240            info, 'cliapp.importerrorapp', None, raise_if_not_found=False241        )242243244def test_get_version(test_apps, capsys):245    """Test of get_version."""246    from flask import __version__ as flask_ver247    from sys import version as py_ver248249    class MockCtx(object):250        resilient_parsing = False251        color = None252253        def exit(self): return254255    ctx = MockCtx()256    get_version(ctx, None, "test")257    out, err = capsys.readouterr()258    assert flask_ver in out259    assert py_ver in out260261262def test_scriptinfo(test_apps, monkeypatch):263    """Test of ScriptInfo."""264    obj = ScriptInfo(app_import_path="cliapp.app:testapp")265    assert obj.load_app().name == "testapp"266    assert obj.load_app().name == "testapp"267268    def create_app(info):269        return Flask("createapp")270271    obj = ScriptInfo(create_app=create_app)272    app = obj.load_app()273    assert app.name == "createapp"274    assert obj.load_app() == app275276    obj = ScriptInfo()277    pytest.raises(NoAppException, obj.load_app)278279    # import app from wsgi.py in current directory280    monkeypatch.chdir(os.path.abspath(os.path.join(281        os.path.dirname(__file__), 'test_apps', 'helloworld'282    )))283    obj = ScriptInfo()284    app = obj.load_app()285    assert app.name == 'hello'286287    # import app from app.py in current directory288    monkeypatch.chdir(os.path.abspath(os.path.join(289        os.path.dirname(__file__), 'test_apps', 'cliapp'290    )))291    obj = ScriptInfo()292    app = obj.load_app()293    assert app.name == 'testapp'294295296def test_with_appcontext(runner):297    """Test of with_appcontext."""298299    @click.command()300    @with_appcontext301    def testcmd():302        click.echo(current_app.name)303304    obj = ScriptInfo(create_app=lambda info: Flask("testapp"))305306    result = runner.invoke(testcmd, obj=obj)307    assert result.exit_code == 0308    assert result.output == 'testapp\n'309310311def test_appgroup(runner):312    """Test of with_appcontext."""313314    @click.group(cls=AppGroup)315    def cli():316        pass317318    @cli.command(with_appcontext=True)319    def test():320        click.echo(current_app.name)321322    @cli.group()323    def subgroup():324        pass325326    @subgroup.command(with_appcontext=True)327    def test2():328        click.echo(current_app.name)329330    obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))331332    result = runner.invoke(cli, ['test'], obj=obj)333    assert result.exit_code == 0334    assert result.output == 'testappgroup\n'335336    result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)337    assert result.exit_code == 0338    assert result.output == 'testappgroup\n'339340341def test_flaskgroup(runner):342    """Test FlaskGroup."""343344    def create_app(info):345        return Flask("flaskgroup")346347    @click.group(cls=FlaskGroup, create_app=create_app)348    def cli(**params):349        pass350351    @cli.command()352    def test():353        click.echo(current_app.name)354355    result = runner.invoke(cli, ['test'])356    assert result.exit_code == 0357    assert result.output == 'flaskgroup\n'358359360def test_print_exceptions(runner):361    """Print the stacktrace if the CLI."""362363    def create_app(info):364        raise Exception("oh no")365        return Flask("flaskgroup")366367    @click.group(cls=FlaskGroup, create_app=create_app)368    def cli(**params):369        pass370371    result = runner.invoke(cli, ['--help'])372    assert result.exit_code == 0373    assert 'Exception: oh no' in result.output374    assert 'Traceback' in result.output375376377class TestRoutes:378    @pytest.fixture379    def invoke(self, runner):380        def create_app(info):381            app = Flask(__name__)382            app.testing = True383384            @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])385            def yyy_get_post(x, y):386                pass387388            @app.route('/zzz_post', methods=['POST'])389            def aaa_post():390                pass391392            return app393394        cli = FlaskGroup(create_app=create_app)395        return partial(runner.invoke, cli)396397    def expect_order(self, order, output):398        # skip the header and match the start of each row399        for expect, line in zip(order, output.splitlines()[2:]):400            # do this instead of startswith for nicer pytest output401            assert line[:len(expect)] == expect402403    def test_simple(self, invoke):404        result = invoke(['routes'])405        assert result.exit_code == 0406        self.expect_order(407            ['aaa_post', 'static', 'yyy_get_post'],408            result.output409        )410411    def test_sort(self, invoke):412        default_output = invoke(['routes']).output413        endpoint_output = invoke(['routes', '-s', 'endpoint']).output414        assert default_output == endpoint_output415        self.expect_order(416            ['static', 'yyy_get_post', 'aaa_post'],417            invoke(['routes', '-s', 'methods']).output418        )419        self.expect_order(420            ['yyy_get_post', 'static', 'aaa_post'],421            invoke(['routes', '-s', 'rule']).output422        )423        self.expect_order(424            ['aaa_post', 'yyy_get_post', 'static'],425            invoke(['routes', '-s', 'match']).output426        )427428    def test_all_methods(self, invoke):429        output = invoke(['routes']).output430        assert 'GET, HEAD, OPTIONS, POST' not in output431        output = invoke(['routes', '--all-methods']).output432        assert 'GET, HEAD, OPTIONS, POST' in output433434435need_dotenv = pytest.mark.skipif(436    dotenv is None, reason='dotenv is not installed'437)438439440@need_dotenv441def test_load_dotenv(monkeypatch):442    # can't use monkeypatch.delitem since the keys don't exist yet443    for item in ('FOO', 'BAR', 'SPAM'):444        monkeypatch._setitem.append((os.environ, item, notset))445446    monkeypatch.setenv('EGGS', '3')447    monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))448    load_dotenv()449    assert os.getcwd() == test_path450    # .flaskenv doesn't overwrite .env451    assert os.environ['FOO'] == 'env'452    # set only in .flaskenv453    assert os.environ['BAR'] == 'bar'454    # set only in .env455    assert os.environ['SPAM'] == '1'456    # set manually, files don't overwrite457    assert os.environ['EGGS'] == '3'458459460@need_dotenv461def test_dotenv_path(monkeypatch):462    for item in ('FOO', 'BAR', 'EGGS'):463        monkeypatch._setitem.append((os.environ, item, notset))464465    cwd = os.getcwd()466    load_dotenv(os.path.join(test_path, '.flaskenv'))467    assert os.getcwd() == cwd468    assert 'FOO' in os.environ469470471def test_dotenv_optional(monkeypatch):472    monkeypatch.setattr('flask.cli.dotenv', None)473    monkeypatch.chdir(test_path)474    load_dotenv()475    assert 'FOO' not in os.environ476477478def test_run_cert_path():479    # no key480    with pytest.raises(click.BadParameter):481        run_command.make_context('run', ['--cert', __file__])482483    # no cert484    with pytest.raises(click.BadParameter):485        run_command.make_context('run', ['--key', __file__])486487    ctx = run_command.make_context(488        'run', ['--cert', __file__, '--key', __file__])489    assert ctx.params['cert'] == (__file__, __file__)490491492def test_run_cert_adhoc(monkeypatch):493    monkeypatch.setitem(sys.modules, 'OpenSSL', None)494495    # pyOpenSSL not installed496    with pytest.raises(click.BadParameter):497        run_command.make_context('run', ['--cert', 'adhoc'])498499    # pyOpenSSL installed500    monkeypatch.setitem(sys.modules, 'OpenSSL', types.ModuleType('OpenSSL'))501    ctx = run_command.make_context('run', ['--cert', 'adhoc'])502    assert ctx.params['cert'] == 'adhoc'503504    # no key with adhoc505    with pytest.raises(click.BadParameter):506        run_command.make_context('run', ['--cert', 'adhoc', '--key', __file__])507508509def test_run_cert_import(monkeypatch):510    monkeypatch.setitem(sys.modules, 'not_here', None)511512    # ImportError513    with pytest.raises(click.BadParameter):514        run_command.make_context('run', ['--cert', 'not_here'])515516    # not an SSLContext517    if sys.version_info >= (2, 7):518        with pytest.raises(click.BadParameter):519            run_command.make_context('run', ['--cert', 'flask'])520521    # SSLContext522    if sys.version_info < (2, 7):523        ssl_context = object()524    else:525        ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)526527    monkeypatch.setitem(sys.modules, 'ssl_context', ssl_context)528    ctx = run_command.make_context('run', ['--cert', 'ssl_context'])529    assert ctx.params['cert'] is ssl_context530531    # no --key with SSLContext532    with pytest.raises(click.BadParameter):533        run_command.make_context(534            'run', ['--cert', 'ssl_context', '--key', __file__])