Skip to content

Commit d8bd200

Browse files
committed
fix default for a nested config
1 parent dfad0c6 commit d8bd200

File tree

3 files changed

+44
-2
lines changed

3 files changed

+44
-2
lines changed

msrc-appconfig-dataclasses/tests/decl_dataclasses_test.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,18 @@ def test_unsupported():
8686
Schema(DictsNotSupported)
8787
with pytest.raises(ValueError):
8888
Schema(NonUniformTuplesNotSupported)
89+
90+
91+
@dataclass(frozen=True)
92+
class Inner():
93+
b: int
94+
95+
96+
@dataclass(frozen=True)
97+
class Outer():
98+
a2: Inner = Inner(2)
99+
100+
101+
def test_dataclass_gather_nested_default():
102+
c = msrc.appconfig.gather_config(Outer, argv=[])
103+
assert c.a2.b == 2

msrc-appconfig/msrc/appconfig/schema.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,20 @@ def __init__(
174174
self.element_type: ElementType = element_type
175175
self.is_secret: bool = is_secret
176176
self.has_default: bool = has_default
177-
self.default_value = default_value
178177
if has_default and not self.type_check(default_value):
179178
raise ValueError("Element default value %r must have type %r."
180179
% (default_value, element_type))
180+
if isinstance(element_type, Schema) and has_default:
181+
# substitute schema elements taking defaults from the default value
182+
for name in element_type.keys():
183+
i = element_type[name]
184+
element_type[name] = Element(
185+
i.element_type,
186+
True,
187+
getattr(default_value, name),
188+
i.help,
189+
i.is_secret)
190+
self.default_value = default_value
181191

182192
def type_check(self, value: object) -> bool:
183193
"""Checks type of the value against element type."""
@@ -349,6 +359,8 @@ def args_generator() -> Iterable[Tuple[str, object]]:
349359
if not isinstance(v, Mapping):
350360
raise ValueError(
351361
f"invalid value {v!r} for {n!r}")
362+
if el.has_default:
363+
v = dict(elt.to_dict(el.default_value, True), **v)
352364
yield n, elt.from_dict(v)
353365
else:
354366
yield n, el.parse(v)

msrc-appconfig/tests/schema_test.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,22 @@ def test_to_dict():
170170
schema = s.Schema(CheckDefaults)
171171
data = dict(f1=34, f6=(12, 13), f8=dict(booleans=(False, True)))
172172
instance = schema.from_dict(data)
173-
assert data == schema.to_dict(instance)
173+
result = schema.to_dict(instance)
174+
assert result == data
175+
result = schema.to_dict(instance, include_defaults=True)
176+
assert result == dict(
177+
f0="string",
178+
f1=34,
179+
f2=3.14,
180+
f3=True,
181+
f4=En.Option2,
182+
f5=("a", "b"),
183+
f6=(12, 13),
184+
f7=(1, 2, 3),
185+
f8=dict(
186+
booleans=(False, True),
187+
options=(En.Option2, En.Option1))
188+
)
174189

175190

176191
def test_to_dict_error():

0 commit comments

Comments
 (0)