Skip to content
Myr

test_config.py

This file

Path

tests/test_config.py

207 lines · 6.0 KiB · Python

Last changed by

Fix config.from_pyfile on Python 3 (#2123)Markus Unterwaditzerbefore adoption789715a

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.test_config4    ~~~~~~~~~~~~~~~~~56    :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7    :license: BSD, see LICENSE for more details.8"""91011from datetime import timedelta12import os13import textwrap1415import flask16from flask._compat import PY217import pytest181920# config keys used for the TestConfig21TEST_KEY = 'foo'22SECRET_KEY = 'devkey'232425def common_object_test(app):26    assert app.secret_key == 'devkey'27    assert app.config['TEST_KEY'] == 'foo'28    assert 'TestConfig' not in app.config293031def test_config_from_file():32    app = flask.Flask(__name__)33    app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')34    common_object_test(app)353637def test_config_from_object():38    app = flask.Flask(__name__)39    app.config.from_object(__name__)40    common_object_test(app)414243def test_config_from_json():44    app = flask.Flask(__name__)45    current_dir = os.path.dirname(os.path.abspath(__file__))46    app.config.from_json(os.path.join(current_dir, 'static', 'config.json'))47    common_object_test(app)484950def test_config_from_mapping():51    app = flask.Flask(__name__)52    app.config.from_mapping({53        'SECRET_KEY': 'devkey',54        'TEST_KEY': 'foo'55    })56    common_object_test(app)5758    app = flask.Flask(__name__)59    app.config.from_mapping([60        ('SECRET_KEY', 'devkey'),61        ('TEST_KEY', 'foo')62    ])63    common_object_test(app)6465    app = flask.Flask(__name__)66    app.config.from_mapping(67        SECRET_KEY='devkey',68        TEST_KEY='foo'69    )70    common_object_test(app)7172    app = flask.Flask(__name__)73    with pytest.raises(TypeError):74        app.config.from_mapping(75            {}, {}76        )777879def test_config_from_class():80    class Base(object):81        TEST_KEY = 'foo'8283    class Test(Base):84        SECRET_KEY = 'devkey'85    app = flask.Flask(__name__)86    app.config.from_object(Test)87    common_object_test(app)888990def test_config_from_envvar():91    env = os.environ92    try:93        os.environ = {}94        app = flask.Flask(__name__)95        with pytest.raises(RuntimeError) as e:96            app.config.from_envvar('FOO_SETTINGS')97        assert "'FOO_SETTINGS' is not set" in str(e.value)98        assert not app.config.from_envvar('FOO_SETTINGS', silent=True)99100        os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}101        assert app.config.from_envvar('FOO_SETTINGS')102        common_object_test(app)103    finally:104        os.environ = env105106107def test_config_from_envvar_missing():108    env = os.environ109    try:110        os.environ = {'FOO_SETTINGS': 'missing.cfg'}111        with pytest.raises(IOError) as e:112            app = flask.Flask(__name__)113            app.config.from_envvar('FOO_SETTINGS')114        msg = str(e.value)115        assert msg.startswith('[Errno 2] Unable to load configuration '116                              'file (No such file or directory):')117        assert msg.endswith("missing.cfg'")118        assert not app.config.from_envvar('FOO_SETTINGS', silent=True)119    finally:120        os.environ = env121122123def test_config_missing():124    app = flask.Flask(__name__)125    with pytest.raises(IOError) as e:126        app.config.from_pyfile('missing.cfg')127    msg = str(e.value)128    assert msg.startswith('[Errno 2] Unable to load configuration '129                          'file (No such file or directory):')130    assert msg.endswith("missing.cfg'")131    assert not app.config.from_pyfile('missing.cfg', silent=True)132133134def test_config_missing_json():135    app = flask.Flask(__name__)136    with pytest.raises(IOError) as e:137        app.config.from_json('missing.json')138    msg = str(e.value)139    assert msg.startswith('[Errno 2] Unable to load configuration '140                          'file (No such file or directory):')141    assert msg.endswith("missing.json'")142    assert not app.config.from_json('missing.json', silent=True)143144145def test_custom_config_class():146    class Config(flask.Config):147        pass148149    class Flask(flask.Flask):150        config_class = Config151    app = Flask(__name__)152    assert isinstance(app.config, Config)153    app.config.from_object(__name__)154    common_object_test(app)155156157def test_session_lifetime():158    app = flask.Flask(__name__)159    app.config['PERMANENT_SESSION_LIFETIME'] = 42160    assert app.permanent_session_lifetime.seconds == 42161162163def test_send_file_max_age():164    app = flask.Flask(__name__)165    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600166    assert app.send_file_max_age_default.seconds == 3600167    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(hours=2)168    assert app.send_file_max_age_default.seconds == 7200169170171def test_get_namespace():172    app = flask.Flask(__name__)173    app.config['FOO_OPTION_1'] = 'foo option 1'174    app.config['FOO_OPTION_2'] = 'foo option 2'175    app.config['BAR_STUFF_1'] = 'bar stuff 1'176    app.config['BAR_STUFF_2'] = 'bar stuff 2'177    foo_options = app.config.get_namespace('FOO_')178    assert 2 == len(foo_options)179    assert 'foo option 1' == foo_options['option_1']180    assert 'foo option 2' == foo_options['option_2']181    bar_options = app.config.get_namespace('BAR_', lowercase=False)182    assert 2 == len(bar_options)183    assert 'bar stuff 1' == bar_options['STUFF_1']184    assert 'bar stuff 2' == bar_options['STUFF_2']185    foo_options = app.config.get_namespace('FOO_', trim_namespace=False)186    assert 2 == len(foo_options)187    assert 'foo option 1' == foo_options['foo_option_1']188    assert 'foo option 2' == foo_options['foo_option_2']189    bar_options = app.config.get_namespace('BAR_', lowercase=False, trim_namespace=False)190    assert 2 == len(bar_options)191    assert 'bar stuff 1' == bar_options['BAR_STUFF_1']192    assert 'bar stuff 2' == bar_options['BAR_STUFF_2']193194195@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])196def test_from_pyfile_weird_encoding(tmpdir, encoding):197    f = tmpdir.join('my_config.py')198    f.write_binary(textwrap.dedent(u'''199    # -*- coding: {0} -*-200    TEST_VALUE = "föö"201    '''.format(encoding)).encode(encoding))202    app = flask.Flask(__name__)203    app.config.from_pyfile(str(f))204    value = app.config['TEST_VALUE']205    if PY2:206        value = value.decode(encoding)207    assert value == u'föö'