File: test_json_loader.py

package info (click to toggle)
python-dynaconf 3.2.12-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,900 kB
  • sloc: python: 21,464; sh: 9; makefile: 4
file content (230 lines) | stat: -rw-r--r-- 6,311 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
from __future__ import annotations

import json

import pytest

from dynaconf import LazySettings
from dynaconf.loaders.json_loader import DynaconfEncoder
from dynaconf.loaders.json_loader import load
from dynaconf.strategies.filtering import PrefixFilter

settings = LazySettings(environments=True, ENV_FOR_DYNACONF="PRODUCTION")


JSON = """
{
    "a": "a,b",
    "default": {
        "password": "@int 99999",
        "host": "server.com",
        "port": "@int 8080",
        "alist": ["item1", "item2", 23],
        "service": {
          "url": "service.com",
          "port": 80,
          "auth": {
            "password": "qwerty",
            "test": 1234
          }
        }
    },
    "development": {
        "password": "@int 88888",
        "host": "devserver.com"
    },
    "production": {
        "password": "@int 11111",
        "host": "prodserver.com"
    },
    "global": {
        "global_value": "global"
    }
}
"""

# the @float is not needed in JSON but kept to ensure it works
JSON2 = """
{
  "global": {
    "secret": "@float 42",
    "password": 123456,
    "host": "otherjson.com"
  }
}
"""

JSONS = [JSON, JSON2]


def test_load_from_json():
    """Assert loads from JSON string"""
    load(settings, filename=JSON)
    assert settings.HOST == "prodserver.com"
    assert settings.PORT == 8080
    assert settings.ALIST == ["item1", "item2", 23]
    assert settings.SERVICE["url"] == "service.com"
    assert settings.SERVICE.url == "service.com"
    assert settings.SERVICE.port == 80
    assert settings.SERVICE.auth.password == "qwerty"
    assert settings.SERVICE.auth.test == 1234
    load(settings, filename=JSON, env="DEVELOPMENT")
    assert settings.HOST == "devserver.com"
    load(settings, filename=JSON)
    assert settings.HOST == "prodserver.com"


def test_load_from_multiple_json():
    """Assert loads from JSON string"""
    load(settings, filename=JSONS)
    assert settings.HOST == "otherjson.com"
    assert settings.PASSWORD == 123456
    assert settings.SECRET == 42.0
    assert settings.PORT == 8080
    assert settings.SERVICE["url"] == "service.com"
    assert settings.SERVICE.url == "service.com"
    assert settings.SERVICE.port == 80
    assert settings.SERVICE.auth.password == "qwerty"
    assert settings.SERVICE.auth.test == 1234
    load(settings, filename=JSONS, env="DEVELOPMENT")
    assert settings.PORT == 8080
    assert settings.HOST == "otherjson.com"
    load(settings, filename=JSONS)
    assert settings.HOST == "otherjson.com"
    assert settings.PASSWORD == 123456
    load(settings, filename=JSON, env="DEVELOPMENT")
    assert settings.PORT == 8080
    assert settings.HOST == "devserver.com"
    load(settings, filename=JSON)
    assert settings.HOST == "prodserver.com"
    assert settings.PASSWORD == 11111


def test_no_filename_is_none():
    """Assert if passed no filename return is None"""
    assert load(settings) is None


def test_key_error_on_invalid_env():
    """Assert error raised if env is not found in JSON"""
    with pytest.raises(KeyError):
        load(settings, filename=JSON, env="FOOBAR", silent=False)


def test_no_key_error_on_invalid_env():
    """Assert error raised if env is not found in JSON"""
    load(settings, filename=JSON, env="FOOBAR", silent=True)


def test_load_single_key():
    """Test loading a single key"""
    _JSON = """
    {
      "foo": {
        "bar": "blaz",
        "zaz": "naz"
      }
    }
    """
    load(settings, filename=_JSON, env="FOO", key="bar")
    assert settings.BAR == "blaz"
    assert settings.exists("BAR") is True
    assert settings.exists("ZAZ") is False


def test_empty_value():
    load(settings, filename="")


def test_multiple_filenames():
    load(settings, filename="a.json,b.json,c.json,d.json")


def test_cleaner():
    load(settings, filename=JSON)
    assert settings.HOST == "prodserver.com"
    assert settings.PORT == 8080
    assert settings.ALIST == ["item1", "item2", 23]
    assert settings.SERVICE["url"] == "service.com"
    assert settings.SERVICE.url == "service.com"
    assert settings.SERVICE.port == 80
    assert settings.SERVICE.auth.password == "qwerty"
    assert settings.SERVICE.auth.test == 1234
    load(settings, filename=JSON, env="DEVELOPMENT")
    assert settings.HOST == "devserver.com"
    load(settings, filename=JSON)
    assert settings.HOST == "prodserver.com"

    settings.clean()
    with pytest.raises(AttributeError):
        assert settings.HOST == "prodserver.com"


def test_using_env(tmpdir):
    load(settings, filename=JSON)
    assert settings.HOST == "prodserver.com"

    tmpfile = tmpdir.mkdir("sub").join("test_using_env.json")
    tmpfile.write(JSON)
    with settings.using_env("DEVELOPMENT", filename=str(tmpfile)):
        assert settings.HOST == "devserver.com"
    assert settings.HOST == "prodserver.com"


def test_load_dunder():
    """Test loading with dunder settings"""
    _JSON = """
    {
      "foo": {
        "colors__yellow__code": "#FFCC00",
        "COLORS__yellow__name": "Yellow"
      }
    }
    """
    load(settings, filename=_JSON, env="FOO")
    assert settings.COLORS.yellow.code == "#FFCC00"
    assert settings.COLORS.yellow.name == "Yellow"


def test_dynaconf_encoder():
    class Dummy:
        def _dynaconf_encode(self):
            return "Dummy"

    class DummyNotSerializable:
        _dynaconf_encode = 42

    data = {"dummy": Dummy()}
    data_error = {"dummy": DummyNotSerializable()}

    assert json.dumps(data, cls=DynaconfEncoder) == '{"dummy": "Dummy"}'

    with pytest.raises(TypeError):
        json.dumps(data_error, cls=DynaconfEncoder)


def test_envless():
    settings = LazySettings()
    _json = """
    {
        "colors__yellow__code": "#FFCC00",
        "COLORS__yellow__name": "Yellow"
    }
    """
    load(settings, filename=_json)
    assert settings.COLORS.yellow.code == "#FFCC00"
    assert settings.COLORS.yellow.name == "Yellow"


def test_prefix():
    settings = LazySettings(filter_strategy=PrefixFilter("prefix"))
    _json = """
    {
        "prefix_colors__yellow__code": "#FFCC00",
        "COLORS__yellow__name": "Yellow"
    }
    """
    load(settings, filename=_json)
    assert settings.COLORS.yellow.code == "#FFCC00"
    with pytest.raises(AttributeError):
        settings.COLORS.yellow.name