Skip to content

Commit

Permalink
More explicit error when trying to access the child of non-container …
Browse files Browse the repository at this point in the history
…node (#444)

When using ${a.b}, if `a` is not a container node, the previous code was
failing with an obscure AssertionError.
  • Loading branch information
odelalleau authored Nov 27, 2020
1 parent 800e8a7 commit 6f06c89
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
6 changes: 5 additions & 1 deletion omegaconf/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,11 @@ def _select_impl(
throw_on_resolution_failure=throw_on_resolution_failure,
)

assert ret is None or isinstance(ret, Container)
if ret is not None and not isinstance(ret, Container):
raise ConfigKeyError(
f"Error trying to access {key}: node `{'.'.join(split[0:i + 1])}` "
f"is not a container and thus cannot contain `{split[i + 1]}``"
)
root = ret

if root is None:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1121,3 +1121,16 @@ def test_errors(expected: Expected, monkeypatch: Any) -> None:
expected.op(cfg)
except Exception as e:
assert e.__cause__ is None


def test_assertion_error(restore_resolvers: Any) -> None:
def assert_false() -> None:
assert False

# The purpose of this test is to cover the case where an `AssertionError`
# is processed in `format_and_raise()`. Using a resolver to trigger the assertion
# error is just one way of achieving this goal.
OmegaConf.register_resolver("assert_false", assert_false)
c = OmegaConf.create({"trigger": "${assert_false:}"})
with pytest.raises(AssertionError):
c.trigger
3 changes: 2 additions & 1 deletion tests/test_interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from omegaconf import Container, IntegerNode, Node, OmegaConf, Resolver, ValidationError
from omegaconf._utils import _ensure_container
from omegaconf.errors import ConfigKeyError


@pytest.mark.parametrize( # type:ignore
Expand Down Expand Up @@ -106,7 +107,7 @@ def test_merge_with_interpolation() -> None:

def test_non_container_interpolation() -> None:
cfg = OmegaConf.create(dict(foo=0, bar="${foo.baz}"))
with pytest.raises(AssertionError):
with pytest.raises(ConfigKeyError):
cfg.bar


Expand Down

0 comments on commit 6f06c89

Please sign in to comment.