Make from_obj() work for List/Dict configtypes

We can't easily make it work for ListOrValue as we don't know which of both we
get at this point.
This commit is contained in:
Florian Bruhin 2018-03-12 08:00:18 +01:00
parent c03ef10d54
commit 990c0707f4
2 changed files with 25 additions and 2 deletions

View File

@ -451,7 +451,7 @@ class List(BaseType):
def from_obj(self, value):
if value is None:
return []
return value
return [self.valtype.from_obj(v) for v in value]
def to_py(self, value):
self._basic_py_validation(value, list)
@ -1199,7 +1199,9 @@ class Dict(BaseType):
def from_obj(self, value):
if value is None:
return {}
return value
return {self.keytype.from_obj(key): self.valtype.from_obj(val)
for key, val in value.items()}
def _fill_fixed_keys(self, value):
"""Fill missing fixed keys with a None-value."""

View File

@ -533,6 +533,14 @@ class FlagListSubclass(configtypes.FlagList):
'foo', 'bar', 'baz')
class FromObjType(configtypes.BaseType):
"""Config type to test from_obj for List/Dict."""
def from_obj(self, obj):
return int(obj)
class TestList:
"""Test List and FlagList."""
@ -647,6 +655,12 @@ class TestList:
with pytest.raises(AssertionError):
typ.to_doc([['foo']])
def test_from_obj_sub(self):
"""Make sure the list calls from_obj() on sub-types."""
typ = configtypes.List(valtype=FromObjType())
value = typ.from_obj(['1', '2'])
assert value == [1, 2]
class TestFlagList:
@ -1665,6 +1679,13 @@ class TestDict:
print(doc)
assert doc == expected
def test_from_obj_sub(self):
"""Make sure the dict calls from_obj() on sub-types."""
typ = configtypes.Dict(keytype=configtypes.String(),
valtype=FromObjType())
value = typ.from_obj({'1': '2'})
assert value == {'1': 2}
def unrequired_class(**kwargs):
return configtypes.File(required=False, **kwargs)