Skip to content
Myr

test_cli.py

This file

Path

tests/test_cli.py

473 lines · 12.9 KiB · Python

Last changed by

Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4

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 sys18from functools import partial1920import click21import pytest22from _pytest.monkeypatch import notset23from click.testing import CliRunner2425from flask import Flask, current_app26from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, \27    find_best_app, get_version, load_dotenv, locate_app, prepare_import, \28    with_appcontext2930cwd = os.getcwd()31test_path = os.path.abspath(os.path.join(32    os.path.dirname(__file__), 'test_apps'33))343536@pytest.fixture(autouse=True)37def manage_os_environ(monkeypatch):38    # can't use monkeypatch.delitem since we don't want to restore a value39    os.environ.pop('FLASK_APP', None)40    os.environ.pop('FLASK_DEBUG', None)41    # use monkeypatch internals to force-delete environ keys42    monkeypatch._setitem.extend((43        (os.environ, 'FLASK_APP', notset),44        (os.environ, 'FLASK_DEBUG', notset),45        (os.environ, 'FLASK_RUN_FROM_CLI', notset),46    ))474849@pytest.fixture50def runner():51    return CliRunner()525354def test_cli_name(test_apps):55    """Make sure the CLI object's name is the app's name and not the app itself"""56    from cliapp.app import testapp57    assert testapp.cli.name == testapp.name585960def test_find_best_app(test_apps):61    """Test if `find_best_app` behaves as expected with different combinations of input."""62    script_info = ScriptInfo()6364    class Module:65        app = Flask('appname')6667    assert find_best_app(script_info, Module) == Module.app6869    class Module:70        application = Flask('appname')7172    assert find_best_app(script_info, Module) == Module.application7374    class Module:75        myapp = Flask('appname')7677    assert find_best_app(script_info, Module) == Module.myapp7879    class Module:80        @staticmethod81        def create_app():82            return Flask('appname')8384    assert isinstance(find_best_app(script_info, Module), Flask)85    assert find_best_app(script_info, Module).name == 'appname'8687    class Module:88        @staticmethod89        def create_app(foo):90            return Flask('appname')9192    assert isinstance(find_best_app(script_info, Module), Flask)93    assert find_best_app(script_info, Module).name == 'appname'9495    class Module:96        @staticmethod97        def create_app(foo=None, script_info=None):98            return Flask('appname')99100    assert isinstance(find_best_app(script_info, Module), Flask)101    assert find_best_app(script_info, Module).name == 'appname'102103    class Module:104        @staticmethod105        def make_app():106            return Flask('appname')107108    assert isinstance(find_best_app(script_info, Module), Flask)109    assert find_best_app(script_info, Module).name == 'appname'110111    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        myapp = Flask('appname1')122123        @staticmethod124        def create_app():125            return Flask('appname2')126127    assert find_best_app(script_info, Module) == Module.myapp128129    class Module:130        pass131132    pytest.raises(NoAppException, find_best_app, script_info, Module)133134    class Module:135        myapp1 = Flask('appname1')136        myapp2 = Flask('appname2')137138    pytest.raises(NoAppException, find_best_app, script_info, Module)139140    class Module:141        @staticmethod142        def create_app(foo, bar):143            return Flask('appname2')144145    pytest.raises(NoAppException, find_best_app, script_info, Module)146147148@pytest.mark.parametrize('value,path,result', (149    ('test', cwd, 'test'),150    ('test.py', cwd, 'test'),151    ('a/test', os.path.join(cwd, 'a'), 'test'),152    ('test/__init__.py', cwd, 'test'),153    ('test/__init__', cwd, 'test'),154    # nested package155    (156        os.path.join(test_path, 'cliapp', 'inner1', '__init__'),157        test_path, 'cliapp.inner1'158    ),159    (160        os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),161        test_path, 'cliapp.inner1.inner2'162    ),163    # dotted name164    ('test.a.b', cwd, 'test.a.b'),165    (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),166    # not a Python file, will be caught during import167    (168        os.path.join(test_path, 'cliapp', 'message.txt'),169        test_path, 'cliapp.message.txt'170    ),171))172def test_prepare_import(request, value, path, result):173    """Expect the correct path to be set and the correct import and app names174    to be returned.175176    :func:`prepare_exec_for_file` has a side effect where the parent directory177    of the given import is added to :data:`sys.path`. This is reset after the178    test runs.179    """180    original_path = sys.path[:]181182    def reset_path():183        sys.path[:] = original_path184185    request.addfinalizer(reset_path)186187    assert prepare_import(value) == result188    assert sys.path[0] == path189190191@pytest.mark.parametrize('iname,aname,result', (192    ('cliapp.app', None, 'testapp'),193    ('cliapp.app', 'testapp', 'testapp'),194    ('cliapp.factory', None, 'app'),195    ('cliapp.factory', 'create_app', 'app'),196    ('cliapp.factory', 'create_app()', 'app'),197    # no script_info198    ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),199    # trailing comma space200    ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),201    # takes script_info202    ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),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    # nested import error217    ('cliapp.importerrorapp', None),218    # not a Python file219    ('cliapp.message.txt', None),220    # space before arg list221    ('cliapp.factory', 'create_app ()'),222))223def test_locate_app_raises(test_apps, iname, aname):224    info = ScriptInfo()225226    with pytest.raises(NoAppException):227        locate_app(info, iname, aname)228229230def test_locate_app_suppress_raise():231    info = ScriptInfo()232    app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)233    assert app is None234235    # only direct import error is suppressed236    with pytest.raises(NoAppException):237        locate_app(238            info, 'cliapp.importerrorapp', None, raise_if_not_found=False239        )240241242def test_get_version(test_apps, capsys):243    """Test of get_version."""244    from flask import __version__ as flask_ver245    from sys import version as py_ver246247    class MockCtx(object):248        resilient_parsing = False249        color = None250251        def exit(self): return252253    ctx = MockCtx()254    get_version(ctx, None, "test")255    out, err = capsys.readouterr()256    assert flask_ver in out257    assert py_ver in out258259260def test_scriptinfo(test_apps, monkeypatch):261    """Test of ScriptInfo."""262    obj = ScriptInfo(app_import_path="cliapp.app:testapp")263    assert obj.load_app().name == "testapp"264    assert obj.load_app().name == "testapp"265266    def create_app(info):267        return Flask("createapp")268269    obj = ScriptInfo(create_app=create_app)270    app = obj.load_app()271    assert app.name == "createapp"272    assert obj.load_app() == app273274    obj = ScriptInfo()275    pytest.raises(NoAppException, obj.load_app)276277    # import app from wsgi.py in current directory278    monkeypatch.chdir(os.path.abspath(os.path.join(279        os.path.dirname(__file__), 'test_apps', 'helloworld'280    )))281    obj = ScriptInfo()282    app = obj.load_app()283    assert app.name == 'hello'284285    # import app from app.py in current directory286    monkeypatch.chdir(os.path.abspath(os.path.join(287        os.path.dirname(__file__), 'test_apps', 'cliapp'288    )))289    obj = ScriptInfo()290    app = obj.load_app()291    assert app.name == 'testapp'292293294def test_with_appcontext(runner):295    """Test of with_appcontext."""296297    @click.command()298    @with_appcontext299    def testcmd():300        click.echo(current_app.name)301302    obj = ScriptInfo(create_app=lambda info: Flask("testapp"))303304    result = runner.invoke(testcmd, obj=obj)305    assert result.exit_code == 0306    assert result.output == 'testapp\n'307308309def test_appgroup(runner):310    """Test of with_appcontext."""311312    @click.group(cls=AppGroup)313    def cli():314        pass315316    @cli.command(with_appcontext=True)317    def test():318        click.echo(current_app.name)319320    @cli.group()321    def subgroup():322        pass323324    @subgroup.command(with_appcontext=True)325    def test2():326        click.echo(current_app.name)327328    obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))329330    result = runner.invoke(cli, ['test'], obj=obj)331    assert result.exit_code == 0332    assert result.output == 'testappgroup\n'333334    result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)335    assert result.exit_code == 0336    assert result.output == 'testappgroup\n'337338339def test_flaskgroup(runner):340    """Test FlaskGroup."""341342    def create_app(info):343        return Flask("flaskgroup")344345    @click.group(cls=FlaskGroup, create_app=create_app)346    def cli(**params):347        pass348349    @cli.command()350    def test():351        click.echo(current_app.name)352353    result = runner.invoke(cli, ['test'])354    assert result.exit_code == 0355    assert result.output == 'flaskgroup\n'356357358def test_print_exceptions(runner):359    """Print the stacktrace if the CLI."""360361    def create_app(info):362        raise Exception("oh no")363        return Flask("flaskgroup")364365    @click.group(cls=FlaskGroup, create_app=create_app)366    def cli(**params):367        pass368369    result = runner.invoke(cli, ['--help'])370    assert result.exit_code == 0371    assert 'Exception: oh no' in result.output372    assert 'Traceback' in result.output373374375class TestRoutes:376    @pytest.fixture377    def invoke(self, runner):378        def create_app(info):379            app = Flask(__name__)380            app.testing = True381382            @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])383            def yyy_get_post(x, y):384                pass385386            @app.route('/zzz_post', methods=['POST'])387            def aaa_post():388                pass389390            return app391392        cli = FlaskGroup(create_app=create_app)393        return partial(runner.invoke, cli)394395    def expect_order(self, order, output):396        # skip the header and match the start of each row397        for expect, line in zip(order, output.splitlines()[2:]):398            # do this instead of startswith for nicer pytest output399            assert line[:len(expect)] == expect400401    def test_simple(self, invoke):402        result = invoke(['routes'])403        assert result.exit_code == 0404        self.expect_order(405            ['aaa_post', 'static', 'yyy_get_post'],406            result.output407        )408409    def test_sort(self, invoke):410        default_output = invoke(['routes']).output411        endpoint_output = invoke(['routes', '-s', 'endpoint']).output412        assert default_output == endpoint_output413        self.expect_order(414            ['static', 'yyy_get_post', 'aaa_post'],415            invoke(['routes', '-s', 'methods']).output416        )417        self.expect_order(418            ['yyy_get_post', 'static', 'aaa_post'],419            invoke(['routes', '-s', 'rule']).output420        )421        self.expect_order(422            ['aaa_post', 'yyy_get_post', 'static'],423            invoke(['routes', '-s', 'match']).output424        )425426    def test_all_methods(self, invoke):427        output = invoke(['routes']).output428        assert 'GET, HEAD, OPTIONS, POST' not in output429        output = invoke(['routes', '--all-methods']).output430        assert 'GET, HEAD, OPTIONS, POST' in output431432433need_dotenv = pytest.mark.skipif(434    dotenv is None, reason='dotenv is not installed'435)436437438@need_dotenv439def test_load_dotenv(monkeypatch):440    # can't use monkeypatch.delitem since the keys don't exist yet441    for item in ('FOO', 'BAR', 'SPAM'):442        monkeypatch._setitem.append((os.environ, item, notset))443444    monkeypatch.setenv('EGGS', '3')445    monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))446    load_dotenv()447    assert os.getcwd() == test_path448    # .flaskenv doesn't overwrite .env449    assert os.environ['FOO'] == 'env'450    # set only in .flaskenv451    assert os.environ['BAR'] == 'bar'452    # set only in .env453    assert os.environ['SPAM'] == '1'454    # set manually, files don't overwrite455    assert os.environ['EGGS'] == '3'456457458@need_dotenv459def test_dotenv_path(monkeypatch):460    for item in ('FOO', 'BAR', 'EGGS'):461        monkeypatch._setitem.append((os.environ, item, notset))462463    cwd = os.getcwd()464    load_dotenv(os.path.join(test_path, '.flaskenv'))465    assert os.getcwd() == cwd466    assert 'FOO' in os.environ467468469def test_dotenv_optional(monkeypatch):470    monkeypatch.setattr('flask.cli.dotenv', None)471    monkeypatch.chdir(test_path)472    load_dotenv()473    assert 'FOO' not in os.environ