Merge pull request #36 from nyanpasu64/validate-yaml

Validate parameters when loading YAML config
pull/357/head
nyanpasu64 2018-08-19 16:19:38 -07:00 zatwierdzone przez GitHub
commit 7117a74fd0
2 zmienionych plików z 22 dodań i 27 usunięć

Wyświetl plik

@ -88,20 +88,9 @@ class _ConfigMixin:
# SafeConstructor.construct_yaml_object() uses __setstate__ to load objects.
def __setstate__(self, state):
""" Checks that all fields match their correct types. """
self.__dict__.update(state)
for field in fields(self):
key = field.name
value = getattr(self, key)
typ = field.type
# # FIXME crashes on generics, https://github.com/Stewori/pytypes ?
# if not isinstance(value, typ):
# name = type(self).__name__
# raise OvgenError(f'{name}.{key} was supplied {repr(value)}, should be of type {typ.__name__}')
if hasattr(self, '__post_init__'):
self.__post_init__()
"""Call the dataclass constructor, to ensure all parameters are valid."""
new = type(self)(**state)
self.__dict__ = new.__dict__
def register_enum(cls: type):

Wyświetl plik

@ -71,21 +71,27 @@ b: b
'''
@pytest.mark.xfail(strict=True)
def test_load_type_checking():
def test_argument_validation():
""" Ensure that loading config via YAML catches missing and invalid parameters. """
@register_config
class Foo:
foo: int
bar: int
class Config:
a: int
yaml.load('''\
!Config
a: 1
''')
with pytest.raises(TypeError):
yaml.load('!Config {}')
with pytest.raises(TypeError):
yaml.load('''\
!Config
a: 1
b: 1
''')
s = '''\
!Foo
foo: "foo"
bar: "bar"
'''
with pytest.raises(OvgenError) as e:
print(yaml.load(s))
print(e)
def test_load_post_init():