Skip to content
Myr

test_config.py

This file

Path

tests/test_config.py

250 lines · 7.5 KiB · Python

Last changed by

drop support for Python 3.10 (#6168)David Lordbefore adoption728c5e4

History of this file

Take it

1import json2import os3import tomllib45import pytest67import flask89# config keys used for the TestConfig10TEST_KEY = "foo"11SECRET_KEY = "config"121314def common_object_test(app):15    assert app.secret_key == "config"16    assert app.config["TEST_KEY"] == "foo"17    assert "TestConfig" not in app.config181920def test_config_from_pyfile():21    app = flask.Flask(__name__)22    app.config.from_pyfile(f"{__file__.rsplit('.', 1)[0]}.py")23    common_object_test(app)242526def test_config_from_object():27    app = flask.Flask(__name__)28    app.config.from_object(__name__)29    common_object_test(app)303132def test_config_from_file_json():33    app = flask.Flask(__name__)34    current_dir = os.path.dirname(os.path.abspath(__file__))35    app.config.from_file(os.path.join(current_dir, "static", "config.json"), json.load)36    common_object_test(app)373839def test_config_from_file_toml():40    app = flask.Flask(__name__)41    current_dir = os.path.dirname(os.path.abspath(__file__))42    app.config.from_file(43        os.path.join(current_dir, "static", "config.toml"), tomllib.load, text=False44    )45    common_object_test(app)464748def test_from_prefixed_env(monkeypatch):49    monkeypatch.setenv("FLASK_STRING", "value")50    monkeypatch.setenv("FLASK_BOOL", "true")51    monkeypatch.setenv("FLASK_INT", "1")52    monkeypatch.setenv("FLASK_FLOAT", "1.2")53    monkeypatch.setenv("FLASK_LIST", "[1, 2]")54    monkeypatch.setenv("FLASK_DICT", '{"k": "v"}')55    monkeypatch.setenv("NOT_FLASK_OTHER", "other")5657    app = flask.Flask(__name__)58    app.config.from_prefixed_env()5960    assert app.config["STRING"] == "value"61    assert app.config["BOOL"] is True62    assert app.config["INT"] == 163    assert app.config["FLOAT"] == 1.264    assert app.config["LIST"] == [1, 2]65    assert app.config["DICT"] == {"k": "v"}66    assert "OTHER" not in app.config676869def test_from_prefixed_env_custom_prefix(monkeypatch):70    monkeypatch.setenv("FLASK_A", "a")71    monkeypatch.setenv("NOT_FLASK_A", "b")7273    app = flask.Flask(__name__)74    app.config.from_prefixed_env("NOT_FLASK")7576    assert app.config["A"] == "b"777879def test_from_prefixed_env_nested(monkeypatch):80    monkeypatch.setenv("FLASK_EXIST__ok", "other")81    monkeypatch.setenv("FLASK_EXIST__inner__ik", "2")82    monkeypatch.setenv("FLASK_EXIST__new__more", '{"k": false}')83    monkeypatch.setenv("FLASK_NEW__K", "v")8485    app = flask.Flask(__name__)86    app.config["EXIST"] = {"ok": "value", "flag": True, "inner": {"ik": 1}}87    app.config.from_prefixed_env()8889    if os.name != "nt":90        assert app.config["EXIST"] == {91            "ok": "other",92            "flag": True,93            "inner": {"ik": 2},94            "new": {"more": {"k": False}},95        }96    else:97        # Windows env var keys are always uppercase.98        assert app.config["EXIST"] == {99            "ok": "value",100            "OK": "other",101            "flag": True,102            "inner": {"ik": 1},103            "INNER": {"IK": 2},104            "NEW": {"MORE": {"k": False}},105        }106107    assert app.config["NEW"] == {"K": "v"}108109110def test_config_from_mapping():111    app = flask.Flask(__name__)112    app.config.from_mapping({"SECRET_KEY": "config", "TEST_KEY": "foo"})113    common_object_test(app)114115    app = flask.Flask(__name__)116    app.config.from_mapping([("SECRET_KEY", "config"), ("TEST_KEY", "foo")])117    common_object_test(app)118119    app = flask.Flask(__name__)120    app.config.from_mapping(SECRET_KEY="config", TEST_KEY="foo")121    common_object_test(app)122123    app = flask.Flask(__name__)124    app.config.from_mapping(SECRET_KEY="config", TEST_KEY="foo", skip_key="skip")125    common_object_test(app)126127    app = flask.Flask(__name__)128    with pytest.raises(TypeError):129        app.config.from_mapping({}, {})130131132def test_config_from_class():133    class Base:134        TEST_KEY = "foo"135136    class Test(Base):137        SECRET_KEY = "config"138139    app = flask.Flask(__name__)140    app.config.from_object(Test)141    common_object_test(app)142143144def test_config_from_envvar(monkeypatch):145    monkeypatch.setattr("os.environ", {})146    app = flask.Flask(__name__)147148    with pytest.raises(RuntimeError) as e:149        app.config.from_envvar("FOO_SETTINGS")150151    assert "'FOO_SETTINGS' is not set" in str(e.value)152    assert not app.config.from_envvar("FOO_SETTINGS", silent=True)153154    monkeypatch.setattr(155        "os.environ", {"FOO_SETTINGS": f"{__file__.rsplit('.', 1)[0]}.py"}156    )157    assert app.config.from_envvar("FOO_SETTINGS")158    common_object_test(app)159160161def test_config_from_envvar_missing(monkeypatch):162    monkeypatch.setattr("os.environ", {"FOO_SETTINGS": "missing.cfg"})163    app = flask.Flask(__name__)164    with pytest.raises(IOError) as e:165        app.config.from_envvar("FOO_SETTINGS")166    msg = str(e.value)167    assert msg.startswith(168        "[Errno 2] Unable to load configuration file (No such file or directory):"169    )170    assert msg.endswith("missing.cfg'")171    assert not app.config.from_envvar("FOO_SETTINGS", silent=True)172173174def test_config_missing():175    app = flask.Flask(__name__)176    with pytest.raises(IOError) as e:177        app.config.from_pyfile("missing.cfg")178    msg = str(e.value)179    assert msg.startswith(180        "[Errno 2] Unable to load configuration file (No such file or directory):"181    )182    assert msg.endswith("missing.cfg'")183    assert not app.config.from_pyfile("missing.cfg", silent=True)184185186def test_config_missing_file():187    app = flask.Flask(__name__)188    with pytest.raises(IOError) as e:189        app.config.from_file("missing.json", load=json.load)190    msg = str(e.value)191    assert msg.startswith(192        "[Errno 2] Unable to load configuration file (No such file or directory):"193    )194    assert msg.endswith("missing.json'")195    assert not app.config.from_file("missing.json", load=json.load, silent=True)196197198def test_custom_config_class():199    class Config(flask.Config):200        pass201202    class Flask(flask.Flask):203        config_class = Config204205    app = Flask(__name__)206    assert isinstance(app.config, Config)207    app.config.from_object(__name__)208    common_object_test(app)209210211def test_session_lifetime():212    app = flask.Flask(__name__)213    app.config["PERMANENT_SESSION_LIFETIME"] = 42214    assert app.permanent_session_lifetime.seconds == 42215216217def test_get_namespace():218    app = flask.Flask(__name__)219    app.config["FOO_OPTION_1"] = "foo option 1"220    app.config["FOO_OPTION_2"] = "foo option 2"221    app.config["BAR_STUFF_1"] = "bar stuff 1"222    app.config["BAR_STUFF_2"] = "bar stuff 2"223    foo_options = app.config.get_namespace("FOO_")224    assert 2 == len(foo_options)225    assert "foo option 1" == foo_options["option_1"]226    assert "foo option 2" == foo_options["option_2"]227    bar_options = app.config.get_namespace("BAR_", lowercase=False)228    assert 2 == len(bar_options)229    assert "bar stuff 1" == bar_options["STUFF_1"]230    assert "bar stuff 2" == bar_options["STUFF_2"]231    foo_options = app.config.get_namespace("FOO_", trim_namespace=False)232    assert 2 == len(foo_options)233    assert "foo option 1" == foo_options["foo_option_1"]234    assert "foo option 2" == foo_options["foo_option_2"]235    bar_options = app.config.get_namespace(236        "BAR_", lowercase=False, trim_namespace=False237    )238    assert 2 == len(bar_options)239    assert "bar stuff 1" == bar_options["BAR_STUFF_1"]240    assert "bar stuff 2" == bar_options["BAR_STUFF_2"]241242243@pytest.mark.parametrize("encoding", ["utf-8", "iso-8859-15", "latin-1"])244def test_from_pyfile_weird_encoding(tmp_path, encoding):245    f = tmp_path / "my_config.py"246    f.write_text(f'# -*- coding: {encoding} -*-\nTEST_VALUE = "föö"\n', encoding)247    app = flask.Flask(__name__)248    app.config.from_pyfile(os.fspath(f))249    value = app.config["TEST_VALUE"]250    assert value == "föö"