File: test_structured_basic.py

package info (click to toggle)
python-omegaconf 2.3.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,244 kB
  • sloc: python: 26,413; makefile: 38; sh: 11
file content (332 lines) | stat: -rw-r--r-- 14,157 bytes parent folder | download | duplicates (2)
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import re
import sys
from importlib import import_module
from typing import Any, Optional

from pytest import fixture, mark, param, raises

from omegaconf import (
    DictConfig,
    IntegerNode,
    Node,
    OmegaConf,
    ValidationError,
    _utils,
    flag_override,
)
from omegaconf._utils import _is_optional, get_type_hint
from omegaconf.errors import ConfigKeyError, UnsupportedValueType
from tests import IllegalType


@fixture(
    params=[
        param("tests.structured_conf.data.dataclasses", id="dataclasses"),
        param(
            "tests.structured_conf.data.dataclasses_pre_311",
            id="dataclasses_pre_311",
            marks=mark.skipif(
                sys.version_info >= (3, 11),
                reason="python >= 3.11 does not support mutable default dataclass arguments",
            ),
        ),
        param("tests.structured_conf.data.attr_classes", id="attr_classes"),
    ],
)
def module(request: Any) -> Any:
    return import_module(request.param)


class TestStructured:
    class TestBasic:
        def test_error_on_non_structured_config_class(self, module: Any) -> None:
            with raises(ValidationError, match="structured config"):
                OmegaConf.structured(module.NotStructuredConfig)

        def test_error_on_non_structured_nested_config_class(self, module: Any) -> None:
            with raises(
                ValidationError,
                match=re.escape("Unexpected type annotation: NotStructuredConfig"),
            ):
                OmegaConf.structured(module.StructuredWithInvalidField)

            ret = OmegaConf.structured(
                module.StructuredWithInvalidField, flags={"allow_objects": True}
            )
            assert list(ret.keys()) == ["bar"]
            assert ret.bar == module.NotStructuredConfig()

        def test_error_on_creation_with_bad_value_type(self, module: Any) -> None:
            with raises(
                ValidationError,
                match=re.escape(
                    "Value 'seven' of type 'str' could not be converted to Integer"
                ),
            ):
                OmegaConf.structured(module.User(age="seven"))

        def test_assignment_of_subclass(self, module: Any) -> None:
            cfg = OmegaConf.create({"plugin": module.Plugin})
            cfg.plugin = OmegaConf.structured(module.ConcretePlugin)
            assert OmegaConf.get_type(cfg.plugin) == module.ConcretePlugin
            assert (
                OmegaConf.get_type(cfg.plugin.params)
                == module.ConcretePlugin.FoobarParams
            )

        def test_assignment_of_non_subclass_1(self, module: Any) -> None:
            cfg = OmegaConf.create(
                {"plugin": DictConfig(module.Plugin, ref_type=module.Plugin)}
            )
            with raises(ValidationError):
                cfg.plugin = OmegaConf.structured(module.FaultyPlugin)

        def test_merge(self, module: Any) -> None:
            cfg1 = OmegaConf.create({"plugin": module.Plugin})
            cfg2 = OmegaConf.create({"plugin": module.ConcretePlugin})
            assert cfg2.plugin == module.ConcretePlugin
            res: Any = OmegaConf.merge(cfg1, cfg2)
            assert OmegaConf.get_type(res.plugin) == module.ConcretePlugin
            assert (
                OmegaConf.get_type(res.plugin.params)
                == module.ConcretePlugin.FoobarParams
            )

        def test_merge_of_non_subclass_1(self, module: Any) -> None:
            cfg1 = OmegaConf.create({"plugin": module.Plugin})
            cfg2 = OmegaConf.create({"plugin": module.FaultyPlugin})
            with raises(ValidationError):
                OmegaConf.merge(cfg1, cfg2)

        def test_merge_error_new_attribute(self, module: Any) -> None:
            cfg = OmegaConf.structured(module.ConcretePlugin)
            cfg2 = OmegaConf.create({"params": {"bar": 10}})
            # raise if an invalid key is merged into a struct
            with raises(ConfigKeyError):
                OmegaConf.merge(cfg, cfg2)

        def test_merge_error_override_bad_type(self, module: Any) -> None:
            cfg = OmegaConf.structured(module.ConcretePlugin)

            # raise if an invalid key is merged into a struct
            with raises(ValidationError):
                OmegaConf.merge(cfg, {"params": {"foo": "zonk"}})

        def test_error_message(self, module: Any) -> None:
            cfg = OmegaConf.structured(module.StructuredOptional)
            msg = re.escape("field 'not_optional' is not Optional")
            with raises(ValidationError, match=msg):
                cfg.not_optional = None

    def test_none_assignment(self, module: Any) -> None:
        cfg = OmegaConf.create({"plugin": module.Plugin})
        # can assign None to params (type Any):
        cfg.plugin.params = None
        assert cfg.plugin.params is None

        cfg2 = OmegaConf.create({"plugin": module.ConcretePlugin})
        with raises(ValidationError):
            cfg2.plugin.params = None

    @mark.parametrize("rhs", [1, "foo"])
    class TestFailedAssignmentOrMerges:
        def test_assignment_of_non_subclass_2(self, module: Any, rhs: Any) -> None:
            cfg = OmegaConf.create(
                {"plugin": DictConfig(module.Plugin, ref_type=module.Plugin)}
            )
            with raises(ValidationError):
                cfg.plugin = rhs

        def test_merge_of_non_subclass_2(self, module: Any, rhs: Any) -> None:
            cfg1 = OmegaConf.create({"plugin": module.Plugin})
            cfg2 = OmegaConf.create({"plugin": rhs})
            with raises(ValidationError):
                OmegaConf.merge(cfg1, cfg2)

    def test_get_type(self, module: Any) -> None:
        cfg1 = OmegaConf.create(module.LinkedList)
        assert OmegaConf.get_type(cfg1) == module.LinkedList
        assert _utils.get_type_hint(cfg1, "next") == Optional[module.LinkedList]
        assert OmegaConf.get_type(cfg1, "next") is None

        assert cfg1.next is None
        assert OmegaConf.is_missing(cfg1, "value")

        cfg2 = OmegaConf.create(module.MissingTest.Missing1)
        assert OmegaConf.is_missing(cfg2, "head")
        assert _utils.get_type_hint(cfg2, "head") == module.LinkedList
        assert OmegaConf.get_type(cfg2, "head") is None

    def test_merge_structured_into_dict(self, module: Any) -> None:
        c1 = OmegaConf.create({"name": 7})
        c2 = OmegaConf.merge(c1, module.User)
        assert c1 == {"name": 7}
        # type of name becomes str
        assert c2 == {"name": "7", "age": "???"}

    def test_merge_structured_into_dict_nested(self, module: Any) -> None:
        c1 = OmegaConf.create({"user": {"name": 7}})
        c2 = OmegaConf.merge(c1, module.MissingUserField)
        assert c1 == {"user": {"name": 7}}
        # type of name becomes str
        assert c2 == {"user": {"name": "7", "age": "???"}}
        assert isinstance(c2, DictConfig)
        assert get_type_hint(c2, "user") == module.User

    def test_merge_structured_into_dict_nested2(self, module: Any) -> None:
        c1 = OmegaConf.create({"user": {"name": IntegerNode(value=7)}})
        c2 = OmegaConf.merge(c1, module.MissingUserField)
        assert c1 == {"user": {"name": 7}}
        # type of name remains int
        assert c2 == {"user": {"name": 7, "age": "???"}}
        assert isinstance(c2, DictConfig)
        assert get_type_hint(c2, "user") == module.User

    def test_merge_structured_into_dict_nested3(self, module: Any) -> None:
        c1 = OmegaConf.create({"user": {"name": "alice"}})
        c2 = OmegaConf.merge(c1, module.MissingUserWithDefaultNameField)
        assert c1 == {"user": {"name": "alice"}}
        # name is not changed
        assert c2 == {"user": {"name": "alice", "age": "???"}}
        assert isinstance(c2, DictConfig)
        assert get_type_hint(c2, "user") == module.UserWithDefaultName

    def test_merge_missing_object_onto_typed_dictconfig(self, module: Any) -> None:
        c1 = OmegaConf.structured(module.DictOfObjects)
        c2 = OmegaConf.merge(c1, {"users": {"bob": "???"}})
        assert isinstance(c2, DictConfig)
        assert OmegaConf.is_missing(c2.users, "bob")

    def test_merge_into_missing_sc(self, module: Any) -> None:
        c1 = OmegaConf.structured(module.PluginHolder)
        c2 = OmegaConf.merge(c1, {"plugin": "???"})
        assert c2.plugin == module.Plugin()

    def test_merge_missing_key_onto_structured_none(self, module: Any) -> None:
        c1 = OmegaConf.create({"foo": OmegaConf.structured(module.OptionalUser)})
        src = OmegaConf.create({"foo": {"user": "???"}})
        c2 = OmegaConf.merge(c1, src)
        assert c1.foo.user is None
        assert c2.foo.user is None
        assert c2.foo._get_node("user")._metadata.ref_type == module.User

    def test_merge_optional_structured_into_dict(self, module: Any) -> None:
        c1 = OmegaConf.create({"user": {"name": "bob"}})
        c2 = OmegaConf.merge(c1, module.OptionalUser(module.User(name="alice")))
        assert c2.user.name == "alice"
        assert get_type_hint(c2, "user") == Optional[module.User]
        assert isinstance(c2, DictConfig)
        c2_user = c2._get_node("user")
        assert isinstance(c2_user, Node)
        # Compared to the previous assert, here we verify that the `ref_type` found
        # in the metadata is *not* optional: instead, the `optional` flag must be set.
        assert c2_user._metadata.ref_type == module.User
        assert c2_user._metadata.optional

    def test_merge_structured_interpolation_onto_dict(self, module: Any) -> None:
        c1 = OmegaConf.create(
            {
                "user_1": {"name": "bob"},
                "user_2": {"name": "alice"},
                "user_3": {"name": "joe"},
            }
        )
        src = OmegaConf.create({"user_2": module.User(), "user_3": module.User()})
        src.user_2 = "${user_1}"
        src.user_3 = None
        c2 = OmegaConf.merge(c1, src)
        assert c2.user_2.name == "bob"
        assert get_type_hint(c2, "user_2") == Any
        assert c2.user_3 is None
        assert get_type_hint(c2, "user_3") == Any

    @mark.parametrize("resolve", [True, False])
    def test_interpolation_to_structured(self, module: Any, resolve: bool) -> None:
        cfg = OmegaConf.create(module.InterpolationToUser)
        if resolve:
            OmegaConf.resolve(cfg)
        assert OmegaConf.get_type(cfg.admin) is module.User
        assert cfg.admin == {"name": "Bond", "age": 7}

    class TestMissing:
        def test_missing1(self, module: Any) -> None:
            cfg = OmegaConf.create(module.MissingTest.Missing1)
            assert OmegaConf.is_missing(cfg, "head")

            assert OmegaConf.get_type(cfg, "head") is None

            with raises(ValidationError):
                cfg.head = 10

        def test_missing2(self, module: Any) -> None:
            cfg = OmegaConf.create(module.MissingTest.Missing2)
            assert cfg == {"head": {"next": "???", "value": 1}}
            assert OmegaConf.is_missing(cfg.head, "next")

            cfg.head.next = module.LinkedList(value=2)
            assert cfg == {"head": {"next": {"next": None, "value": 2}, "value": 1}}

        def test_plugin_holder(self, module: Any) -> None:
            cfg = OmegaConf.create(module.PluginHolder)

            assert _is_optional(cfg, "none")
            assert _utils.get_type_hint(cfg, "none") == Optional[module.Plugin]
            assert OmegaConf.get_type(cfg, "none") is None

            assert not _is_optional(cfg, "missing")
            assert _utils.get_type_hint(cfg, "missing") == module.Plugin
            assert OmegaConf.get_type(cfg, "missing") is None

            assert not _is_optional(cfg, "plugin")
            assert _utils.get_type_hint(cfg, "plugin") == module.Plugin
            assert OmegaConf.get_type(cfg, "plugin") == module.Plugin

            cfg.plugin = module.ConcretePlugin()
            assert not _is_optional(cfg, "plugin")
            assert _utils.get_type_hint(cfg, "plugin") == module.Plugin
            assert OmegaConf.get_type(cfg, "plugin") == module.ConcretePlugin

            assert not _is_optional(cfg, "plugin2")
            assert _utils.get_type_hint(cfg, "plugin2") == module.Plugin
            assert OmegaConf.get_type(cfg, "plugin2") == module.ConcretePlugin

        def test_plugin_merge(self, module: Any) -> None:
            plugin = OmegaConf.structured(module.Plugin)
            concrete = OmegaConf.structured(module.ConcretePlugin)
            ret = OmegaConf.merge(plugin, concrete)
            assert ret == concrete
            assert OmegaConf.get_type(ret) == module.ConcretePlugin

        def test_plugin_merge_2(self, module: Any) -> None:
            plugin = OmegaConf.structured(module.Plugin)
            more_fields = OmegaConf.structured(module.PluginWithAdditionalField)
            ret = OmegaConf.merge(plugin, more_fields)
            assert ret == more_fields
            assert OmegaConf.get_type(ret) == module.PluginWithAdditionalField

        def test_native_missing(self, module: Any) -> None:
            cfg = OmegaConf.create(module.WithNativeMISSING)
            assert OmegaConf.is_missing(cfg, "num")

        def test_allow_objects(self, module: Any) -> None:
            cfg = OmegaConf.structured(module.Plugin)
            iv = IllegalType()
            with raises(UnsupportedValueType):
                cfg.params = iv
            cfg = OmegaConf.structured(module.Plugin, flags={"allow_objects": True})
            cfg.params = iv
            assert cfg.params == iv

            cfg = OmegaConf.structured(module.Plugin)
            with flag_override(cfg, "allow_objects", True):
                cfg.params = iv
                assert cfg.params == iv

            cfg = OmegaConf.structured({"plugin": module.Plugin})
            pwo = module.Plugin(name="foo", params=iv)
            with raises(UnsupportedValueType):
                cfg.plugin = pwo

            with flag_override(cfg, "allow_objects", True):
                cfg.plugin = pwo
                assert cfg.plugin == pwo