Skip to content

Commit

Permalink
raise error when given extra fields for dataclasses
Browse files Browse the repository at this point in the history
  • Loading branch information
glorpen committed Apr 28, 2022
1 parent c2bf92d commit f2a6a54
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/glorpen/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,14 +116,18 @@ def _get_default_factory(cls, field: dataclasses.Field):
def _from_dataclass(self, data: typing.Dict, cls):
kwargs = {}
errors = {}
# TODO: error on when more fields are provided
known_fields = set()
for field in dataclasses.fields(cls):
known_fields.add(field.name)
try:
kwargs[field.name] = self._as_model(data.get(field.name), field.type, metadata=field.metadata,
default_factory=self._get_default_factory(field))
except ValueError as e:
errors[field.name] = e

for extra_field in set(data.keys()).difference(known_fields):
errors[extra_field] = ValueError("Extra field")

if errors:
raise CollectionValueError(errors)

Expand Down
11 changes: 11 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,17 @@ class Data:
assert m.value_field == "default-value"
assert m.optional_field is None

def test_too_many_properties(self):
c = create_config()
c.register_type(SimpleTypes)

@dataclasses.dataclass
class Data:
a_prop: str

with pytest.raises(ValueError, match="Extra field"):
c.to_model({"a_prop": "asd", "test": "test"}, Data)

def test_validation_with_asserts(self):
c = create_config()
c.register_type(SimpleTypes)
Expand Down

0 comments on commit f2a6a54

Please sign in to comment.