Skip to content

Commit

Permalink
improved error message for invalid input class
Browse files Browse the repository at this point in the history
  • Loading branch information
omry committed Jan 28, 2020
1 parent 7e77071 commit bcd785c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
19 changes: 17 additions & 2 deletions omegaconf/omegaconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,15 @@ def create( # noqa F811
elif is_primitive_list(obj) or OmegaConf.is_list(obj):
return ListConfig(obj, parent)
else:
raise ValidationError("Unsupported type {}".format(type(obj).__name__))
if isinstance(obj, type):
raise ValidationError(
f"Input class '{obj.__name__}' is not a structured config. "
"did you forget to decorate it as a dataclass?"
)
else:
raise ValidationError(
"Unsupported type {}".format(type(obj).__name__)
)

@staticmethod
def load(file_: Union[str, IO[bytes]]) -> Union[DictConfig, ListConfig]:
Expand Down Expand Up @@ -436,6 +444,7 @@ def _node_wrap(
elif type_ == str:
node = StringNode(value=value, parent=parent, is_optional=is_optional)
else:

raise ValueError("Unexpected object type : {}".format(type_.__name__))
return node

Expand Down Expand Up @@ -492,8 +501,14 @@ def _maybe_wrap(
f"Value type {type(value).__name__} does not match declared type {annotated_type}"
)

if not _valid_value_annotation_type(annotated_type):
raise ValidationError(
f"Annotated class '{annotated_type.__name__}' is not a structured config. "
"did you forget to decorate it as a dataclass?"
)

value = _node_wrap(
type_=annotated_type, parent=parent, is_optional=is_optional, value=value
type_=annotated_type, parent=parent, is_optional=is_optional, value=value,
)
assert isinstance(value, Node)
return value
Expand Down
25 changes: 24 additions & 1 deletion tests/test_create.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"""Testing for OmegaConf"""
import re
import sys
from dataclasses import dataclass
from typing import Any, Dict, List

import pytest

from omegaconf import OmegaConf
from omegaconf.errors import UnsupportedValueType
from omegaconf.errors import UnsupportedValueType, ValidationError

from . import IllegalType

Expand Down Expand Up @@ -110,3 +111,25 @@ def test_create_from_oc_with_flags() -> None:
c2 = OmegaConf.create(c1)
assert c1 == c2
assert c1.flags == c2.flags


def test_error_on_non_structured_config_class() -> None:
class Foo:
name: str = "Bond"
age: int = 7

with pytest.raises(ValidationError, match="structured config"):
OmegaConf.structured(Foo)


def test_error_on_non_structured_nested_config_class() -> None:
class Bar:
name: str = "Bond"
age: int = 7

@dataclass
class Foo:
bar: Bar = Bar()

with pytest.raises(ValidationError, match="structured config"):
OmegaConf.structured(Foo)

0 comments on commit bcd785c

Please sign in to comment.