diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eb208dada03bbd9975633d6f42eb036c09e33125 --- /dev/null +++ b/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2018, Omry Yadan +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..5204b8d8c2997de4218c3186b4a2e14a45540511 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,3 @@ +include LICENSE +include requirements/base.txt +recursive-include tests *.py diff --git a/PKG-INFO b/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..8cb609a9799d8970cd4ac1068ac81a916ec0adbd --- /dev/null +++ b/PKG-INFO @@ -0,0 +1,42 @@ +Metadata-Version: 2.1 +Name: omegaconf +Version: 2.0.6 +Summary: A flexible configuration library +Home-page: https://github.com/omry/omegaconf +Author: Omry Yadan +Author-email: omry@yadan.net +License: UNKNOWN +Description: # OmegaConf + | | Description | + | --- | --- | + | Project | [![PyPI version](https://badge.fury.io/py/omegaconf.svg)](https://badge.fury.io/py/omegaconf)[![Downloads](https://pepy.tech/badge/omegaconf/month)](https://pepy.tech/project/omegaconf/month?versions=1.4.*&versions=2.0*)![PyPI - Python Version](https://img.shields.io/pypi/pyversions/omegaconf.svg) | + | Code quality| [![CircleCI](https://img.shields.io/circleci/build/github/omry/omegaconf?logo=s&token=5de2f8dc2a0dd78438520575431aa533150806e3)](https://circleci.com/gh/omry/omegaconf)[![Coverage Status](https://coveralls.io/repos/github/omry/omegaconf/badge.svg)](https://coveralls.io/github/omry/omegaconf)[![Total alerts](https://img.shields.io/lgtm/alerts/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/alerts/)[![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/context:python)| + | Docs and support |[![Documentation Status](https://readthedocs.org/projects/omegaconf/badge/?version=2.0_branch)](https://omegaconf.readthedocs.io/en/latest/?badge=2.0_branch)[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb)[![](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://hydra-framework.zulipchat.com)| + + + OmegaConf is a hierarchical configuration system, with support for merging configurations from multiple sources (YAML config files, dataclasses/objects and CLI arguments) + providing a consistent API regardless of how the configuration was created. + + ## Releases + ### Stable (2.0) + OmegaConf 2.0 stable version. + + * [What's new](https://github.com/omry/omegaconf/releases/tag/2.0.0) + * [Documentation](https://omegaconf.readthedocs.io/en/2.0_branch/) + * [Slides](https://docs.google.com/presentation/d/e/2PACX-1vT_UIV7hCnquIbLUm4NnkUpXvPEh33IKiUEvPRF850WKA8opOlZOszjKdZ3tPmf8u7hGNP6HpqS-NT5/pub?start=false&loop=false&delayms=3000) + * [Source code](https://github.com/omry/omegaconf/tree/2.0_branch) + + Install with `pip install --upgrade omegaconf` + + ## Live tutorial + Run the live tutorial : [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb) + +Keywords: yaml configuration config +Platform: UNKNOWN +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Requires-Python: >=3.6 +Description-Content-Type: text/markdown diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1a6fa97602dfcabca0289cfd50710cec980822d3 --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +# OmegaConf +| | Description | +| --- | --- | +| Project | [![PyPI version](https://badge.fury.io/py/omegaconf.svg)](https://badge.fury.io/py/omegaconf)[![Downloads](https://pepy.tech/badge/omegaconf/month)](https://pepy.tech/project/omegaconf/month?versions=1.4.*&versions=2.0*)![PyPI - Python Version](https://img.shields.io/pypi/pyversions/omegaconf.svg) | +| Code quality| [![CircleCI](https://img.shields.io/circleci/build/github/omry/omegaconf?logo=s&token=5de2f8dc2a0dd78438520575431aa533150806e3)](https://circleci.com/gh/omry/omegaconf)[![Coverage Status](https://coveralls.io/repos/github/omry/omegaconf/badge.svg)](https://coveralls.io/github/omry/omegaconf)[![Total alerts](https://img.shields.io/lgtm/alerts/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/alerts/)[![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/context:python)| +| Docs and support |[![Documentation Status](https://readthedocs.org/projects/omegaconf/badge/?version=2.0_branch)](https://omegaconf.readthedocs.io/en/latest/?badge=2.0_branch)[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb)[![](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://hydra-framework.zulipchat.com)| + + +OmegaConf is a hierarchical configuration system, with support for merging configurations from multiple sources (YAML config files, dataclasses/objects and CLI arguments) +providing a consistent API regardless of how the configuration was created. + +## Releases +### Stable (2.0) +OmegaConf 2.0 stable version. + +* [What's new](https://github.com/omry/omegaconf/releases/tag/2.0.0) +* [Documentation](https://omegaconf.readthedocs.io/en/2.0_branch/) +* [Slides](https://docs.google.com/presentation/d/e/2PACX-1vT_UIV7hCnquIbLUm4NnkUpXvPEh33IKiUEvPRF850WKA8opOlZOszjKdZ3tPmf8u7hGNP6HpqS-NT5/pub?start=false&loop=false&delayms=3000) +* [Source code](https://github.com/omry/omegaconf/tree/2.0_branch) + +Install with `pip install --upgrade omegaconf` + +## Live tutorial +Run the live tutorial : [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb) diff --git a/omegaconf.egg-info/PKG-INFO b/omegaconf.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..8cb609a9799d8970cd4ac1068ac81a916ec0adbd --- /dev/null +++ b/omegaconf.egg-info/PKG-INFO @@ -0,0 +1,42 @@ +Metadata-Version: 2.1 +Name: omegaconf +Version: 2.0.6 +Summary: A flexible configuration library +Home-page: https://github.com/omry/omegaconf +Author: Omry Yadan +Author-email: omry@yadan.net +License: UNKNOWN +Description: # OmegaConf + | | Description | + | --- | --- | + | Project | [![PyPI version](https://badge.fury.io/py/omegaconf.svg)](https://badge.fury.io/py/omegaconf)[![Downloads](https://pepy.tech/badge/omegaconf/month)](https://pepy.tech/project/omegaconf/month?versions=1.4.*&versions=2.0*)![PyPI - Python Version](https://img.shields.io/pypi/pyversions/omegaconf.svg) | + | Code quality| [![CircleCI](https://img.shields.io/circleci/build/github/omry/omegaconf?logo=s&token=5de2f8dc2a0dd78438520575431aa533150806e3)](https://circleci.com/gh/omry/omegaconf)[![Coverage Status](https://coveralls.io/repos/github/omry/omegaconf/badge.svg)](https://coveralls.io/github/omry/omegaconf)[![Total alerts](https://img.shields.io/lgtm/alerts/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/alerts/)[![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/omry/omegaconf.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/omry/omegaconf/context:python)| + | Docs and support |[![Documentation Status](https://readthedocs.org/projects/omegaconf/badge/?version=2.0_branch)](https://omegaconf.readthedocs.io/en/latest/?badge=2.0_branch)[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb)[![](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://hydra-framework.zulipchat.com)| + + + OmegaConf is a hierarchical configuration system, with support for merging configurations from multiple sources (YAML config files, dataclasses/objects and CLI arguments) + providing a consistent API regardless of how the configuration was created. + + ## Releases + ### Stable (2.0) + OmegaConf 2.0 stable version. + + * [What's new](https://github.com/omry/omegaconf/releases/tag/2.0.0) + * [Documentation](https://omegaconf.readthedocs.io/en/2.0_branch/) + * [Slides](https://docs.google.com/presentation/d/e/2PACX-1vT_UIV7hCnquIbLUm4NnkUpXvPEh33IKiUEvPRF850WKA8opOlZOszjKdZ3tPmf8u7hGNP6HpqS-NT5/pub?start=false&loop=false&delayms=3000) + * [Source code](https://github.com/omry/omegaconf/tree/2.0_branch) + + Install with `pip install --upgrade omegaconf` + + ## Live tutorial + Run the live tutorial : [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/omry/omegaconf/master?filepath=docs%2Fnotebook%2FTutorial.ipynb) + +Keywords: yaml configuration config +Platform: UNKNOWN +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Requires-Python: >=3.6 +Description-Content-Type: text/markdown diff --git a/omegaconf.egg-info/SOURCES.txt b/omegaconf.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6e0664a119be0040cecd4bb0f5a3dfe30c2471c --- /dev/null +++ b/omegaconf.egg-info/SOURCES.txt @@ -0,0 +1,52 @@ +LICENSE +MANIFEST.in +README.md +pyproject.toml +setup.cfg +setup.py +omegaconf/__init__.py +omegaconf/_utils.py +omegaconf/base.py +omegaconf/basecontainer.py +omegaconf/dictconfig.py +omegaconf/errors.py +omegaconf/listconfig.py +omegaconf/nodes.py +omegaconf/omegaconf.py +omegaconf/py.typed +omegaconf/version.py +omegaconf.egg-info/PKG-INFO +omegaconf.egg-info/SOURCES.txt +omegaconf.egg-info/dependency_links.txt +omegaconf.egg-info/requires.txt +omegaconf.egg-info/top_level.txt +requirements/base.txt +tests/__init__.py +tests/conftest.py +tests/test_base_config.py +tests/test_basic_ops_dict.py +tests/test_basic_ops_list.py +tests/test_config_eq.py +tests/test_create.py +tests/test_errors.py +tests/test_get_full_key.py +tests/test_interpolation.py +tests/test_matrix.py +tests/test_merge.py +tests/test_nodes.py +tests/test_omegaconf.py +tests/test_readonly.py +tests/test_select.py +tests/test_serialization.py +tests/test_struct.py +tests/test_to_yaml.py +tests/test_update.py +tests/test_utils.py +tests/examples/__init__.py +tests/examples/test_dataclass_example.py +tests/structured_conf/__init__.py +tests/structured_conf/test_structured_basic.py +tests/structured_conf/test_structured_config.py +tests/structured_conf/data/__init__.py +tests/structured_conf/data/attr_classes.py +tests/structured_conf/data/dataclasses.py \ No newline at end of file diff --git a/omegaconf.egg-info/dependency_links.txt b/omegaconf.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/omegaconf.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/omegaconf.egg-info/requires.txt b/omegaconf.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..d315abab2e26c35f1ef886636609f6c109b9e3d3 --- /dev/null +++ b/omegaconf.egg-info/requires.txt @@ -0,0 +1,5 @@ +PyYAML>=5.1.* +typing-extensions + +[:python_version == "3.6"] +dataclasses diff --git a/omegaconf.egg-info/top_level.txt b/omegaconf.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..3d2e72e354c47c261c653ffe8a3768ce6f32348b --- /dev/null +++ b/omegaconf.egg-info/top_level.txt @@ -0,0 +1 @@ +omegaconf diff --git a/omegaconf/__init__.py b/omegaconf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10f26285c503087092d398d1396e9198d566cfa0 --- /dev/null +++ b/omegaconf/__init__.py @@ -0,0 +1,58 @@ +from .base import Container, Node +from .dictconfig import DictConfig +from .errors import ( + KeyValidationError, + MissingMandatoryValue, + ReadonlyConfigError, + UnsupportedValueType, + ValidationError, +) +from .listconfig import ListConfig +from .nodes import ( + AnyNode, + BooleanNode, + EnumNode, + FloatNode, + IntegerNode, + StringNode, + ValueNode, +) +from .omegaconf import ( + II, + MISSING, + SI, + OmegaConf, + Resolver, + flag_override, + open_dict, + read_write, +) +from .version import __version__ + +__all__ = [ + "__version__", + "MissingMandatoryValue", + "ValidationError", + "ReadonlyConfigError", + "UnsupportedValueType", + "KeyValidationError", + "Container", + "ListConfig", + "DictConfig", + "OmegaConf", + "Resolver", + "flag_override", + "read_write", + "open_dict", + "Node", + "ValueNode", + "AnyNode", + "IntegerNode", + "StringNode", + "BooleanNode", + "EnumNode", + "FloatNode", + "MISSING", + "SI", + "II", +] diff --git a/omegaconf/_utils.py b/omegaconf/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a5077aaebdf57236f1b6255d957669f8aa8150c4 --- /dev/null +++ b/omegaconf/_utils.py @@ -0,0 +1,772 @@ +import copy +import os +import re +import string +import sys +import warnings +from enum import Enum +from textwrap import dedent +from typing import Any, Dict, List, Match, Optional, Tuple, Type, Union + +import yaml + +from .errors import ( + ConfigIndexError, + ConfigTypeError, + ConfigValueError, + KeyValidationError, + OmegaConfBaseException, + ValidationError, +) + +try: + import dataclasses + +except ImportError: # pragma: no cover + dataclasses = None # type: ignore # pragma: no cover + +try: + import attr + +except ImportError: # pragma: no cover + attr = None # type: ignore # pragma: no cover + + +# source: https://yaml.org/type/bool.html +YAML_BOOL_TYPES = [ + "y", + "Y", + "yes", + "Yes", + "YES", + "n", + "N", + "no", + "No", + "NO", + "true", + "True", + "TRUE", + "false", + "False", + "FALSE", + "on", + "On", + "ON", + "off", + "Off", + "OFF", +] + + +class OmegaConfDumper(yaml.Dumper): # type: ignore + str_representer_added = False + + @staticmethod + def str_representer(dumper: yaml.Dumper, data: str) -> yaml.ScalarNode: + with_quotes = yaml_is_bool(data) or is_int(data) or is_float(data) + return dumper.represent_scalar( + yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, + data, + style=("'" if with_quotes else None), + ) + + +def get_omega_conf_dumper() -> Type[OmegaConfDumper]: + if not OmegaConfDumper.str_representer_added: + OmegaConfDumper.add_representer(str, OmegaConfDumper.str_representer) + OmegaConfDumper.str_representer_added = True + return OmegaConfDumper + + +def yaml_is_bool(b: str) -> bool: + return b in YAML_BOOL_TYPES + + +def get_yaml_loader() -> Any: + # Custom constructor that checks for duplicate keys + # (from https://gist.github.com/pypt/94d747fe5180851196eb) + def no_duplicates_constructor( + loader: yaml.Loader, node: yaml.Node, deep: bool = False + ) -> Any: + mapping: Dict[str, Any] = {} + for key_node, value_node in node.value: + key = loader.construct_object(key_node, deep=deep) + value = loader.construct_object(value_node, deep=deep) + if key in mapping: + raise yaml.constructor.ConstructorError( + "while constructing a mapping", + node.start_mark, + f"found duplicate key {key}", + key_node.start_mark, + ) + mapping[key] = value + return loader.construct_mapping(node, deep) + + class OmegaConfLoader(yaml.SafeLoader): # type: ignore + pass + + loader = OmegaConfLoader + loader.add_implicit_resolver( + "tag:yaml.org,2002:float", + re.compile( + """^(?: + [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)? + |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) + |\\.[0-9_]+(?:[eE][-+][0-9]+)? + |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]* + |[-+]?\\.(?:inf|Inf|INF) + |\\.(?:nan|NaN|NAN))$""", + re.X, + ), + list("-+0123456789."), + ) # type : ignore + loader.yaml_implicit_resolvers = { + key: [ + (tag, regexp) + for tag, regexp in resolvers + if tag != "tag:yaml.org,2002:timestamp" + ] + for key, resolvers in loader.yaml_implicit_resolvers.items() + } + loader.add_constructor( + yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, no_duplicates_constructor + ) + return loader + + +def _get_class(path: str) -> type: + from importlib import import_module + + module_path, _, class_name = path.rpartition(".") + mod = import_module(module_path) + try: + klass: type = getattr(mod, class_name) + except AttributeError: + raise ImportError(f"Class {class_name} is not in module {module_path}") + return klass + + +def _is_union(type_: Any) -> bool: + return getattr(type_, "__origin__", None) is Union + + +def _resolve_optional(type_: Any) -> Tuple[bool, Any]: + if getattr(type_, "__origin__", None) is Union: + args = type_.__args__ + if len(args) == 2 and args[1] == type(None): # noqa E721 + return True, args[0] + if type_ is Any: + return True, Any + + return False, type_ + + +def _resolve_forward(type_: Type[Any], module: str) -> Type[Any]: + import typing # lgtm [py/import-and-import-from] + + forward = typing.ForwardRef if hasattr(typing, "ForwardRef") else typing._ForwardRef # type: ignore + if type(type_) is forward: + return _get_class(f"{module}.{type_.__forward_arg__}") + else: + return type_ + + +def _raise_missing_error(obj: Any, name: str) -> None: + raise ValueError( + f"Missing default value for {get_type_of(obj).__name__}.{name}, to indicate " + "default must be populated later use OmegaConf.MISSING" + ) + + +def get_attr_data(obj: Any) -> Dict[str, Any]: + from omegaconf.omegaconf import _maybe_wrap + + d = {} + is_type = isinstance(obj, type) + obj_type = obj if is_type else type(obj) + for name, attrib in attr.fields_dict(obj_type).items(): + is_optional, type_ = _resolve_optional(attrib.type) + is_nested = is_attr_class(type_) + type_ = _resolve_forward(type_, obj.__module__) + if not is_type: + value = getattr(obj, name) + else: + value = attrib.default + if value == attr.NOTHING: + if is_nested: + msg = dedent( + f""" + The field `{name}` of type '{type_str(type_)}' does not have a default value. + The behavior of OmegaConf for such cases is changing in OmegaConf 2.1. + See https://github.com/omry/omegaconf/issues/412 for more details. + """ + ) + warnings.warn(category=UserWarning, message=msg, stacklevel=8) + value = type_ + else: + _raise_missing_error(obj, name) + assert False + if _is_union(type_): + e = ConfigValueError( + f"Union types are not supported:\n{name}: {type_str(type_)}" + ) + format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e)) + + d[name] = _maybe_wrap( + ref_type=type_, is_optional=is_optional, key=name, value=value, parent=None + ) + return d + + +def get_dataclass_data(obj: Any) -> Dict[str, Any]: + from omegaconf.omegaconf import _maybe_wrap + + d = {} + for field in dataclasses.fields(obj): + name = field.name + is_optional, type_ = _resolve_optional(field.type) + type_ = _resolve_forward(type_, obj.__module__) + is_nested = is_structured_config(type_) + + if hasattr(obj, name): + value = getattr(obj, name) + if value == dataclasses.MISSING: + _raise_missing_error(obj, name) + assert False + else: + if field.default_factory == dataclasses.MISSING: # type: ignore + if is_nested: + msg = dedent( + f""" + The field `{name}` of type '{type_str(type_)}' does not have a default value. + The behavior of OmegaConf for such cases is changing in OmegaConf 2.1. + See https://github.com/omry/omegaconf/issues/412 for more details. + """ + ) + warnings.warn(category=UserWarning, message=msg, stacklevel=8) + + value = type_ + else: + _raise_missing_error(obj, name) + assert False + else: + value = field.default_factory() # type: ignore + + if _is_union(type_): + e = ConfigValueError( + f"Union types are not supported:\n{name}: {type_str(type_)}" + ) + format_and_raise(node=None, key=None, value=value, cause=e, msg=str(e)) + d[name] = _maybe_wrap( + ref_type=type_, is_optional=is_optional, key=name, value=value, parent=None + ) + return d + + +def is_dataclass(obj: Any) -> bool: + from omegaconf.base import Node + + if dataclasses is None or isinstance(obj, Node): + return False + return dataclasses.is_dataclass(obj) + + +def is_attr_class(obj: Any) -> bool: + from omegaconf.base import Node + + if attr is None or isinstance(obj, Node): + return False + return attr.has(obj) + + +def is_structured_config(obj: Any) -> bool: + return is_attr_class(obj) or is_dataclass(obj) + + +def is_dataclass_frozen(type_: Any) -> bool: + return type_.__dataclass_params__.frozen # type: ignore + + +def is_attr_frozen(type_: type) -> bool: + # This is very hacky and probably fragile as well. + # Unfortunately currently there isn't an official API in attr that can detect that. + # noinspection PyProtectedMember + return type_.__setattr__ == attr._make._frozen_setattrs # type: ignore + + +def get_type_of(class_or_object: Any) -> Type[Any]: + type_ = class_or_object + if not isinstance(type_, type): + type_ = type(class_or_object) + assert isinstance(type_, type) + return type_ + + +def is_structured_config_frozen(obj: Any) -> bool: + type_ = get_type_of(obj) + + if is_dataclass(type_): + return is_dataclass_frozen(type_) + if is_attr_class(type_): + return is_attr_frozen(type_) + return False + + +def get_structured_config_data(obj: Any) -> Dict[str, Any]: + if is_dataclass(obj): + return get_dataclass_data(obj) + elif is_attr_class(obj): + return get_attr_data(obj) + else: + raise ValueError(f"Unsupported type: {type(obj).__name__}") + + +class ValueKind(Enum): + VALUE = 0 + MANDATORY_MISSING = 1 + INTERPOLATION = 2 + STR_INTERPOLATION = 3 + + +def get_value_kind(value: Any, return_match_list: bool = False) -> Any: + """ + Determine the kind of a value + Examples: + MANDATORY_MISSING : "??? + VALUE : "10", "20", True, + INTERPOLATION: "${foo}", "${foo.bar}" + STR_INTERPOLATION: "ftp://${host}/path" + + :param value: input string to classify + :param return_match_list: True to return the match list as well + :return: ValueKind + """ + + key_prefix = r"\${(\w+:)?" + legal_characters = r"([\w\.%_ \\/:,-]*?)}" + match_list: Optional[List[Match[str]]] = None + + def ret( + value_kind: ValueKind, + ) -> Union[ValueKind, Tuple[ValueKind, Optional[List[Match[str]]]]]: + if return_match_list: + return value_kind, match_list + else: + return value_kind + + from .base import Container + + if isinstance(value, Container): + if value._is_interpolation() or value._is_missing(): + value = value._value() + + value = _get_value(value) + if value == "???": + return ret(ValueKind.MANDATORY_MISSING) + + if not isinstance(value, str): + return ret(ValueKind.VALUE) + + match_list = list(re.finditer(key_prefix + legal_characters, value)) + if len(match_list) == 0: + return ret(ValueKind.VALUE) + + if len(match_list) == 1 and value == match_list[0].group(0): + return ret(ValueKind.INTERPOLATION) + else: + return ret(ValueKind.STR_INTERPOLATION) + + +def is_bool(st: str) -> bool: + st = str.lower(st) + return st == "true" or st == "false" + + +def is_float(st: str) -> bool: + try: + float(st) + return True + except ValueError: + return False + + +def is_int(st: str) -> bool: + try: + int(st) + return True + except ValueError: + return False + + +def decode_primitive(s: str) -> Any: + if is_bool(s): + return str.lower(s) == "true" + + if is_int(s): + return int(s) + + if is_float(s): + return float(s) + + return s + + +def is_primitive_list(obj: Any) -> bool: + from .base import Container + + return not isinstance(obj, Container) and isinstance(obj, (list, tuple)) + + +def is_primitive_dict(obj: Any) -> bool: + t = get_type_of(obj) + return t is dict + + +def is_dict_annotation(type_: Any) -> bool: + origin = getattr(type_, "__origin__", None) + if sys.version_info < (3, 7, 0): + return origin is Dict or type_ is Dict # pragma: no cover + else: + return origin is dict # pragma: no cover + + +def is_list_annotation(type_: Any) -> bool: + origin = getattr(type_, "__origin__", None) + if sys.version_info < (3, 7, 0): + return origin is List or type_ is List # pragma: no cover + else: + return origin is list # pragma: no cover + + +def is_tuple_annotation(type_: Any) -> bool: + origin = getattr(type_, "__origin__", None) + if sys.version_info < (3, 7, 0): + return origin is Tuple or type_ is Tuple # pragma: no cover + else: + return origin is tuple # pragma: no cover + + +def is_dict_subclass(type_: Any) -> bool: + return type_ is not None and isinstance(type_, type) and issubclass(type_, Dict) + + +def is_dict(obj: Any) -> bool: + return is_primitive_dict(obj) or is_dict_annotation(obj) or is_dict_subclass(obj) + + +def is_primitive_container(obj: Any) -> bool: + return is_primitive_list(obj) or is_primitive_dict(obj) + + +def get_list_element_type(ref_type: Optional[Type[Any]]) -> Optional[Type[Any]]: + args = getattr(ref_type, "__args__", None) + if ref_type is not List and args is not None and args[0] is not Any: + element_type = args[0] + else: + element_type = None + + if not (valid_value_annotation_type(element_type)): + raise ValidationError(f"Unsupported value type : {element_type}") + assert element_type is None or isinstance(element_type, type) + return element_type + + +def get_dict_key_value_types(ref_type: Any) -> Tuple[Any, Any]: + + args = getattr(ref_type, "__args__", None) + if args is None: + bases = getattr(ref_type, "__orig_bases__", None) + if bases is not None and len(bases) > 0: + args = getattr(bases[0], "__args__", None) + + key_type: Any + element_type: Any + if ref_type is None: + key_type = None + element_type = None + else: + if args is not None: + key_type = args[0] + element_type = args[1] + # None is the sentry for any type + if key_type is Any: + key_type = None + if element_type is Any: + element_type = None + else: + key_type = None + element_type = None + + if not valid_value_annotation_type(element_type) and not is_structured_config( + element_type + ): + raise ValidationError(f"Unsupported value type : {element_type}") + + if not _valid_dict_key_annotation_type(key_type): + raise KeyValidationError(f"Unsupported key type {key_type}") + return key_type, element_type + + +def valid_value_annotation_type(type_: Any) -> bool: + return type_ is Any or is_primitive_type(type_) or is_structured_config(type_) + + +def _valid_dict_key_annotation_type(type_: Any) -> bool: + return type_ is None or issubclass(type_, str) or issubclass(type_, Enum) + + +def is_primitive_type(type_: Any) -> bool: + type_ = get_type_of(type_) + return issubclass(type_, Enum) or type_ in (int, float, bool, str, type(None)) + + +def _is_interpolation(v: Any) -> bool: + if isinstance(v, str): + ret = get_value_kind(v) in ( + ValueKind.INTERPOLATION, + ValueKind.STR_INTERPOLATION, + ) + assert isinstance(ret, bool) + return ret + return False + + +def _get_value(value: Any) -> Any: + from .base import Container + from .nodes import ValueNode + + if isinstance(value, Container) and value._is_none(): + return None + if isinstance(value, ValueNode): + value = value._value() + return value + + +def get_ref_type(obj: Any, key: Any = None) -> Optional[Type[Any]]: + from omegaconf import DictConfig, ListConfig + from omegaconf.base import Container, Node + from omegaconf.nodes import ValueNode + + def none_as_any(t: Optional[Type[Any]]) -> Union[Type[Any], Any]: + if t is None: + return Any + else: + return t + + if isinstance(obj, Container) and key is not None: + obj = obj._get_node(key) + + is_optional = True + ref_type = None + if isinstance(obj, ValueNode): + is_optional = obj._is_optional() + ref_type = obj._metadata.ref_type + elif isinstance(obj, Container): + if isinstance(obj, Node): + ref_type = obj._metadata.ref_type + is_optional = obj._is_optional() + kt = none_as_any(obj._metadata.key_type) + vt = none_as_any(obj._metadata.element_type) + if ( + ref_type is Any + and kt is Any + and vt is Any + and not obj._is_missing() + and not obj._is_none() + ): + ref_type = Any # type: ignore + elif not is_structured_config(ref_type): + if kt is Any: + kt = Union[str, Enum] + if isinstance(obj, DictConfig): + ref_type = Dict[kt, vt] # type: ignore + elif isinstance(obj, ListConfig): + ref_type = List[vt] # type: ignore + else: + if isinstance(obj, dict): + ref_type = Dict[Union[str, Enum], Any] + elif isinstance(obj, (list, tuple)): + ref_type = List[Any] + else: + ref_type = get_type_of(obj) + + ref_type = none_as_any(ref_type) + if is_optional and ref_type is not Any: + ref_type = Optional[ref_type] # type: ignore + return ref_type + + +def _raise(ex: Exception, cause: Exception) -> None: + # Set the environment variable OC_CAUSE=1 to get a stacktrace that includes the + # causing exception. + env_var = os.environ["OC_CAUSE"] if "OC_CAUSE" in os.environ else None + debugging = sys.gettrace() is not None + full_backtrace = (debugging and not env_var == "0") or (env_var == "1") + if full_backtrace: + ex.__cause__ = cause + else: + ex.__cause__ = None + raise ex # set end OC_CAUSE=1 for full backtrace + + +def format_and_raise( + node: Any, + key: Any, + value: Any, + msg: str, + cause: Exception, + type_override: Any = None, +) -> None: + from omegaconf import OmegaConf + from omegaconf.base import Node + + if isinstance(cause, OmegaConfBaseException) and cause._initialized: + ex = cause + if type_override is not None: + ex = type_override(str(cause)) + ex.__dict__ = copy.deepcopy(cause.__dict__) + _raise(ex, cause) + + object_type: Optional[Type[Any]] + object_type_str: Optional[str] = None + ref_type: Optional[Type[Any]] + ref_type_str: Optional[str] + + child_node: Optional[Node] = None + if node is None: + full_key = "" + object_type = None + ref_type = None + ref_type_str = None + else: + if key is not None and not OmegaConf.is_none(node): + child_node = node._get_node(key, validate_access=False) + + full_key = node._get_full_key(key=key) + + object_type = OmegaConf.get_type(node) + object_type_str = type_str(object_type) + + ref_type = get_ref_type(node) + ref_type_str = type_str(ref_type) + + msg = string.Template(msg).substitute( + REF_TYPE=ref_type_str, + OBJECT_TYPE=object_type_str, + KEY=key, + FULL_KEY=full_key, + VALUE=value, + VALUE_TYPE=f"{type(value).__name__}", + KEY_TYPE=f"{type(key).__name__}", + ) + + template = """$MSG +\tfull_key: $FULL_KEY +\treference_type=$REF_TYPE +\tobject_type=$OBJECT_TYPE""" + + s = string.Template(template=template) + + message = s.substitute( + REF_TYPE=ref_type_str, OBJECT_TYPE=object_type_str, MSG=msg, FULL_KEY=full_key + ) + exception_type = type(cause) if type_override is None else type_override + if exception_type == TypeError: + exception_type = ConfigTypeError + elif exception_type == IndexError: + exception_type = ConfigIndexError + + ex = exception_type(f"{message}") + if issubclass(exception_type, OmegaConfBaseException): + ex._initialized = True + ex.msg = message + ex.parent_node = node + ex.child_node = child_node + ex.key = key + ex.full_key = full_key + ex.value = value + ex.object_type = object_type + ex.object_type_str = object_type_str + ex.ref_type = ref_type + ex.ref_type_str = ref_type_str + + _raise(ex, cause) + + +def type_str(t: Any) -> str: + is_optional, t = _resolve_optional(t) + if t is None: + return type(t).__name__ + if t is Any: + return "Any" + if sys.version_info < (3, 7, 0): # pragma: no cover + # Python 3.6 + if hasattr(t, "__name__"): + name = str(t.__name__) + else: + if t.__origin__ is not None: + name = type_str(t.__origin__) + else: + name = str(t) + if name.startswith("typing."): + name = name[len("typing.") :] + else: # pragma: no cover + # Python >= 3.7 + if hasattr(t, "__name__"): + name = str(t.__name__) + else: + if t._name is None: + if t.__origin__ is not None: + name = type_str(t.__origin__) + else: + name = str(t._name) + + args = getattr(t, "__args__", None) + if args is not None: + args = ", ".join([type_str(t) for t in (list(t.__args__))]) + ret = f"{name}[{args}]" + else: + ret = name + if is_optional: + return f"Optional[{ret}]" + else: + return ret + + +def _ensure_container(target: Any) -> Any: + from omegaconf import OmegaConf + + if is_primitive_container(target): + assert isinstance(target, (list, dict)) + target = OmegaConf.create(target) + elif is_structured_config(target): + target = OmegaConf.structured(target) + assert OmegaConf.is_config(target) + return target + + +def is_generic_list(type_: Any) -> bool: + """ + Checks if a type is a generic list, for example: + list returns False + typing.List returns False + typing.List[T] returns True + + :param type_: variable type + :return: bool + """ + return is_list_annotation(type_) and get_list_element_type(type_) is not None + + +def is_generic_dict(type_: Any) -> bool: + """ + Checks if a type is a generic dict, for example: + list returns False + typing.List returns False + typing.List[T] returns True + + :param type_: variable type + :return: bool + """ + return is_dict_annotation(type_) and len(get_dict_key_value_types(type_)) > 0 diff --git a/omegaconf/base.py b/omegaconf/base.py new file mode 100644 index 0000000000000000000000000000000000000000..dcbba0d52cb154ddc6e5d2811f2d646494383cd8 --- /dev/null +++ b/omegaconf/base.py @@ -0,0 +1,430 @@ +from abc import ABC, abstractmethod +from collections import defaultdict +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, Iterator, Optional, Tuple, Type, Union + +from ._utils import ValueKind, _get_value, format_and_raise, get_value_kind +from .errors import ConfigKeyError, MissingMandatoryValue, UnsupportedInterpolationType + + +@dataclass +class Metadata: + + ref_type: Optional[Type[Any]] + + object_type: Optional[Type[Any]] + + optional: bool + + key: Any + + # Flags have 3 modes: + # unset : inherit from parent (None if no parent specifies) + # set to true: flag is true + # set to false: flag is false + flags: Dict[str, bool] = field(default_factory=dict) + resolver_cache: Dict[str, Any] = field(default_factory=lambda: defaultdict(dict)) + + +@dataclass +class ContainerMetadata(Metadata): + key_type: Any = None + element_type: Any = None + + def __post_init__(self) -> None: + assert self.key_type is None or isinstance(self.key_type, type) + assert self.element_type is None or isinstance(self.element_type, type) + + +class Node(ABC): + _metadata: Metadata + + parent: Optional["Container"] + + def __init__(self, parent: Optional["Container"], metadata: Metadata): + self.__dict__["_metadata"] = metadata + self.__dict__["_parent"] = parent + + def _set_parent(self, parent: Optional["Container"]) -> None: + assert parent is None or isinstance(parent, Container) + self.__dict__["_parent"] = parent + + def _get_parent(self) -> Optional["Container"]: + parent = self.__dict__["_parent"] + assert parent is None or isinstance(parent, Container) + return parent + + def _set_flag(self, flag: str, value: Optional[bool]) -> "Node": + assert value is None or isinstance(value, bool) + if value is None: + if flag in self._metadata.flags: + del self._metadata.flags[flag] + else: + self._metadata.flags[flag] = value + return self + + def _get_node_flag(self, flag: str) -> Optional[bool]: + """ + :param flag: flag to inspect + :return: the state of the flag on this node. + """ + return self._metadata.flags[flag] if flag in self._metadata.flags else None + + def _get_flag(self, flag: str) -> Optional[bool]: + """ + Returns True if this config node flag is set + A flag is set if node.set_flag(True) was called + or one if it's parents is flag is set + :return: + """ + flags = self._metadata.flags + if flag in flags and flags[flag] is not None: + return flags[flag] + + parent = self._get_parent() + if parent is None: + return None + else: + # noinspection PyProtectedMember + return parent._get_flag(flag) + + def _format_and_raise( + self, key: Any, value: Any, cause: Exception, type_override: Any = None + ) -> None: + format_and_raise( + node=self, + key=key, + value=value, + msg=str(cause), + cause=cause, + type_override=type_override, + ) + assert False + + @abstractmethod + def _get_full_key(self, key: Union[str, Enum, int, None]) -> str: + ... + + def _dereference_node( + self, throw_on_missing: bool = False, throw_on_resolution_failure: bool = True + ) -> Optional["Node"]: + from .nodes import StringNode + + if self._is_interpolation(): + value_kind, match_list = get_value_kind( + value=self._value(), return_match_list=True + ) + match = match_list[0] + parent = self._get_parent() + key = self._key() + if value_kind == ValueKind.INTERPOLATION: + assert parent is not None + v = parent._resolve_simple_interpolation( + key=key, + inter_type=match.group(1), + inter_key=match.group(2), + throw_on_missing=throw_on_missing, + throw_on_resolution_failure=throw_on_resolution_failure, + ) + return v + elif value_kind == ValueKind.STR_INTERPOLATION: + assert parent is not None + ret = parent._resolve_interpolation( + key=key, + value=self, + throw_on_missing=throw_on_missing, + throw_on_resolution_failure=throw_on_resolution_failure, + ) + if ret is None: + return ret + return StringNode( + value=ret, + key=key, + parent=parent, + is_optional=self._metadata.optional, + ) + assert False + else: + # not interpolation, compare directly + if throw_on_missing: + value = self._value() + if value == "???": + raise MissingMandatoryValue("Missing mandatory value") + return self + + @abstractmethod + def __eq__(self, other: Any) -> bool: + ... + + @abstractmethod + def __ne__(self, other: Any) -> bool: + ... + + @abstractmethod + def __hash__(self) -> int: + ... + + @abstractmethod + def _value(self) -> Any: + ... + + @abstractmethod + def _set_value(self, value: Any) -> None: + ... + + @abstractmethod + def _is_none(self) -> bool: + ... + + @abstractmethod + def _is_optional(self) -> bool: + ... + + @abstractmethod + def _is_missing(self) -> bool: + ... + + @abstractmethod + def _is_interpolation(self) -> bool: + ... + + def _key(self) -> Any: + return self._metadata.key + + def _set_key(self, key: Any) -> None: + self._metadata.key = key + + +class Container(Node): + """ + Container tagging interface + """ + + _metadata: ContainerMetadata + + @abstractmethod + def pretty(self, resolve: bool = False, sort_keys: bool = False) -> str: + ... + + @abstractmethod + def update_node(self, key: str, value: Any = None) -> None: + ... + + @abstractmethod + def select(self, key: str, throw_on_missing: bool = False) -> Any: + ... + + def _get_node(self, key: Any, validate_access: bool = True) -> Optional[Node]: + ... + + @abstractmethod + def __delitem__(self, key: Any) -> None: + ... + + @abstractmethod + def __setitem__(self, key: Any, value: Any) -> None: + ... + + @abstractmethod + def __iter__(self) -> Iterator[str]: + ... + + @abstractmethod + def __getitem__(self, key_or_index: Any) -> Any: + ... + + def _get_root(self) -> "Container": + root: Optional[Container] = self._get_parent() + if root is None: + return self + assert root is not None and isinstance(root, Container) + while root._get_parent() is not None: + root = root._get_parent() + assert root is not None and isinstance(root, Container) + return root + + def _select_impl( + self, key: str, throw_on_missing: bool, throw_on_resolution_failure: bool + ) -> Tuple[Optional["Container"], Optional[str], Optional[Node]]: + """ + Select a value using dot separated key sequence + :param key: + :return: + """ + from .omegaconf import _select_one + + if key == "": + return self, "", self + + split = key.split(".") + root: Optional[Container] = self + for i in range(len(split) - 1): + if root is None: + break + + k = split[i] + ret, _ = _select_one( + c=root, + key=k, + throw_on_missing=throw_on_missing, + throw_on_type_error=throw_on_resolution_failure, + ) + if isinstance(ret, Node): + ret = ret._dereference_node( + throw_on_missing=throw_on_missing, + throw_on_resolution_failure=throw_on_resolution_failure, + ) + + assert ret is None or isinstance(ret, Container) + root = ret + + if root is None: + return None, None, None + + last_key = split[-1] + value, _ = _select_one( + c=root, + key=last_key, + throw_on_missing=throw_on_missing, + throw_on_type_error=throw_on_resolution_failure, + ) + if value is None: + return root, last_key, value + value = root._resolve_interpolation( + key=last_key, + value=value, + throw_on_missing=False, + throw_on_resolution_failure=True, + ) + return root, last_key, value + + def _resolve_simple_interpolation( + self, + key: Any, + inter_type: str, + inter_key: str, + throw_on_missing: bool, + throw_on_resolution_failure: bool, + ) -> Optional["Node"]: + from omegaconf import OmegaConf + + from .nodes import ValueNode + + root_node = self._get_root() + + inter_type = ("str:" if inter_type is None else inter_type)[0:-1] + if inter_type == "str": + parent, last_key, value = root_node._select_impl( + inter_key, + throw_on_missing=throw_on_missing, + throw_on_resolution_failure=throw_on_resolution_failure, + ) + + # if parent is None or (value is None and last_key not in parent): # type: ignore + if parent is None or value is None: + if throw_on_resolution_failure: + raise ConfigKeyError( + f"{inter_type} interpolation key '{inter_key}' not found" + ) + else: + return None + assert isinstance(value, Node) + return value + else: + resolver = OmegaConf.get_resolver(inter_type) + if resolver is not None: + try: + value = resolver(root_node, inter_key) + return ValueNode( + value=value, + parent=self, + metadata=Metadata( + ref_type=None, object_type=None, key=key, optional=True + ), + ) + except Exception as e: + self._format_and_raise(key=inter_key, value=None, cause=e) + assert False + else: + if throw_on_resolution_failure: + raise UnsupportedInterpolationType( + f"Unsupported interpolation type {inter_type}" + ) + else: + return None + + def _resolve_interpolation( + self, + key: Any, + value: "Node", + throw_on_missing: bool, + throw_on_resolution_failure: bool, + ) -> Any: + from .nodes import StringNode + + value_kind, match_list = get_value_kind(value=value, return_match_list=True) + if value_kind not in (ValueKind.INTERPOLATION, ValueKind.STR_INTERPOLATION): + return value + + if value_kind == ValueKind.INTERPOLATION: + # simple interpolation, inherit type + match = match_list[0] + return self._resolve_simple_interpolation( + key=key, + inter_type=match.group(1), + inter_key=match.group(2), + throw_on_missing=throw_on_missing, + throw_on_resolution_failure=throw_on_resolution_failure, + ) + elif value_kind == ValueKind.STR_INTERPOLATION: + value = _get_value(value) + assert isinstance(value, str) + orig = value + new = "" + last_index = 0 + for match in match_list: + new_val = self._resolve_simple_interpolation( + key=key, + inter_type=match.group(1), + inter_key=match.group(2), + throw_on_missing=throw_on_missing, + throw_on_resolution_failure=throw_on_resolution_failure, + ) + # if failed to resolve, return None for the whole thing. + if new_val is None: + return None + new += orig[last_index : match.start(0)] + str(new_val) + last_index = match.end(0) + + new += orig[last_index:] + return StringNode(value=new, key=key) + else: + assert False + + def _re_parent(self) -> None: + from .dictconfig import DictConfig + from .listconfig import ListConfig + + # update parents of first level Config nodes to self + + if isinstance(self, Container): + if isinstance(self, DictConfig): + content = self.__dict__["_content"] + if isinstance(content, dict): + for _key, value in self.__dict__["_content"].items(): + if value is not None: + value._set_parent(self) + if isinstance(value, Container): + value._re_parent() + elif isinstance(self, ListConfig): + content = self.__dict__["_content"] + if isinstance(content, list): + for item in self.__dict__["_content"]: + if item is not None: + item._set_parent(self) + if isinstance(item, Container): + item._re_parent() + + def _has_ref_type(self) -> bool: + return self._metadata.ref_type is not Any diff --git a/omegaconf/basecontainer.py b/omegaconf/basecontainer.py new file mode 100644 index 0000000000000000000000000000000000000000..e31cf32ef57f9d9a47f9c4ad81787ef0b21490d0 --- /dev/null +++ b/omegaconf/basecontainer.py @@ -0,0 +1,626 @@ +import copy +import sys +import warnings +from abc import ABC, abstractmethod +from enum import Enum +from textwrap import dedent +from typing import Any, Dict, List, Optional, Tuple, Union + +import yaml + +from ._utils import ( + ValueKind, + _ensure_container, + _get_value, + _is_interpolation, + _resolve_optional, + get_ref_type, + get_value_kind, + get_yaml_loader, + is_dict_annotation, + is_list_annotation, + is_primitive_dict, + is_primitive_type, + is_structured_config, +) +from .base import Container, ContainerMetadata, Node +from .errors import MissingMandatoryValue, ReadonlyConfigError, ValidationError + +DEFAULT_VALUE_MARKER: Any = str("__DEFAULT_VALUE_MARKER__") + + +class BaseContainer(Container, ABC): + # static + _resolvers: Dict[str, Any] = {} + + def __init__(self, parent: Optional["Container"], metadata: ContainerMetadata): + super().__init__(parent=parent, metadata=metadata) + self.__dict__["_content"] = None + self._normalize_ref_type() + + def _normalize_ref_type(self) -> None: + if self._metadata.ref_type is None: + self._metadata.ref_type = Any # type: ignore + + def _resolve_with_default( + self, + key: Union[str, int, Enum], + value: Any, + default_value: Any = DEFAULT_VALUE_MARKER, + ) -> Any: + """returns the value with the specified key, like obj.key and obj['key']""" + + def is_mandatory_missing(val: Any) -> bool: + return get_value_kind(val) == ValueKind.MANDATORY_MISSING # type: ignore + + value = _get_value(value) + has_default = default_value is not DEFAULT_VALUE_MARKER + if has_default and (value is None or is_mandatory_missing(value)): + return default_value + + resolved = self._resolve_interpolation( + key=key, + value=value, + throw_on_missing=not has_default, + throw_on_resolution_failure=not has_default, + ) + if resolved is None and has_default: + return default_value + + if is_mandatory_missing(resolved): + if has_default: + return default_value + else: + raise MissingMandatoryValue("Missing mandatory value: $FULL_KEY") + + return _get_value(resolved) + + def __str__(self) -> str: + return self.__repr__() + + def __repr__(self) -> str: + if self.__dict__["_content"] is None: + return "None" + elif self._is_interpolation() or self._is_missing(): + v = self.__dict__["_content"] + return f"'{v}'" + else: + return self.__dict__["_content"].__repr__() # type: ignore + + # Support pickle + def __getstate__(self) -> Dict[str, Any]: + return self.__dict__ + + # Support pickle + def __setstate__(self, d: Dict[str, Any]) -> None: + self.__dict__.update(d) + + @abstractmethod + def __delitem__(self, key: Any) -> None: + ... + + def __len__(self) -> int: + return self.__dict__["_content"].__len__() # type: ignore + + def merge_with_cli(self) -> None: + args_list = sys.argv[1:] + self.merge_with_dotlist(args_list) + + def merge_with_dotlist(self, dotlist: List[str]) -> None: + from omegaconf import OmegaConf + + def fail() -> None: + raise ValueError("Input list must be a list or a tuple of strings") + + if not isinstance(dotlist, (list, tuple)): + fail() + + for arg in dotlist: + if not isinstance(arg, str): + fail() + + idx = arg.find("=") + if idx == -1: + key = arg + value = None + else: + key = arg[0:idx] + value = arg[idx + 1 :] + value = yaml.load(value, Loader=get_yaml_loader()) + + OmegaConf.update(self, key, value, merge=True) + + def select(self, key: str, throw_on_missing: bool = False) -> Any: + from omegaconf import OmegaConf + + warnings.warn( + "select() is deprecated, use OmegaConf.select(). (Since 2.0)", + category=UserWarning, + stacklevel=2, + ) + + return OmegaConf.select(self, key, throw_on_missing) + + def update_node(self, key: str, value: Any = None) -> None: + from omegaconf import OmegaConf + + warnings.warn( + "update_node() is deprecated, use OmegaConf.update(). (Since 2.0)", + category=UserWarning, + stacklevel=2, + ) + + OmegaConf.update(self, key, value, merge=False) + + def is_empty(self) -> bool: + """return true if config is empty""" + return len(self.__dict__["_content"]) == 0 + + @staticmethod + def _to_content( + conf: Container, resolve: bool, enum_to_str: bool = False + ) -> Union[None, str, Dict[str, Any], List[Any]]: + from .dictconfig import DictConfig + from .listconfig import ListConfig + + def convert(val: Node) -> Any: + value = val._value() + if enum_to_str and isinstance(value, Enum): + value = f"{value.name}" + + return value + + assert isinstance(conf, Container) + if conf._is_none(): + return None + elif conf._is_interpolation() and not resolve: + inter = conf._value() + assert isinstance(inter, str) + return inter + elif conf._is_missing(): + return "???" + elif isinstance(conf, DictConfig): + retdict: Dict[str, Any] = {} + for key in conf.keys(): + node = conf._get_node(key) + assert node is not None + if resolve: + node = node._dereference_node( + throw_on_missing=False, throw_on_resolution_failure=True + ) + + assert node is not None + if isinstance(node, Container): + retdict[key] = BaseContainer._to_content( + node, resolve=resolve, enum_to_str=enum_to_str + ) + else: + retdict[key] = convert(node) + return retdict + elif isinstance(conf, ListConfig): + retlist: List[Any] = [] + for index in range(len(conf)): + node = conf._get_node(index) + assert node is not None + if resolve: + node = node._dereference_node( + throw_on_missing=False, throw_on_resolution_failure=True + ) + assert node is not None + if isinstance(node, Container): + item = BaseContainer._to_content( + node, resolve=resolve, enum_to_str=enum_to_str + ) + retlist.append(item) + else: + retlist.append(convert(node)) + + return retlist + + assert False + + def pretty(self, resolve: bool = False, sort_keys: bool = False) -> str: + from omegaconf import OmegaConf + + warnings.warn( + dedent( + """\ + cfg.pretty() is deprecated and will be removed in a future version. + Use OmegaConf.to_yaml(cfg) + """ + ), + category=UserWarning, + ) + + return OmegaConf.to_yaml(self, resolve=resolve, sort_keys=sort_keys) + + @staticmethod + def _map_merge(dest: "BaseContainer", src: "BaseContainer") -> None: + """merge src into dest and return a new copy, does not modified input""" + from omegaconf import DictConfig, OmegaConf, ValueNode + + assert isinstance(dest, DictConfig) + assert isinstance(src, DictConfig) + src_type = src._metadata.object_type + + # if source DictConfig is an interpolation set the DictConfig one to be the same interpolation. + if src._is_interpolation(): + dest._set_value(src._value()) + return + # if source DictConfig is missing set the DictConfig one to be missing too. + if src._is_missing(): + dest._set_value("???") + return + dest._validate_set_merge_impl(key=None, value=src, is_assign=False) + + def expand(node: Container) -> None: + type_ = get_ref_type(node) + if type_ is not None: + _is_optional, type_ = _resolve_optional(type_) + if is_dict_annotation(type_): + node._set_value({}) + elif is_list_annotation(type_): + node._set_value([]) + else: + node._set_value(type_) + + if dest._is_interpolation() or dest._is_missing(): + expand(dest) + + for key, src_value in src.items_ex(resolve=False): + + dest_node = dest._get_node(key, validate_access=False) + if isinstance(dest_node, Container) and OmegaConf.is_none(dest, key): + if not OmegaConf.is_none(src_value): + expand(dest_node) + + if dest_node is not None: + if dest_node._is_interpolation(): + target_node = dest_node._dereference_node( + throw_on_resolution_failure=False + ) + if isinstance(target_node, Container): + dest[key] = target_node + dest_node = dest._get_node(key) + + if is_structured_config(dest._metadata.element_type): + dest[key] = DictConfig(content=dest._metadata.element_type, parent=dest) + dest_node = dest._get_node(key) + + if dest_node is not None: + if isinstance(dest_node, BaseContainer): + if isinstance(src_value, BaseContainer): + dest._validate_merge(key=key, value=src_value) + dest_node._merge_with(src_value) + else: + dest.__setitem__(key, src_value) + else: + if isinstance(src_value, BaseContainer): + dest.__setitem__(key, src_value) + else: + assert isinstance(dest_node, ValueNode) + try: + dest_node._set_value(src_value) + except (ValidationError, ReadonlyConfigError) as e: + dest._format_and_raise(key=key, value=src_value, cause=e) + else: + from omegaconf import open_dict + + if is_structured_config(src_type): + # verified to be compatible above in _validate_set_merge_impl + with open_dict(dest): + dest[key] = src._get_node(key) + else: + dest[key] = src._get_node(key) + + if src_type is not None and not is_primitive_dict(src_type): + dest._metadata.object_type = src_type + + # explicit flags on the source config are replacing the flag values in the destination + for flag, value in src._metadata.flags.items(): + if value is not None: + dest._set_flag(flag, value) + + def merge_with( + self, + *others: Union["BaseContainer", Dict[str, Any], List[Any], Tuple[Any], Any], + ) -> None: + try: + self._merge_with(*others) + except Exception as e: + self._format_and_raise(key=None, value=None, cause=e) + + def _merge_with( + self, + *others: Union["BaseContainer", Dict[str, Any], List[Any], Tuple[Any], Any], + ) -> None: + from .dictconfig import DictConfig + from .listconfig import ListConfig + from .omegaconf import OmegaConf + + """merge a list of other Config objects into this one, overriding as needed""" + for other in others: + if other is None: + raise ValueError("Cannot merge with a None config") + other = _ensure_container(other) + if isinstance(self, DictConfig) and isinstance(other, DictConfig): + BaseContainer._map_merge(self, other) + elif isinstance(self, ListConfig) and isinstance(other, ListConfig): + self.__dict__["_content"] = [] + + if other._is_interpolation(): + self._set_value(other._value()) + elif other._is_missing(): + self._set_value("???") + elif other._is_none(): + self._set_value(None) + else: + et = self._metadata.element_type + if is_structured_config(et): + prototype = OmegaConf.structured(et) + for item in other: + if isinstance(item, DictConfig): + item = OmegaConf.merge(prototype, item) + self.append(item) + + else: + for item in other: + self.append(item) + + # explicit flags on the source config are replacing the flag values in the destination + for flag, value in other._metadata.flags.items(): + if value is not None: + self._set_flag(flag, value) + else: + raise TypeError("Cannot merge DictConfig with ListConfig") + + # recursively correct the parent hierarchy after the merge + self._re_parent() + + # noinspection PyProtectedMember + def _set_item_impl(self, key: Any, value: Any) -> None: + """ + Changes the value of the node key with the desired value. If the node key doesn't + exist it creates a new one. + """ + from omegaconf.omegaconf import OmegaConf, _maybe_wrap + + from .nodes import AnyNode, ValueNode + + if isinstance(value, Node): + try: + old = value._key() + value._set_key(key) + self._validate_set(key, value) + finally: + value._set_key(old) + else: + self._validate_set(key, value) + + if self._get_flag("readonly"): + raise ReadonlyConfigError("Cannot change read-only config container") + + input_config = isinstance(value, Container) + target_node_ref = self._get_node(key) + special_value = value is None or value == "???" + + input_node = isinstance(value, ValueNode) + if isinstance(self.__dict__["_content"], dict): + target_node = key in self.__dict__["_content"] and isinstance( + target_node_ref, ValueNode + ) + + elif isinstance(self.__dict__["_content"], list): + target_node = isinstance(target_node_ref, ValueNode) + # We use set_value if: + # 1. Target node is a container and the value is MISSING or None + # 2. Target node is a container and has an explicit ref_type + # 3. If the target is a NodeValue then it should set his value. + #  Furthermore if it's an AnyNode it should wrap when the input is + # a container and set when the input is an compatible type(primitive type). + + should_set_value = target_node_ref is not None and ( + ( + isinstance(target_node_ref, Container) + and (special_value or target_node_ref._has_ref_type()) + ) + or (target_node and not isinstance(target_node_ref, AnyNode)) + or (isinstance(target_node_ref, AnyNode) and is_primitive_type(value)) + ) + + def wrap(key: Any, val: Any) -> Node: + is_optional = True + if not is_structured_config(val): + ref_type = self._metadata.element_type + else: + target = self._get_node(key) + if target is None: + if is_structured_config(val): + ref_type = OmegaConf.get_type(val) + else: + is_optional = target._is_optional() + ref_type = target._metadata.ref_type + return _maybe_wrap( + ref_type=ref_type, + key=key, + value=val, + is_optional=is_optional, + parent=self, + ) + + def assign(value_key: Any, value_to_assign: Any) -> None: + v = copy.deepcopy(value_to_assign) + v._set_parent(self) + v._set_key(value_key) + self.__dict__["_content"][value_key] = v + + if input_node and target_node: + # both nodes, replace existing node with new one + assign(key, value) + elif not input_node and target_node: + # input is not node, can be primitive or config + if should_set_value: + self.__dict__["_content"][key]._set_value(value) + elif input_config: + assign(key, value) + else: + self.__dict__["_content"][key] = wrap(key, value) + elif input_node and not target_node: + # target must be config, replace target with input node + assign(key, value) + elif not input_node and not target_node: + if should_set_value: + self.__dict__["_content"][key]._set_value(value) + elif input_config: + assign(key, value) + else: + self.__dict__["_content"][key] = wrap(key, value) + + @staticmethod + def _item_eq( + c1: Container, k1: Union[str, int], c2: Container, k2: Union[str, int] + ) -> bool: + v1 = c1._get_node(k1) + v2 = c2._get_node(k2) + assert v1 is not None and v2 is not None + + if v1._is_none() and v2._is_none(): + return True + + if v1._is_missing() and v2._is_missing(): + return True + + v1_inter = v1._is_interpolation() + v2_inter = v2._is_interpolation() + dv1: Optional[Node] = v1 + dv2: Optional[Node] = v2 + + if v1_inter: + dv1 = v1._dereference_node( + throw_on_missing=False, throw_on_resolution_failure=False + ) + if v2_inter: + dv2 = v2._dereference_node( + throw_on_missing=False, throw_on_resolution_failure=False + ) + + if v1_inter and v2_inter: + if dv1 is None or dv2 is None: + return v1 == v2 + else: + # both are not none, if both are containers compare as container + if isinstance(dv1, Container) and isinstance(dv2, Container): + if dv1 != dv2: + return False + dv1 = _get_value(dv1) + dv2 = _get_value(dv2) + return dv1 == dv2 + elif not v1_inter and not v2_inter: + v1 = _get_value(v1) + v2 = _get_value(v2) + return v1 == v2 + else: + dv1 = _get_value(dv1) + dv2 = _get_value(dv2) + return dv1 == dv2 + + def _is_none(self) -> bool: + return self.__dict__["_content"] is None + + def _is_missing(self) -> bool: + try: + self._dereference_node( + throw_on_resolution_failure=False, throw_on_missing=True + ) + return False + except MissingMandatoryValue: + ret = True + + assert isinstance(ret, bool) + return ret + + def _is_optional(self) -> bool: + return self.__dict__["_metadata"].optional is True + + def _is_interpolation(self) -> bool: + return _is_interpolation(self.__dict__["_content"]) + + @abstractmethod + def _validate_get(self, key: Any, value: Any = None) -> None: + ... + + @abstractmethod + def _validate_set(self, key: Any, value: Any) -> None: + ... + + def _value(self) -> Any: + return self.__dict__["_content"] + + def _get_full_key(self, key: Union[str, Enum, int, slice, None]) -> str: + from .listconfig import ListConfig + from .omegaconf import _select_one + + if not isinstance(key, (int, str, Enum, slice, type(None))): + return "" + + def _slice_to_str(x: slice) -> str: + if x.step is not None: + return f"{x.start}:{x.stop}:{x.step}" + else: + return f"{x.start}:{x.stop}" + + def prepand(full_key: str, parent_type: Any, cur_type: Any, key: Any) -> str: + if isinstance(key, slice): + key = _slice_to_str(key) + elif isinstance(key, Enum): + key = key.name + + if issubclass(parent_type, ListConfig): + if full_key != "": + if issubclass(cur_type, ListConfig): + full_key = f"[{key}]{full_key}" + else: + full_key = f"[{key}].{full_key}" + else: + full_key = f"[{key}]" + else: + if full_key == "": + full_key = key + else: + if issubclass(cur_type, ListConfig): + full_key = f"{key}{full_key}" + else: + full_key = f"{key}.{full_key}" + return full_key + + if key is not None and key != "": + assert isinstance(self, Container) + cur, _ = _select_one( + c=self, key=str(key), throw_on_missing=False, throw_on_type_error=False + ) + if cur is None: + cur = self + full_key = prepand("", type(cur), None, key) + if cur._key() is not None: + full_key = prepand( + full_key, type(cur._get_parent()), type(cur), cur._key() + ) + else: + full_key = prepand("", type(cur._get_parent()), type(cur), cur._key()) + else: + cur = self + if cur._key() is None: + return "" + full_key = self._key() + + assert cur is not None + while cur._get_parent() is not None: + cur = cur._get_parent() + assert cur is not None + key = cur._key() + if key is not None: + full_key = prepand( + full_key, type(cur._get_parent()), type(cur), cur._key() + ) + + return full_key diff --git a/omegaconf/dictconfig.py b/omegaconf/dictconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..c739fd3a053664b9b98126b5424d57ff636405a1 --- /dev/null +++ b/omegaconf/dictconfig.py @@ -0,0 +1,579 @@ +import copy +from enum import Enum +from typing import ( + AbstractSet, + Any, + Dict, + Iterable, + Iterator, + List, + MutableMapping, + Optional, + Tuple, + Type, + Union, +) + +from ._utils import ( + ValueKind, + _is_interpolation, + get_structured_config_data, + get_type_of, + get_value_kind, + is_dict, + is_generic_dict, + is_generic_list, + is_primitive_dict, + is_structured_config, + is_structured_config_frozen, + type_str, +) +from .base import Container, ContainerMetadata, Node +from .basecontainer import DEFAULT_VALUE_MARKER, BaseContainer +from .errors import ( + ConfigAttributeError, + ConfigKeyError, + ConfigTypeError, + KeyValidationError, + MissingMandatoryValue, + OmegaConfBaseException, + ReadonlyConfigError, + UnsupportedInterpolationType, + ValidationError, +) +from .nodes import EnumNode, ValueNode + + +class DictConfig(BaseContainer, MutableMapping[str, Any]): + + _metadata: ContainerMetadata + + def __init__( + self, + content: Union[Dict[str, Any], Any], + key: Any = None, + parent: Optional[Container] = None, + ref_type: Union[Type[Any], Any] = Any, + key_type: Optional[Type[Any]] = None, + element_type: Optional[Type[Any]] = None, + is_optional: bool = True, + ) -> None: + super().__init__( + parent=parent, + metadata=ContainerMetadata( + key=key, + optional=is_optional, + ref_type=ref_type, + object_type=None, + key_type=key_type, + element_type=element_type, + ), + ) + + if is_structured_config(content) or is_structured_config(ref_type): + self._set_value(content) + if is_structured_config_frozen(content) or is_structured_config_frozen( + ref_type + ): + self._set_flag("readonly", True) + + else: + self._set_value(content) + if isinstance(content, DictConfig): + metadata = copy.deepcopy(content._metadata) + metadata.key = key + metadata.optional = is_optional + metadata.element_type = element_type + metadata.key_type = key_type + self.__dict__["_metadata"] = metadata + + def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "DictConfig": + res = DictConfig({}) + for k, v in self.__dict__.items(): + res.__dict__[k] = copy.deepcopy(v, memo=memo) + res._re_parent() + return res + + def __copy__(self) -> "DictConfig": + from .omegaconf import MISSING + + res = DictConfig(content=None) + for k, v in self.__dict__.items(): + res.__dict__[k] = copy.copy(v) + res._re_parent() + content = self.__dict__["_content"] + if content != MISSING and content is not None: + for k, v in content.items(): + if isinstance(v, ValueNode): + res.__dict__["_content"][k] = copy.copy(v) + + return res + + def copy(self) -> "DictConfig": + return copy.copy(self) + + def _is_typed(self) -> bool: + return self._metadata.object_type not in (Any, None) and not is_dict( + self._metadata.object_type + ) + + def _validate_get(self, key: Any, value: Any = None) -> None: + is_typed = self._is_typed() + + is_struct = self._get_flag("struct") is True + if key not in self.__dict__["_content"]: + if is_typed: + # do not raise an exception if struct is explicitly set to False + if self._get_node_flag("struct") is False: + return + if is_typed or is_struct: + if is_typed: + assert self._metadata.object_type is not None + msg = f"Key '{key}' not in '{self._metadata.object_type.__name__}'" + else: + msg = f"Key '{key}' is not in struct" + self._format_and_raise( + key=key, value=value, cause=ConfigAttributeError(msg) + ) + + def _validate_merge(self, key: Any, value: Any) -> None: + self._validate_set_merge_impl(key, value, is_assign=False) + + def _validate_set(self, key: Any, value: Any) -> None: + self._validate_set_merge_impl(key, value, is_assign=True) + + def _validate_set_merge_impl(self, key: Any, value: Any, is_assign: bool) -> None: + from omegaconf import OmegaConf + + vk = get_value_kind(value) + if vk in (ValueKind.INTERPOLATION, ValueKind.STR_INTERPOLATION): + return + + if OmegaConf.is_none(value): + if key is not None: + child = self._get_node(key) + if child is not None and not child._is_optional(): + self._format_and_raise( + key=key, + value=value, + cause=ValidationError("child '$FULL_KEY' is not Optional"), + ) + else: + if not self._is_optional(): + self._format_and_raise( + key=None, + value=value, + cause=ValidationError("field '$FULL_KEY' is not Optional"), + ) + + if value == "???": + return + + target: Optional[Node] + if key is None: + target = self + else: + target = self._get_node(key) + + if target is None: + return + + def is_typed(c: Any) -> bool: + return isinstance(c, DictConfig) and c._metadata.ref_type not in (Any, dict) + + if not is_typed(target): + return + + # target must be optional by now. no need to check the type of value if None. + if value is None: + return + + target_type = target._metadata.ref_type + value_type = OmegaConf.get_type(value) + + if is_dict(value_type) and is_dict(target_type): + return + + if is_generic_list(target_type) or is_generic_dict(target_type): + return + # TODO: simplify this flow. (if assign validate assign else validate merge) + # is assignment illegal? + validation_error = ( + target_type is not None + and value_type is not None + and not issubclass(value_type, target_type) + ) + + if not is_assign: + # merge + # Merging of a dictionary is allowed even if assignment is illegal (merge would do deeper checks) + validation_error = not is_dict(value_type) and validation_error + + if validation_error: + assert value_type is not None + assert target_type is not None + msg = ( + f"Invalid type assigned : {type_str(value_type)} is not a " + f"subclass of {type_str(target_type)}. value: {value}" + ) + raise ValidationError(msg) + + def _validate_and_normalize_key(self, key: Any) -> Union[str, Enum]: + return self._s_validate_and_normalize_key(self._metadata.key_type, key) + + def _s_validate_and_normalize_key( + self, key_type: Any, key: Any + ) -> Union[str, Enum]: + if key_type is None: + for t in (str, Enum): + try: + return self._s_validate_and_normalize_key(key_type=t, key=key) + except KeyValidationError: + pass + raise KeyValidationError("Incompatible key type '$KEY_TYPE'") + elif key_type == str: + if not isinstance(key, str): + raise KeyValidationError( + f"Key $KEY ($KEY_TYPE) is incompatible with ({key_type.__name__})" + ) + + return key + elif issubclass(key_type, Enum): + try: + ret = EnumNode.validate_and_convert_to_enum(key_type, key) + assert ret is not None + return ret + except ValidationError: + valid = ", ".join([x for x in key_type.__members__.keys()]) + raise KeyValidationError( + f"Key '$KEY' is incompatible with the enum type '{key_type.__name__}', valid: [{valid}]" + ) + else: + assert False + + def __setitem__(self, key: Union[str, Enum], value: Any) -> None: + try: + self.__set_impl(key=key, value=value) + except AttributeError as e: + self._format_and_raise( + key=key, value=value, type_override=ConfigKeyError, cause=e + ) + except Exception as e: + self._format_and_raise(key=key, value=value, cause=e) + + def __set_impl(self, key: Union[str, Enum], value: Any) -> None: + key = self._validate_and_normalize_key(key) + self._set_item_impl(key, value) + + # hide content while inspecting in debugger + def __dir__(self) -> Iterable[str]: + if self._is_missing() or self._is_none(): + return [] + return self.__dict__["_content"].keys() # type: ignore + + def __setattr__(self, key: str, value: Any) -> None: + """ + Allow assigning attributes to DictConfig + :param key: + :param value: + :return: + """ + try: + self.__set_impl(key, value) + except Exception as e: + if isinstance(e, OmegaConfBaseException) and e._initialized: + raise e + self._format_and_raise(key=key, value=value, cause=e) + assert False + + def __getattr__(self, key: str) -> Any: + """ + Allow accessing dictionary values as attributes + :param key: + :return: + """ + try: + # PyCharm is sometimes inspecting __members__, be sure to tell it we don't have that. + if key == "__members__": + raise ConfigAttributeError() + + if key == "__name__": + raise ConfigAttributeError() + + return self._get_impl(key=key, default_value=DEFAULT_VALUE_MARKER) + except Exception as e: + self._format_and_raise(key=key, value=None, cause=e) + + def __getitem__(self, key: Union[str, Enum]) -> Any: + """ + Allow map style access + :param key: + :return: + """ + + try: + return self._get_impl(key=key, default_value=DEFAULT_VALUE_MARKER) + except AttributeError as e: + self._format_and_raise( + key=key, value=None, cause=e, type_override=ConfigKeyError + ) + except Exception as e: + self._format_and_raise(key=key, value=None, cause=e) + + def __delitem__(self, key: Union[str, int, Enum]) -> None: + if self._get_flag("readonly"): + self._format_and_raise( + key=key, + value=None, + cause=ReadonlyConfigError( + "DictConfig in read-only mode does not support deletion" + ), + ) + if self._get_flag("struct"): + self._format_and_raise( + key=key, + value=None, + cause=ConfigTypeError( + "DictConfig in struct mode does not support deletion" + ), + ) + if self._is_typed() and self._get_node_flag("struct") is not False: + self._format_and_raise( + key=key, + value=None, + cause=ConfigTypeError( + f"{type_str(self._metadata.object_type)} (DictConfig) does not support deletion" + ), + ) + + del self.__dict__["_content"][key] + + def get( + self, key: Union[str, Enum], default_value: Any = DEFAULT_VALUE_MARKER + ) -> Any: + try: + return self._get_impl(key=key, default_value=default_value) + except Exception as e: + self._format_and_raise(key=key, value=None, cause=e) + + def _get_impl(self, key: Union[str, Enum], default_value: Any) -> Any: + try: + node = self._get_node(key=key) + except ConfigAttributeError: + if default_value != DEFAULT_VALUE_MARKER: + node = default_value + else: + raise + return self._resolve_with_default( + key=key, value=node, default_value=default_value + ) + + def _get_node( + self, key: Union[str, Enum], validate_access: bool = True + ) -> Optional[Node]: + try: + key = self._validate_and_normalize_key(key) + except KeyValidationError: + if validate_access: + raise + else: + return None + + if validate_access: + self._validate_get(key) + + value: Node = self.__dict__["_content"].get(key) + + return value + + def pop(self, key: Union[str, Enum], default: Any = DEFAULT_VALUE_MARKER) -> Any: + try: + if self._get_flag("readonly"): + raise ReadonlyConfigError("Cannot pop from read-only node") + if self._get_flag("struct"): + raise ConfigTypeError("DictConfig in struct mode does not support pop") + if self._is_typed() and self._get_node_flag("struct") is not False: + raise ConfigTypeError( + f"{type_str(self._metadata.object_type)} (DictConfig) does not support pop" + ) + key = self._validate_and_normalize_key(key) + node = self._get_node(key=key, validate_access=False) + if node is not None: + value = self._resolve_with_default( + key=key, value=node, default_value=default + ) + + del self[key] + return value + else: + if default is not DEFAULT_VALUE_MARKER: + return default + else: + full = self._get_full_key(key=key) + if full != key: + raise ConfigKeyError(f"Key not found: '{key}' (path: '{full}')") + else: + raise ConfigKeyError(f"Key not found: '{key}'") + except Exception as e: + self._format_and_raise(key=key, value=None, cause=e) + + def keys(self) -> Any: + if self._is_missing() or self._is_interpolation() or self._is_none(): + return list() + return self.__dict__["_content"].keys() + + def __contains__(self, key: object) -> bool: + """ + A key is contained in a DictConfig if there is an associated value and + it is not a mandatory missing value ('???'). + :param key: + :return: + """ + + key = self._validate_and_normalize_key(key) + try: + node: Optional[Node] = self._get_node(key) + except (KeyError, AttributeError): + node = None + + if node is None: + return False + else: + try: + self._resolve_with_default(key=key, value=node) + return True + except UnsupportedInterpolationType: + # Value that has unsupported interpolation counts as existing. + return True + except (MissingMandatoryValue, KeyError): + return False + + def __iter__(self) -> Iterator[str]: + return iter(self.keys()) + + def items(self) -> AbstractSet[Tuple[str, Any]]: + return self.items_ex(resolve=True, keys=None) + + def setdefault(self, key: Union[str, Enum], default: Any = None) -> Any: + if key in self: + ret = self.__getitem__(key) + else: + ret = default + self.__setitem__(key, default) + return ret + + def items_ex( + self, resolve: bool = True, keys: Optional[List[str]] = None + ) -> AbstractSet[Tuple[str, Any]]: + # Using a dictionary because the keys are ordered + items: Dict[Tuple[str, Any], None] = {} + for key in self.keys(): + if resolve: + value = self.get(key) + else: + value = self.__dict__["_content"][key] + if isinstance(value, ValueNode): + value = value._value() + if keys is None or key in keys: + items[(key, value)] = None + + return items.keys() + + def __eq__(self, other: Any) -> bool: + if other is None: + return self.__dict__["_content"] is None + if is_primitive_dict(other) or is_structured_config(other): + other = DictConfig(other) + return DictConfig._dict_conf_eq(self, other) + if isinstance(other, DictConfig): + return DictConfig._dict_conf_eq(self, other) + return NotImplemented + + def __ne__(self, other: Any) -> bool: + x = self.__eq__(other) + if x is not NotImplemented: + return not x + return NotImplemented + + def __hash__(self) -> int: + return hash(str(self)) + + def _promote(self, type_or_prototype: Optional[Type[Any]]) -> None: + """ + Retypes a node. + This should only be used in rare circumstances, where you want to dynamically change + the runtime structured-type of a DictConfig. + It will change the type and add the additional fields based on the input class or object + """ + if type_or_prototype is None: + return + if not is_structured_config(type_or_prototype): + raise ValueError(f"Expected structured config class : {type_or_prototype}") + + from omegaconf import OmegaConf + + proto: DictConfig = OmegaConf.structured(type_or_prototype) + object_type = proto._metadata.object_type + # remove the type to prevent assignment validation from rejecting the promotion. + proto._metadata.object_type = None + self.merge_with(proto) + # restore the type. + self._metadata.object_type = object_type + + def _set_value(self, value: Any) -> None: + from omegaconf import OmegaConf + + assert not isinstance(value, ValueNode) + self._validate_set(key=None, value=value) + + if OmegaConf.is_none(value): + self.__dict__["_content"] = None + self._metadata.object_type = None + elif _is_interpolation(value): + self.__dict__["_content"] = value + self._metadata.object_type = None + elif value == "???": + self.__dict__["_content"] = "???" + self._metadata.object_type = None + else: + self.__dict__["_content"] = {} + if is_structured_config(value): + self._metadata.object_type = None + data = get_structured_config_data(value) + for k, v in data.items(): + self.__setitem__(k, v) + self._metadata.object_type = get_type_of(value) + elif isinstance(value, DictConfig): + self._metadata.object_type = dict + for k, v in value.__dict__["_content"].items(): + self.__setitem__(k, v) + self.__dict__["_metadata"] = copy.deepcopy(value._metadata) + + elif isinstance(value, dict): + for k, v in value.items(): + self.__setitem__(k, v) + else: + msg = f"Unsupported value type : {value}" + raise ValidationError(msg=msg) # pragma: no cover + + @staticmethod + def _dict_conf_eq(d1: "DictConfig", d2: "DictConfig") -> bool: + + d1_none = d1.__dict__["_content"] is None + d2_none = d2.__dict__["_content"] is None + if d1_none and d2_none: + return True + if d1_none != d2_none: + return False + + assert isinstance(d1, DictConfig) + assert isinstance(d2, DictConfig) + if len(d1) != len(d2): + return False + for k, v in d1.items_ex(resolve=False): + if k not in d2.__dict__["_content"]: + return False + if not BaseContainer._item_eq(d1, k, d2, k): + return False + + return True diff --git a/omegaconf/errors.py b/omegaconf/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..a709f71231e3cd8a33ff69c6f1bd0a00d1641fc5 --- /dev/null +++ b/omegaconf/errors.py @@ -0,0 +1,105 @@ +from typing import Any, Optional, Type + + +class OmegaConfBaseException(Exception): + # would ideally be typed Optional[Node] + parent_node: Any + child_node: Any + key: Any + full_key: Optional[str] + value: Any + msg: Optional[str] + cause: Optional[Exception] + object_type: Optional[Type[Any]] + object_type_str: Optional[str] + ref_type: Optional[Type[Any]] + ref_type_str: Optional[str] + + _initialized: bool = False + + def __init__(self, *_args: Any, **_kwargs: Any) -> None: + self.parent_node = None + self.child_node = None + self.key = None + self.full_key = None + self.value = None + self.msg = None + self.object_type = None + self.ref_type = None + + +class MissingMandatoryValue(OmegaConfBaseException): + """Thrown when a variable flagged with '???' value is accessed to + indicate that the value was not set""" + + +class KeyValidationError(OmegaConfBaseException, ValueError): + """ + Thrown when an a key of invalid type is used + """ + + +class ValidationError(OmegaConfBaseException, ValueError): + """ + Thrown when a value fails validation + """ + + +class UnsupportedValueType(ValidationError, ValueError): + """ + Thrown when an input value is not of supported type + """ + + +class ReadonlyConfigError(OmegaConfBaseException): + """ + Thrown when someone tries to modify a frozen config + """ + + +class UnsupportedInterpolationType(OmegaConfBaseException, ValueError): + """ + Thrown when an attempt to use an unregistered interpolation is made + """ + + +class ConfigKeyError(OmegaConfBaseException, KeyError): + """ + Thrown from DictConfig when a regular dict access would have caused a KeyError. + """ + + msg: str + + def __init__(self, msg: str) -> None: + super().__init__(msg) + self.msg = msg + + def __str__(self) -> str: + """ + Workaround to nasty KeyError quirk: https://bugs.python.org/issue2651 + """ + return self.msg + + +class ConfigAttributeError(OmegaConfBaseException, AttributeError): + """ + Thrown from a config object when a regular access would have caused an AttributeError. + """ + + +class ConfigTypeError(OmegaConfBaseException, TypeError): + """ + Thrown from a config object when a regular access would have caused a TypeError. + """ + + +class ConfigIndexError(OmegaConfBaseException, IndexError): + """ + Thrown from a config object when a regular access would have caused an IndexError. + """ + + +class ConfigValueError(OmegaConfBaseException, ValueError): + """ + Thrown from a config object when a regular access would have caused a ValueError. + """ diff --git a/omegaconf/listconfig.py b/omegaconf/listconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..ca5bd83c5e1262e9cb23536c2542ef01803f3880 --- /dev/null +++ b/omegaconf/listconfig.py @@ -0,0 +1,544 @@ +import copy +import itertools +from typing import ( + Any, + Callable, + Dict, + Iterable, + Iterator, + List, + MutableSequence, + Optional, + Tuple, + Type, + Union, +) + +from ._utils import ( + ValueKind, + _get_value, + format_and_raise, + get_value_kind, + is_int, + is_primitive_list, + is_structured_config, + type_str, +) +from .base import Container, ContainerMetadata, Node +from .basecontainer import BaseContainer +from .errors import ( + ConfigAttributeError, + ConfigTypeError, + ConfigValueError, + KeyValidationError, + MissingMandatoryValue, + ReadonlyConfigError, + ValidationError, +) + + +class ListConfig(BaseContainer, MutableSequence[Any]): + + _content: Union[List[Optional[Node]], None, str] + + def __init__( + self, + content: Union[List[Any], Tuple[Any, ...], str, None], + key: Any = None, + parent: Optional[Container] = None, + element_type: Optional[Type[Any]] = None, + is_optional: bool = True, + ref_type: Union[Type[Any], Any] = Any, + ) -> None: + try: + super().__init__( + parent=parent, + metadata=ContainerMetadata( + ref_type=ref_type, + object_type=list, + key=key, + optional=is_optional, + element_type=element_type, + key_type=int, + ), + ) + self.__dict__["_content"] = None + self._set_value(value=content) + except Exception as ex: + format_and_raise(node=None, key=None, value=None, cause=ex, msg=str(ex)) + + def _validate_get(self, key: Any, value: Any = None) -> None: + if not isinstance(key, (int, slice)): + raise KeyValidationError( + "ListConfig indices must be integers or slices, not $KEY_TYPE" + ) + + def _validate_set(self, key: Any, value: Any) -> None: + from omegaconf import OmegaConf + + self._validate_get(key, value) + + if self._get_flag("readonly"): + raise ReadonlyConfigError("ListConfig is read-only") + + if 0 <= key < self.__len__(): + target = self._get_node(key) + if target is not None: + if value is None and not target._is_optional(): + raise ValidationError( + "$FULL_KEY is not optional and cannot be assigned None" + ) + + target_type = self._metadata.element_type + value_type = OmegaConf.get_type(value) + if is_structured_config(target_type): + if ( + target_type is not None + and value_type is not None + and not issubclass(value_type, target_type) + ): + msg = ( + f"Invalid type assigned : {type_str(value_type)} is not a " + f"subclass of {type_str(target_type)}. value: {value}" + ) + raise ValidationError(msg) + + def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "ListConfig": + res = ListConfig(content=[]) + for k, v in self.__dict__.items(): + res.__dict__[k] = copy.deepcopy(v, memo=memo) + res._re_parent() + return res + + # hide content while inspecting in debugger + def __dir__(self) -> Iterable[str]: + if self._is_missing() or self._is_none(): + return [] + return [str(x) for x in range(0, len(self))] + + def __len__(self) -> int: + if self._is_none(): + return 0 + if self._is_missing(): + return 0 + assert isinstance(self.__dict__["_content"], list) + return len(self.__dict__["_content"]) + + def __setattr__(self, key: str, value: Any) -> None: + self._format_and_raise( + key=key, + value=value, + cause=ConfigAttributeError("ListConfig does not support attribute access"), + ) + assert False + + def __getattr__(self, key: str) -> Any: + if is_int(key): + return self.__getitem__(int(key)) + else: + self._format_and_raise( + key=key, + value=None, + cause=ConfigAttributeError( + "ListConfig does not support attribute access" + ), + ) + + def __getitem__(self, index: Union[int, slice]) -> Any: + try: + if self._is_missing(): + raise MissingMandatoryValue("ListConfig is missing") + self._validate_get(index, None) + if self._is_none(): + raise TypeError( + "ListConfig object representing None is not subscriptable" + ) + + assert isinstance(self.__dict__["_content"], list) + if isinstance(index, slice): + result = [] + start, stop, step = self._correct_index_params(index) + for slice_idx in itertools.islice( + range(0, len(self)), start, stop, step + ): + val = self._resolve_with_default( + key=slice_idx, value=self.__dict__["_content"][slice_idx] + ) + result.append(val) + if index.step and index.step < 0: + result.reverse() + return result + else: + return self._resolve_with_default( + key=index, value=self.__dict__["_content"][index] + ) + except Exception as e: + self._format_and_raise(key=index, value=None, cause=e) + + def _correct_index_params(self, index: slice) -> Tuple[int, int, int]: + start = index.start + stop = index.stop + step = index.step + if index.start and index.start < 0: + start = self.__len__() + index.start + if index.stop and index.stop < 0: + stop = self.__len__() + index.stop + if index.step and index.step < 0: + step = abs(step) + if start and stop: + if start > stop: + start, stop = stop + 1, start + 1 + else: + start = stop = 0 + elif not start and stop: + start = list(range(self.__len__() - 1, stop, -step))[0] + stop = None + elif start and not stop: + stop = start + 1 + start = (stop - 1) % step + else: + start = (self.__len__() - 1) % step + return start, stop, step + + def _set_at_index(self, index: Union[int, slice], value: Any) -> None: + self._set_item_impl(index, value) + + def __setitem__(self, index: Union[int, slice], value: Any) -> None: + try: + self._set_at_index(index, value) + except Exception as e: + self._format_and_raise(key=index, value=value, cause=e) + + def append(self, item: Any) -> None: + try: + from omegaconf.omegaconf import OmegaConf, _maybe_wrap + + index = len(self) + self._validate_set(key=index, value=item) + + node = _maybe_wrap( + ref_type=self.__dict__["_metadata"].element_type, + key=index, + value=item, + is_optional=OmegaConf.is_optional(item), + parent=self, + ) + self.__dict__["_content"].append(node) + except Exception as e: + self._format_and_raise(key=index, value=item, cause=e) + assert False + + def _update_keys(self) -> None: + for i in range(len(self)): + node = self._get_node(i) + if node is not None: + node._metadata.key = i + + def insert(self, index: int, item: Any) -> None: + from omegaconf.omegaconf import OmegaConf, _maybe_wrap + + try: + if self._get_flag("readonly"): + raise ReadonlyConfigError("Cannot insert into a read-only ListConfig") + if self._is_none(): + raise TypeError( + "Cannot insert into ListConfig object representing None" + ) + if self._is_missing(): + raise MissingMandatoryValue("Cannot insert into missing ListConfig") + + try: + assert isinstance(self.__dict__["_content"], list) + # insert place holder + self.__dict__["_content"].insert(index, None) + node = _maybe_wrap( + ref_type=self.__dict__["_metadata"].element_type, + key=index, + value=item, + is_optional=OmegaConf.is_optional(item), + parent=self, + ) + self._validate_set(key=index, value=node) + self._set_at_index(index, node) + self._update_keys() + except Exception: + del self.__dict__["_content"][index] + self._update_keys() + raise + except Exception as e: + self._format_and_raise(key=index, value=item, cause=e) + assert False + + def extend(self, lst: Iterable[Any]) -> None: + assert isinstance(lst, (tuple, list, ListConfig)) + for x in lst: + self.append(x) + + def remove(self, x: Any) -> None: + del self[self.index(x)] + + def __delitem__(self, key: Union[int, slice]) -> None: + if self._get_flag("readonly"): + self._format_and_raise( + key=key, + value=None, + cause=ReadonlyConfigError( + "Cannot delete item from read-only ListConfig" + ), + ) + del self.__dict__["_content"][key] + self._update_keys() + + def clear(self) -> None: + del self[:] + + def index( + self, x: Any, start: Optional[int] = None, end: Optional[int] = None + ) -> int: + if start is None: + start = 0 + if end is None: + end = len(self) + assert start >= 0 + assert end <= len(self) + found_idx = -1 + for idx in range(start, end): + item = self[idx] + if x == item: + found_idx = idx + break + if found_idx != -1: + return found_idx + else: + self._format_and_raise( + key=None, + value=None, + cause=ConfigValueError("Item not found in ListConfig"), + ) + assert False + + def count(self, x: Any) -> int: + c = 0 + for item in self: + if item == x: + c = c + 1 + return c + + def copy(self) -> "ListConfig": + return copy.copy(self) + + def _get_node( + self, key: Union[int, slice], validate_access: bool = True + ) -> Optional[Node]: + try: + if self._is_none(): + raise TypeError( + "Cannot get_node from a ListConfig object representing None" + ) + if self._is_missing(): + raise MissingMandatoryValue("Cannot get_node from a missing ListConfig") + assert isinstance(self.__dict__["_content"], list) + if validate_access: + self._validate_get(key) + return self.__dict__["_content"][key] # type: ignore + except (IndexError, TypeError, MissingMandatoryValue, KeyValidationError) as e: + if validate_access: + self._format_and_raise(key=key, value=None, cause=e) + assert False + else: + return None + + def get(self, index: int, default_value: Any = None) -> Any: + try: + if self._is_none(): + raise TypeError("Cannot get from a ListConfig object representing None") + if self._is_missing(): + raise MissingMandatoryValue("Cannot get from a missing ListConfig") + self._validate_get(index, None) + assert isinstance(self.__dict__["_content"], list) + return self._resolve_with_default( + key=index, + value=self.__dict__["_content"][index], + default_value=default_value, + ) + except Exception as e: + self._format_and_raise(key=index, value=None, cause=e) + assert False + + def pop(self, index: int = -1) -> Any: + try: + if self._get_flag("readonly"): + raise ReadonlyConfigError("Cannot pop from read-only ListConfig") + if self._is_none(): + raise TypeError("Cannot pop from a ListConfig object representing None") + if self._is_missing(): + raise MissingMandatoryValue("Cannot pop from a missing ListConfig") + + assert isinstance(self.__dict__["_content"], list) + ret = self._resolve_with_default( + key=index, value=self._get_node(index), default_value=None + ) + del self.__dict__["_content"][index] + self._update_keys() + return ret + except KeyValidationError as e: + self._format_and_raise( + key=index, value=None, cause=e, type_override=ConfigTypeError + ) + assert False + except Exception as e: + self._format_and_raise(key=index, value=None, cause=e) + assert False + + def sort( + self, key: Optional[Callable[[Any], Any]] = None, reverse: bool = False + ) -> None: + try: + if self._get_flag("readonly"): + raise ReadonlyConfigError("Cannot sort a read-only ListConfig") + if self._is_none(): + raise TypeError("Cannot sort a ListConfig object representing None") + if self._is_missing(): + raise MissingMandatoryValue("Cannot sort a missing ListConfig") + + if key is None: + + def key1(x: Any) -> Any: + return x._value() + + else: + + def key1(x: Any) -> Any: + return key(x._value()) # type: ignore + + assert isinstance(self.__dict__["_content"], list) + self.__dict__["_content"].sort(key=key1, reverse=reverse) + + except Exception as e: + self._format_and_raise(key=None, value=None, cause=e) + assert False + + def __eq__(self, other: Any) -> bool: + if isinstance(other, (list, tuple)) or other is None: + other = ListConfig(other) + return ListConfig._list_eq(self, other) + if other is None or isinstance(other, ListConfig): + return ListConfig._list_eq(self, other) + return NotImplemented + + def __ne__(self, other: Any) -> bool: + x = self.__eq__(other) + if x is not NotImplemented: + return not x + return NotImplemented + + def __hash__(self) -> int: + return hash(str(self)) + + def __iter__(self) -> Iterator[Any]: + return self._iter_ex(resolve=True) + + def _iter_ex(self, resolve: bool) -> Iterator[Any]: + try: + if self._is_none(): + raise TypeError("Cannot iterate a ListConfig object representing None") + if self._is_missing(): + raise MissingMandatoryValue("Cannot iterate a missing ListConfig") + + class MyItems(Iterator[Any]): + def __init__(self, lst: ListConfig) -> None: + self.lst = lst + self.index = 0 + + def __next__(self) -> Any: + if self.index == len(self.lst): + raise StopIteration() + if resolve: + v = self.lst[self.index] + else: + v = self.lst.__dict__["_content"][self.index] + if v is not None: + v = _get_value(v) + self.index = self.index + 1 + return v + + assert isinstance(self.__dict__["_content"], list) + return MyItems(self) + except (ReadonlyConfigError, TypeError, MissingMandatoryValue) as e: + self._format_and_raise(key=None, value=None, cause=e) + assert False + + def __add__(self, other: Union[List[Any], "ListConfig"]) -> "ListConfig": + # res is sharing this list's parent to allow interpolation to work as expected + res = ListConfig(parent=self._get_parent(), content=[]) + res.extend(self) + res.extend(other) + return res + + def __iadd__(self, other: Iterable[Any]) -> "ListConfig": + self.extend(other) + return self + + def __contains__(self, item: Any) -> bool: + for x in iter(self): + if x == item: + return True + return False + + def _set_value(self, value: Any) -> None: + from omegaconf import OmegaConf + + if OmegaConf.is_none(value): + if not self._is_optional(): + raise ValidationError( + "Non optional ListConfig cannot be constructed from None" + ) + self.__dict__["_content"] = None + elif get_value_kind(value) == ValueKind.MANDATORY_MISSING: + self.__dict__["_content"] = "???" + elif get_value_kind(value) in ( + ValueKind.INTERPOLATION, + ValueKind.STR_INTERPOLATION, + ): + self.__dict__["_content"] = value + else: + if not (is_primitive_list(value) or isinstance(value, ListConfig)): + type_ = type(value) + msg = ( + f"Invalid value assigned : {type_.__name__} is not a " + f"subclass of ListConfig or list." + ) + raise ValidationError(msg) + self.__dict__["_content"] = [] + if isinstance(value, ListConfig): + self.__dict__["_metadata"] = copy.deepcopy(value._metadata) + self.__dict__["_metadata"].flags = {} + for item in value._iter_ex(resolve=False): + self.append(item) + self.__dict__["_metadata"].flags = copy.deepcopy(value._metadata.flags) + elif is_primitive_list(value): + for item in value: + self.append(item) + + if isinstance(value, ListConfig): + self.__dict__["_metadata"].flags = value._metadata.flags + + @staticmethod + def _list_eq(l1: Optional["ListConfig"], l2: Optional["ListConfig"]) -> bool: + + l1_none = l1.__dict__["_content"] is None + l2_none = l2.__dict__["_content"] is None + if l1_none and l2_none: + return True + if l1_none != l2_none: + return False + + assert isinstance(l1, ListConfig) + assert isinstance(l2, ListConfig) + if len(l1) != len(l2): + return False + for i in range(len(l1)): + if not BaseContainer._item_eq(l1, i, l2, i): + return False + + return True diff --git a/omegaconf/nodes.py b/omegaconf/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..315cc603e83af6000cd753e95e5a186be91a39dd --- /dev/null +++ b/omegaconf/nodes.py @@ -0,0 +1,397 @@ +import copy +import math +import sys +from enum import Enum +from typing import Any, Dict, Optional, Type, Union + +from omegaconf._utils import _is_interpolation, get_type_of, is_primitive_container +from omegaconf.base import Container, Metadata, Node +from omegaconf.errors import ( + MissingMandatoryValue, + ReadonlyConfigError, + UnsupportedValueType, + ValidationError, +) + + +class ValueNode(Node): + _val: Any + + def __init__(self, parent: Optional[Container], value: Any, metadata: Metadata): + from omegaconf import read_write + + super().__init__(parent=parent, metadata=metadata) + with read_write(self): + self._set_value(value) + + def _value(self) -> Any: + return self._val + + def _set_value(self, value: Any) -> None: + from ._utils import ValueKind, get_value_kind + + if self._get_flag("readonly"): + raise ReadonlyConfigError("Cannot set value of read-only config node") + + if isinstance(value, str) and get_value_kind(value) in ( + ValueKind.INTERPOLATION, + ValueKind.STR_INTERPOLATION, + ValueKind.MANDATORY_MISSING, + ): + self._val = value + else: + if not self._metadata.optional and value is None: + raise ValidationError("Non optional field cannot be assigned None") + self._val = self.validate_and_convert(value) + + def validate_and_convert(self, value: Any) -> Any: + """ + Validates input and converts to canonical form + :param value: input value + :return: converted value ("100" may be converted to 100 for example) + """ + return value + + def __str__(self) -> str: + return str(self._val) + + def __repr__(self) -> str: + return repr(self._val) if hasattr(self, "_val") else "__INVALID__" + + def __eq__(self, other: Any) -> bool: + if isinstance(other, AnyNode): + return self._val == other._val # type: ignore + else: + return self._val == other # type: ignore + + def __ne__(self, other: Any) -> bool: + x = self.__eq__(other) + assert x is not NotImplemented + return not x + + def __hash__(self) -> int: + return hash(self._val) + + def _deepcopy_impl(self, res: Any, memo: Optional[Dict[int, Any]] = {}) -> None: + res.__dict__ = copy.deepcopy(self.__dict__, memo=memo) + + def _is_none(self) -> bool: + if self._is_interpolation(): + node = self._dereference_node( + throw_on_resolution_failure=False, throw_on_missing=False + ) + if node is None: + # missing or resolution failure + return False + else: + node = self + return node._value() is None + + def _is_optional(self) -> bool: + node = self._dereference_node() + assert node is not None + return node._metadata.optional + + def _is_missing(self) -> bool: + try: + if self._is_interpolation(): + node = self._dereference_node( + throw_on_resolution_failure=False, throw_on_missing=True + ) + if node is None: + # resolution failure + return False + else: + node = self + + assert node is not None + if isinstance(node, Container): + ret = node._is_missing() + else: + ret = node._value() == "???" + except MissingMandatoryValue: + ret = True + assert isinstance(ret, bool) + return ret + + def _is_interpolation(self) -> bool: + return _is_interpolation(self._value()) + + def _get_full_key(self, key: Union[str, Enum, int, None]) -> str: + parent = self._get_parent() + if parent is None: + if self._metadata.key is None: + return "" + else: + return str(self._metadata.key) + else: + return parent._get_full_key(self._metadata.key) + + +class AnyNode(ValueNode): + def __init__( + self, + value: Any = None, + key: Any = None, + parent: Optional[Container] = None, + is_optional: bool = True, + ): + super().__init__( + parent=parent, + value=value, + metadata=Metadata( + ref_type=Any, object_type=None, key=key, optional=is_optional # type: ignore + ), + ) + + def validate_and_convert(self, value: Any) -> Any: + from ._utils import is_primitive_type + + if not is_primitive_type(value): + t = get_type_of(value) + raise UnsupportedValueType( + f"Value '{t.__name__}' is not a supported primitive type" + ) + return value + + def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "AnyNode": + res = AnyNode() + self._deepcopy_impl(res, memo) + return res + + +class StringNode(ValueNode): + def __init__( + self, + value: Any = None, + key: Any = None, + parent: Optional[Container] = None, + is_optional: bool = True, + ): + super().__init__( + parent=parent, + value=value, + metadata=Metadata( + key=key, optional=is_optional, ref_type=str, object_type=str + ), + ) + + def validate_and_convert(self, value: Any) -> Optional[str]: + from omegaconf import OmegaConf + + if OmegaConf.is_config(value) or is_primitive_container(value): + raise ValidationError("Cannot convert '$VALUE_TYPE' to string : '$VALUE'") + return str(value) if value is not None else None + + def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "StringNode": + res = StringNode() + self._deepcopy_impl(res, memo) + return res + + +class IntegerNode(ValueNode): + def __init__( + self, + value: Any = None, + key: Any = None, + parent: Optional[Container] = None, + is_optional: bool = True, + ): + super().__init__( + parent=parent, + value=value, + metadata=Metadata( + key=key, optional=is_optional, ref_type=int, object_type=int + ), + ) + + def validate_and_convert(self, value: Any) -> Optional[int]: + try: + if value is None: + val = None + elif type(value) in (str, int): + val = int(value) + else: + raise ValueError() + except ValueError: + raise ValidationError("Value '$VALUE' could not be converted to Integer") + return val + + def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "IntegerNode": + res = IntegerNode() + self._deepcopy_impl(res, memo) + return res + + +class FloatNode(ValueNode): + def __init__( + self, + value: Any = None, + key: Any = None, + parent: Optional[Container] = None, + is_optional: bool = True, + ): + super().__init__( + parent=parent, + value=value, + metadata=Metadata( + key=key, optional=is_optional, ref_type=float, object_type=float + ), + ) + + def validate_and_convert(self, value: Any) -> Optional[float]: + if value is None: + return None + try: + if type(value) in (float, str, int): + return float(value) + else: + raise ValueError() + except ValueError: + raise ValidationError("Value '$VALUE' could not be converted to Float") + + def __eq__(self, other: Any) -> bool: + if isinstance(other, ValueNode): + other_val = other._val + else: + other_val = other + if self._val is None and other is None: + return True + if self._val is None and other is not None: + return False + if self._val is not None and other is None: + return False + nan1 = math.isnan(self._val) if isinstance(self._val, float) else False + nan2 = math.isnan(other_val) if isinstance(other_val, float) else False + return self._val == other_val or (nan1 and nan2) + + def __hash__(self) -> int: + return hash(self._val) + + def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "FloatNode": + res = FloatNode() + self._deepcopy_impl(res, memo) + return res + + +class BooleanNode(ValueNode): + def __init__( + self, + value: Any = None, + key: Any = None, + parent: Optional[Container] = None, + is_optional: bool = True, + ): + super().__init__( + parent=parent, + value=value, + metadata=Metadata( + key=key, optional=is_optional, ref_type=bool, object_type=bool + ), + ) + + def validate_and_convert(self, value: Any) -> Optional[bool]: + if isinstance(value, bool): + return value + if isinstance(value, int): + return value != 0 + elif value is None: + return None + elif isinstance(value, str): + try: + return self.validate_and_convert(int(value)) + except ValueError as e: + if value.lower() in ("yes", "y", "on", "true"): + return True + elif value.lower() in ("no", "n", "off", "false"): + return False + else: + raise ValidationError( + "Value '$VALUE' is not a valid bool (type $VALUE_TYPE)" + ).with_traceback(sys.exc_info()[2]) from e + else: + raise ValidationError( + "Value '$VALUE' is not a valid bool (type $VALUE_TYPE)" + ) + + def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "BooleanNode": + res = BooleanNode() + self._deepcopy_impl(res, memo) + return res + + +class EnumNode(ValueNode): # lgtm [py/missing-equals] : Intentional. + """ + NOTE: EnumNode is serialized to yaml as a string ("Color.BLUE"), not as a fully qualified yaml type. + this means serialization to YAML of a typed config (with EnumNode) will not retain the type of the Enum + when loaded. + This is intentional, Please open an issue against OmegaConf if you wish to discuss this decision. + """ + + def __init__( + self, + enum_type: Type[Enum], + value: Optional[Union[Enum, str]] = None, + key: Any = None, + parent: Optional[Container] = None, + is_optional: bool = True, + ): + if not isinstance(enum_type, type) or not issubclass(enum_type, Enum): + raise ValidationError( + f"EnumNode can only operate on Enum subclasses ({enum_type})" + ) + self.fields: Dict[str, str] = {} + self.enum_type: Type[Enum] = enum_type + for name, constant in enum_type.__members__.items(): + self.fields[name] = constant.value + super().__init__( + parent=parent, + value=value, + metadata=Metadata( + key=key, optional=is_optional, ref_type=enum_type, object_type=enum_type + ), + ) + + def validate_and_convert(self, value: Any) -> Optional[Enum]: + return self.validate_and_convert_to_enum(enum_type=self.enum_type, value=value) + + @staticmethod + def validate_and_convert_to_enum( + enum_type: Type[Enum], value: Any + ) -> Optional[Enum]: + if value is None: + return None + + if not isinstance(value, (str, int)) and not isinstance(value, enum_type): + raise ValidationError( + f"Value $VALUE ($VALUE_TYPE) is not a valid input for {enum_type}" + ) + + if isinstance(value, enum_type): + return value + + try: + if isinstance(value, (float, bool)): + raise ValueError + + if isinstance(value, int): + return enum_type(value) + + if isinstance(value, str): + prefix = f"{enum_type.__name__}." + if value.startswith(prefix): + value = value[len(prefix) :] + return enum_type[value] + + assert False + + except (ValueError, KeyError) as e: + valid = ", ".join([x for x in enum_type.__members__.keys()]) + raise ValidationError( + f"Invalid value '$VALUE', expected one of [{valid}]" + ).with_traceback(sys.exc_info()[2]) from e + + def __deepcopy__(self, memo: Dict[int, Any] = {}) -> "EnumNode": + res = EnumNode(enum_type=self.enum_type) + self._deepcopy_impl(res, memo) + return res diff --git a/omegaconf/omegaconf.py b/omegaconf/omegaconf.py new file mode 100644 index 0000000000000000000000000000000000000000..99675813edc3e3edbfdf0cb7542383d3b816651d --- /dev/null +++ b/omegaconf/omegaconf.py @@ -0,0 +1,813 @@ +"""OmegaConf module""" +import copy +import io +import os +import pathlib +import re +import sys +import warnings +from collections import defaultdict +from contextlib import contextmanager +from enum import Enum +from textwrap import dedent +from typing import ( + IO, + Any, + Callable, + Dict, + Generator, + List, + Match, + Optional, + Tuple, + Type, + Union, + overload, +) + +import yaml +from typing_extensions import Protocol + +from . import DictConfig, ListConfig +from ._utils import ( + _ensure_container, + _get_value, + decode_primitive, + format_and_raise, + get_dict_key_value_types, + get_list_element_type, + get_omega_conf_dumper, + get_type_of, + is_attr_class, + is_dataclass, + is_dict_annotation, + is_int, + is_list_annotation, + is_primitive_container, + is_primitive_dict, + is_primitive_list, + is_structured_config, + is_tuple_annotation, + type_str, +) +from .base import Container, Node +from .basecontainer import BaseContainer +from .errors import ( + MissingMandatoryValue, + OmegaConfBaseException, + UnsupportedInterpolationType, + ValidationError, +) +from .nodes import ( + AnyNode, + BooleanNode, + EnumNode, + FloatNode, + IntegerNode, + StringNode, + ValueNode, +) + +MISSING: Any = "???" + +# A marker used in OmegaConf.create() to differentiate between creating an empty {} DictConfig +# and creating a DictConfig with None content. +_EMPTY_MARKER_ = object() + + +def II(interpolation: str) -> Any: + """ + Equivalent to ${interpolation} + :param interpolation: + :return: input ${node} with type Any + """ + return "${" + interpolation + "}" + + +def SI(interpolation: str) -> Any: + """ + Use this for String interpolation, for example "http://${host}:${port}" + :param interpolation: interpolation string + :return: input interpolation with type Any + """ + return interpolation + + +class Resolver0(Protocol): + def __call__(self) -> Any: + ... + + +class Resolver1(Protocol): + def __call__(self, __x1: str) -> Any: + ... + + +class Resolver2(Protocol): + def __call__(self, __x1: str, __x2: str) -> Any: + ... + + +class Resolver3(Protocol): + def __call__(self, __x1: str, __x2: str, __x3: str) -> Any: + ... + + +Resolver = Union[Resolver0, Resolver1, Resolver2, Resolver3] + + +def register_default_resolvers() -> None: + def env(key: str, default: Optional[str] = None) -> Any: + try: + return decode_primitive(os.environ[key]) + except KeyError: + if default is not None: + return decode_primitive(default) + else: + raise ValidationError(f"Environment variable '{key}' not found") + + OmegaConf.register_resolver("env", env) + + +class OmegaConf: + """OmegaConf primary class""" + + def __init__(self) -> None: + raise NotImplementedError("Use one of the static construction functions") + + @staticmethod + def structured(obj: Any, parent: Optional[BaseContainer] = None) -> Any: + return OmegaConf.create(obj, parent) + + @staticmethod + @overload + def create( + obj: str, parent: Optional[BaseContainer] = None + ) -> Union[DictConfig, ListConfig]: + ... + + @staticmethod + @overload + def create( + obj: Union[List[Any], Tuple[Any, ...]], parent: Optional[BaseContainer] = None + ) -> ListConfig: + ... + + @staticmethod + @overload + def create(obj: DictConfig, parent: Optional[BaseContainer] = None) -> DictConfig: + ... + + @staticmethod + @overload + def create(obj: ListConfig, parent: Optional[BaseContainer] = None) -> ListConfig: + ... + + @staticmethod + @overload + def create( + obj: Union[Dict[str, Any], None] = None, parent: Optional[BaseContainer] = None + ) -> DictConfig: + ... + + @staticmethod + def create( # noqa F811 + obj: Any = _EMPTY_MARKER_, parent: Optional[BaseContainer] = None + ) -> Union[DictConfig, ListConfig]: + return OmegaConf._create_impl(obj=obj, parent=parent) + + @staticmethod + def _create_impl( # noqa F811 + obj: Any = _EMPTY_MARKER_, parent: Optional[BaseContainer] = None + ) -> Union[DictConfig, ListConfig]: + try: + from ._utils import get_yaml_loader + from .dictconfig import DictConfig + from .listconfig import ListConfig + + if obj is _EMPTY_MARKER_: + obj = {} + if isinstance(obj, str): + obj = yaml.load(obj, Loader=get_yaml_loader()) + if obj is None: + return OmegaConf.create({}) + elif isinstance(obj, str): + return OmegaConf.create({obj: None}) + else: + assert isinstance(obj, (list, dict)) + return OmegaConf.create(obj) + + else: + if ( + is_primitive_dict(obj) + or OmegaConf.is_dict(obj) + or is_structured_config(obj) + or obj is None + ): + ref_type = None + if is_structured_config(obj): + ref_type = get_type_of(obj) + elif OmegaConf.is_dict(obj): + ref_type = obj._metadata.ref_type + + if ref_type is None: + ref_type = OmegaConf.get_type(obj) + + if isinstance(obj, DictConfig): + key_type = obj._metadata.key_type + element_type = obj._metadata.element_type + else: + key_type, element_type = get_dict_key_value_types(ref_type) + return DictConfig( + content=obj, + parent=parent, + ref_type=ref_type, + key_type=key_type, + element_type=element_type, + ) + elif is_primitive_list(obj) or OmegaConf.is_list(obj): + ref_type = OmegaConf.get_type(obj) + element_type = get_list_element_type(ref_type) + return ListConfig( + element_type=element_type, content=obj, parent=parent + ) + else: + 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( + f"Object of unsupported type: '{type(obj).__name__}'" + ) + except OmegaConfBaseException as e: + format_and_raise(node=None, key=None, value=None, msg=str(e), cause=e) + assert False + + @staticmethod + def load(file_: Union[str, pathlib.Path, IO[Any]]) -> Union[DictConfig, ListConfig]: + from ._utils import get_yaml_loader + + if isinstance(file_, (str, pathlib.Path)): + with io.open(os.path.abspath(file_), "r", encoding="utf-8") as f: + obj = yaml.load(f, Loader=get_yaml_loader()) + if obj is None: + res = OmegaConf.create() + else: + res = OmegaConf.create(obj) + assert isinstance(res, (ListConfig, DictConfig)) + return res + elif getattr(file_, "read", None): + obj = yaml.load(file_, Loader=get_yaml_loader()) + assert isinstance( + obj, (list, dict, str) + ), f"Invalid loaded object type : {type(obj).__name__}" + return OmegaConf.create(obj) + else: + raise TypeError("Unexpected file type") + + @staticmethod + def save( + config: Any, f: Union[str, pathlib.Path, IO[Any]], resolve: bool = False + ) -> None: + """ + Save as configuration object to a file + :param config: omegaconf.Config object (DictConfig or ListConfig). + :param f: filename or file object + :param resolve: True to save a resolved config (defaults to False) + """ + if is_dataclass(config) or is_attr_class(config): + config = OmegaConf.create(config) + data = OmegaConf.to_yaml(config, resolve=resolve) + if isinstance(f, (str, pathlib.Path)): + with io.open(os.path.abspath(f), "w", encoding="utf-8") as file: + file.write(data) + elif hasattr(f, "write"): + f.write(data) + f.flush() + else: + raise TypeError("Unexpected file type") + + @staticmethod + def from_cli(args_list: Optional[List[str]] = None) -> DictConfig: + if args_list is None: + # Skip program name + args_list = sys.argv[1:] + return OmegaConf.from_dotlist(args_list) + + @staticmethod + def from_dotlist(dotlist: List[str]) -> DictConfig: + """ + Creates config from the content sys.argv or from the specified args list of not None + :param dotlist: + :return: + """ + conf = OmegaConf.create() + conf.merge_with_dotlist(dotlist) + return conf + + @staticmethod + def merge( + *others: Union[BaseContainer, Dict[str, Any], List[Any], Tuple[Any, ...], Any] + ) -> Union[ListConfig, DictConfig]: + """Merge a list of previously created configs into a single one""" + assert len(others) > 0 + target = copy.deepcopy(others[0]) + target = _ensure_container(target) + assert isinstance(target, (DictConfig, ListConfig)) + + with flag_override(target, "readonly", False): + target.merge_with(*others[1:]) + turned_readonly = target._get_flag("readonly") is True + + if turned_readonly: + OmegaConf.set_readonly(target, True) + + return target + + @staticmethod + def _tokenize_args(string: Optional[str]) -> List[str]: + if string is None or string == "": + return [] + + def _unescape_word_boundary(match: Match[str]) -> str: + if match.start() == 0 or match.end() == len(match.string): + return "" + return match.group(0) + + escaped = re.split(r"(? None: + assert callable(resolver), "resolver must be callable" + # noinspection PyProtectedMember + assert ( + name not in BaseContainer._resolvers + ), "resolved {} is already registered".format(name) + + def caching(config: BaseContainer, key: str) -> Any: + cache = OmegaConf.get_cache(config)[name] + val = ( + cache[key] if key in cache else resolver(*OmegaConf._tokenize_args(key)) + ) + cache[key] = val + return val + + # noinspection PyProtectedMember + BaseContainer._resolvers[name] = caching + + @staticmethod + def get_resolver(name: str) -> Optional[Callable[[Container, Any], Any]]: + # noinspection PyProtectedMember + return ( + BaseContainer._resolvers[name] if name in BaseContainer._resolvers else None + ) + + # noinspection PyProtectedMember + @staticmethod + def clear_resolvers() -> None: + BaseContainer._resolvers = {} + register_default_resolvers() + + @staticmethod + def get_cache(conf: BaseContainer) -> Dict[str, Any]: + return conf._metadata.resolver_cache + + @staticmethod + def set_cache(conf: BaseContainer, cache: Dict[str, Any]) -> None: + conf._metadata.resolver_cache = copy.deepcopy(cache) + + @staticmethod + def clear_cache(conf: BaseContainer) -> None: + OmegaConf.set_cache(conf, defaultdict(dict, {})) + + @staticmethod + def copy_cache(from_config: BaseContainer, to_config: BaseContainer) -> None: + OmegaConf.set_cache(to_config, OmegaConf.get_cache(from_config)) + + @staticmethod + def set_readonly(conf: Node, value: Optional[bool]) -> None: + # noinspection PyProtectedMember + conf._set_flag("readonly", value) + + @staticmethod + def is_readonly(conf: Node) -> Optional[bool]: + # noinspection PyProtectedMember + return conf._get_flag("readonly") + + @staticmethod + def set_struct(conf: Container, value: Optional[bool]) -> None: + # noinspection PyProtectedMember + conf._set_flag("struct", value) + + @staticmethod + def is_struct(conf: Container) -> Optional[bool]: + # noinspection PyProtectedMember + return conf._get_flag("struct") + + @staticmethod + def masked_copy(conf: DictConfig, keys: Union[str, List[str]]) -> DictConfig: + """ + Create a masked copy of of this config that contains a subset of the keys + :param conf: DictConfig object + :param keys: keys to preserve in the copy + :return: + """ + from .dictconfig import DictConfig + + if not isinstance(conf, DictConfig): + raise ValueError("masked_copy is only supported for DictConfig") + + if isinstance(keys, str): + keys = [keys] + content = {key: value for key, value in conf.items_ex(resolve=False, keys=keys)} + return DictConfig(content=content) + + @staticmethod + def to_container( + cfg: Any, resolve: bool = False, enum_to_str: bool = False + ) -> Union[Dict[str, Any], List[Any], None, str]: + """ + Resursively converts an OmegaConf config to a primitive container (dict or list). + :param cfg: the config to convert + :param resolve: True to resolve all values + :param enum_to_str: True to convert Enum values to strings + :return: A dict or a list representing this config as a primitive container. + """ + assert isinstance(cfg, Container) + # noinspection PyProtectedMember + return BaseContainer._to_content(cfg, resolve=resolve, enum_to_str=enum_to_str) + + @staticmethod + def is_missing(cfg: Any, key: Union[int, str]) -> bool: + assert isinstance(cfg, Container) + try: + node = cfg._get_node(key) + if node is None: + return False + return node._is_missing() + except (UnsupportedInterpolationType, KeyError, AttributeError): + return False + + @staticmethod + def is_optional(obj: Any, key: Optional[Union[int, str]] = None) -> bool: + if key is not None: + assert isinstance(obj, Container) + obj = obj._get_node(key) + if isinstance(obj, Node): + return obj._is_optional() + else: + return True + + @staticmethod + def is_none(obj: Any, key: Optional[Union[int, str]] = None) -> bool: + if key is not None: + assert isinstance(obj, Container) + obj = obj._get_node(key) + if isinstance(obj, Node): + return obj._is_none() + else: + return obj is None + + @staticmethod + def is_interpolation(node: Any, key: Optional[Union[int, str]] = None) -> bool: + if key is not None: + assert isinstance(node, Container) + target = node._get_node(key) + else: + target = node + if target is not None: + assert isinstance(target, Node) + return target._is_interpolation() + return False + + @staticmethod + def is_list(obj: Any) -> bool: + from . import ListConfig + + return isinstance(obj, ListConfig) + + @staticmethod + def is_dict(obj: Any) -> bool: + from . import DictConfig + + return isinstance(obj, DictConfig) + + @staticmethod + def is_config(obj: Any) -> bool: + from . import Container + + return isinstance(obj, Container) + + @staticmethod + def get_type(obj: Any, key: Optional[str] = None) -> Optional[Type[Any]]: + if key is not None: + c = obj._get_node(key) + else: + c = obj + return OmegaConf._get_obj_type(c) + + @staticmethod + def _get_obj_type(c: Any) -> Optional[Type[Any]]: + if is_structured_config(c): + return get_type_of(c) + elif c is None: + return None + elif isinstance(c, DictConfig): + if c._is_none(): + return None + elif c._is_missing(): + return None + else: + if is_structured_config(c._metadata.object_type): + return c._metadata.object_type + else: + return dict + elif isinstance(c, ListConfig): + return list + elif isinstance(c, ValueNode): + return type(c._value()) + elif isinstance(c, dict): + return dict + elif isinstance(c, (list, tuple)): + return list + else: + return get_type_of(c) + + @staticmethod + def select(cfg: Container, key: str, throw_on_missing: bool = False) -> Any: + try: + _root, _last_key, value = cfg._select_impl( + key, throw_on_missing=throw_on_missing, throw_on_resolution_failure=True + ) + if value is not None and value._is_missing(): + # throw_on_missing must be False + return None + + return _get_value(value) + except Exception as e: + format_and_raise(node=cfg, key=key, value=None, cause=e, msg=str(e)) + + @staticmethod + def update( + cfg: Container, key: str, value: Any = None, merge: Optional[bool] = None + ) -> None: + """ + Updates a dot separated key sequence to a value + + :param cfg: input config to update + :param key: key to update (can be a dot separated path) + :param value: value to set, if value if a list or a dict it will be merged or set + depending on merge_config_values + :param merge: If value is a dict or a list, True for merge, False for set. + True to merge + False to set + None (default) : deprecation warning and default to False + """ + + if merge is None: + warnings.warn( + dedent( + """\ + update() merge flag is is not specified, defaulting to False. + For more details, see https://github.com/omry/omegaconf/issues/367""" + ), + category=UserWarning, + stacklevel=1, + ) + merge = False + + split = key.split(".") + root = cfg + for i in range(len(split) - 1): + k = split[i] + # if next_root is a primitive (string, int etc) replace it with an empty map + next_root, key_ = _select_one(root, k, throw_on_missing=False) + if not isinstance(next_root, Container): + root[key_] = {} + root = root[key_] + + last = split[-1] + + assert isinstance( + root, Container + ), f"Unexpected type for root : {type(root).__name__}" + + last_key: Union[str, int] = last + if isinstance(root, ListConfig): + last_key = int(last) + + if merge and (OmegaConf.is_config(value) or is_primitive_container(value)): + assert isinstance(root, BaseContainer) + node = root._get_node(last_key) + if OmegaConf.is_config(node): + assert isinstance(node, BaseContainer) + node.merge_with(value) + return + + if OmegaConf.is_dict(root): + assert isinstance(last_key, str) + root.__setattr__(last_key, value) + elif OmegaConf.is_list(root): + assert isinstance(last_key, int) + root.__setitem__(last_key, value) + else: + assert False + + @staticmethod + def to_yaml(cfg: Any, *, resolve: bool = False, sort_keys: bool = False) -> str: + """ + returns a yaml dump of this config object. + :param cfg: Config object, Structured Config type or instance + :param resolve: if True, will return a string with the interpolations resolved, otherwise + interpolations are preserved + :param sort_keys: If True, will print dict keys in sorted order. default False. + :return: A string containing the yaml representation. + """ + cfg = _ensure_container(cfg) + container = OmegaConf.to_container(cfg, resolve=resolve, enum_to_str=True) + return yaml.dump( # type: ignore + container, + default_flow_style=False, + allow_unicode=True, + sort_keys=sort_keys, + Dumper=get_omega_conf_dumper(), + ) + + +# register all default resolvers +register_default_resolvers() + + +@contextmanager +def flag_override( + config: Node, name: str, value: Optional[bool] +) -> Generator[Node, None, None]: + prev_state = config._get_flag(name) + try: + config._set_flag(name, value) + yield config + finally: + config._set_flag(name, prev_state) + + +@contextmanager +def read_write(config: Node) -> Generator[Node, None, None]: + prev_state = config._get_node_flag("readonly") + try: + OmegaConf.set_readonly(config, False) + yield config + finally: + OmegaConf.set_readonly(config, prev_state) + + +@contextmanager +def open_dict(config: Container) -> Generator[Container, None, None]: + prev_state = config._get_node_flag("struct") + try: + OmegaConf.set_struct(config, False) + yield config + finally: + OmegaConf.set_struct(config, prev_state) + + +# === private === # + + +def _node_wrap( + type_: Any, + parent: Optional[BaseContainer], + is_optional: bool, + value: Any, + key: Any, + ref_type: Any = None, +) -> Node: + node: Node + is_dict = type(value) is dict or is_dict_annotation(type_) + is_list = ( + type(value) in (list, tuple) + or is_list_annotation(type_) + or is_tuple_annotation(type_) + ) + if is_dict: + key_type, element_type = get_dict_key_value_types(type_) + node = DictConfig( + content=value, + key=key, + parent=parent, + ref_type=type_, + is_optional=is_optional, + key_type=key_type, + element_type=element_type, + ) + elif is_list: + element_type = get_list_element_type(type_) + node = ListConfig( + content=value, + key=key, + parent=parent, + is_optional=is_optional, + element_type=element_type, + ref_type=ref_type, + ) + elif is_structured_config(type_) or is_structured_config(value): + key_type, element_type = get_dict_key_value_types(type_) + node = DictConfig( + ref_type=type_, + is_optional=is_optional, + content=value, + key=key, + parent=parent, + key_type=key_type, + element_type=element_type, + ) + elif type_ == Any or type_ is None: + node = AnyNode(value=value, key=key, parent=parent, is_optional=is_optional) + elif issubclass(type_, Enum): + node = EnumNode( + enum_type=type_, + value=value, + key=key, + parent=parent, + is_optional=is_optional, + ) + elif type_ == int: + node = IntegerNode(value=value, key=key, parent=parent, is_optional=is_optional) + elif type_ == float: + node = FloatNode(value=value, key=key, parent=parent, is_optional=is_optional) + elif type_ == bool: + node = BooleanNode(value=value, key=key, parent=parent, is_optional=is_optional) + elif type_ == str: + node = StringNode(value=value, key=key, parent=parent, is_optional=is_optional) + else: + raise ValidationError(f"Unexpected object type : {type_str(type_)}") + return node + + +def _maybe_wrap( + ref_type: Any, + key: Any, + value: Any, + is_optional: bool, + parent: Optional[BaseContainer], +) -> Node: + # if already a node, update key and parent and return as is. + # NOTE: that this mutate the input node! + if isinstance(value, Node): + value._set_key(key) + value._set_parent(parent) + return value + else: + return _node_wrap( + type_=ref_type, + parent=parent, + is_optional=is_optional, + value=value, + key=key, + ref_type=ref_type, + ) + + +def _select_one( + c: Container, key: str, throw_on_missing: bool, throw_on_type_error: bool = True +) -> Tuple[Optional[Node], Union[str, int]]: + from .dictconfig import DictConfig + from .listconfig import ListConfig + + ret_key: Union[str, int] = key + assert isinstance(c, (DictConfig, ListConfig)), f"Unexpected type : {c}" + if isinstance(c, DictConfig): + assert isinstance(ret_key, str) + val: Optional[Node] = c._get_node(ret_key, validate_access=False) + if val is not None: + if val._is_missing(): + if throw_on_missing: + raise MissingMandatoryValue( + f"Missing mandatory value : {c._get_full_key(ret_key)}" + ) + else: + return val, ret_key + else: + val = None + elif isinstance(c, ListConfig): + assert isinstance(ret_key, str) + if not is_int(ret_key): + if throw_on_type_error: + raise TypeError( + f"Index '{ret_key}' ({type(ret_key).__name__}) is not an int" + ) + else: + val = None + else: + ret_key = int(ret_key) + if ret_key < 0 or ret_key + 1 > len(c): + val = None + else: + val = c._get_node(ret_key) + else: + assert False + + return val, ret_key diff --git a/omegaconf/py.typed b/omegaconf/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/omegaconf/version.py b/omegaconf/version.py new file mode 100644 index 0000000000000000000000000000000000000000..ff3dcb1fcec46cdfa5cc192aaad582ae0adcbdb4 --- /dev/null +++ b/omegaconf/version.py @@ -0,0 +1,13 @@ +import sys # pragma: no cover + +__version__ = "2.0.6" + +msg = """OmegaConf 2.0 and above is compatible with Python 3.6 and newer. +You have the following options: +1. Upgrade to Python 3.6 or newer. + This is highly recommended. new features will not be added to OmegaConf 1.4. +2. Continue using OmegaConf 1.4: + You can pip install 'OmegaConf<1.5' to do that. +""" +if sys.version_info < (3, 6): + raise ImportError(msg) # pragma: no cover diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..33b088eaf7ca5f765c884ffc42cc38a2ade74303 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,35 @@ +[tool.towncrier] + package = "omegaconf" + package_dir = "" + filename = "NEWS.md" + directory = "news/" + title_format = "## {version} ({project_date})" + template = "news/_template.rst" + issue_format = "[#{issue}](https://github.com/omry/omegaconf/issues/{issue})" + start_string = "\n" + underlines = [""] + + [[tool.towncrier.type]] + directory = "feature" + name = "Features" + showcontent = true + + [[tool.towncrier.type]] + directory = "bugfix" + name = "Bug Fixes" + showcontent = true + + [[tool.towncrier.type]] + directory = "removal" + name = "Deprecations and Removals" + showcontent = true + + [[tool.towncrier.type]] + directory = "docs" + name = "Improved Documentation" + showcontent = true + + [[tool.towncrier.type]] + directory = "misc" + name = "Miscellaneous changes" + showcontent = true diff --git a/requirements/base.txt b/requirements/base.txt new file mode 100644 index 0000000000000000000000000000000000000000..8746b97b2b8ed4f9eef1e0eaf55fa4286d261918 --- /dev/null +++ b/requirements/base.txt @@ -0,0 +1,4 @@ +PyYAML>=5.1.* +# Use dataclasses backport for Python 3.6. +dataclasses;python_version=='3.6' +typing-extensions diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..461579be26026c05dbcdeec58eb8be52eb91937d --- /dev/null +++ b/setup.cfg @@ -0,0 +1,11 @@ +[aliases] +test = pytest + +[mypy] +python_version = 3.6 +mypy_path = .stubs + +[egg_info] +tag_build = +tag_date = 0 + diff --git a/setup.py b/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d33e7759ac1c959bdaee1fa43edfd033fde765f9 --- /dev/null +++ b/setup.py @@ -0,0 +1,65 @@ +# type: ignore +""" +OmegaConf setup + Instructions: + # Build: + rm -rf dist/ omegaconf.egg-info/ + python setup.py sdist bdist_wheel + # Upload: + twine upload dist/* +""" +import codecs +import os +import pathlib +import re + +import pkg_resources +import setuptools + +with pathlib.Path("requirements/base.txt").open() as requirements_txt: + install_requires = [ + str(requirement) + for requirement in pkg_resources.parse_requirements(requirements_txt) + ] + + +def find_version(*file_paths): + here = os.path.abspath(os.path.dirname(__file__)) + + def read(*parts): + with codecs.open(os.path.join(here, *parts), "r") as fp: + return fp.read() + + version_file = read(*file_paths) + version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) + if version_match: + return version_match.group(1) + raise RuntimeError("Unable to find version string.") + + +with open("README.md", "r") as fh: + LONG_DESC = fh.read() + setuptools.setup( + name="omegaconf", + version=find_version("omegaconf", "version.py"), + author="Omry Yadan", + author_email="omry@yadan.net", + description="A flexible configuration library", + long_description=LONG_DESC, + long_description_content_type="text/markdown", + setup_requires=["pytest-runner"], + tests_require=["pytest"], + url="https://github.com/omry/omegaconf", + keywords="yaml configuration config", + packages=["omegaconf"], + python_requires=">=3.6", + classifiers=[ + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + ], + install_requires=install_requires, + package_data={"omegaconf": ["py.typed"]}, + ) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b600faa2a79be323332b720f4cadaf321c06e2 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,156 @@ +from contextlib import contextmanager +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, Iterator, List, Optional, Union + +import attr + +from omegaconf import II, MISSING + + +class IllegalType: + def __init__(self) -> None: + pass + + def __eq__(self, other: Any) -> bool: + if isinstance(other, IllegalType): + return True + return False + + +@contextmanager +def does_not_raise(enter_result: Any = None) -> Iterator[Any]: + yield enter_result + + +class Color(Enum): + RED = 1 + GREEN = 2 + BLUE = 3 + + +@dataclass +class User: + name: str = MISSING + age: int = MISSING + + +@dataclass +class Group: + admin: Optional[User] = None + + +class Enum1(Enum): + FOO = 1 + BAR = 2 + + +@dataclass +class Users: + name2user: Dict[str, User] = field(default_factory=dict) + + +@dataclass +class ConfWithMissingDict: + dict: Dict[str, Any] = MISSING + + +@dataclass +class Plugin: + name: str = MISSING + params: Any = MISSING + + +@dataclass +class ConcretePlugin(Plugin): + name: str = "foobar_plugin" + + @dataclass + class FoobarParams: + foo: int = 10 + + params: FoobarParams = FoobarParams() + + +@dataclass +class StructuredWithMissing: + num: int = MISSING + opt_num: Optional[int] = MISSING + dict: Dict[str, str] = MISSING + opt_dict: Optional[Dict[str, str]] = MISSING + list: List[str] = MISSING + opt_list: Optional[List[str]] = MISSING + user: User = MISSING + opt_user: Optional[User] = MISSING + inter_num: int = II("num") + inter_user: User = II("user") + inter_opt_user: Optional[User] = II("opt_user") + + +@dataclass +class UnionError: + x: Union[int, str] = 10 + + +@dataclass +class MissingList: + list: List[str] = MISSING + + +@dataclass +class MissingDict: + dict: Dict[str, str] = MISSING + + +@dataclass +class DictEnum: + color_key: Dict[Color, str] = field(default_factory=lambda: {}) + color_val: Dict[str, Color] = field(default_factory=lambda: {}) + + +@dataclass +class A: + a: int = 10 + + +@dataclass +class B: + x: A = MISSING + + +@dataclass +class C: + x: Optional[A] = None + + +@dataclass +class PersonD: + age: int = 18 + registered: bool = True + + +@attr.s(auto_attribs=True) +class PersonA: + age: int = 18 + registered: bool = True + + +@dataclass +class Module: + name: str = MISSING + classes: List[str] = MISSING + + +@dataclass +class Package: + modules: List[Module] = MISSING + + +@dataclass +class InterpolationList: + list: List[float] = II("optimization.lr") + + +@dataclass +class InterpolationDict: + dict: Dict[str, int] = II("optimization.lr") diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..c3711da3ebf190b449bb9ad47a8b7007c37fc5f5 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,18 @@ +import copy +from typing import Any + +import pytest + +from omegaconf.basecontainer import BaseContainer + + +@pytest.fixture(scope="function") # type: ignore +def restore_resolvers() -> Any: + """ + A fixture to restore singletons state after this the function. + This is useful for functions that are making a one-off change to singlestons that should not effect + other tests + """ + state = copy.deepcopy(BaseContainer._resolvers) + yield + BaseContainer._resolvers = state diff --git a/tests/examples/__init__.py b/tests/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/examples/test_dataclass_example.py b/tests/examples/test_dataclass_example.py new file mode 100644 index 0000000000000000000000000000000000000000..7711600d3c991b29037a4e08ab14e8a043fea63e --- /dev/null +++ b/tests/examples/test_dataclass_example.py @@ -0,0 +1,381 @@ +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, List, Optional + +import pytest + +from omegaconf import ( + MISSING, + DictConfig, + MissingMandatoryValue, + OmegaConf, + ReadonlyConfigError, + ValidationError, +) + + +class Height(Enum): + SHORT = 0 + TALL = 1 + + +@dataclass +class SimpleTypes: + num: int = 10 + pi: float = 3.1415 + is_awesome: bool = True + height: Height = Height.SHORT + description: str = "text" + + +def test_simple_types_class() -> None: + # Instantiate from a class + conf = OmegaConf.structured(SimpleTypes) + assert conf.num == 10 + assert conf.pi == 3.1415 + assert conf.is_awesome is True + assert conf.height == Height.SHORT + assert conf.description == "text" + + +def test_static_typing() -> None: + conf: SimpleTypes = OmegaConf.structured(SimpleTypes) + assert conf.description == "text" # passes static type checking + with pytest.raises(AttributeError): + # This will fail both the static type checking and at runtime + # noinspection PyStatementEffect + conf.no_such_attribute # type: ignore + + +def test_simple_types_obj() -> None: + # Instantiate from an Object, any value can be overridden + # at construction + conf = OmegaConf.structured(SimpleTypes(num=20, pi=3)) + assert conf.num == 20 + assert conf.pi == 3 + # Everything not overridden at construction takes the default value + assert conf.is_awesome is True + assert conf.height == Height.SHORT + assert conf.description == "text" + + +def test_conversions() -> None: + conf: SimpleTypes = OmegaConf.structured(SimpleTypes) + + # OmegaConf can convert types at runtime + conf.num = 20 # ok, type matches + + # ok, the String "20" is converted to the int 20 + conf.num = "20" # type: ignore + + assert conf.num == 20 + with pytest.raises(ValidationError): + # ValidationError: "one" cannot be converted to an integer + conf.num = "one" # type: ignore + + # booleans can take many forms + for expected, values in { + True: ["on", "yes", "true", True, "1"], + False: ["off", "no", "false", False, "0"], + }.items(): + for b in values: + conf.is_awesome = b # type: ignore + assert conf.is_awesome == expected + + # Enums too + for expected1, values1 in { + Height.SHORT: [Height.SHORT, "Height.SHORT", "SHORT", 0], + Height.TALL: [Height.TALL, "Height.TALL", "TALL", 1], + }.items(): + for b in values1: + conf.height = b # type: ignore + assert conf.height == expected1 + + +@dataclass +class Modifiers: + # regular field + num: int = 10 + + # Fields can be optional + optional_num: Optional[int] = None + + # MISSING fields must be populated at runtime before access. accessing them while they + # are missing will result in a MissingMandatoryValue exception + another_num: int = MISSING + + +def test_modifiers() -> None: + conf: Modifiers = OmegaConf.structured(Modifiers) + # regular fields cannot take None + with pytest.raises(ValidationError): + conf.num = None # type: ignore + + # but Optional fields can + conf.optional_num = None + assert conf.optional_num is None + + # Accessing a missing field will trigger MissingMandatoryValue exception + with pytest.raises(MissingMandatoryValue): + # noinspection PyStatementEffect + conf.another_num + + # but you can access it once it's been assigned + conf.another_num = 42 + assert conf.another_num == 42 + + +@dataclass +class User: + # A simple user class with two missing fields + name: str = MISSING + height: Height = MISSING + + +# Group class contains two instances of User. +@dataclass +class Group: + name: str = MISSING + # data classes can be nested + admin: User = User # type: ignore + + # You can also specify different defaults for nested classes + manager: User = User(name="manager", height=Height.TALL) + + +def test_nesting() -> None: + conf = OmegaConf.structured(Group) + assert conf == { + "name": "???", + "admin": {"name": MISSING, "height": MISSING}, + "manager": {"name": "manager", "height": Height.TALL}, + } + + expected = """name: ??? +admin: + name: ??? + height: ??? +manager: + name: manager + height: TALL +""" + assert OmegaConf.to_yaml(conf) == expected + + # you can assign a different object of the same type + conf.admin = User(name="omry", height=Height.TALL) + with pytest.raises(ValidationError): + # but not incompatible types + conf.admin = 10 + + with pytest.raises(ValidationError): + # You can't assign a dict even if the field matches + conf.manager = {"name": "secret", "height": Height.TALL} + + +@dataclass +class Lists: + # List with Any as type can take any primitive type OmegaConf supports: + # int, float, bool, str and Enums as well as Any (which is the same as not having a specified type). + untyped_list: List[Any] = field(default_factory=lambda: [1, "foo", True]) + + # typed lists can hold int, bool, str, float or enums. + int_list: List[int] = field(default_factory=lambda: [10, 20, 30]) + + +def test_typed_list_runtime_validation() -> None: + conf = OmegaConf.structured(Lists) + + conf.untyped_list[0] = True # okay, list can hold any primitive type + + conf.int_list[0] = 999 # okay + assert conf.int_list[0] == 999 + + conf.int_list[0] = "1000" # also ok! + assert conf.int_list[0] == 1000 + + with pytest.raises(ValidationError): + conf.int_list[0] = "fail" + + +# Dicts +@dataclass +class Dicts: + # Key must be a string or Enum, value can be any primitive type OmegaConf supports: + # int, float, bool, str and Enums as well as Any (which is the same as not having a specified type). + untyped_dict: Dict[str, Any] = field( + default_factory=lambda: {"foo": True, "bar": 100} + ) + + # maps string to height Enum + str_to_height: Dict[str, Height] = field( + default_factory=lambda: {"Yoda": Height.SHORT, "3-CPO": Height.TALL} + ) + + +def test_typed_dict_runtime_validation() -> None: + conf = OmegaConf.structured(Dicts) + conf.untyped_dict["foo"] = "buzz" # okay, list can hold any primitive type + conf.str_to_height["Shorty"] = Height.SHORT # Okay + with pytest.raises(ValidationError): + # runtime failure, cannot convert True to Height + conf.str_to_height["Yoda"] = True + + +# Frozen +@dataclass(frozen=True) +class FrozenClass: + x: int = 10 + list: List[int] = field(default_factory=lambda: [1, 2, 3]) + + +def test_frozen() -> None: + # frozen classes are read only, attempts to modify them at runtime + # will result in a ReadonlyConfigError + conf = OmegaConf.structured(FrozenClass) + with pytest.raises(ReadonlyConfigError): + conf.x = 20 + + # Read-only flag is recursive + with pytest.raises(ReadonlyConfigError): + conf.list[0] = 20 + + +class Protocol(Enum): + HTTP = 0 + HTTPS = 1 + + +@dataclass +class Domain: + name: str = MISSING + path: str = MISSING + protocols: List[Protocol] = field(default_factory=lambda: [Protocol.HTTPS]) + + +@dataclass +class WebServer(DictConfig): + protocol_ports: Dict[Protocol, int] = field( + default_factory=lambda: {Protocol.HTTP: 80, Protocol.HTTPS: 443} + ) + # Dict of name to domain + domains: Dict[str, Domain] = field(default_factory=dict) + + # List of all domains + domains_list: List[Domain] = field(default_factory=list) + + +# Test that Enum can be used a dictionary key +def test_enum_key() -> None: + conf = OmegaConf.structured(WebServer) + # When an Enum is a dictionary key the name of the Enum is actually used + # as the key + assert conf.protocol_ports.HTTP == 80 + assert conf.protocol_ports["HTTP"] == 80 + assert conf.protocol_ports[Protocol.HTTP] == 80 + + +def test_dict_of_objects() -> None: + conf: WebServer = OmegaConf.structured(WebServer) + conf.domains["blog"] = Domain(name="blog.example.com", path="/www/blog.example.com") + with pytest.raises(ValidationError): + conf.domains.foo = 10 # type: ignore + + assert conf.domains["blog"].name == "blog.example.com" + assert conf.domains["blog"].path == "/www/blog.example.com" + assert conf == { + "protocol_ports": {Protocol.HTTP: 80, Protocol.HTTPS: 443}, + "domains": { + "blog": { + "name": "blog.example.com", + "path": "/www/blog.example.com", + "protocols": [Protocol.HTTPS], + } + }, + "domains_list": [], + } + + +def test_list_of_objects() -> None: + conf: WebServer = OmegaConf.structured(WebServer) + conf.domains_list.append( + Domain(name="blog.example.com", path="/www/blog.example.com") + ) + with pytest.raises(ValidationError): + conf.domains_list.append(10) # type: ignore + + assert conf.domains_list[0].name == "blog.example.com" + assert conf.domains_list[0].path == "/www/blog.example.com" + assert conf == { + "protocol_ports": {Protocol.HTTP: 80, Protocol.HTTPS: 443}, + "domains": {}, + "domains_list": [ + { + "name": "blog.example.com", + "path": "/www/blog.example.com", + "protocols": [Protocol.HTTPS], + } + ], + } + + +def test_merge() -> None: + @dataclass + class Config: + num: int = 10 + user: User = User(name=MISSING, height=MISSING) + domains: Dict[str, Domain] = field(default_factory=dict) + + yaml = """ +user: + name: Omry +domains: + blog_website: + name: blog + protocols: + - HTTPS +""" + + schema: Config = OmegaConf.structured(Config) + cfg = OmegaConf.create(yaml) + merged: Any = OmegaConf.merge(schema, cfg) + assert merged == { + "num": 10, + "user": {"name": "Omry", "height": "???"}, + "domains": { + "blog_website": { + "name": "blog", + "path": "???", + "protocols": [Protocol.HTTPS], + } + }, + } + assert OmegaConf.is_missing(merged.domains.blog_website, "path") + + +def test_merge_example() -> None: + @dataclass + class Server: + port: int = MISSING + + @dataclass + class Log: + file: str = MISSING + rotation: int = MISSING + + @dataclass + class MyConfig: + server: Server = Server() + log: Log = Log() + users: List[str] = field(default_factory=list) + numbers: List[int] = field(default_factory=list) + + schema = OmegaConf.structured(MyConfig) + with pytest.raises(ValidationError): + OmegaConf.merge(schema, OmegaConf.create({"log": {"rotation": "foo"}})) + + with pytest.raises(ValidationError): + cfg = schema.copy() + cfg.numbers.append("fo") + + with pytest.raises(ValidationError): + OmegaConf.merge(schema, OmegaConf.create({"numbers": ["foo"]})) diff --git a/tests/structured_conf/__init__.py b/tests/structured_conf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/structured_conf/data/__init__.py b/tests/structured_conf/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/structured_conf/data/attr_classes.py b/tests/structured_conf/data/attr_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..e81073fcf465ac2faf8008e862b2f729518460a9 --- /dev/null +++ b/tests/structured_conf/data/attr_classes.py @@ -0,0 +1,472 @@ +from typing import Any, Dict, List, Optional, Tuple, Union + +import attr +import pytest + +from omegaconf import II, MISSING, SI +from tests import Color + +# attr is a dependency of pytest which means it's always available when testing with pytest. +pytest.importorskip("attr") + + +class NotStructuredConfig: + name: str = "Bond" + age: int = 7 + + +@attr.s(auto_attribs=True) +class StructuredWithInvalidField: + bar: NotStructuredConfig = NotStructuredConfig() + + +@attr.s(auto_attribs=True) +class User: + name: str = MISSING + age: int = MISSING + + +@attr.s(auto_attribs=True) +class UserList: + list: List[User] = MISSING + + +@attr.s(auto_attribs=True) +class UserDict: + dict: Dict[str, User] = MISSING + + +@attr.s(auto_attribs=True) +class AnyTypeConfig: + with_default: Any = "Can get any type at runtime" + null_default: Any = None + # Access to this prior to assigning a value to it will result in + # a MissingMandatoryValue exception. + # Equivalent to "???" in YAML files + mandatory_missing: Any = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: Any = II("with_default") + + # specific types assigned + int_default: Any = 12 + float_default: Any = 10.0 + str_default: Any = "foobar" + bool_default: Any = True + enum_default: Any = Color.BLUE + + # test mixing with variable with a specific type annotation + typed_int_default: int = 10 + + +@attr.s(auto_attribs=True) +class BoolConfig: + + # with default value + with_default: bool = True + + # default is None + null_default: Optional[bool] = None + + # explicit no default + mandatory_missing: bool = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: bool = II("with_default") + + +@attr.s(auto_attribs=True) +class IntegersConfig: + + # with default value + with_default: int = 10 + + # default is None + null_default: Optional[int] = None + + # explicit no default + mandatory_missing: int = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: int = II("with_default") + + +@attr.s(auto_attribs=True) +class StringConfig: + + # with default value + with_default: str = "foo" + + # default is None + null_default: Optional[str] = None + + # explicit no default + mandatory_missing: str = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: str = II("with_default") + + +@attr.s(auto_attribs=True) +class FloatConfig: + + # with default value + with_default: float = 0.10 + + # default is None + null_default: Optional[float] = None + + # explicit no default + mandatory_missing: float = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: float = II("with_default") + + +@attr.s(auto_attribs=True) +class EnumConfig: + + # with default value + with_default: Color = Color.BLUE + + # default is None + null_default: Optional[Color] = None + + # explicit no default + mandatory_missing: Color = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: Color = II("with_default") + + +@attr.s(auto_attribs=True) +class ConfigWithList: + list1: List[int] = [1, 2, 3] + list2: Tuple[int, int, int] = (1, 2, 3) + missing: List[int] = MISSING + + +@attr.s(auto_attribs=True) +class ConfigWithDict: + dict1: Dict[str, Any] = {"foo": "bar"} + missing: Dict[str, Any] = MISSING + + +@attr.s(auto_attribs=True) +class ConfigWithDict2: + dict1: Dict[str, int] = {"foo": 2} + + +@attr.s(auto_attribs=True) +class Nested: + # with default value + with_default: int = 10 + + # default is None + null_default: Optional[int] = None + + # explicit no default + mandatory_missing: int = MISSING + + # Note that since relative interpolations are not yet supported, + # Nested configs and interpolations does not play too well together + interpolation: int = II("value_at_root") + + +@attr.s(auto_attribs=True) +class NestedSubclass(Nested): + additional: int = 20 + + +@attr.s(auto_attribs=True) +class NestedConfig: + default_value: Nested + + # with default value + user_provided_default: Nested = Nested(with_default=42) + + value_at_root: int = 1000 + + +@attr.s(auto_attribs=True) +class NestedWithAny: + var: Any = Nested() + + +@attr.s(auto_attribs=True) +class NoDefaultErrors: + no_default: Any + + +@attr.s(auto_attribs=True) +class Interpolation: + x: int = 100 + y: int = 200 + # The real type of y is int, cast the interpolation string + # to help static type checkers to see this truth + z1: int = II("x") + z2: str = SI("${x}_${y}") + + +@attr.s(auto_attribs=True) +class BoolOptional: + with_default: Optional[bool] = True + as_none: Optional[bool] = None + not_optional: bool = True + + +@attr.s(auto_attribs=True) +class IntegerOptional: + with_default: Optional[int] = 1 + as_none: Optional[int] = None + not_optional: int = 1 + + +@attr.s(auto_attribs=True) +class FloatOptional: + with_default: Optional[float] = 1.0 + as_none: Optional[float] = None + not_optional: float = 1 + + +@attr.s(auto_attribs=True) +class StringOptional: + with_default: Optional[str] = "foo" + as_none: Optional[str] = None + not_optional: str = "foo" + + +@attr.s(auto_attribs=True) +class ListOptional: + with_default: Optional[List[int]] = [1, 2, 3] + as_none: Optional[List[int]] = None + not_optional: List[int] = [1, 2, 3] + + +@attr.s(auto_attribs=True) +class TupleOptional: + with_default: Optional[Tuple[int, int, int]] = (1, 2, 3) + as_none: Optional[Tuple[int, int, int]] = None + not_optional: Tuple[int, int, int] = (1, 2, 3) + + +@attr.s(auto_attribs=True) +class EnumOptional: + with_default: Optional[Color] = Color.BLUE + as_none: Optional[Color] = None + not_optional: Color = Color.BLUE + + +@attr.s(auto_attribs=True) +class DictOptional: + with_default: Optional[Dict[str, int]] = {"a": 10} + as_none: Optional[Dict[str, int]] = None + not_optional: Dict[str, int] = {"a": 10} + + +@attr.s(auto_attribs=True) +class StructuredOptional: + with_default: Optional[Nested] = Nested() + as_none: Optional[Nested] = None + not_optional: Nested = Nested() + + +@attr.s(auto_attribs=True, frozen=True) +class FrozenClass: + user: User = User(name="Bart", age=10) + x: int = 10 + list: List[int] = [1, 2, 3] + + +@attr.s(auto_attribs=True) +class ContainsFrozen: + x: int = 10 + frozen: FrozenClass = FrozenClass() + + +@attr.s(auto_attribs=True) +class WithTypedList: + list: List[int] = [1, 2, 3] + + +@attr.s(auto_attribs=True) +class WithTypedDict: + dict: Dict[str, int] = {"foo": 10, "bar": 20} + + +@attr.s(auto_attribs=True) +class ErrorDictIntKey: + # invalid dict key, must be str + dict: Dict[int, str] = {10: "foo", 20: "bar"} + + +class RegularClass: + pass + + +@attr.s(auto_attribs=True) +class ErrorDictUnsupportedValue: + # invalid dict value type, not one of the supported types + dict: Dict[str, RegularClass] = {} + + +@attr.s(auto_attribs=True) +class ErrorListUnsupportedValue: + # invalid dict value type, not one of the supported types + dict: List[RegularClass] = [] + + +@attr.s(auto_attribs=True) +class ListExamples: + any: List[Any] = [1, "foo"] + ints: List[int] = [1, 2] + strings: List[str] = ["foo", "bar"] + booleans: List[bool] = [True, False] + colors: List[Color] = [Color.RED, Color.GREEN] + + +@attr.s(auto_attribs=True) +class TupleExamples: + any: Tuple[Any, Any] = (1, "foo") + ints: Tuple[int, int] = (1, 2) + strings: Tuple[str, str] = ("foo", "bar") + booleans: Tuple[bool, bool] = (True, False) + colors: Tuple[Color, Color] = (Color.RED, Color.GREEN) + + +@attr.s(auto_attribs=True) +class DictExamples: + any: Dict[str, Any] = {"a": 1, "b": "foo"} + ints: Dict[str, int] = {"a": 10, "b": 20} + strings: Dict[str, str] = {"a": "foo", "b": "bar"} + booleans: Dict[str, bool] = {"a": True, "b": False} + colors: Dict[str, Color] = { + "red": Color.RED, + "green": Color.GREEN, + "blue": Color.BLUE, + } + + +@attr.s(auto_attribs=True) +class DictWithEnumKeys: + enum_key: Dict[Color, str] = {Color.RED: "red", Color.GREEN: "green"} + + +@attr.s(auto_attribs=True) +class DictOfObjects: + users: Dict[str, User] = {"joe": User(name="Joe", age=18)} + + +@attr.s(auto_attribs=True) +class ListOfObjects: + users: List[User] = [User(name="Joe", age=18)] + + +class DictSubclass: + @attr.s(auto_attribs=True) + class Str2Str(Dict[str, str]): + pass + + @attr.s(auto_attribs=True) + class Color2Str(Dict[Color, str]): + pass + + @attr.s(auto_attribs=True) + class Color2Color(Dict[Color, Color]): + pass + + @attr.s(auto_attribs=True) + class Str2User(Dict[str, User]): + pass + + @attr.s(auto_attribs=True) + class Str2StrWithField(Dict[str, str]): + foo: str = "bar" + + @attr.s(auto_attribs=True) + class Str2IntWithStrField(Dict[str, int]): + foo: str = "bar" + + class Error: + @attr.s(auto_attribs=True) + class User2Str(Dict[User, str]): + pass + + +@attr.s(auto_attribs=True) +class Plugin: + name: str = MISSING + params: Any = MISSING + + +@attr.s(auto_attribs=True) +class ConcretePlugin(Plugin): + name: str = "foobar_plugin" + + @attr.s(auto_attribs=True) + class FoobarParams: + foo: int = 10 + + params: FoobarParams = FoobarParams() + + +@attr.s(auto_attribs=True) +class PluginWithAdditionalField(Plugin): + name: str = "foobar2_plugin" + additional: int = 10 + + +# Does not extend Plugin, cannot be assigned or merged +@attr.s(auto_attribs=True) +class FaultyPlugin: + name: str = "faulty_plugin" + + +@attr.s(auto_attribs=True) +class PluginHolder: + none: Optional[Plugin] = None + missing: Plugin = MISSING + plugin: Plugin = Plugin() + plugin2: Plugin = ConcretePlugin() + + +@attr.s(auto_attribs=True) +class LinkedList: + next: Optional["LinkedList"] = None + value: Any = MISSING + + +class MissingTest: + @attr.s(auto_attribs=True) + class Missing1: + head: LinkedList = MISSING + + @attr.s(auto_attribs=True) + class Missing2: + head: LinkedList = LinkedList(next=MISSING, value=1) + + +@attr.s(auto_attribs=True) +class NestedWithNone: + plugin: Optional[Plugin] = None + + +@attr.s(auto_attribs=True) +class UnionError: + x: Union[int, str] = 10 + + +@attr.s(auto_attribs=True) +class WithNativeMISSING: + num: int = attr.NOTHING # type: ignore + + +@attr.s(auto_attribs=True) +class MissingStructuredConfigField: + plugin: Plugin = MISSING + + +@attr.s(auto_attribs=True) +class ListClass: + list: List[int] = [] + tuple: Tuple[int, int] = (1, 2) diff --git a/tests/structured_conf/data/dataclasses.py b/tests/structured_conf/data/dataclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..f94bc472dd1115ad05c309d0ba4ab6db00e81006 --- /dev/null +++ b/tests/structured_conf/data/dataclasses.py @@ -0,0 +1,484 @@ +import dataclasses +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Tuple, Union + +import pytest + +from omegaconf import II, MISSING, SI +from tests import Color + +# skip test if dataclasses are not available +pytest.importorskip("dataclasses") + + +class NotStructuredConfig: + name: str = "Bond" + age: int = 7 + + +@dataclass +class StructuredWithInvalidField: + bar: NotStructuredConfig = NotStructuredConfig() + + +@dataclass +class User: + name: str = MISSING + age: int = MISSING + + +@dataclass +class UserList: + list: List[User] = MISSING + + +@dataclass +class UserDict: + dict: Dict[str, User] = MISSING + + +@dataclass +class AnyTypeConfig: + with_default: Any = "Can get any type at runtime" + null_default: Any = None + # Access to this prior to assigning a value to it will result in + # a MissingMandatoryValue exception. + # Equivalent to "???" in YAML files + mandatory_missing: Any = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: Any = II("with_default") + + # specific types assigned + int_default: Any = 12 + float_default: Any = 10.0 + str_default: Any = "foobar" + bool_default: Any = True + enum_default: Any = Color.BLUE + + # test mixing with variable with a specific type annotation + typed_int_default: int = 10 + + +@dataclass +class BoolConfig: + # with default value + with_default: bool = True + + # default is None + null_default: Optional[bool] = None + + # explicit no default + mandatory_missing: bool = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: bool = II("with_default") + + +@dataclass +class IntegersConfig: + # with default value + with_default: int = 10 + + # default is None + null_default: Optional[int] = None + + # explicit no default + mandatory_missing: int = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: int = II("with_default") + + +@dataclass +class StringConfig: + # with default value + with_default: str = "foo" + + # default is None + null_default: Optional[str] = None + + # explicit no default + mandatory_missing: str = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: str = II("with_default") + + +@dataclass +class FloatConfig: + # with default value + with_default: float = 0.10 + + # default is None + null_default: Optional[float] = None + + # explicit no default + mandatory_missing: float = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: float = II("with_default") + + +@dataclass +class EnumConfig: + # with default value + with_default: Color = Color.BLUE + + # default is None + null_default: Optional[Color] = None + + # explicit no default + mandatory_missing: Color = MISSING + + # interpolation, will inherit the type and value of `with_default' + interpolation: Color = II("with_default") + + +@dataclass +class ConfigWithList: + list1: List[int] = field(default_factory=lambda: [1, 2, 3]) + list2: Tuple[int, int, int] = field(default_factory=lambda: (1, 2, 3)) + missing: List[int] = MISSING + + +@dataclass +class ConfigWithDict: + dict1: Dict[str, Any] = field(default_factory=lambda: {"foo": "bar"}) + missing: Dict[str, Any] = MISSING + + +@dataclass +class ConfigWithDict2: + dict1: Dict[str, int] = field(default_factory=lambda: {"foo": 2}) + + +@dataclass +class Nested: + # with default value + with_default: int = 10 + + # default is None + null_default: Optional[int] = None + + # explicit no default + mandatory_missing: int = MISSING + + # Note that since relative interpolations are not yet supported, + # Nested configs and interpolations does not play too well together + interpolation: int = II("value_at_root") + + +@dataclass +class NestedSubclass(Nested): + additional: int = 20 + + +@dataclass +class NestedConfig: + default_value: Nested + + # with default value + user_provided_default: Nested = Nested(with_default=42) + + value_at_root: int = 1000 + + +@dataclass +class NestedWithAny: + var: Any = Nested() + + +@dataclass +class NoDefaultErrors: + no_default: Any + + +@dataclass +class Interpolation: + x: int = 100 + y: int = 200 + # The real type of y is int, cast the interpolation string + # to help static type checkers to see this truth + z1: int = II("x") + z2: str = SI("${x}_${y}") + + +@dataclass +class BoolOptional: + with_default: Optional[bool] = True + as_none: Optional[bool] = None + not_optional: bool = True + + +@dataclass +class IntegerOptional: + with_default: Optional[int] = 1 + as_none: Optional[int] = None + not_optional: int = 1 + + +@dataclass +class FloatOptional: + with_default: Optional[float] = 1.0 + as_none: Optional[float] = None + not_optional: float = 1 + + +@dataclass +class StringOptional: + with_default: Optional[str] = "foo" + as_none: Optional[str] = None + not_optional: str = "foo" + + +@dataclass +class ListOptional: + with_default: Optional[List[int]] = field(default_factory=lambda: [1, 2, 3]) + as_none: Optional[List[int]] = None + not_optional: List[int] = field(default_factory=lambda: [1, 2, 3]) + + +@dataclass +class TupleOptional: + with_default: Optional[Tuple[int, int, int]] = field( + default_factory=lambda: (1, 2, 3) + ) + as_none: Optional[Tuple[int, int, int]] = None + not_optional: Tuple[int, int, int] = field(default_factory=lambda: (1, 2, 3)) + + +@dataclass +class EnumOptional: + with_default: Optional[Color] = Color.BLUE + as_none: Optional[Color] = None + not_optional: Color = Color.BLUE + + +@dataclass +class DictOptional: + with_default: Optional[Dict[str, int]] = field(default_factory=lambda: {"a": 10}) + as_none: Optional[Dict[str, int]] = None + not_optional: Dict[str, int] = field(default_factory=lambda: {"a": 10}) + + +@dataclass +class StructuredOptional: + with_default: Optional[Nested] = Nested() + as_none: Optional[Nested] = None + not_optional: Nested = Nested() + + +@dataclass(frozen=True) +class FrozenClass: + user: User = User(name="Bart", age=10) + x: int = 10 + list: List[int] = field(default_factory=lambda: [1, 2, 3]) + + +@dataclass +class ContainsFrozen: + x: int = 10 + frozen: FrozenClass = FrozenClass() + + +@dataclass +class WithTypedList: + list: List[int] = field(default_factory=lambda: [1, 2, 3]) + + +@dataclass +class WithTypedDict: + dict: Dict[str, int] = field(default_factory=lambda: {"foo": 10, "bar": 20}) + + +@dataclass +class ErrorDictIntKey: + # invalid dict key, must be str + dict: Dict[int, str] = field(default_factory=lambda: {10: "foo", 20: "bar"}) + + +class RegularClass: + pass + + +@dataclass +class ErrorDictUnsupportedValue: + # invalid dict value type, not one of the supported types + dict: Dict[str, RegularClass] = field(default_factory=dict) + + +@dataclass +class ErrorListUnsupportedValue: + # invalid dict value type, not one of the supported types + dict: List[RegularClass] = field(default_factory=list) + + +@dataclass +class ErrorListUnsupportedStructuredConfig: + # Nesting of structured configs in Dict and List is not currently supported + list: List[User] = field(default_factory=list) + + +@dataclass +class ListExamples: + any: List[Any] = field(default_factory=lambda: [1, "foo"]) + ints: List[int] = field(default_factory=lambda: [1, 2]) + strings: List[str] = field(default_factory=lambda: ["foo", "bar"]) + booleans: List[bool] = field(default_factory=lambda: [True, False]) + colors: List[Color] = field(default_factory=lambda: [Color.RED, Color.GREEN]) + + +@dataclass +class TupleExamples: + any: Tuple[Any, Any] = field(default_factory=lambda: (1, "foo")) + ints: Tuple[int, int] = field(default_factory=lambda: (1, 2)) + strings: Tuple[str, str] = field(default_factory=lambda: ("foo", "bar")) + booleans: Tuple[bool, bool] = field(default_factory=lambda: (True, False)) + colors: Tuple[Color, Color] = field( + default_factory=lambda: (Color.RED, Color.GREEN) + ) + + +@dataclass +class DictExamples: + any: Dict[str, Any] = field(default_factory=lambda: {"a": 1, "b": "foo"}) + ints: Dict[str, int] = field(default_factory=lambda: {"a": 10, "b": 20}) + strings: Dict[str, str] = field(default_factory=lambda: {"a": "foo", "b": "bar"}) + booleans: Dict[str, bool] = field(default_factory=lambda: {"a": True, "b": False}) + colors: Dict[str, Color] = field( + default_factory=lambda: { + "red": Color.RED, + "green": Color.GREEN, + "blue": Color.BLUE, + } + ) + + +@dataclass +class DictWithEnumKeys: + enum_key: Dict[Color, str] = field( + default_factory=lambda: {Color.RED: "red", Color.GREEN: "green"} + ) + + +@dataclass +class DictOfObjects: + users: Dict[str, User] = field( + default_factory=lambda: {"joe": User(name="Joe", age=18)} + ) + + +@dataclass +class ListOfObjects: + users: List[User] = field(default_factory=lambda: [User(name="Joe", age=18)]) + + +class DictSubclass: + @dataclass + class Str2Str(Dict[str, str]): + pass + + @dataclass + class Color2Str(Dict[Color, str]): + pass + + @dataclass + class Color2Color(Dict[Color, Color]): + pass + + @dataclass + class Str2User(Dict[str, User]): + pass + + @dataclass + class Str2StrWithField(Dict[str, str]): + foo: str = "bar" + + @dataclass + class Str2IntWithStrField(Dict[str, int]): + foo: str = "bar" + + class Error: + @dataclass + class User2Str(Dict[User, str]): + pass + + +@dataclass +class Plugin: + name: str = MISSING + params: Any = MISSING + + +@dataclass +class ConcretePlugin(Plugin): + name: str = "foobar_plugin" + + @dataclass + class FoobarParams: + foo: int = 10 + + params: FoobarParams = FoobarParams() + + +@dataclass +class PluginWithAdditionalField(Plugin): + name: str = "foobar2_plugin" + additional: int = 10 + + +# Does not extend Plugin, cannot be assigned or merged +@dataclass +class FaultyPlugin: + name: str = "faulty_plugin" + + +@dataclass +class PluginHolder: + none: Optional[Plugin] = None + missing: Plugin = MISSING + plugin: Plugin = Plugin() + plugin2: Plugin = ConcretePlugin() + + +@dataclass +class LinkedList: + next: Optional["LinkedList"] = None + value: Any = MISSING + + +class MissingTest: + @dataclass + class Missing1: + head: LinkedList = MISSING + + @dataclass + class Missing2: + head: LinkedList = LinkedList(next=MISSING, value=1) + + +@dataclass +class NestedWithNone: + plugin: Optional[Plugin] = None + + +@dataclass +class UnionError: + x: Union[int, str] = 10 + + +@dataclass +class WithNativeMISSING: + num: int = dataclasses.MISSING # type: ignore + + +@dataclass +class MissingStructuredConfigField: + plugin: Plugin = MISSING + + +@dataclass +class ListClass: + list: List[int] = field(default_factory=lambda: []) + tuple: Tuple[int, int] = field(default_factory=lambda: (1, 2)) diff --git a/tests/structured_conf/test_structured_basic.py b/tests/structured_conf/test_structured_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..f92eb093b7485ced3a9c7dda30ffc4680b161e99 --- /dev/null +++ b/tests/structured_conf/test_structured_basic.py @@ -0,0 +1,201 @@ +import re +from importlib import import_module +from typing import Any, Optional + +import pytest + +from omegaconf import OmegaConf, ValidationError, _utils +from omegaconf.errors import ConfigKeyError + + +@pytest.mark.parametrize( + "class_type", + [ + "tests.structured_conf.data.dataclasses", + "tests.structured_conf.data.attr_classes", + ], +) +class TestStructured: + class TestBasic: + def test_error_on_non_structured_config_class(self, class_type: str) -> None: + module: Any = import_module(class_type) + with pytest.raises(ValidationError, match="structured config"): + OmegaConf.structured(module.NotStructuredConfig) + + def test_error_on_non_structured_nested_config_class( + self, class_type: str + ) -> None: + module: Any = import_module(class_type) + with pytest.raises( + ValidationError, + match=re.escape("Unexpected object type : NotStructuredConfig"), + ): + OmegaConf.structured(module.StructuredWithInvalidField) + + def test_assignment_of_subclass(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.create({"plugin": module.Plugin}) + cfg.plugin = OmegaConf.structured(module.ConcretePlugin) + assert OmegaConf.get_type(cfg.plugin) == module.ConcretePlugin + assert ( + OmegaConf.get_type(cfg.plugin.params) + == module.ConcretePlugin.FoobarParams + ) + + def test_assignment_of_non_subclass_1(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.create({"plugin": module.Plugin}) + with pytest.raises(ValidationError): + cfg.plugin = OmegaConf.structured(module.FaultyPlugin) + + def test_merge(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg1 = OmegaConf.create({"plugin": module.Plugin}) + cfg2 = OmegaConf.create({"plugin": module.ConcretePlugin}) + assert cfg2.plugin == module.ConcretePlugin + res: Any = OmegaConf.merge(cfg1, cfg2) + assert OmegaConf.get_type(res.plugin) == module.ConcretePlugin + assert ( + OmegaConf.get_type(res.plugin.params) + == module.ConcretePlugin.FoobarParams + ) + + def test_merge_of_non_subclass_1(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg1 = OmegaConf.create({"plugin": module.Plugin}) + cfg2 = OmegaConf.create({"plugin": module.FaultyPlugin}) + with pytest.raises(ValidationError): + OmegaConf.merge(cfg1, cfg2) + + def test_merge_error_new_attribute(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.ConcretePlugin) + cfg2 = OmegaConf.create({"params": {"bar": 10}}) + # raise if an invalid key is merged into a struct + with pytest.raises(ConfigKeyError): + OmegaConf.merge(cfg, cfg2) + + def test_merge_error_override_bad_type(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.ConcretePlugin) + + # raise if an invalid key is merged into a struct + with pytest.raises(ValidationError): + OmegaConf.merge(cfg, {"params": {"foo": "zonk"}}) + + def test_error_message(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.StructuredOptional) + msg = re.escape("child 'not_optional' is not Optional") + with pytest.raises(ValidationError, match=msg): + cfg.not_optional = None + + def test_none_assignment(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.create({"plugin": module.Plugin}) + # can assign None to params (type Any): + cfg.plugin.params = None + assert cfg.plugin.params is None + + cfg2 = OmegaConf.create({"plugin": module.ConcretePlugin}) + with pytest.raises(ValidationError): + cfg2.plugin.params = None + + @pytest.mark.parametrize("rhs", [1, "foo"]) + class TestFailedAssignmentOrMerges: + def test_assignment_of_non_subclass_2(self, class_type: str, rhs: Any) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.create({"plugin": module.Plugin}) + with pytest.raises(ValidationError): + cfg.plugin = rhs + + def test_merge_of_non_subclass_2(self, class_type: str, rhs: Any) -> None: + module: Any = import_module(class_type) + cfg1 = OmegaConf.create({"plugin": module.Plugin}) + cfg2 = OmegaConf.create({"plugin": rhs}) + with pytest.raises(ValidationError): + OmegaConf.merge(cfg1, cfg2) + + def test_get_type(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg1 = OmegaConf.create(module.LinkedList) + assert OmegaConf.get_type(cfg1) == module.LinkedList + assert _utils.get_ref_type(cfg1, "next") == Optional[module.LinkedList] + assert OmegaConf.get_type(cfg1, "next") is None + + assert cfg1.next is None + assert OmegaConf.is_missing(cfg1, "value") + + cfg2 = OmegaConf.create(module.MissingTest.Missing1) + assert OmegaConf.is_missing(cfg2, "head") + assert _utils.get_ref_type(cfg2, "head") == module.LinkedList + assert OmegaConf.get_type(cfg2, "head") is None + + class TestMissing: + def test_missing1(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.create(module.MissingTest.Missing1) + assert OmegaConf.is_missing(cfg, "head") + + assert OmegaConf.get_type(cfg, "head") is None + + with pytest.raises(ValidationError): + cfg.head = 10 + + def test_missing2(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.create(module.MissingTest.Missing2) + assert cfg == {"head": {"next": "???", "value": 1}} + assert OmegaConf.is_missing(cfg.head, "next") + + cfg.head.next = module.LinkedList(value=2) + assert cfg == {"head": {"next": {"next": None, "value": 2}, "value": 1}} + + def test_plugin_holder(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.create(module.PluginHolder) + + assert OmegaConf.is_optional(cfg, "none") + assert _utils.get_ref_type(cfg, "none") == Optional[module.Plugin] + assert OmegaConf.get_type(cfg, "none") is None + + assert not OmegaConf.is_optional(cfg, "missing") + assert _utils.get_ref_type(cfg, "missing") == module.Plugin + assert OmegaConf.get_type(cfg, "missing") is None + + assert not OmegaConf.is_optional(cfg, "plugin") + assert _utils.get_ref_type(cfg, "plugin") == module.Plugin + assert OmegaConf.get_type(cfg, "plugin") == module.Plugin + + cfg.plugin = module.ConcretePlugin() + assert not OmegaConf.is_optional(cfg, "plugin") + assert _utils.get_ref_type(cfg, "plugin") == module.Plugin + assert OmegaConf.get_type(cfg, "plugin") == module.ConcretePlugin + + assert not OmegaConf.is_optional(cfg, "plugin2") + assert _utils.get_ref_type(cfg, "plugin2") == module.Plugin + assert OmegaConf.get_type(cfg, "plugin2") == module.ConcretePlugin + + def test_plugin_merge(self, class_type: str) -> None: + module: Any = import_module(class_type) + plugin = OmegaConf.structured(module.Plugin) + concrete = OmegaConf.structured(module.ConcretePlugin) + ret = OmegaConf.merge(plugin, concrete) + assert ret == concrete + assert OmegaConf.get_type(ret) == module.ConcretePlugin + + more_fields = OmegaConf.structured(module.PluginWithAdditionalField) + ret = OmegaConf.merge(plugin, more_fields) + assert ret == more_fields + assert OmegaConf.get_type(ret) == module.PluginWithAdditionalField + + def test_native_missing(self, class_type: str) -> None: + module: Any = import_module(class_type) + with pytest.raises( + ValueError, + match=re.escape( + "Missing default value for WithNativeMISSING.num," + " to indicate default must be populated later use OmegaConf.MISSING" + ), + ): + OmegaConf.create(module.WithNativeMISSING) diff --git a/tests/structured_conf/test_structured_config.py b/tests/structured_conf/test_structured_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cd63984427dca8b29b29ed006e8325995fcb0b76 --- /dev/null +++ b/tests/structured_conf/test_structured_config.py @@ -0,0 +1,983 @@ +import re +from importlib import import_module +from typing import Any, Dict, Optional + +import pytest + +from omegaconf import ( + MISSING, + AnyNode, + DictConfig, + KeyValidationError, + MissingMandatoryValue, + OmegaConf, + ReadonlyConfigError, + ValidationError, + _utils, +) +from omegaconf.errors import ConfigKeyError +from tests import Color + + +class EnumConfigAssignments: + legal = [ + (Color.RED, Color.RED), + (Color.GREEN, Color.GREEN), + (Color.BLUE, Color.BLUE), + ("RED", Color.RED), + ("GREEN", Color.GREEN), + ("BLUE", Color.BLUE), + ("Color.RED", Color.RED), + ("Color.GREEN", Color.GREEN), + ("Color.BLUE", Color.BLUE), + (1, Color.RED), + (2, Color.GREEN), + (3, Color.BLUE), + ] + illegal = ["foo", True, False, 4, 1.0] + + +class IntegersConfigAssignments: + legal = [("10", 10), ("-10", -10), 100, 0, 1, 1] + illegal = ["foo", 1.0, float("inf"), float("nan"), Color.BLUE] + + +class StringConfigAssignments: + legal = ["10", "-10", "foo", "", (Color.BLUE, "Color.BLUE")] + illegal: Any = [] + + +class FloatConfigAssignments: + legal = [ + ("inf", float("inf")), + ("-inf", float("-inf")), + (10, 10.0), + (10.1, 10.1), + ("10.2", 10.2), + ("10e-3", 10e-3), + ] + illegal = ["foo", True, False, Color.BLUE] + + +class BoolConfigAssignments: + legal = [ + (True, True), + ("Y", True), + ("true", True), + ("Yes", True), + ("On", True), + ("1", True), + (100, True), + (False, False), + ("N", False), + ("false", False), + ("No", False), + ("Off", False), + ("0", False), + (0, False), + ] + illegal = [100.0, Color.BLUE] + + +class AnyTypeConfigAssignments: + legal = [True, False, 10, 10.0, "foobar", Color.BLUE] + + illegal: Any = [] + + +@pytest.mark.parametrize( + "class_type", + [ + "tests.structured_conf.data.dataclasses", + "tests.structured_conf.data.attr_classes", + ], +) +class TestConfigs: + def test_nested_config_is_none(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.NestedWithNone) + assert cfg == {"plugin": None} + assert OmegaConf.get_type(cfg, "plugin") is None + assert _utils.get_ref_type(cfg, "plugin") == Optional[module.Plugin] + + def test_nested_config(self, class_type: str) -> None: + module: Any = import_module(class_type) + + def validate(cfg: DictConfig) -> None: + assert cfg == { + "default_value": { + "with_default": 10, + "null_default": None, + "mandatory_missing": "???", + "interpolation": "${value_at_root}", + }, + "user_provided_default": { + "with_default": 42, + "null_default": None, + "mandatory_missing": "???", + "interpolation": "${value_at_root}", + }, + "value_at_root": 1000, + } + + with pytest.raises(ValidationError): + cfg.user_provided_default = 10 + + with pytest.raises(ValidationError): + cfg.default_value = 10 + + # assign subclass + cfg.default_value = module.NestedSubclass() + assert cfg.default_value == { + "additional": 20, + "with_default": 10, + "null_default": None, + "mandatory_missing": "???", + "interpolation": "${value_at_root}", + } + + # assign original ref type back + cfg.default_value = module.Nested() + assert cfg.default_value == module.Nested() + + with pytest.warns(UserWarning): + conf1 = OmegaConf.structured(module.NestedConfig) + validate(conf1) + conf1 = OmegaConf.structured(module.NestedConfig(default_value=module.Nested())) + validate(conf1) + + def test_value_without_a_default(self, class_type: str) -> None: + module: Any = import_module(class_type) + with pytest.raises( + ValueError, + match=re.escape( + "Missing default value for NoDefaultErrors.no_default," + " to indicate default must be populated later use OmegaConf.MISSING" + ), + ): + OmegaConf.structured(module.NoDefaultErrors) + + OmegaConf.structured(module.NoDefaultErrors(no_default=10)) == { + "no_default": 10 + } + + def test_union_errors(self, class_type: str) -> None: + module: Any = import_module(class_type) + with pytest.raises(ValueError): + OmegaConf.structured(module.UnionError) + + def test_config_with_list(self, class_type: str) -> None: + module: Any = import_module(class_type) + + def validate(cfg: DictConfig) -> None: + assert cfg == {"list1": [1, 2, 3], "list2": [1, 2, 3], "missing": MISSING} + with pytest.raises(ValidationError): + cfg.list1[1] = "foo" + + assert OmegaConf.is_missing(cfg, "missing") + + conf1 = OmegaConf.structured(module.ConfigWithList) + validate(conf1) + + conf1 = OmegaConf.structured(module.ConfigWithList()) + validate(conf1) + + def test_assignment_to_nested_structured_config(self, class_type: str) -> None: + module: Any = import_module(class_type) + with pytest.warns(UserWarning): + conf = OmegaConf.structured(module.NestedConfig) + with pytest.raises(ValidationError): + conf.default_value = 10 + + conf.default_value = module.Nested() + + def test_assignment_to_structured_inside_dict_config(self, class_type: str) -> None: + module: Any = import_module(class_type) + conf = OmegaConf.create({"val": module.Nested}) + with pytest.raises(ValidationError): + conf.val = 10 + + def test_config_with_dict(self, class_type: str) -> None: + module: Any = import_module(class_type) + + def validate(cfg: DictConfig) -> None: + assert cfg == {"dict1": {"foo": "bar"}, "missing": MISSING} + assert OmegaConf.is_missing(cfg, "missing") + + conf1 = OmegaConf.structured(module.ConfigWithDict) + validate(conf1) + conf1 = OmegaConf.structured(module.ConfigWithDict()) + validate(conf1) + + def test_structured_config_struct_behavior(self, class_type: str) -> None: + module: Any = import_module(class_type) + + def validate(cfg: DictConfig) -> None: + assert not OmegaConf.is_struct(cfg) + with pytest.raises(AttributeError): + # noinspection PyStatementEffect + cfg.foo + + cfg.dict1.foo = 10 + assert cfg.dict1.foo == 10 + + # setting struct False on a specific typed node opens it up even though it's + # still typed + OmegaConf.set_struct(cfg, False) + cfg.foo = 20 + assert cfg.foo == 20 + + conf = OmegaConf.structured(module.ConfigWithDict) + validate(conf) + conf = OmegaConf.structured(module.ConfigWithDict()) + validate(conf) + + @pytest.mark.parametrize( # type:ignore + "tested_type,assignment_data, init_dict", + [ + # Use class to build config + ("BoolConfig", BoolConfigAssignments, {}), + ("IntegersConfig", IntegersConfigAssignments, {}), + ("FloatConfig", FloatConfigAssignments, {}), + ("StringConfig", StringConfigAssignments, {}), + ("EnumConfig", EnumConfigAssignments, {}), + # Use instance to build config + ("BoolConfig", BoolConfigAssignments, {"with_default": False}), + ("IntegersConfig", IntegersConfigAssignments, {"with_default": 42}), + ("FloatConfig", FloatConfigAssignments, {"with_default": 42.0}), + ("StringConfig", StringConfigAssignments, {"with_default": "fooooooo"}), + ("EnumConfig", EnumConfigAssignments, {"with_default": Color.BLUE}), + ("AnyTypeConfig", AnyTypeConfigAssignments, {}), + ], + ) + def test_field_with_default_value( + self, + class_type: str, + tested_type: str, + init_dict: Dict[str, Any], + assignment_data: Any, + ) -> None: + module: Any = import_module(class_type) + input_class = getattr(module, tested_type) + + def validate(input_: Any, expected: Any) -> None: + conf = OmegaConf.structured(input_) + # Test access + assert conf.with_default == expected.with_default + assert conf.null_default is None + # Test that accessing a variable without a default value + # results in a MissingMandatoryValue exception + with pytest.raises(MissingMandatoryValue): + # noinspection PyStatementEffect + conf.mandatory_missing + + # Test interpolation preserves type and value + assert type(conf.with_default) == type(conf.interpolation) # noqa E721 + assert conf.with_default == conf.interpolation + + # Test that assignment of illegal values + for illegal_value in assignment_data.illegal: + with pytest.raises(ValidationError): + conf.with_default = illegal_value + + with pytest.raises(ValidationError): + conf.null_default = illegal_value + + with pytest.raises(ValidationError): + conf.mandatory_missing = illegal_value + + # Test assignment of legal values + for legal_value in assignment_data.legal: + expected_data = legal_value + if isinstance(legal_value, tuple): + expected_data = legal_value[1] + legal_value = legal_value[0] + conf.with_default = legal_value + conf.null_default = legal_value + conf.mandatory_missing = legal_value + + msg = "Error: {} : {}".format(input_class.__name__, legal_value) + assert conf.with_default == expected_data, msg + assert conf.null_default == expected_data, msg + assert conf.mandatory_missing == expected_data, msg + + validate(input_class, input_class()) + validate(input_class(**init_dict), input_class(**init_dict)) + + @pytest.mark.parametrize( # type: ignore + "input_init, expected_init", + [ + # attr class as class + (None, {}), + # attr class object with custom values + ({"int_default": 30}, {"int_default": 30}), + # dataclass as class + (None, {}), + # dataclass as object with custom values + ({"int_default": 30}, {"int_default": 30}), + ], + ) + def test_untyped( + self, class_type: str, input_init: Any, expected_init: Any + ) -> None: + module: Any = import_module(class_type) + input_ = module.AnyTypeConfig + expected = input_(**expected_init) + if input_init is not None: + input_ = input_(**input_init) + + conf = OmegaConf.structured(input_) + assert conf.null_default == expected.null_default + assert conf.int_default == expected.int_default + assert conf.float_default == expected.float_default + assert conf.str_default == expected.str_default + assert conf.bool_default == expected.bool_default + # yes, this is weird. + assert "mandatory_missing" in conf.keys() and "mandatory_missing" not in conf + + with pytest.raises(MissingMandatoryValue): + # noinspection PyStatementEffect + conf.mandatory_missing + + assert type(conf._get_node("null_default")) == AnyNode + assert type(conf._get_node("int_default")) == AnyNode + assert type(conf._get_node("float_default")) == AnyNode + assert type(conf._get_node("str_default")) == AnyNode + assert type(conf._get_node("bool_default")) == AnyNode + assert type(conf._get_node("mandatory_missing")) == AnyNode + + assert conf.int_default == expected.int_default + with pytest.raises(ValidationError): + conf.typed_int_default = "foo" + + values = [10, True, False, None, 1.0, -1.0, "10", float("inf")] + for val in values: + conf.null_default = val + conf.int_default = val + conf.float_default = val + conf.str_default = val + conf.bool_default = val + + assert conf.null_default == val + assert conf.int_default == val + assert conf.float_default == val + assert conf.str_default == val + assert conf.bool_default == val + + def test_interpolation(self, class_type: str) -> Any: + module: Any = import_module(class_type) + input_ = module.Interpolation() + conf = OmegaConf.structured(input_) + assert conf.x == input_.x + assert conf.z1 == conf.x + assert conf.z2 == f"{conf.x}_{conf.y}" + assert type(conf.x) == int + assert type(conf.y) == int + assert type(conf.z1) == int + assert type(conf.z2) == str + + @pytest.mark.parametrize( # type: ignore + "tested_type", + [ + "BoolOptional", + "IntegerOptional", + "FloatOptional", + "StringOptional", + "ListOptional", + "TupleOptional", + "EnumOptional", + "StructuredOptional", + "DictOptional", + ], + ) + def test_optional(self, class_type: str, tested_type: str) -> None: + module: Any = import_module(class_type) + input_ = getattr(module, tested_type) + obj = input_() + conf = OmegaConf.structured(input_) + + # verify non-optional fields are rejecting None + with pytest.raises(ValidationError): + conf.not_optional = None + + assert conf.as_none is None + assert conf.with_default == obj.with_default + # assign None to an optional field + conf.with_default = None + assert conf.with_default is None + + def test_typed_list(self, class_type: str) -> None: + module: Any = import_module(class_type) + input_ = module.WithTypedList + conf = OmegaConf.structured(input_) + with pytest.raises(ValidationError): + conf.list[0] = "fail" + + with pytest.raises(ValidationError): + conf.list.append("fail") + + with pytest.raises(ValidationError): + cfg2 = OmegaConf.create({"list": ["fail"]}) + OmegaConf.merge(conf, cfg2) + + def test_typed_dict(self, class_type: str) -> None: + module: Any = import_module(class_type) + input_ = module.WithTypedDict + conf = OmegaConf.structured(input_) + with pytest.raises(ValidationError): + conf.dict["foo"] = "fail" + + with pytest.raises(ValidationError): + OmegaConf.merge(conf, OmegaConf.create({"dict": {"foo": "fail"}})) + + def test_merged_type1(self, class_type: str) -> None: + # Test that the merged type is that of the last merged config + module: Any = import_module(class_type) + input_ = module.WithTypedDict + conf = OmegaConf.structured(input_) + res = OmegaConf.merge(OmegaConf.create(), conf) + assert OmegaConf.get_type(res) == input_ + + def test_merged_type2(self, class_type: str) -> None: + # Test that the merged type is that of the last merged config + module: Any = import_module(class_type) + input_ = module.WithTypedDict + conf = OmegaConf.structured(input_) + res = OmegaConf.merge(conf, {"dict": {"foo": 99}}) + assert OmegaConf.get_type(res) == input_ + + def test_merged_with_subclass(self, class_type: str) -> None: + # Test that the merged type is that of the last merged config + module: Any = import_module(class_type) + c1 = OmegaConf.structured(module.Plugin) + c2 = OmegaConf.structured(module.ConcretePlugin) + res = OmegaConf.merge(c1, c2) + assert OmegaConf.get_type(res) == module.ConcretePlugin + + def test_merge_missing_structured_config_is_missing(self, class_type: str) -> None: + # Test that the merged type is that of the last merged config + module: Any = import_module(class_type) + c1 = OmegaConf.structured(module.MissingStructuredConfigField) + assert OmegaConf.is_missing(c1, "plugin") + c2 = OmegaConf.merge(c1, module.MissingStructuredConfigField) + assert OmegaConf.is_missing(c2, "plugin") + + def test_merge_none_is_none(self, class_type: str) -> None: + # Test that the merged type is that of the last merged config + module: Any = import_module(class_type) + c1 = OmegaConf.structured(module.StructuredOptional) + assert c1.with_default == module.Nested() + c2 = OmegaConf.merge(c1, {"with_default": None}) + assert OmegaConf.is_none(c2, "with_default") + + def test_merge_with_subclass_into_missing(self, class_type: str) -> None: + module: Any = import_module(class_type) + base = OmegaConf.structured(module.PluginHolder) + assert _utils.get_ref_type(base, "missing") == module.Plugin + assert OmegaConf.get_type(base, "missing") is None + res = OmegaConf.merge(base, {"missing": module.Plugin}) + assert OmegaConf.get_type(res) == module.PluginHolder + assert _utils.get_ref_type(base, "missing") == module.Plugin + assert OmegaConf.get_type(res, "missing") == module.Plugin + + def test_merged_with_nons_subclass(self, class_type: str) -> None: + module: Any = import_module(class_type) + c1 = OmegaConf.structured(module.Plugin) + c2 = OmegaConf.structured(module.FaultyPlugin) + with pytest.raises(ValidationError): + OmegaConf.merge(c1, c2) + + def test_merge_into_Dict(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.DictExamples) + res = OmegaConf.merge(cfg, {"strings": {"x": "abc"}}) + assert res.strings == {"a": "foo", "b": "bar", "x": "abc"} + + def test_merge_user_list_with_wrong_key(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.UserList) + with pytest.raises(ConfigKeyError): + OmegaConf.merge(cfg, {"list": [{"foo": "var"}]}) + + def test_merge_list_with_correct_type(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.UserList) + user = module.User(name="John", age=21) + res = OmegaConf.merge(cfg, {"list": [user]}) + assert res.list == [user] + + def test_merge_dict_with_wrong_type(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.UserDict) + with pytest.raises(ValidationError): + OmegaConf.merge(cfg, {"dict": {"foo": "var"}}) + + def test_merge_dict_with_correct_type(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.UserDict) + user = module.User(name="John", age=21) + res = OmegaConf.merge(cfg, {"dict": {"foo": user}}) + assert res.dict == {"foo": user} + + def test_typed_dict_key_error(self, class_type: str) -> None: + module: Any = import_module(class_type) + input_ = module.ErrorDictIntKey + with pytest.raises(KeyValidationError): + OmegaConf.structured(input_) + + def test_typed_dict_value_error(self, class_type: str) -> None: + module: Any = import_module(class_type) + input_ = module.ErrorDictUnsupportedValue + with pytest.raises(ValidationError): + OmegaConf.structured(input_) + + def test_typed_list_value_error(self, class_type: str) -> None: + module: Any = import_module(class_type) + input_ = module.ErrorListUnsupportedValue + with pytest.raises(ValidationError): + OmegaConf.structured(input_) + + @pytest.mark.parametrize( # type: ignore + "example", ["ListExamples", "TupleExamples"] + ) + def test_list_examples(self, class_type: str, example: str) -> None: + module: Any = import_module(class_type) + input_ = getattr(module, example) + conf = OmegaConf.structured(input_) + + def test_any(name: str) -> None: + conf[name].append(True) + conf[name].extend([Color.RED, 3.1415]) + conf[name][2] = False + assert conf[name] == [1, "foo", False, Color.RED, 3.1415] + + # any and untyped + test_any("any") + + # test ints + with pytest.raises(ValidationError): + conf.ints[0] = "foo" + conf.ints.append(10) + assert conf.ints == [1, 2, 10] + + # test strings + conf.strings.append(Color.BLUE) + assert conf.strings == ["foo", "bar", "Color.BLUE"] + + # test booleans + with pytest.raises(ValidationError): + conf.booleans[0] = "foo" + conf.booleans.append(True) + conf.booleans.append("off") + conf.booleans.append(1) + assert conf.booleans == [True, False, True, False, True] + + # test colors + with pytest.raises(ValidationError): + conf.colors[0] = "foo" + conf.colors.append(Color.BLUE) + conf.colors.append("RED") + conf.colors.append("Color.GREEN") + conf.colors.append(3) + assert conf.colors == [ + Color.RED, + Color.GREEN, + Color.BLUE, + Color.RED, + Color.GREEN, + Color.BLUE, + ] + + def test_dict_examples(self, class_type: str) -> None: + module: Any = import_module(class_type) + conf = OmegaConf.structured(module.DictExamples) + + def test_any(name: str) -> None: + conf[name].c = True + conf[name].d = Color.RED + conf[name].e = 3.1415 + assert conf[name] == { + "a": 1, + "b": "foo", + "c": True, + "d": Color.RED, + "e": 3.1415, + } + + # any and untyped + test_any("any") + + # test ints + with pytest.raises(ValidationError): + conf.ints.a = "foo" + conf.ints.c = 10 + assert conf.ints == {"a": 10, "b": 20, "c": 10} + + # test strings + conf.strings.c = Color.BLUE + assert conf.strings == {"a": "foo", "b": "bar", "c": "Color.BLUE"} + + # tests booleans + with pytest.raises(ValidationError): + conf.booleans.a = "foo" + conf.booleans.c = True + conf.booleans.d = "off" + conf.booleans.e = 1 + assert conf.booleans == { + "a": True, + "b": False, + "c": True, + "d": False, + "e": True, + } + + # test colors + with pytest.raises(ValidationError): + conf.colors.foo = "foo" + conf.colors.c = Color.BLUE + conf.colors.d = "RED" + conf.colors.e = "Color.GREEN" + conf.colors.f = 3 + assert conf.colors == { + "red": Color.RED, + "green": Color.GREEN, + "blue": Color.BLUE, + "c": Color.BLUE, + "d": Color.RED, + "e": Color.GREEN, + "f": Color.BLUE, + } + + def test_enum_key(self, class_type: str) -> None: + module: Any = import_module(class_type) + conf = OmegaConf.structured(module.DictWithEnumKeys) + + # When an Enum is a dictionary key the name of the Enum is actually used + # as the key + assert conf.enum_key.RED == "red" + assert conf.enum_key["GREEN"] == "green" + assert conf.enum_key[Color.GREEN] == "green" + + conf.enum_key["BLUE"] = "Blue too" + assert conf.enum_key[Color.BLUE] == "Blue too" + with pytest.raises(KeyValidationError): + conf.enum_key["error"] = "error" + + def test_dict_of_objects(self, class_type: str) -> None: + module: Any = import_module(class_type) + conf = OmegaConf.structured(module.DictOfObjects) + assert conf.users.joe.age == 18 + assert conf.users.joe.name == "Joe" + + conf.users.bond = module.User(name="James Bond", age=7) + assert conf.users.bond.name == "James Bond" + assert conf.users.bond.age == 7 + + with pytest.raises(ValidationError): + conf.users.fail = "fail" + + def test_list_of_objects(self, class_type: str) -> None: + module: Any = import_module(class_type) + conf = OmegaConf.structured(module.ListOfObjects) + assert conf.users[0].age == 18 + assert conf.users[0].name == "Joe" + + conf.users.append(module.User(name="James Bond", age=7)) + assert conf.users[1].name == "James Bond" + assert conf.users[1].age == 7 + + with pytest.raises(ValidationError): + conf.users.append("fail") + + def test_promote_api(self, class_type: str) -> None: + module: Any = import_module(class_type) + conf = OmegaConf.create(module.AnyTypeConfig) + conf._promote(None) + assert conf == OmegaConf.create(module.AnyTypeConfig) + with pytest.raises(ValueError): + conf._promote(42) + assert conf == OmegaConf.create(module.AnyTypeConfig) + + def test_promote_to_class(self, class_type: str) -> None: + module: Any = import_module(class_type) + + conf = OmegaConf.create(module.AnyTypeConfig) + assert OmegaConf.get_type(conf) == module.AnyTypeConfig + + conf._promote(module.BoolConfig) + + assert OmegaConf.get_type(conf) == module.BoolConfig + assert conf.with_default is True + assert conf.null_default is None + assert OmegaConf.is_missing(conf, "mandatory_missing") + + def test_promote_to_object(self, class_type: str) -> None: + module: Any = import_module(class_type) + + conf = OmegaConf.create(module.AnyTypeConfig) + assert OmegaConf.get_type(conf) == module.AnyTypeConfig + + conf._promote(module.BoolConfig(with_default=False)) + assert OmegaConf.get_type(conf) == module.BoolConfig + assert conf.with_default is False + + def test_set_key_with_with_dataclass(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.create({"foo": [1, 2]}) + cfg.foo = module.ListClass() + + def test_set_list_correct_type(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.ListClass) + value = [1, 2, 3] + cfg.list = value + cfg.tuple = value + assert cfg.list == value + assert cfg.tuple == value + + @pytest.mark.parametrize("value", [1, True, "str", 3.1415, ["foo", True, 1.2]]) # type: ignore + def test_assign_wrong_type_to_list(self, class_type: str, value: Any) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.ListClass) + with pytest.raises(ValidationError): + cfg.list = value + with pytest.raises(ValidationError): + cfg.tuple = value + + @pytest.mark.parametrize( # type: ignore + "value", [1, True, "str", 3.1415, ["foo", True, 1.2], {"foo": True}] + ) + def test_assign_wrong_type_to_dict(self, class_type: str, value: Any) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.ConfigWithDict2) + with pytest.raises(ValidationError): + cfg.dict1 = value + + +def validate_frozen_impl(conf: DictConfig) -> None: + with pytest.raises(ReadonlyConfigError): + conf.x = 20 + + with pytest.raises(ReadonlyConfigError): + conf.list[0] = 10 + + with pytest.raises(ReadonlyConfigError): + conf.user.age = 20 + + # merge into is rejected because it mutates a readonly object + with pytest.raises(ReadonlyConfigError): + conf.merge_with({"user": {"name": "iceman"}}) + + # Normal merge is allowed. + ret = OmegaConf.merge(conf, {"user": {"name": "iceman"}}) + assert ret == {"user": {"name": "iceman", "age": 10}, "x": 10, "list": [1, 2, 3]} + with pytest.raises(ReadonlyConfigError): + ret.user.age = 20 + + +def test_attr_frozen() -> None: + from tests.structured_conf.data.attr_classes import FrozenClass + + validate_frozen_impl(OmegaConf.structured(FrozenClass)) + validate_frozen_impl(OmegaConf.structured(FrozenClass())) + + +def test_dataclass_frozen() -> None: + from tests.structured_conf.data.dataclasses import FrozenClass + + validate_frozen_impl(OmegaConf.structured(FrozenClass)) + validate_frozen_impl(OmegaConf.structured(FrozenClass())) + + +@pytest.mark.parametrize( + "class_type", + [ + "tests.structured_conf.data.dataclasses", + "tests.structured_conf.data.attr_classes", + ], +) +class TestDictSubclass: + def test_str2str(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.DictSubclass.Str2Str()) + cfg.hello = "world" + assert cfg.hello == "world" + + with pytest.raises(KeyValidationError): + cfg[Color.RED] = "fail" + + def test_str2str_as_sub_node(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.create({"foo": module.DictSubclass.Str2Str}) + assert OmegaConf.get_type(cfg.foo) == module.DictSubclass.Str2Str + assert _utils.get_ref_type(cfg.foo) == Optional[module.DictSubclass.Str2Str] + + cfg.foo.hello = "world" + assert cfg.foo.hello == "world" + + with pytest.raises(KeyValidationError): + cfg.foo[Color.RED] = "fail" + + def test_color2str(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.DictSubclass.Color2Str()) + cfg[Color.RED] = "red" + + with pytest.raises(KeyValidationError): + cfg.greeen = "nope" + + def test_color2color(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.DictSubclass.Color2Color()) + + # add key + cfg[Color.RED] = "GREEN" + assert cfg[Color.RED] == Color.GREEN + + # replace key + cfg[Color.RED] = "RED" + assert cfg[Color.RED] == Color.RED + + cfg[Color.BLUE] = Color.BLUE + assert cfg[Color.BLUE] == Color.BLUE + + cfg.RED = Color.RED + assert cfg.RED == Color.RED + + with pytest.raises(ValidationError): + # bad value + cfg[Color.GREEN] = 10 + + with pytest.raises(KeyValidationError): + # bad key + cfg.greeen = "nope" + + def test_str2user(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.DictSubclass.Str2User()) + + cfg.bond = module.User(name="James Bond", age=7) + assert cfg.bond.name == "James Bond" + assert cfg.bond.age == 7 + + with pytest.raises(ValidationError): + # bad value + cfg.hello = "world" + + with pytest.raises(KeyValidationError): + # bad key + cfg[Color.BLUE] = "nope" + + def test_str2str_with_field(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.DictSubclass.Str2StrWithField()) + assert cfg.foo == "bar" + cfg.hello = "world" + assert cfg.hello == "world" + + with pytest.raises(KeyValidationError): + cfg[Color.RED] = "fail" + + def test_str2int_with_field_of_different_type(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.DictSubclass.Str2IntWithStrField()) + assert cfg.foo == "bar" + + cfg.one = 1 + assert cfg.one == 1 + + with pytest.raises(ValidationError): + # bad + cfg.hello = "world" + + class TestErrors: + def test_usr2str(self, class_type: str) -> None: + module: Any = import_module(class_type) + with pytest.raises(KeyValidationError): + OmegaConf.structured(module.DictSubclass.Error.User2Str()) + + def test_construct_from_another_retain_node_types(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg1 = OmegaConf.create(module.User(name="James Bond", age=7)) + with pytest.raises(ValidationError): + cfg1.age = "not a number" + + cfg2 = OmegaConf.create(cfg1) + with pytest.raises(ValidationError): + cfg2.age = "not a number" + + def test_nested_with_any_var_type(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.NestedWithAny) + assert cfg == { + "var": { + "with_default": 10, + "null_default": None, + "mandatory_missing": "???", + "interpolation": "${value_at_root}", + } + } + + def test_noop_merge_into_frozen(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.ContainsFrozen) + ret = OmegaConf.merge(cfg, {"x": 20, "frozen": {}}) + assert ret == { + "x": 20, + "frozen": {"user": {"name": "Bart", "age": 10}, "x": 10, "list": [1, 2, 3]}, + } + + def test_merge_into_none_list(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.ListOptional) + assert OmegaConf.merge(cfg, {"as_none": [4, 5, 6]}) == { + "with_default": [1, 2, 3], + "as_none": [4, 5, 6], + "not_optional": [1, 2, 3], + } + + assert OmegaConf.merge(cfg, cfg) == cfg + + def test_merge_into_none_dict(self, class_type: str) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.DictOptional) + assert OmegaConf.merge(cfg, {"as_none": {"x": 100}}) == { + "with_default": {"a": 10}, + "as_none": {"x": 100}, + "not_optional": {"a": 10}, + } + + assert OmegaConf.merge(cfg, cfg) == cfg + + @pytest.mark.parametrize( # type: ignore + "update_value,expected", + [ + pytest.param([], {"list": []}, id="empty"), + pytest.param( + [{"name": "Bond"}], + {"list": [{"name": "Bond", "age": "???"}]}, + id="partial", + ), + pytest.param( + [{"name": "Bond", "age": 7}], + {"list": [{"name": "Bond", "age": 7}]}, + id="complete", + ), + pytest.param( + [{"age": "double o seven"}], + pytest.raises(ValidationError), + id="complete", + ), + ], + ) + def test_update_userlist( + self, class_type: str, update_value: Any, expected: Any + ) -> None: + module: Any = import_module(class_type) + cfg = OmegaConf.structured(module.UserList) + if isinstance(expected, dict): + OmegaConf.update(cfg, "list", update_value, merge=True) + assert cfg == expected + else: + with pytest.raises(ValidationError): + OmegaConf.update(cfg, "list", update_value, merge=True) diff --git a/tests/test_base_config.py b/tests/test_base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cb4bf09b247343db0285a675e1896ab2b73328ca --- /dev/null +++ b/tests/test_base_config.py @@ -0,0 +1,586 @@ +import copy +from enum import Enum +from typing import Any, Dict, List, Union + +import pytest +from pytest import raises + +from omegaconf import ( + Container, + DictConfig, + IntegerNode, + ListConfig, + OmegaConf, + ReadonlyConfigError, + StringNode, + ValidationError, + flag_override, + open_dict, + read_write, +) +from omegaconf.errors import ConfigKeyError + +from . import Color, StructuredWithMissing, does_not_raise + + +@pytest.mark.parametrize( # type: ignore + "input_, key, value, expected", + [ + # dict + (dict(), "foo", 10, dict(foo=10)), + (dict(), "foo", IntegerNode(10), dict(foo=10)), + (dict(foo=5), "foo", IntegerNode(10), dict(foo=10)), + # changing type of a node + (dict(foo=StringNode("str")), "foo", IntegerNode(10), dict(foo=10)), + # list + ([0], 0, 10, [10]), + (["a", "b", "c"], 1, 10, ["a", 10, "c"]), + ([1, 2], 1, IntegerNode(10), [1, 10]), + ([1, IntegerNode(2)], 1, IntegerNode(10), [1, 10]), + # changing type of a node + ([1, StringNode("str")], 1, IntegerNode(10), [1, 10]), + ], +) +def test_set_value( + input_: Any, key: Union[str, int], value: Any, expected: Any +) -> None: + c = OmegaConf.create(input_) + c[key] = value + assert c == expected + + +@pytest.mark.parametrize( # type: ignore + "input_, key, value", + [ + # dict + ({"foo": IntegerNode(10)}, "foo", "str"), + # list + ([1, IntegerNode(10)], 1, "str"), + ], +) +def test_set_value_validation_fail(input_: Any, key: Any, value: Any) -> None: + c = OmegaConf.create(input_) + with raises(ValidationError): + c[key] = value + + +@pytest.mark.parametrize( # type: ignore + "input_, key, value", + [ + # dict + (dict(foo=IntegerNode(10)), "foo", StringNode("str")), + # list + ([1, IntegerNode(10)], 1, StringNode("str")), + ], +) +def test_replace_value_node_type_with_another( + input_: Any, key: Any, value: Any +) -> None: + c = OmegaConf.create(input_) + c[key] = value + assert c[key] == value + assert c[key] == value._value() + + +@pytest.mark.parametrize( # type: ignore + "input_", + [ + pytest.param([1, 2, 3], id="list"), + pytest.param([1, 2, {"a": 3}], id="dict_in_list"), + pytest.param([1, 2, [10, 20]], id="list_in_list"), + pytest.param({"b": {"b": 10}}, id="dict_in_dict"), + pytest.param({"b": [False, 1, "2", 3.0, Color.RED]}, id="list_in_dict"), + pytest.param({"b": DictConfig(content=None)}, id="none_dictconfig"), + pytest.param({"b": ListConfig(content=None)}, id="none_listconfig"), + pytest.param({"b": DictConfig(content="???")}, id="missing_dictconfig"), + pytest.param({"b": ListConfig(content="???")}, id="missing_listconfig"), + ], +) +def test_to_container_returns_primitives(input_: Any) -> None: + def assert_container_with_primitives(item: Any) -> None: + if isinstance(item, list): + for v in item: + assert_container_with_primitives(v) + elif isinstance(item, dict): + for _k, v in item.items(): + assert_container_with_primitives(v) + else: + assert isinstance(item, (int, float, str, bool, type(None), Enum)) + + c = OmegaConf.create(input_) + res = OmegaConf.to_container(c, resolve=True) + assert_container_with_primitives(res) + + +@pytest.mark.parametrize( # type: ignore + "src, expected, expected_with_resolve", + [ + pytest.param([], None, None, id="empty_list"), + pytest.param([1, 2, 3], None, None, id="list"), + pytest.param([None], None, None, id="list_with_none"), + pytest.param([1, "${0}", 3], None, [1, 1, 3], id="list_with_inter"), + pytest.param({}, None, None, id="empty_dict"), + pytest.param({"foo": "bar"}, None, None, id="dict"), + pytest.param( + {"foo": "${bar}", "bar": "zonk"}, + None, + {"foo": "zonk", "bar": "zonk"}, + id="dict_with_inter", + ), + pytest.param({"foo": None}, None, None, id="dict_with_none"), + pytest.param({"foo": "???"}, None, None, id="dict_missing_value"), + pytest.param({"foo": None}, None, None, id="dict_none_value"), + # containers + pytest.param( + {"foo": DictConfig(is_optional=True, content=None)}, + {"foo": None}, + None, + id="dict_none_dictconfig", + ), + pytest.param( + {"foo": DictConfig(content="???")}, + {"foo": "???"}, + None, + id="dict_missing_dictconfig", + ), + pytest.param( + {"foo": DictConfig(content="${bar}"), "bar": 10}, + {"foo": "${bar}", "bar": 10}, + {"foo": 10, "bar": 10}, + id="dict_inter_dictconfig", + ), + pytest.param( + {"foo": ListConfig(content="???")}, + {"foo": "???"}, + None, + id="dict_missing_listconfig", + ), + pytest.param( + {"foo": ListConfig(is_optional=True, content=None)}, + {"foo": None}, + None, + id="dict_none_listconfig", + ), + pytest.param( + {"foo": ListConfig(content="${bar}"), "bar": 10}, + {"foo": "${bar}", "bar": 10}, + {"foo": 10, "bar": 10}, + id="dict_inter_listconfig", + ), + ], +) +def test_to_container(src: Any, expected: Any, expected_with_resolve: Any) -> None: + if expected is None: + expected = src + if expected_with_resolve is None: + expected_with_resolve = expected + cfg = OmegaConf.create(src) + container = OmegaConf.to_container(cfg) + assert container == expected + container = OmegaConf.to_container(cfg, resolve=True) + assert container == expected_with_resolve + + +def test_string_interpolation_with_readonly_parent() -> None: + cfg = OmegaConf.create({"a": 10, "b": {"c": "hello_${a}"}}) + OmegaConf.set_readonly(cfg, True) + assert OmegaConf.to_container(cfg, resolve=True) == { + "a": 10, + "b": {"c": "hello_10"}, + } + + +@pytest.mark.parametrize( # type: ignore + "src,expected", + [ + pytest.param(DictConfig(content="${bar}"), "${bar}", id="DictConfig"), + pytest.param( + OmegaConf.create({"foo": DictConfig(content="${bar}")}), + {"foo": "${bar}"}, + id="nested_DictConfig", + ), + ], +) +def test_to_container_missing_inter_no_resolve(src: Any, expected: Any) -> None: + res = OmegaConf.to_container(src, resolve=False) + assert res == expected + + +@pytest.mark.parametrize( # type: ignore + "input_, is_empty", [([], True), ({}, True), ([1, 2], False), (dict(a=10), False)] +) +def test_empty(input_: Any, is_empty: bool) -> None: + c = OmegaConf.create(input_) + assert c.is_empty() == is_empty + + +@pytest.mark.parametrize("func", [str, repr]) # type: ignore +@pytest.mark.parametrize( # type: ignore + "input_, expected", + [ + pytest.param([], "[]", id="list"), + pytest.param({}, "{}", id="dict"), + pytest.param([1, 2, 3], "[1, 2, 3]", id="list"), + pytest.param([1, 2, {"a": 3}], "[1, 2, {'a': 3}]", id="dict_in_list"), + pytest.param([1, 2, [10, 20]], "[1, 2, [10, 20]]", id="list_in_list"), + pytest.param({"b": {"b": 10}}, "{'b': {'b': 10}}", id="dict"), + pytest.param({"b": [1, 2, 3]}, "{'b': [1, 2, 3]}", id="list_in_dict"), + pytest.param( + StructuredWithMissing, + ( + "{'num': '???', 'opt_num': '???', 'dict': '???', 'opt_dict': '???', 'list': " + "'???', 'opt_list': '???', 'user': '???', 'opt_user': '???', 'inter_num': " + "'${num}', 'inter_user': '${user}', 'inter_opt_user': '${opt_user}'}" + ), + id="structured_with_missing", + ), + ], +) +def test_str(func: Any, input_: Any, expected: str) -> None: + c = OmegaConf.create(input_) + string = func(c) + assert string == expected + + +@pytest.mark.parametrize("flag", ["readonly", "struct"]) # type: ignore +def test_flag_dict(flag: str) -> None: + c = OmegaConf.create() + assert c._get_flag(flag) is None + c._set_flag(flag, True) + assert c._get_flag(flag) is True + c._set_flag(flag, False) + assert not c._get_flag(flag) is True + c._set_flag(flag, None) + assert c._get_flag(flag) is None + + +@pytest.mark.parametrize("flag", ["readonly", "struct"]) # type: ignore +def test_freeze_nested_dict(flag: str) -> None: + c = OmegaConf.create(dict(a=dict(b=2))) + assert not c._get_flag(flag) + assert not c.a._get_flag(flag) + c._set_flag(flag, True) + assert c._get_flag(flag) + assert c.a._get_flag(flag) + c._set_flag(flag, False) + assert not c._get_flag(flag) + assert not c.a._get_flag(flag) + c._set_flag(flag, None) + assert not c._get_flag(flag) + assert not c.a._get_flag(flag) + c.a._set_flag(flag, True) + assert not c._get_flag(flag) + assert c.a._get_flag(flag) + + +@pytest.mark.parametrize( + "src", [[], [1, 2, 3], dict(), dict(a=10), StructuredWithMissing] +) +class TestDeepCopy: + def test_deepcopy(self, src: Any) -> None: + c1 = OmegaConf.create(src) + c2 = copy.deepcopy(c1) + assert c1 == c2 + + assert c1.__dict__.keys() == c2.__dict__.keys() + for k in c1.__dict__.keys(): + assert c1.__dict__[k] == c2.__dict__[k] + + assert id(c1) != id(c2) + + if isinstance(c2, ListConfig): + c2.append(1000) + elif isinstance(c2, DictConfig): + c2.num = 42 + assert c1 != c2 + + def test_deepcopy_readonly(self, src: Any) -> None: + c1 = OmegaConf.create(src) + OmegaConf.set_readonly(c1, True) + c2 = copy.deepcopy(c1) + assert c1 == c2 + if isinstance(c2, ListConfig): + with raises(ReadonlyConfigError): + c2.append(1000) + elif isinstance(c2, DictConfig): + with raises(ReadonlyConfigError): + c2.num = 42 + assert c1 == c2 + + def test_deepcopy_struct(self, src: Any) -> None: + c1 = OmegaConf.create(src) + OmegaConf.set_struct(c1, True) + c2 = copy.deepcopy(c1) + assert c1 == c2 + if isinstance(c2, ListConfig): + c2.append(1000) + elif isinstance(c2, DictConfig): + with raises(AttributeError): + c2.foo = 42 + + +def test_deepcopy_after_del() -> None: + # make sure that deepcopy does not resurrect deleted fields (as it once did, believe it or not). + c1 = OmegaConf.create(dict(foo=[1, 2, 3], bar=10)) + c2 = copy.deepcopy(c1) + assert c1 == c2 + del c1["foo"] + c3 = copy.deepcopy(c1) + assert c1 == c3 + + +def test_deepcopy_after_pop() -> None: + c1 = OmegaConf.create(dict(foo=[1, 2, 3], bar=10)) + c2 = copy.deepcopy(c1) + assert c1 == c2 + c2.pop("foo") + assert "foo" not in c2 + assert "foo" in c1 + c3 = copy.deepcopy(c1) + assert "foo" in c3 + + +def test_deepcopy_with_interpolation() -> None: + c1 = OmegaConf.create(dict(a=dict(b="${c}"), c=10)) + assert c1.a.b == 10 + c2 = copy.deepcopy(c1) + assert c2.a.b == 10 + + +# Yes, there was a bug that was a combination of an interaction between the three +def test_deepcopy_and_merge_and_flags() -> None: + c1 = OmegaConf.create( + {"dataset": {"name": "imagenet", "path": "/datasets/imagenet"}, "defaults": []} + ) + OmegaConf.set_struct(c1, True) + c2 = copy.deepcopy(c1) + with raises(ConfigKeyError): + OmegaConf.merge(c2, OmegaConf.from_dotlist(["dataset.bad_key=yes"])) + + +@pytest.mark.parametrize( # type: ignore + "cfg", [ListConfig(element_type=int, content=[]), DictConfig(content={})] +) +def test_deepcopy_preserves_container_type(cfg: Container) -> None: + cp: Container = copy.deepcopy(cfg) + assert cp._metadata.element_type == cfg._metadata.element_type + + +@pytest.mark.parametrize( # type: ignore + "src, flag_name, func, expectation", + [ + pytest.param( + {}, + "struct", + lambda c: c.__setitem__("foo", 1), + raises(KeyError), + id="struct_setiitem", + ), + pytest.param( + {}, + "struct", + lambda c: c.__setattr__("foo", 1), + raises(AttributeError), + id="struct_setattr", + ), + pytest.param( + {}, + "readonly", + lambda c: c.__setitem__("foo", 1), + raises(ReadonlyConfigError), + id="readonly", + ), + ], +) +def test_flag_override( + src: Dict[str, Any], flag_name: str, func: Any, expectation: Any +) -> None: + c = OmegaConf.create(src) + c._set_flag(flag_name, True) + with expectation: + func(c) + + with does_not_raise(): + with flag_override(c, flag_name, False): + func(c) + + +@pytest.mark.parametrize( # type: ignore + "src, func, expectation", + [ + ({}, lambda c: c.__setitem__("foo", 1), raises(ReadonlyConfigError)), + ([], lambda c: c.append(1), raises(ReadonlyConfigError)), + ], +) +def test_read_write_override(src: Any, func: Any, expectation: Any) -> None: + c = OmegaConf.create(src) + OmegaConf.set_readonly(c, True) + + with expectation: + func(c) + + with does_not_raise(): + with read_write(c): + func(c) + + +@pytest.mark.parametrize( # type: ignore + "string, tokenized", + [ + ("dog,cat", ["dog", "cat"]), + ("dog\\,cat\\ ", ["dog,cat "]), + ("dog,\\ cat", ["dog", " cat"]), + ("\\ ,cat", [" ", "cat"]), + ("dog, cat", ["dog", "cat"]), + ("dog, ca t", ["dog", "ca t"]), + ("dog, cat", ["dog", "cat"]), + ("whitespace\\ , before comma", ["whitespace ", "before comma"]), + (None, []), + ("", []), + ("no , escape", ["no", "escape"]), + ], +) +def test_tokenize_with_escapes(string: str, tokenized: List[str]) -> None: + assert OmegaConf._tokenize_args(string) == tokenized + + +@pytest.mark.parametrize( # type: ignore + "src, func, expectation", + [({}, lambda c: c.__setattr__("foo", 1), raises(AttributeError))], +) +def test_struct_override(src: Any, func: Any, expectation: Any) -> None: + c = OmegaConf.create(src) + OmegaConf.set_struct(c, True) + + with expectation: + func(c) + + with does_not_raise(): + with open_dict(c): + func(c) + + +@pytest.mark.parametrize( # type: ignore + "flag_name,ctx", [("struct", open_dict), ("readonly", read_write)] +) +def test_open_dict_restore(flag_name: str, ctx: Any) -> None: + """ + Tests that internal flags are restored properly when applying context on a child node + """ + cfg = OmegaConf.create({"foo": {"bar": 10}}) + cfg._set_flag(flag_name, True) + assert cfg._get_node_flag(flag_name) + assert not cfg.foo._get_node_flag(flag_name) + with ctx(cfg.foo): + cfg.foo.bar = 20 + assert cfg._get_node_flag(flag_name) + assert not cfg.foo._get_node_flag(flag_name) + + +@pytest.mark.parametrize("copy_method", [lambda x: copy.copy(x), lambda x: x.copy()]) +class TestCopy: + @pytest.mark.parametrize( # type: ignore + "src", [[], [1, 2], ["a", "b", "c"], {}, {"a": "b"}, {"a": {"b": []}}] + ) + def test_copy(self, copy_method: Any, src: Any) -> None: + src = OmegaConf.create(src) + cp = copy_method(src) + assert id(src) != id(cp) + assert src == cp + + @pytest.mark.parametrize( # type: ignore + "src,interpolating_key,interpolated_key", + [([1, 2, "${0}"], 2, 0), ({"a": 10, "b": "${a}"}, "b", "a")], + ) + def test_copy_with_interpolation( + self, copy_method: Any, src: Any, interpolating_key: str, interpolated_key: str + ) -> None: + cfg = OmegaConf.create(src) + assert cfg[interpolated_key] == cfg[interpolating_key] + cp = copy_method(cfg) + assert id(cfg) != id(cp) + assert cp[interpolated_key] == cp[interpolating_key] + assert cfg[interpolated_key] == cp[interpolating_key] + + # Interpolation is preserved in original + cfg[interpolated_key] = "XXX" + assert cfg[interpolated_key] == cfg[interpolating_key] + + # Test interpolation is preserved in copy + cp[interpolated_key] = "XXX" + assert cp[interpolated_key] == cp[interpolating_key] + + def test_list_copy_is_shallow(self, copy_method: Any) -> None: + cfg = OmegaConf.create([[10, 20]]) + cp = copy_method(cfg) + assert id(cfg) != id(cp) + assert id(cfg[0]) == id(cp[0]) + + +def test_not_implemented() -> None: + with raises(NotImplementedError): + OmegaConf() + + +@pytest.mark.parametrize( # type: ignore + "query, result", + [ + ("a", "a"), + ("${foo}", 10), + ("${bar}", 10), + ("foo_${foo}", "foo_10"), + ("foo_${bar}", "foo_10"), + ], +) +def test_resolve_str_interpolation(query: str, result: Any) -> None: + cfg = OmegaConf.create({"foo": 10, "bar": "${foo}"}) + assert ( + cfg._resolve_interpolation( + key=None, + value=StringNode(value=query), + throw_on_missing=False, + throw_on_resolution_failure=True, + ) + == result + ) + + +def test_omegaconf_create() -> None: + assert OmegaConf.create([]) == [] + assert OmegaConf.create({}) == {} + with raises(ValidationError): + assert OmegaConf.create(10) # type: ignore + + +@pytest.mark.parametrize( # type: ignore + "parent, key, value, expected", + [ + ([10, 11], 0, ["a", "b"], [["a", "b"], 11]), + ([None], 0, {"foo": "bar"}, [{"foo": "bar"}]), + ([None], 0, OmegaConf.create({"foo": "bar"}), [{"foo": "bar"}]), + ({}, "foo", ["a", "b"], {"foo": ["a", "b"]}), + ({}, "foo", ("a", "b"), {"foo": ["a", "b"]}), + ({}, "foo", OmegaConf.create({"foo": "bar"}), {"foo": {"foo": "bar"}}), + ], +) +def test_assign(parent: Any, key: Union[str, int], value: Any, expected: Any) -> None: + c = OmegaConf.create(parent) + c[key] = value + assert c == expected + + +@pytest.mark.parametrize( # type: ignore + "cfg, key, expected", + [ + # dict + (OmegaConf.create({"foo": "bar"}), "foo", "bar"), + (OmegaConf.create({"foo": None}), "foo", None), + (OmegaConf.create({"foo": "???"}), "foo", "???"), + # list + (OmegaConf.create([10, 20, 30]), 1, 20), + (OmegaConf.create([10, None, 30]), 1, None), + (OmegaConf.create([10, "???", 30]), 1, "???"), + ], +) +def test_get_node(cfg: Any, key: Any, expected: Any) -> None: + assert cfg._get_node(key) == expected diff --git a/tests/test_basic_ops_dict.py b/tests/test_basic_ops_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c1e12475347b3e0654e7a40cf3356bce30bce1 --- /dev/null +++ b/tests/test_basic_ops_dict.py @@ -0,0 +1,737 @@ +# -*- coding: utf-8 -*- +import re +import tempfile +from typing import Any, Dict, List, Optional, Union + +import pytest + +from omegaconf import ( + MISSING, + DictConfig, + ListConfig, + MissingMandatoryValue, + OmegaConf, + UnsupportedValueType, + ValidationError, + _utils, + open_dict, +) +from omegaconf.basecontainer import BaseContainer +from omegaconf.errors import ConfigKeyError, ConfigTypeError, KeyValidationError + +from . import ( + ConcretePlugin, + Enum1, + IllegalType, + Plugin, + StructuredWithMissing, + User, + does_not_raise, +) + + +def test_setattr_deep_value() -> None: + c = OmegaConf.create({"a": {"b": {"c": 1}}}) + c.a.b = 9 + assert {"a": {"b": 9}} == c + + +def test_setattr_deep_from_empty() -> None: + c = OmegaConf.create() + # Unfortunately we can't just do c.a.b = 9 here. + # The reason is that if c.a is being accessed first and it does not exist, so there + # is nothing to call .b = 9 on. + # The alternative is to auto-create fields as they are being accessed, but this is opening + # a whole new can of worms, and is also breaking map semantics. + c.a = {} + c.a.b = 9 # type: ignore + assert {"a": {"b": 9}} == c + + +def test_setattr_deep_map() -> None: + c = OmegaConf.create(dict(a=dict(b=dict(c=1)))) + c.a.b = {"z": 10} + assert {"a": {"b": {"z": 10}}} == c + + +def test_getattr() -> None: + c = OmegaConf.create("a: b") + assert isinstance(c, DictConfig) + assert "b" == c.a + + +def test_getattr_dict() -> None: + c = OmegaConf.create("a: {b: 1}") + assert isinstance(c, DictConfig) + assert {"b": 1} == c.a + + +def test_mandatory_value() -> None: + c = OmegaConf.create({"a": "???"}) + with pytest.raises(MissingMandatoryValue, match="a"): + c.a + + +def test_nested_dict_mandatory_value() -> None: + c = OmegaConf.create(dict(a=dict(b="???"))) + with pytest.raises(MissingMandatoryValue): + c.a.b + + +def test_subscript_get() -> None: + c = OmegaConf.create("a: b") + assert isinstance(c, DictConfig) + assert "b" == c["a"] + + +def test_subscript_set() -> None: + c = OmegaConf.create() + c["a"] = "b" + assert {"a": "b"} == c + + +def test_default_value() -> None: + c = OmegaConf.create() + assert c.missing_key or "a default value" == "a default value" + + +def test_get_default_value() -> None: + c = OmegaConf.create() + assert c.get("missing_key", "a default value") == "a default value" + + +def test_scientific_notation_float() -> None: + c = OmegaConf.create("a: 10e-3") + assert isinstance(c, DictConfig) + assert 10e-3 == c.a + + +@pytest.mark.parametrize("struct", [None, True, False]) # type: ignore +@pytest.mark.parametrize("default_val", [4, True, False, None]) # type: ignore +@pytest.mark.parametrize( # type: ignore + "d,select,key", + [ + ({"hello": {"a": 2}}, "", "missing"), + ({"hello": {"a": 2}}, "hello", "missing"), + ({"hello": "???"}, "", "hello"), + ({"hello": "${foo}", "foo": "???"}, "", "hello"), + ({"hello": None}, "", "hello"), + ({"hello": "${foo}"}, "", "hello"), + ({"hello": "${foo}", "foo": "???"}, "", "hello"), + ({"hello": DictConfig(is_optional=True, content=None)}, "", "hello"), + ({"hello": DictConfig(content="???")}, "", "hello"), + ({"hello": DictConfig(content="${foo}")}, "", "hello"), + ({"hello": ListConfig(is_optional=True, content=None)}, "", "hello"), + ({"hello": ListConfig(content="???")}, "", "hello"), + ], +) +def test_dict_get_with_default( + d: Any, select: Any, key: Any, default_val: Any, struct: Any +) -> None: + c = OmegaConf.create(d) + c = OmegaConf.select(c, select) + OmegaConf.set_struct(c, struct) + assert c.get(key, default_val) == default_val + + +def test_map_expansion() -> None: + c = OmegaConf.create("{a: 2, b: 10}") + assert isinstance(c, DictConfig) + + def foo(a: int, b: int) -> int: + return a + b + + assert 12 == foo(**c) + + +def test_items() -> None: + c = OmegaConf.create(dict(a=2, b=10)) + assert sorted([("a", 2), ("b", 10)]) == sorted(list(c.items())) + + items = c.items() + for x in [("a", 2), ("b", 10)]: + assert x in items + + items2 = iter(c.items()) + assert next(items2) == ("a", 2) + assert next(items2) == ("b", 10) + with pytest.raises(StopIteration): + next(items2) + + +def test_items2() -> None: + c = OmegaConf.create(dict(a=dict(v=1), b=dict(v=1))) + for k, v in c.items(): + v.v = 2 + + assert c.a.v == 2 + assert c.b.v == 2 + + +def test_items_with_interpolation() -> None: + c = OmegaConf.create(dict(a=2, b="${a}")) + r = {} + for k, v in c.items(): + r[k] = v + assert r["a"] == 2 + assert r["b"] == 2 + + +def test_dict_keys() -> None: + c = OmegaConf.create("{a: 2, b: 10}") + assert isinstance(c, DictConfig) + assert {"a": 2, "b": 10}.keys() == c.keys() + + +def test_pickle_get_root() -> None: + # Test that get_root() is reconstructed correctly for pickle loaded files. + with tempfile.TemporaryFile() as fp: + c1 = OmegaConf.create(dict(a=dict(a1=1, a2=2))) + + c2 = OmegaConf.create(dict(b=dict(b1="${a.a1}", b2=4, bb=dict(bb1=3, bb2=4)))) + c3 = OmegaConf.merge(c1, c2) + assert isinstance(c3, DictConfig) + + import pickle + + pickle.dump(c3, fp) + fp.flush() + fp.seek(0) + loaded_c3 = pickle.load(fp) + + def test(conf: DictConfig) -> None: + assert conf._get_root() == conf + assert conf.a._get_root() == conf + assert conf.b._get_root() == conf + assert conf.b.bb._get_root() == conf + + assert c3 == loaded_c3 + test(c3) + test(loaded_c3) + + +def test_iterate_dictionary() -> None: + c = OmegaConf.create({"a": 1, "b": 2}) + m2 = {} + for key in c: + m2[key] = c[key] + assert m2 == c + + +def test_iterate_dict_with_interpolation() -> None: + c = OmegaConf.create({"a": "${b}", "b": 2}) + expected = [("a", 2), ("b", 2)] + i = 0 + for k, v in c.items(): + assert k == expected[i][0] + assert v == expected[i][1] + i = i + 1 + + +@pytest.mark.parametrize( # type: ignore + "cfg, key, default_, expected", + [ + pytest.param({"a": 1, "b": 2}, "a", "__NO_DEFAULT__", 1, id="no_default"), + pytest.param({"a": 1, "b": 2}, "not_found", None, None, id="none_default"), + pytest.param( + {"a": 1, "b": 2}, "not_found", "default", "default", id="with_default" + ), + # Interpolations + pytest.param( + {"a": "${b}", "b": 2}, "a", "__NO_DEFAULT__", 2, id="interpolation" + ), + pytest.param( + {"a": "${b}"}, "a", "default", "default", id="interpolation_with_default" + ), + # enum key + pytest.param( + {Enum1.FOO: "bar"}, + Enum1.FOO, + "__NO_DEFAULT__", + "bar", + id="enum_key_no_default", + ), + pytest.param( + {Enum1.FOO: "bar"}, Enum1.BAR, None, None, id="enum_key_with_none_default" + ), + pytest.param( + {Enum1.FOO: "bar"}, + Enum1.BAR, + "default", + "default", + id="enum_key_with_default", + ), + ], +) +def test_dict_pop(cfg: Dict[Any, Any], key: Any, default_: Any, expected: Any) -> None: + c = OmegaConf.create(cfg) + + if default_ != "__NO_DEFAULT__": + val = c.pop(key, default_) + else: + val = c.pop(key) + + assert val == expected + assert type(val) == type(expected) + + +def test_dict_struct_mode_pop() -> None: + cfg = OmegaConf.create({"name": "Bond", "age": 7}) + cfg._set_flag("struct", True) + with pytest.raises(ConfigTypeError): + cfg.pop("name") + + with pytest.raises(ConfigTypeError): + cfg.pop("bar") + + with pytest.raises(ConfigTypeError): + cfg.pop("bar", "not even with default") + + +def test_dict_structured_mode_pop() -> None: + cfg = OmegaConf.create({"user": User(name="Bond")}) + with pytest.raises(ConfigTypeError): + cfg.user.pop("name") + + with pytest.raises(ConfigTypeError): + cfg.user.pop("bar") + + with pytest.raises(ConfigTypeError): + cfg.user.pop("bar", "not even with default") + + # Unlocking the top level node is not enough. + with pytest.raises(ConfigTypeError): + with open_dict(cfg): + cfg.user.pop("name") + + # You need to unlock the specified structured node to pop a field from it. + with open_dict(cfg.user): + cfg.user.pop("name") + assert "name" not in cfg.user + + +@pytest.mark.parametrize( # type: ignore + "cfg, key, expectation", + [ + ({"a": 1, "b": 2}, "not_found", pytest.raises(KeyError)), + # Interpolations + ({"a": "???", "b": 2}, "a", pytest.raises(MissingMandatoryValue)), + ({"a": "${b}", "b": "???"}, "a", pytest.raises(MissingMandatoryValue)), + # enum key + ({Enum1.FOO: "bar"}, Enum1.BAR, pytest.raises(KeyError)), + ], +) +def test_dict_pop_error(cfg: Dict[Any, Any], key: Any, expectation: Any) -> None: + c = OmegaConf.create(cfg) + with expectation: + c.pop(key) + assert c == cfg + + +@pytest.mark.parametrize( # type: ignore + "conf,key,expected", + [ + ({"a": 1, "b": {}}, "a", True), + ({"a": 1, "b": {}}, "b", True), + ({"a": 1, "b": {}}, "c", False), + ({"a": 1, "b": "${a}"}, "b", True), + ({"a": 1, "b": "???"}, "b", False), + ({"a": 1, "b": "???", "c": "${b}"}, "c", False), + ({"a": 1, "b": "${not_found}"}, "b", False), + ({"a": "${unknown_resolver:bar}"}, "a", True), + ({"a": None, "b": "${a}"}, "b", True), + ({"a": "cat", "b": "${a}"}, "b", True), + ({Enum1.FOO: 1, "b": {}}, Enum1.FOO, True), + ], +) +def test_in_dict(conf: Any, key: str, expected: Any) -> None: + conf = OmegaConf.create(conf) + assert (key in conf) == expected + + +def test_get_root() -> None: + c = OmegaConf.create(dict(a=123, b=dict(bb=456, cc=7))) + assert c._get_root() == c + assert c.b._get_root() == c + + +def test_get_root_of_merged() -> None: + c1 = OmegaConf.create(dict(a=dict(a1=1, a2=2))) + + c2 = OmegaConf.create(dict(b=dict(b1="???", b2=4, bb=dict(bb1=3, bb2=4)))) + c3 = OmegaConf.merge(c1, c2) + assert isinstance(c3, DictConfig) + + assert c3._get_root() == c3 + assert c3.a._get_root() == c3 + assert c3.b._get_root() == c3 + assert c3.b.bb._get_root() == c3 + + +def test_dict_config() -> None: + c = OmegaConf.create(dict()) + assert isinstance(c, DictConfig) + + +def test_dict_delitem() -> None: + src = {"a": 10, "b": 11} + c = OmegaConf.create(src) + assert c == src + del c["a"] + assert c == {"b": 11} + with pytest.raises(KeyError): + del c["not_found"] + + +def test_dict_struct_delitem() -> None: + src = {"a": 10, "b": 11} + c = OmegaConf.create(src) + OmegaConf.set_struct(c, True) + with pytest.raises(ConfigTypeError): + del c["a"] + with open_dict(c): + del c["a"] + assert "a" not in c + + +def test_dict_structured_delitem() -> None: + c = OmegaConf.structured(User(name="Bond")) + with pytest.raises(ConfigTypeError): + del c["name"] + + with open_dict(c): + del c["name"] + assert "name" not in c + + +def test_dict_nested_structured_delitem() -> None: + c = OmegaConf.create({"user": User(name="Bond")}) + with pytest.raises(ConfigTypeError): + del c.user["name"] + + # Unlocking the top level node is not enough. + with pytest.raises(ConfigTypeError): + with open_dict(c): + del c.user["name"] + + # You need to unlock the specified structured node to delete a field from it. + with open_dict(c.user): + del c.user["name"] + assert "name" not in c.user + + +@pytest.mark.parametrize( # type: ignore + "d, expected", [({}, 0), ({"a": 10, "b": 11}, 2)] +) +def test_dict_len(d: Any, expected: Any) -> None: + c = OmegaConf.create(d) + assert len(c) == expected + + +def test_dict_assign_illegal_value() -> None: + c = OmegaConf.create() + with pytest.raises(UnsupportedValueType, match=re.escape("key: a")): + c.a = IllegalType() + + +def test_dict_assign_illegal_value_nested() -> None: + c = OmegaConf.create({"a": {}}) + with pytest.raises(UnsupportedValueType, match=re.escape("key: a.b")): + c.a.b = IllegalType() + + +def test_assign_dict_in_dict() -> None: + c = OmegaConf.create({}) + c.foo = {"foo": "bar"} + assert c.foo == {"foo": "bar"} + assert isinstance(c.foo, DictConfig) + + +def test_instantiate_config_fails() -> None: + with pytest.raises(TypeError): + BaseContainer() # type: ignore + + +@pytest.mark.parametrize( # type: ignore + "cfg, key, expected", + [ + ({"a": 1, "b": 2, "c": 3}, None, ["a", "b", "c"]), + ({"a": {}}, "a", []), + (StructuredWithMissing, "dict", []), + ], +) +def test_dir(cfg: Any, key: Any, expected: Any) -> None: + c = OmegaConf.create(cfg) + if key is None: + assert dir(c) == expected + else: + assert dir(c._get_node(key)) == expected + + +def test_hash() -> None: + c1 = OmegaConf.create(dict(a=10)) + c2 = OmegaConf.create(dict(a=10)) + assert hash(c1) == hash(c2) + c2.a = 20 + assert hash(c1) != hash(c2) + + +@pytest.mark.parametrize("default", ["default", 0, None]) # type: ignore +def test_get_with_default_from_struct_not_throwing(default: Any) -> None: + c = OmegaConf.create({"a": 10, "b": 20}) + OmegaConf.set_struct(c, True) + assert c.get("z", default) == default + + +def test_members() -> None: + # Make sure accessing __members__ does not return None or throw. + c = OmegaConf.create({"foo": {}}) + with pytest.raises(AttributeError): + c.__members__ + + +@pytest.mark.parametrize( # type: ignore + "in_cfg, mask_keys, expected", + [ + ({}, [], {}), + ({"a": 1}, "a", {"a": 1}), + ({"a": 1}, ["b"], {}), + ({"a": 1, "b": 2}, "b", {"b": 2}), + ({"a": 1, "b": 2}, ["a", "b"], {"a": 1, "b": 2}), + ], +) +def test_masked_copy( + in_cfg: Dict[str, Any], mask_keys: Union[str, List[str]], expected: Any +) -> None: + cfg = OmegaConf.create(in_cfg) + masked = OmegaConf.masked_copy(cfg, keys=mask_keys) + assert masked == expected + + +def test_masked_copy_is_deep() -> None: + cfg = OmegaConf.create({"a": {"b": 1, "c": 2}}) + expected = {"a": {"b": 1, "c": 2}} + masked = OmegaConf.masked_copy(cfg, keys=["a"]) + assert masked == expected + cfg.a.b = 2 + assert cfg != expected + + with pytest.raises(ValueError): + OmegaConf.masked_copy("fail", []) # type: ignore + + +def test_shallow_copy() -> None: + cfg = OmegaConf.create({"a": 1, "b": 2}) + c = cfg.copy() + cfg.a = 42 + assert cfg.a == 42 + assert c.a == 1 + + +def test_shallow_copy_missing() -> None: + cfg = DictConfig(content=MISSING) + c = cfg.copy() + c._set_value({"foo": 1}) + assert c.foo == 1 + assert cfg._is_missing() + + +def test_shallow_copy_none() -> None: + cfg = DictConfig(content=None) + c = cfg.copy() + c._set_value({"foo": 1}) + assert c.foo == 1 + assert cfg._is_none() + + +def test_creation_with_invalid_key() -> None: + with pytest.raises(KeyValidationError): + OmegaConf.create({1: "a"}) # type: ignore + + +def test_set_with_invalid_key() -> None: + cfg = OmegaConf.create() + with pytest.raises(KeyValidationError): + cfg[1] = "a" # type: ignore + + +def test_get_with_invalid_key() -> None: + cfg = OmegaConf.create() + with pytest.raises(KeyValidationError): + cfg[1] # type: ignore + + +def test_hasattr() -> None: + cfg = OmegaConf.create({"foo": "bar"}) + OmegaConf.set_struct(cfg, True) + assert hasattr(cfg, "foo") + assert not hasattr(cfg, "buz") + + +def test_struct_mode_missing_key_getitem() -> None: + cfg = OmegaConf.create({"foo": "bar"}) + OmegaConf.set_struct(cfg, True) + with pytest.raises(KeyError): + cfg.__getitem__("zoo") + + +def test_struct_mode_missing_key_setitem() -> None: + cfg = OmegaConf.create({"foo": "bar"}) + OmegaConf.set_struct(cfg, True) + with pytest.raises(KeyError): + cfg.__setitem__("zoo", 10) + + +def test_get_type() -> None: + + cfg = OmegaConf.structured(User) + assert OmegaConf.get_type(cfg) == User + + cfg = OmegaConf.structured(User(name="bond")) + assert OmegaConf.get_type(cfg) == User + + cfg = OmegaConf.create({"user": User, "inter": "${user}"}) + assert OmegaConf.get_type(cfg.user) == User + assert OmegaConf.get_type(cfg.inter) == User + + +@pytest.mark.parametrize( # type: ignore + "cfg, expected_ref_type", + [ + ( + OmegaConf.create( + {"plugin": DictConfig(ref_type=Plugin, content=ConcretePlugin)} + ), + Optional[Plugin], + ), + ( + OmegaConf.create( + { + "plugin": DictConfig( + ref_type=Plugin, content=ConcretePlugin, is_optional=False + ) + } + ), + Plugin, + ), + ], +) +def test_get_ref_type(cfg: Any, expected_ref_type: Any) -> None: + assert _utils.get_ref_type(cfg.plugin) == expected_ref_type + + +def test_get_ref_type_with_conflict() -> None: + cfg = OmegaConf.create( + {"user": User, "inter": DictConfig(ref_type=Plugin, content="${user}")} + ) + + assert OmegaConf.get_type(cfg.user) == User + assert _utils.get_ref_type(cfg.user) == Optional[User] + + # Interpolation inherits both type and ref type from the target + assert OmegaConf.get_type(cfg.inter) == User + assert _utils.get_ref_type(cfg.inter) == Optional[User] + + +def test_is_missing() -> None: + cfg = OmegaConf.create( + { + "missing_node": DictConfig(content="???"), + "foo": "???", + "inter": "${foo}", + "str_inter": "zoo_${foo}", + "missing_node_inter": "${missing_node}", + } + ) + assert cfg._get_node("foo")._is_missing() # type:ignore + assert cfg._get_node("inter")._is_missing() # type:ignore + assert cfg._get_node("str_inter")._is_missing() # type:ignore + assert cfg._get_node("missing_node")._is_missing() # type:ignore + assert cfg._get_node("missing_node_inter")._is_missing() # type:ignore + + +@pytest.mark.parametrize("ref_type", [None, Any]) # type: ignore +@pytest.mark.parametrize("assign", [None, {}, {"foo": "bar"}, [1, 2, 3]]) # type: ignore +def test_assign_to_reftype_none_or_any(ref_type: Any, assign: Any) -> None: + cfg = OmegaConf.create({"foo": DictConfig(ref_type=ref_type, content={})}) + cfg.foo = assign + assert cfg.foo == assign + + +@pytest.mark.parametrize( # type: ignore + "ref_type,values,assign,expectation", + [ + (Plugin, [None, "???", Plugin], None, does_not_raise), + (Plugin, [None, "???", Plugin], Plugin, does_not_raise), + (Plugin, [None, "???", Plugin], Plugin(), does_not_raise), + (Plugin, [None, "???", Plugin], ConcretePlugin, does_not_raise), + (Plugin, [None, "???", Plugin], ConcretePlugin(), does_not_raise), + (Plugin, [None, "???", Plugin], 10, lambda: pytest.raises(ValidationError)), + (ConcretePlugin, [None, "???", ConcretePlugin], None, does_not_raise), + ( + ConcretePlugin, + [None, "???", ConcretePlugin], + Plugin, + lambda: pytest.raises(ValidationError), + ), + ( + ConcretePlugin, + [None, "???", ConcretePlugin], + Plugin(), + lambda: pytest.raises(ValidationError), + ), + ( + ConcretePlugin, + [None, "???", ConcretePlugin], + ConcretePlugin, + does_not_raise, + ), + ( + ConcretePlugin, + [None, "???", ConcretePlugin], + ConcretePlugin(), + does_not_raise, + ), + ], +) +def test_assign_to_reftype_plugin( + ref_type: Any, values: List[Any], assign: Any, expectation: Any +) -> None: + for value in values: + cfg = OmegaConf.create({"foo": DictConfig(ref_type=ref_type, content=value)}) + with expectation(): + assert _utils.get_ref_type(cfg, "foo") == Optional[ref_type] + cfg.foo = assign + assert cfg.foo == assign + # validate assignment does not change ref type. + assert _utils.get_ref_type(cfg, "foo") == Optional[ref_type] + + if value is not None: + cfg = OmegaConf.create( + {"foo": DictConfig(ref_type=ref_type, content=value)} + ) + with expectation(): + cfg2 = OmegaConf.merge(cfg, {"foo": assign}) + assert isinstance(cfg2, DictConfig) + assert cfg2.foo == assign + + +def test_setdefault() -> None: + cfg = OmegaConf.create({}) + assert cfg.setdefault("foo", 10) == 10 + assert cfg["foo"] == 10 + assert cfg.setdefault("foo", 20) == 10 + assert cfg["foo"] == 10 + + cfg = OmegaConf.create({}) + OmegaConf.set_struct(cfg, True) + with pytest.raises(ConfigKeyError): + assert cfg.setdefault("foo", 10) == 10 + assert cfg == {} + with open_dict(cfg): + assert cfg.setdefault("foo", 10) == 10 + + assert cfg.setdefault("foo", 20) == 10 + assert cfg["foo"] == 10 + + assert cfg["foo"] == 10 diff --git a/tests/test_basic_ops_list.py b/tests/test_basic_ops_list.py new file mode 100644 index 0000000000000000000000000000000000000000..e345edfb407fcf9bb648c790e8f0e355b2af9f6f --- /dev/null +++ b/tests/test_basic_ops_list.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +import re +from typing import Any, List, Optional + +import pytest + +from omegaconf import AnyNode, ListConfig, OmegaConf +from omegaconf.errors import ( + ConfigKeyError, + ConfigTypeError, + KeyValidationError, + MissingMandatoryValue, + UnsupportedValueType, + ValidationError, +) +from omegaconf.nodes import IntegerNode, StringNode + +from . import Color, IllegalType, User, does_not_raise + + +def test_list_value() -> None: + c = OmegaConf.create("a: [1,2]") + assert {"a": [1, 2]} == c + + +def test_list_of_dicts() -> None: + v = [dict(key1="value1"), dict(key2="value2")] + c = OmegaConf.create(v) + assert c[0].key1 == "value1" + assert c[1].key2 == "value2" + + +def test_list_get_with_default() -> None: + c = OmegaConf.create([None, "???", "found"]) + assert c.get(0, "default_value") == "default_value" + assert c.get(1, "default_value") == "default_value" + assert c.get(2, "default_value") == "found" + + +@pytest.mark.parametrize( # type: ignore + "input_, expected, list_key", + [ + pytest.param([1, 2], [1, 2], None, id="simple"), + pytest.param(["${1}", 2], [2, 2], None, id="interpolation"), + pytest.param( + { + "defaults": [ + {"optimizer": "adam"}, + {"dataset": "imagenet"}, + {"foo": "${defaults.0.optimizer}_${defaults.1.dataset}"}, + ] + }, + [{"optimizer": "adam"}, {"dataset": "imagenet"}, {"foo": "adam_imagenet"}], + "defaults", + id="str_interpolation", + ), + ], +) +def test_iterate_list(input_: Any, expected: Any, list_key: str) -> None: + c = OmegaConf.create(input_) + if list_key is not None: + lst = c.get(list_key) + else: + lst = c + items = [x for x in lst] + assert items == expected + + +def test_iterate_list_with_missing_interpolation() -> None: + c = OmegaConf.create([1, "${10}"]) + itr = iter(c) + assert 1 == next(itr) + with pytest.raises(ConfigKeyError): + next(itr) + + +def test_iterate_list_with_missing() -> None: + c = OmegaConf.create([1, "???"]) + itr = iter(c) + assert 1 == next(itr) + with pytest.raises(MissingMandatoryValue): + next(itr) + + +def test_items_with_interpolation() -> None: + c = OmegaConf.create(["foo", "${0}"]) + assert c == ["foo", "foo"] + + +def test_list_pop() -> None: + c = OmegaConf.create([1, 2, 3, 4]) + assert c.pop(0) == 1 + assert c.pop() == 4 + assert c == [2, 3] + with pytest.raises(IndexError): + c.pop(100) + validate_list_keys(c) + + +def test_list_pop_on_unexpected_exception_not_modifying() -> None: + src = [1, 2, 3, 4] + c = OmegaConf.create(src) + + with pytest.raises(ConfigTypeError): + c.pop("foo") # type: ignore + assert c == src + + +def test_in_list() -> None: + c = OmegaConf.create([10, 11, dict(a=12)]) + assert 10 in c + assert 11 in c + assert dict(a=12) in c + assert "blah" not in c + + +def test_list_config_with_list() -> None: + c = OmegaConf.create([]) + assert isinstance(c, ListConfig) + + +def test_list_config_with_tuple() -> None: + c = OmegaConf.create(()) + assert isinstance(c, ListConfig) + + +def test_items_on_list() -> None: + c = OmegaConf.create([1, 2]) + with pytest.raises(AttributeError): + c.items() + + +def test_list_enumerate() -> None: + src: List[Optional[str]] = ["a", "b", "c", "d"] + c = OmegaConf.create(src) + for i, v in enumerate(c): + assert src[i] == v + assert v is not None + src[i] = None + + for v in src: + assert v is None + + +def test_list_delitem() -> None: + c = OmegaConf.create([1, 2, 3]) + assert c == [1, 2, 3] + del c[0] + assert c == [2, 3] + with pytest.raises(IndexError): + del c[100] + + validate_list_keys(c) + + +@pytest.mark.parametrize( # type: ignore + "lst,expected", + [ + (OmegaConf.create([1, 2]), 2), + (ListConfig(content=None), 0), + (ListConfig(content="???"), 0), + ], +) +def test_list_len(lst: Any, expected: Any) -> None: + assert len(lst) == expected + + +def test_nested_list_assign_illegal_value() -> None: + c = OmegaConf.create({"a": [None]}) + with pytest.raises( + UnsupportedValueType, + match=re.escape( + "Value 'IllegalType' is not a supported primitive type\n\tfull_key: a[0]" + ), + ): + c.a[0] = IllegalType() + + +def test_list_append() -> None: + c = OmegaConf.create([]) + c.append(1) + c.append(2) + c.append({}) + c.append([]) + assert c == [1, 2, {}, []] + + validate_list_keys(c) + + +@pytest.mark.parametrize( # type: ignore + "lc,element,expected", + [ + pytest.param( + ListConfig(content=[], element_type=int), + "foo", + pytest.raises( + ValidationError, + match=re.escape("Value 'foo' could not be converted to Integer"), + ), + id="append_str_to_list[int]", + ), + pytest.param( + ListConfig(content=[], element_type=Color), + "foo", + pytest.raises( + ValidationError, + match=re.escape( + "Invalid value 'foo', expected one of [RED, GREEN, BLUE]" + ), + ), + id="append_str_to_list[Color]", + ), + pytest.param( + ListConfig(content=[], element_type=User), + "foo", + pytest.raises( + ValidationError, + match=re.escape( + "Invalid type assigned : str is not a subclass of User. value: foo" + ), + ), + id="append_str_to_list[User]", + ), + pytest.param( + ListConfig(content=[], element_type=User), + {"name": "Bond", "age": 7}, + pytest.raises( + ValidationError, + match=re.escape( + "Invalid type assigned : dict is not a subclass of User. value: {'name': 'Bond', 'age': 7}" + ), + ), + id="list:convert_dict_to_user", + ), + pytest.param( + ListConfig(content=[], element_type=User), + {}, + pytest.raises( + ValidationError, + match=re.escape( + "Invalid type assigned : dict is not a subclass of User. value: {}" + ), + ), + id="list:convert_empty_dict_to_user", + ), + ], +) +def test_append_invalid_element_type( + lc: ListConfig, element: Any, expected: Any +) -> None: + with expected: + lc.append(element) + + +@pytest.mark.parametrize( # type: ignore + "lc,element,expected", + [ + pytest.param( + ListConfig(content=[], element_type=int), + "10", + 10, + id="list:convert_str_to_int", + ), + pytest.param( + ListConfig(content=[], element_type=float), + "10", + 10.0, + id="list:convert_str_to_float", + ), + pytest.param( + ListConfig(content=[], element_type=Color), + "RED", + Color.RED, + id="list:convert_str_to_float", + ), + ], +) +def test_append_convert(lc: ListConfig, element: Any, expected: Any) -> None: + lc.append(element) + value = lc[-1] + assert value == expected + assert type(value) == type(expected) + + +@pytest.mark.parametrize( # type: ignore + "index, expected", [(slice(1, 3), [11, 12]), (slice(0, 3, 2), [10, 12]), (-1, 13)] +) +def test_list_index(index: Any, expected: Any) -> None: + c = OmegaConf.create([10, 11, 12, 13]) + assert c[index] == expected + + +@pytest.mark.parametrize( # type: ignore + "cfg, expected", + [ + (OmegaConf.create([1, 2, 3]), ["0", "1", "2"]), + (ListConfig(content="???"), []), + (ListConfig(content=None), []), + ], +) +def test_list_dir(cfg: Any, expected: Any) -> None: + assert dir(cfg) == expected + + +def validate_list_keys(c: Any) -> None: + # validate keys are maintained + for i in range(len(c)): + assert c._get_node(i)._metadata.key == i + + +@pytest.mark.parametrize( # type: ignore + "input_, index, value, expected, expected_node_type, expectation", + [ + (["a", "b", "c"], 1, 100, ["a", 100, "b", "c"], AnyNode, None), + ( + ["a", "b", "c"], + 1, + IntegerNode(100), + ["a", 100, "b", "c"], + IntegerNode, + None, + ), + (["a", "b", "c"], 1, "foo", ["a", "foo", "b", "c"], AnyNode, None), + ( + ["a", "b", "c"], + 1, + StringNode("foo"), + ["a", "foo", "b", "c"], + StringNode, + None, + ), + ( + ListConfig(element_type=int, content=[]), + 0, + "foo", + None, + None, + ValidationError, + ), + ], +) +def test_insert( + input_: List[str], + index: int, + value: Any, + expected: Any, + expected_node_type: type, + expectation: Any, +) -> None: + c = OmegaConf.create(input_) + if expectation is None: + c.insert(index, value) + assert c == expected + assert type(c._get_node(index)) == expected_node_type + else: + with pytest.raises(expectation): + c.insert(index, value) + validate_list_keys(c) + + +@pytest.mark.parametrize( # type: ignore + "lst,idx,value,expectation", + [ + (ListConfig(content=None), 0, 10, pytest.raises(TypeError)), + (ListConfig(content="???"), 0, 10, pytest.raises(MissingMandatoryValue)), + ], +) +def test_insert_special_list(lst: Any, idx: Any, value: Any, expectation: Any) -> None: + with expectation: + lst.insert(idx, value) + + +@pytest.mark.parametrize( # type: ignore + "src, append, result", + [ + ([], [], []), + ([1, 2], [3], [1, 2, 3]), + ([1, 2], ("a", "b", "c"), [1, 2, "a", "b", "c"]), + ], +) +def test_extend(src: List[Any], append: List[Any], result: List[Any]) -> None: + lst = OmegaConf.create(src) + lst.extend(append) + assert lst == result + + +@pytest.mark.parametrize( # type: ignore + "src, remove, result, expectation", + [ + ([10], 10, [], does_not_raise()), + ([], "oops", None, pytest.raises(ValueError)), + ([0, dict(a="blah"), 10], dict(a="blah"), [0, 10], does_not_raise()), + ([1, 2, 1, 2], 2, [1, 1, 2], does_not_raise()), + ], +) +def test_remove(src: List[Any], remove: Any, result: Any, expectation: Any) -> None: + with expectation: + lst = OmegaConf.create(src) + assert isinstance(lst, ListConfig) + lst.remove(remove) + assert lst == result + + +@pytest.mark.parametrize("src", [[], [1, 2, 3], [None, dict(foo="bar")]]) # type: ignore +@pytest.mark.parametrize("num_clears", [1, 2]) # type: ignore +def test_clear(src: List[Any], num_clears: int) -> None: + lst = OmegaConf.create(src) + for i in range(num_clears): + lst.clear() + assert lst == [] + + +@pytest.mark.parametrize( # type: ignore + "src, item, expected_index, expectation", + [ + ([], 20, -1, pytest.raises(ValueError)), + ([10, 20], 10, 0, does_not_raise()), + ([10, 20], 20, 1, does_not_raise()), + ], +) +def test_index( + src: List[Any], item: Any, expected_index: int, expectation: Any +) -> None: + with expectation: + lst = OmegaConf.create(src) + assert lst.index(item) == expected_index + + +def test_index_with_range() -> None: + lst = OmegaConf.create([10, 20, 30, 40, 50]) + assert lst.index(x=30) == 2 + assert lst.index(x=30, start=1) == 2 + assert lst.index(x=30, start=1, end=3) == 2 + with pytest.raises(ValueError): + lst.index(x=30, start=3) + + with pytest.raises(ValueError): + lst.index(x=30, end=2) + + +@pytest.mark.parametrize( # type: ignore + "src, item, count", + [([], 10, 0), ([10], 10, 1), ([10, 2, 10], 10, 2), ([10, 2, 10], None, 0)], +) +def test_count(src: List[Any], item: Any, count: int) -> None: + lst = OmegaConf.create(src) + assert lst.count(item) == count + + +def test_sort() -> None: + c = OmegaConf.create(["bbb", "aa", "c"]) + c.sort() + assert ["aa", "bbb", "c"] == c + c.sort(reverse=True) + assert ["c", "bbb", "aa"] == c + c.sort(key=len) + assert ["c", "aa", "bbb"] == c + c.sort(key=len, reverse=True) + assert ["bbb", "aa", "c"] == c + + +def test_insert_throws_not_changing_list() -> None: + c = OmegaConf.create([]) + with pytest.raises(ValueError): + c.insert(0, IllegalType()) + assert len(c) == 0 + assert c == [] + + +def test_append_throws_not_changing_list() -> None: + c = OmegaConf.create([]) + v = IllegalType() + with pytest.raises(ValueError): + c.append(v) + assert len(c) == 0 + assert c == [] + validate_list_keys(c) + + +def test_hash() -> None: + c1 = OmegaConf.create([10]) + c2 = OmegaConf.create([10]) + assert hash(c1) == hash(c2) + c2[0] = 20 + assert hash(c1) != hash(c2) + + +@pytest.mark.parametrize( + "in_list1, in_list2,in_expected", + [ + ([], [], []), + ([1, 2], [3, 4], [1, 2, 3, 4]), + (["x", 2, "${0}"], [5, 6, 7], ["x", 2, "x", 5, 6, 7]), + ], +) +class TestListAdd: + def test_list_plus( + self, in_list1: List[Any], in_list2: List[Any], in_expected: List[Any] + ) -> None: + list1 = OmegaConf.create(in_list1) + list2 = OmegaConf.create(in_list2) + expected = OmegaConf.create(in_expected) + ret = list1 + list2 + assert ret == expected + + def test_list_plus_eq( + self, in_list1: List[Any], in_list2: List[Any], in_expected: List[Any] + ) -> None: + list1 = OmegaConf.create(in_list1) + list2 = OmegaConf.create(in_list2) + expected = OmegaConf.create(in_expected) + list1 += list2 + assert list1 == expected + + +def test_deep_add() -> None: + cfg = OmegaConf.create({"foo": [1, 2, "${bar}"], "bar": "xx"}) + lst = cfg.foo + [10, 20] + assert lst == [1, 2, "xx", 10, 20] + + +def test_set_with_invalid_key() -> None: + cfg = OmegaConf.create([1, 2, 3]) + with pytest.raises(KeyValidationError): + cfg["foo"] = 4 # type: ignore + + +@pytest.mark.parametrize( # type: ignore + "lst,idx,expected", + [ + (OmegaConf.create([1, 2]), 0, 1), + (ListConfig(content=None), 0, TypeError), + (ListConfig(content="???"), 0, MissingMandatoryValue), + ], +) +def test_getitem(lst: Any, idx: Any, expected: Any) -> None: + if isinstance(expected, type): + with pytest.raises(expected): + lst.__getitem__(idx) + else: + assert lst.__getitem__(idx) == expected + + +@pytest.mark.parametrize( # type: ignore + "sli", + [ + (slice(None, None, None)), + (slice(1, None, None)), + (slice(-1, None, None)), + (slice(None, 1, None)), + (slice(None, -1, None)), + (slice(None, None, 1)), + (slice(None, None, -1)), + (slice(1, None, -2)), + (slice(None, 1, -2)), + (slice(1, 3, -1)), + (slice(3, 1, -1)), + ], +) +def test_getitem_slice(sli: slice) -> None: + lst = [1, 2, 3] + olst = OmegaConf.create([1, 2, 3]) + expected = lst[sli.start : sli.stop : sli.step] + assert olst.__getitem__(sli) == expected + + +@pytest.mark.parametrize( # type: ignore + "lst,idx,expected", + [ + (OmegaConf.create([1, 2]), 0, 1), + (OmegaConf.create([1, 2]), "foo", KeyValidationError), + (ListConfig(content=None), 0, TypeError), + (ListConfig(content="???"), 0, MissingMandatoryValue), + ], +) +def test_get(lst: Any, idx: Any, expected: Any) -> None: + if isinstance(expected, type): + with pytest.raises(expected): + lst.get(idx) + else: + lst.__getitem__(idx) == expected + + +def test_getattr() -> None: + src = ["a", "b", "c"] + cfg = OmegaConf.create(src) + with pytest.raises(AttributeError): + getattr(cfg, "foo") + assert getattr(cfg, "0") == src[0] + assert getattr(cfg, "1") == src[1] + assert getattr(cfg, "2") == src[2] diff --git a/tests/test_config_eq.py b/tests/test_config_eq.py new file mode 100644 index 0000000000000000000000000000000000000000..6bb5e019d36927c1debea193fb5e35efb48e723c --- /dev/null +++ b/tests/test_config_eq.py @@ -0,0 +1,165 @@ +from typing import Any + +import pytest + +from omegaconf import AnyNode, DictConfig, ListConfig, OmegaConf + +from . import Group, User + + +@pytest.mark.parametrize( # type: ignore + "i1,i2", + [ + # === LISTS === + # empty list + pytest.param([], [], id="empty"), + # simple list + pytest.param(["a", 12, "15"], ["a", 12, "15"], id="simple_list"), + # raw vs any + ([1, 2, 12], [1, 2, AnyNode(12)]), + # nested empty dict + ([12, {}], [12, {}]), + # nested dict + ([12, {"c": 10}], [12, {"c": 10}]), + # nested list + ([1, 2, 3, [10, 20, 30]], [1, 2, 3, [10, 20, 30]]), + # nested list with any + ([1, 2, 3, [1, 2, AnyNode(3)]], [1, 2, 3, [1, 2, AnyNode(3)]]), + # === DICTS === + # empty + ({}, {}), + # simple + ({"a": 12}, {"a": 12}), + # any vs raw + ({"a": 12}, {"a": AnyNode(12)}), + # nested dict empty + (dict(a=12, b=dict()), dict(a=12, b=dict())), + # nested dict + (dict(a=12, b=dict(c=10)), dict(a=12, b=dict(c=10))), + # nested list + (dict(a=12, b=[1, 2, 3]), dict(a=12, b=[1, 2, 3])), + # nested list with any + (dict(a=12, b=[1, 2, AnyNode(3)]), dict(a=12, b=[1, 2, AnyNode(3)])), + # In python 3.6+ insert order changes iteration order. this ensures that equality is preserved. + (dict(a=1, b=2, c=3, d=4, e=5), dict(e=5, b=2, c=3, d=4, a=1)), + (DictConfig(content=None), DictConfig(content=None)), + pytest.param({"a": [1, 2]}, {"a": [1, 2]}, id="list_in_dict"), + # With interpolations + ([10, "${0}"], [10, 10]), + (dict(a=12, b="${a}"), dict(a=12, b=12)), + # With missing interpolation + pytest.param([10, "${0}"], [10, 10], id="list_simple_interpolation"), + pytest.param( + {"a": "${ref_error}"}, {"a": "${ref_error}"}, id="dict==dict,ref_error" + ), + pytest.param({"a": "???"}, {"a": "???"}, id="dict==dict,missing"), + pytest.param(User, User, id="User==User"), + pytest.param( + {"name": "poo", "age": 7}, User(name="poo", age=7), id="dict==User" + ), + pytest.param(Group, Group, id="Group==Group"), + pytest.param({"group": {"admin": None}}, {"group": Group}, id="dict==Group"), + pytest.param( + {"i1": "${n1}", "n1": {"a": 10}}, + {"i1": "${n1}", "n1": {"a": 10}}, + id="node_interpolation", + ), + # Inter containers + pytest.param( + {"foo": DictConfig(content="${bar}"), "bar": 10}, + {"foo": 10, "bar": 10}, + id="dictconfig_inter", + ), + pytest.param( + {"foo": ListConfig(content="${bar}"), "bar": 10}, + {"foo": 10, "bar": 10}, + id="listconfig_inter", + ), + # None containers + pytest.param( + {"foo": DictConfig(content=None)}, {"foo": None}, id="dictconfig_none" + ), + pytest.param( + {"foo": ListConfig(content=None)}, {"foo": None}, id="listconfig_none" + ), + # Missing containers + pytest.param( + {"foo": DictConfig(content="???")}, {"foo": "???"}, id="dictconfig_missing" + ), + pytest.param( + {"foo": ListConfig(content="???")}, {"foo": "???"}, id="listconfig_missing" + ), + ], +) +def test_eq(i1: Any, i2: Any) -> None: + c1 = OmegaConf.create(i1) + c2 = OmegaConf.create(i2) + + def eq(a: Any, b: Any) -> None: + assert a == b + assert b == a + assert not a != b + assert not b != a + + eq(c1, c2) + eq(c1, i1) + eq(c2, i2) + + +@pytest.mark.parametrize( # type: ignore + "input1, input2", + [ + # Dicts + pytest.param({}, {"a": 10}, id="empty_dict_neq_dict"), + pytest.param({}, [], id="empty_dict_vs_list"), + pytest.param({}, None, id="dict_neq_none"), + pytest.param({"foo": None}, {"foo": "bar"}, id="dict_none_neq_dict_not_none"), + pytest.param({"a": 12}, {"a": 13}, id="simple_dict_neq"), + pytest.param({"a": 0}, {"b": 0}, id="different_key_same_value"), + pytest.param(dict(a=12), dict(a=AnyNode(13))), + pytest.param(dict(a=12, b=dict()), dict(a=13, b=dict())), + pytest.param(dict(a=12, b=dict(c=10)), dict(a=13, b=dict(c=10))), + pytest.param(dict(a=12, b=[1, 2, 3]), dict(a=12, b=[10, 2, 3])), + pytest.param( + dict(a=12, b=[1, 2, AnyNode(3)]), dict(a=12, b=[1, 2, AnyNode(30)]) + ), + # Lists + pytest.param([], [10], id="list:empty_vs_full"), + pytest.param([10], [11], id="list:different_value"), + ([12], [AnyNode(13)]), + ([12, dict()], [13, dict()]), + ([12, dict(c=10)], [13, dict(c=10)]), + ([12, [1, 2, 3]], [12, [10, 2, 3]]), + ([12, [1, 2, AnyNode(3)]], [12, [1, 2, AnyNode(30)]]), + (dict(a="${foo1}"), dict(a="${foo2}")), + pytest.param( + {"i1": "${n1}", "n1": {"a": 10}}, + {"i1": "${n1}", "n1": {"a": 20}}, + id="node_interpolation", + ), + ], +) +def test_not_eq(input1: Any, input2: Any) -> None: + c1 = OmegaConf.create(input1) + c2 = OmegaConf.create(input2) + + def neq(a: Any, b: Any) -> None: + assert a != b + assert b != a + assert not a == b + assert not b == a + + neq(c1, c2) + neq(c2, c1) + + +# --- +def test_config_eq_mismatch_types() -> None: + c1 = OmegaConf.create({}) + c2 = OmegaConf.create([]) + assert c1 != c2 + + +def test_dict_not_eq_with_another_class() -> None: + assert OmegaConf.create({}) != "string" + assert OmegaConf.create([]) != "string" diff --git a/tests/test_create.py b/tests/test_create.py new file mode 100644 index 0000000000000000000000000000000000000000..74e5aa0284c15c83ab4e5d32317c626ea676f99b --- /dev/null +++ b/tests/test_create.py @@ -0,0 +1,150 @@ +"""Testing for OmegaConf""" +import re +import sys +from typing import Any, Dict, List + +import pytest +import yaml + +from omegaconf import DictConfig, ListConfig, OmegaConf +from omegaconf.errors import UnsupportedValueType + +from . import ConcretePlugin, IllegalType, Plugin + + +@pytest.mark.parametrize( # type: ignore + "input_,expected", + [ + # No content + (None, None), + # empty + ({}, {}), + # simple value + ("hello", {"hello": None}), + # simple key:value" + ("hello: world", {"hello": "world"}), + ({"hello": {"a": 2}}, {"hello": {"a": 2}}), + # empty input + ("", {}), + # list value + ([1, 2], [1, 2]), + # For simplicity, tuples are converted to lists. + ((1, 2), [1, 2]), + # dict 1 + ({"a": 2, "b": 10}, {"a": 2, "b": 10}), + # dict 2 + (dict(a=2, b=10), dict(a=2, b=10)), + # nested dict + ( + {"a": 2, "b": {"c": {"f": 1}, "d": {}}}, + {"a": 2, "b": {"c": {"f": 1}, "d": {}}}, + ), + ({"a": None}, {"a": None}), + ({"foo": "${missing}"}, {"foo": "${missing}"}), + (OmegaConf.create({"foo": "${missing}"}), {"foo": "${missing}"}), + (OmegaConf.create(), {}), + (OmegaConf.create({}), {}), + (OmegaConf.create([]), []), + (OmegaConf.create({"foo": OmegaConf.create([])}), {"foo": []}), + (OmegaConf.create([OmegaConf.create({})]), [{}]), # type: ignore + ], +) +def test_create_value(input_: Any, expected: Any) -> None: + assert OmegaConf.create(input_) == expected + + +def test_create_from_cli() -> None: + sys.argv = ["program.py", "a=1", "b.c=2"] + c = OmegaConf.from_cli() + assert {"a": 1, "b": {"c": 2}} == c + + +def test_cli_passing() -> None: + args_list = ["a=1", "b.c=2"] + c = OmegaConf.from_cli(args_list) + assert {"a": 1, "b": {"c": 2}} == c + + +@pytest.mark.parametrize( # type: ignore + "input_,expected", + [ + # simple + (["a=1", "b.c=2"], dict(a=1, b=dict(c=2))), + # string + (["a=hello", "b=world"], dict(a="hello", b="world")), + # date-formatted string + (["my_date=2019-12-11"], dict(my_date="2019-12-11")), + ], +) +def test_dotlist(input_: List[str], expected: Dict[str, Any]) -> None: + c = OmegaConf.from_dotlist(input_) + assert c == expected + + +def test_create_list_with_illegal_value_idx0() -> None: + with pytest.raises(UnsupportedValueType, match=re.escape("key: [0]")): + OmegaConf.create([IllegalType()]) + + +def test_create_list_with_illegal_value_idx1() -> None: + lst = [1, IllegalType(), 3] + with pytest.raises(UnsupportedValueType, match=re.escape("key: [1]")): + OmegaConf.create(lst) + + +def test_create_dict_with_illegal_value() -> None: + with pytest.raises(UnsupportedValueType, match=re.escape("key: a")): + OmegaConf.create({"a": IllegalType()}) + + +def test_create_nested_dict_with_illegal_value() -> None: + with pytest.raises(ValueError, match=re.escape("key: a.b")): + OmegaConf.create({"a": {"b": IllegalType()}}) + + +def test_create_from_oc() -> None: + c = OmegaConf.create( + {"a": OmegaConf.create([1, 2, 3]), "b": OmegaConf.create({"c": 10})} + ) + assert c == {"a": [1, 2, 3], "b": {"c": 10}} + + +def test_create_from_oc_with_flags() -> None: + c1 = OmegaConf.create({"foo": "bar"}) + OmegaConf.set_struct(c1, True) + c2 = OmegaConf.create(c1) + assert c1 == c2 + assert c1._metadata.flags == c2._metadata.flags + + +def test_create_from_dictconfig_preserves_metadata() -> None: + cfg1 = DictConfig(ref_type=Plugin, is_optional=False, content=ConcretePlugin) + OmegaConf.set_struct(cfg1, True) + OmegaConf.set_readonly(cfg1, True) + cfg2 = OmegaConf.create(cfg1) + assert cfg1 == cfg2 + assert cfg1._metadata == cfg2._metadata + + +def test_create_from_listconfig_preserves_metadata() -> None: + cfg1 = ListConfig(element_type=int, is_optional=False, content=[1, 2, 3]) + OmegaConf.set_struct(cfg1, True) + OmegaConf.set_readonly(cfg1, True) + cfg2 = OmegaConf.create(cfg1) + assert cfg1 == cfg2 + assert cfg1._metadata == cfg2._metadata + + +@pytest.mark.parametrize("node", [({"bar": 10}), ([1, 2, 3])]) # type: ignore +def test_create_node_parent_retained_on_create(node: Any) -> None: + cfg1 = OmegaConf.create({"foo": node}) + cfg2 = OmegaConf.create({"zonk": cfg1.foo}) + assert cfg2 == {"zonk": node} + assert cfg1.foo._get_parent() == cfg1 + + +def test_create_unmodified_loader() -> None: + cfg = OmegaConf.create("gitrev: 100e100") + yaml_cfg = yaml.load("gitrev: 100e100", Loader=yaml.loader.SafeLoader) + assert cfg.gitrev == 1e102 + assert yaml_cfg["gitrev"] == "100e100" diff --git a/tests/test_errors.py b/tests/test_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..fd8b9525b88db1858d1c69dbd783ce29b4ae3ccb --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,1098 @@ +import re +from dataclasses import dataclass +from enum import Enum +from typing import Any, Dict, List, Optional, Type, Union + +import pytest + +from omegaconf import ( + DictConfig, + IntegerNode, + ListConfig, + OmegaConf, + ReadonlyConfigError, + UnsupportedValueType, + ValidationError, +) +from omegaconf.errors import ( + ConfigAttributeError, + ConfigKeyError, + ConfigTypeError, + ConfigValueError, + KeyValidationError, + MissingMandatoryValue, + OmegaConfBaseException, +) + +from . import ( + A, + Color, + ConcretePlugin, + IllegalType, + Module, + Package, + Plugin, + StructuredWithMissing, + UnionError, + User, +) + + +# tests classes +@dataclass +class NotOptionalInt: + foo: int = None # type:ignore + + +@dataclass +class NotOptionalA: + x: A = None # type: ignore + + +@dataclass +class Expected: + exception_type: Type[Exception] + msg: str + + # "Low level exceptions" are thrown from internal APIs are are not populating all the fields + low_level: bool = False + key: Any = None + # "AUTO" : determine automatically based on OmegaConf.get_type(cfg) + object_type: Any = "AUTO" + ref_type: Any = None + + # "AUTO: full_key is key + full_key: Any = "AUTO" + create: Any = lambda: None + op: Any = lambda _cfg: None + child_node: Any = lambda cfg: None + parent_node: Any = lambda cfg: cfg + + object_type_str: Optional[str] = "AUTO" + ref_type_str: Optional[str] = "AUTO" + num_lines: int = 3 + + def finalize(self, cfg: Any) -> None: + if self.object_type == "AUTO": + self.object_type = OmegaConf.get_type(cfg) + + if self.full_key == "AUTO": + if self.key is None: + self.full_key = "" + else: + if isinstance(self.key, (str, int, Enum, slice)): + self.full_key = self.key + else: + self.full_key = "" + + +params = [ + ############## + # DictConfig # + ############## + # update + pytest.param( + Expected( + create=lambda: OmegaConf.structured(StructuredWithMissing), + op=lambda cfg: OmegaConf.update(cfg, "num", "hello", merge=True), + exception_type=ValidationError, + msg="Value 'hello' could not be converted to Integer", + parent_node=lambda cfg: cfg, + child_node=lambda cfg: cfg._get_node("num"), + object_type=StructuredWithMissing, + ref_type=Optional[StructuredWithMissing], + key="num", + ), + id="structured:update_with_invalid_value", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(StructuredWithMissing), + op=lambda cfg: OmegaConf.update(cfg, "num", None, merge=True), + exception_type=ValidationError, + msg="child 'num' is not Optional", + parent_node=lambda cfg: cfg, + child_node=lambda cfg: cfg._get_node("num"), + object_type=StructuredWithMissing, + ref_type=Optional[StructuredWithMissing], + key="num", + ), + id="structured:update:none_to_non_optional", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create({}), + op=lambda cfg: OmegaConf.update(cfg, "a", IllegalType(), merge=True), + key="a", + exception_type=UnsupportedValueType, + ref_type=Optional[Dict[Union[str, Enum], Any]], + msg="Value 'IllegalType' is not a supported primitive type", + ), + id="dict:update:object_of_illegal_type", + ), + # pop + pytest.param( + Expected( + create=lambda: create_readonly({"foo": "bar"}), + op=lambda cfg: cfg.pop("foo"), + key="foo", + child_node=lambda cfg: cfg._get_node("foo"), + exception_type=ReadonlyConfigError, + ref_type=Optional[Dict[Union[str, Enum], Any]], + msg="Cannot pop from read-only node", + ), + id="dict,readonly:pop", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create({"foo": "bar"}), + op=lambda cfg: cfg.pop("nevermind"), + key="nevermind", + exception_type=ConfigKeyError, + msg="Key not found: 'nevermind'", + ), + id="dict:pop_invalid", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create({"foo": {}}), + op=lambda cfg: cfg.foo.pop("nevermind"), + key="nevermind", + full_key="foo.nevermind", + parent_node=lambda cfg: cfg.foo, + exception_type=ConfigKeyError, + msg="Key not found: 'nevermind' (path: 'foo.nevermind')", + ), + id="dict:pop_invalid_nested", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(ConcretePlugin), + op=lambda cfg: getattr(cfg, "fail"), + exception_type=ConfigAttributeError, + msg="Key 'fail' not in 'ConcretePlugin'", + key="fail", + object_type=ConcretePlugin, + ref_type=Optional[ConcretePlugin], + ), + id="structured:access_invalid_attribute", + ), + # getattr + pytest.param( + Expected( + create=lambda: create_struct({"foo": "bar"}), + op=lambda cfg: getattr(cfg, "fail"), + exception_type=ConfigAttributeError, + msg="Key 'fail' is not in struct", + key="fail", + ), + id="dict,struct:access_invalid_attribute", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create({"foo": "${missing}"}), + op=lambda cfg: getattr(cfg, "foo"), + exception_type=ConfigKeyError, + msg="str interpolation key 'missing' not found", + key="foo", + child_node=lambda cfg: cfg._get_node("foo"), + ), + id="dict,accessing_missing_interpolation", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create({"foo": "foo_${missing}"}), + op=lambda cfg: getattr(cfg, "foo"), + exception_type=ConfigKeyError, + msg="str interpolation key 'missing' not found", + key="foo", + child_node=lambda cfg: cfg._get_node("foo"), + ), + id="dict,accessing_missing_str_interpolation", + ), + # setattr + pytest.param( + Expected( + create=lambda: create_struct({"foo": "bar"}), + op=lambda cfg: setattr(cfg, "zlonk", "zlank"), + exception_type=ConfigAttributeError, + msg="Key 'zlonk' is not in struct", + key="zlonk", + ), + id="dict,struct:set_invalid_attribute", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(ConcretePlugin), + op=lambda cfg: setattr(cfg, "params", 20), + exception_type=ValidationError, + msg="Invalid type assigned : int is not a subclass of FoobarParams. value: 20", + key="params", + object_type=ConcretePlugin, + ref_type=Optional[ConcretePlugin], + child_node=lambda cfg: cfg.params, + ), + id="structured:setattr,invalid_type_assigned_to_structured", + ), + pytest.param( + Expected( + create=lambda: create_readonly({"foo": "bar"}), + op=lambda cfg: setattr(cfg, "foo", 20), + exception_type=ReadonlyConfigError, + msg="Cannot change read-only config container", + key="foo", + child_node=lambda cfg: cfg.foo, + ), + id="dict,readonly:set_attribute", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create( + {"foo": DictConfig(is_optional=False, content={})} + ), + op=lambda cfg: setattr(cfg, "foo", None), + exception_type=ValidationError, + msg="child 'foo' is not Optional", + key="foo", + full_key="foo", + child_node=lambda cfg: cfg.foo, + ), + id="dict:setattr:not_optional:set_none", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(ConcretePlugin), + op=lambda cfg: cfg.params.__setattr__("foo", "bar"), + exception_type=ValidationError, + msg="Value 'bar' could not be converted to Integer", + key="foo", + full_key="params.foo", + object_type=ConcretePlugin.FoobarParams, + child_node=lambda cfg: cfg.params.foo, + parent_node=lambda cfg: cfg.params, + ), + id="structured:setattr,invalid_type_assigned_to_field", + ), + # setitem + pytest.param( + Expected( + create=lambda: create_struct({"foo": "bar"}), + op=lambda cfg: cfg.__setitem__("zoo", "zonk"), + exception_type=KeyError, + msg="Key 'zoo' is not in struct", + key="zoo", + ), + id="dict,struct:setitem_on_none_existing_key", + ), + pytest.param( + Expected( + create=lambda: DictConfig(key_type=Color, element_type=str, content={}), + op=lambda cfg: cfg.__setitem__("foo", "bar"), + exception_type=KeyValidationError, + msg="Key 'foo' is incompatible with the enum type 'Color', valid: [RED, GREEN, BLUE]", + full_key="foo", + key="foo", + ), + id="DictConfig[Color,str]:setitem_bad_key", + ), + pytest.param( + Expected( + create=lambda: DictConfig(key_type=str, element_type=Color, content={}), + op=lambda cfg: cfg.__setitem__("foo", "bar"), + exception_type=ValidationError, + msg="Invalid value 'bar', expected one of [RED, GREEN, BLUE]", + full_key="foo", + key="foo", + ), + id="DictConfig[str,Color]:setitem_bad_value", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(User), + op=lambda cfg: cfg.__setitem__("name", [1, 2]), + exception_type=ValidationError, + msg="Cannot convert 'list' to string : '[1, 2]'", + full_key="name", + key="name", + low_level=True, + ), + id="DictConfig[Any,Any]:setitem_stringnode_bad_value", + ), + # getitem + pytest.param( + Expected( + create=lambda: create_struct({"foo": "bar"}), + op=lambda cfg: cfg.__getitem__("zoo"), + exception_type=KeyError, + msg="Key 'zoo' is not in struct", + key="zoo", + ), + id="dict,struct:getitem_key_not_in_struct", + ), + pytest.param( + Expected( + create=lambda: DictConfig(key_type=Color, element_type=str, content={}), + op=lambda cfg: cfg.__getitem__("foo"), + exception_type=KeyValidationError, + msg="Key 'foo' is incompatible with the enum type 'Color', valid: [RED, GREEN, BLUE]", + key="foo", + num_lines=3, + ), + id="DictConfig[Color,str]:getitem_str_key", + ), + pytest.param( + Expected( + create=lambda: DictConfig(key_type=str, element_type=str, content={}), + op=lambda cfg: cfg.__getitem__(Color.RED), + exception_type=KeyValidationError, + msg="Key Color.RED (Color) is incompatible with (str)", + full_key="RED", + key=Color.RED, + ), + id="DictConfig[str,str]:getitem_color_key", + ), + pytest.param( + Expected( + create=lambda: create_readonly({"foo1": "bar"}), + op=lambda cfg: cfg.merge_with({"foo2": "bar"}), + exception_type=ReadonlyConfigError, + key="foo2", + msg="Cannot change read-only config container", + ), + id="dict,readonly:merge_with", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(ConcretePlugin), + op=lambda cfg: OmegaConf.merge(cfg, {"params": {"foo": "bar"}}), + exception_type=ValidationError, + msg="Value 'bar' could not be converted to Integer", + key="foo", + full_key="params.foo", + object_type=ConcretePlugin.FoobarParams, + child_node=lambda cfg: cfg.params.foo, + parent_node=lambda cfg: cfg.params, + ), + id="structured:merge,invalid_field_type", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(ConcretePlugin), + op=lambda cfg: OmegaConf.merge(cfg, {"params": {"zlonk": 10}}), + exception_type=ConfigKeyError, + msg="Key 'zlonk' not in 'FoobarParams'", + key="zlonk", + full_key="params.zlonk", + object_type=ConcretePlugin.FoobarParams, + parent_node=lambda cfg: cfg.params, + ), + id="structured:merge,adding_an_invalid_key", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(Package), + op=lambda cfg: OmegaConf.merge(cfg, {"modules": [{"foo": "var"}]}), + exception_type=ConfigKeyError, + msg="Key 'foo' not in 'Module'", + key="foo", + full_key="modules[0].foo", + object_type=Module, + low_level=True, + ), + id="structured:merge,bad_key_merge", + ), + # merge_with + pytest.param( + Expected( + create=lambda: OmegaConf.structured(ConcretePlugin), + op=lambda cfg: cfg.merge_with(Plugin), + exception_type=ValidationError, + msg="Plugin is not a subclass of ConcretePlugin. value: {'name': '???', 'params': '???'}", + object_type=ConcretePlugin, + ), + id="structured:merge_invalid_dataclass", + ), + # get + pytest.param( + Expected( + create=lambda: OmegaConf.create(), + op=lambda cfg: cfg.get(IllegalType), + exception_type=KeyValidationError, + msg="Incompatible key type 'type'", + key=IllegalType, + full_key="", + ), + id="dict:get_illegal_type", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create(), + op=lambda cfg: cfg.get(IllegalType()), + exception_type=KeyValidationError, + msg="Incompatible key type 'IllegalType'", + key=IllegalType(), + ), + id="dict:get_object_of_illegal_type", + ), + # dict:create + pytest.param( + Expected( + create=lambda: None, + op=lambda cfg: OmegaConf.structured(NotOptionalInt), + exception_type=ValidationError, + msg="Non optional field cannot be assigned None", + object_type_str=None, + ref_type_str=None, + ), + id="dict:create_none_optional_with_none", + ), + pytest.param( + Expected( + create=lambda: None, + op=lambda cfg: OmegaConf.structured(NotOptionalInt), + exception_type=ValidationError, + object_type=None, + msg="Non optional field cannot be assigned None", + object_type_str="NotOptionalInt", + ref_type_str=None, + ), + id="dict:create:not_optional_int_field_with_none", + ), + pytest.param( + Expected( + create=lambda: None, + op=lambda cfg: OmegaConf.structured(NotOptionalA), + exception_type=ValidationError, + object_type=None, + key=None, + full_key="x", + msg="field 'x' is not Optional", + object_type_str="NotOptionalInt", + ref_type_str=None, + ), + id="dict:create:not_optional_A_field_with_none", + ), + pytest.param( + Expected( + create=lambda: None, + op=lambda cfg: OmegaConf.structured(IllegalType), + exception_type=ValidationError, + msg="Input class 'IllegalType' is not a structured config. did you forget to decorate it as a dataclass?", + object_type_str=None, + ref_type_str=None, + ), + id="dict_create_from_illegal_type", + ), + pytest.param( + Expected( + create=lambda: None, + op=lambda cfg: OmegaConf.structured(IllegalType()), + exception_type=ValidationError, + msg="Object of unsupported type: 'IllegalType'", + object_type_str=None, + ref_type_str=None, + ), + id="structured:create_from_unsupported_object", + ), + pytest.param( + Expected( + create=lambda: None, + op=lambda cfg: OmegaConf.structured(UnionError), + exception_type=ValueError, + msg="Union types are not supported:\nx: Union[int, str]", + object_type_str=None, + ref_type_str=None, + num_lines=4, + ), + id="structured:create_with_union_error", + ), + # assign + pytest.param( + Expected( + create=lambda: DictConfig(ref_type=ConcretePlugin, content="???"), + op=lambda cfg: cfg._set_value(1), + exception_type=ValidationError, + msg="Invalid type assigned : int is not a subclass of ConcretePlugin. value: 1", + low_level=True, + ref_type=Optional[ConcretePlugin], + ), + id="dict:set_value:reftype_mismatch", + ), + pytest.param( + Expected( + create=lambda: DictConfig( + key_type=str, element_type=int, content={"foo": 10, "bar": 20} + ), + op=lambda cfg: cfg.__setitem__("baz", "fail"), + exception_type=ValidationError, + msg="Value 'fail' could not be converted to Integer", + key="baz", + ref_type=Optional[Dict[str, int]], + ), + id="DictConfig[str,int]:assigned_str_value", + ), + # delete + pytest.param( + Expected( + create=lambda: create_readonly({"foo": "bar"}), + op=lambda cfg: cfg.__delitem__("foo"), + exception_type=ReadonlyConfigError, + msg="DictConfig in read-only mode does not support deletion", + key="foo", + child_node=lambda cfg: cfg.foo, + ), + id="dict,readonly:del", + ), + pytest.param( + Expected( + create=lambda: create_struct({"foo": "bar"}), + op=lambda cfg: cfg.__delitem__("foo"), + exception_type=ConfigTypeError, + msg="DictConfig in struct mode does not support deletion", + key="foo", + child_node=lambda cfg: cfg.foo, + ), + id="dict,struct:del", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(User(name="bond")), + op=lambda cfg: cfg.__delitem__("name"), + exception_type=ConfigTypeError, + msg="User (DictConfig) does not support deletion", + object_type=User, + key="name", + child_node=lambda cfg: cfg.name, + ), + id="dict,structured:del", + ), + ############## + # ListConfig # + ############## + # getattr + pytest.param( + Expected( + create=lambda: OmegaConf.create([1, 2, 3]), + op=lambda cfg: setattr(cfg, "foo", 10), + exception_type=ConfigAttributeError, + key="foo", + full_key="[foo]", + msg="ListConfig does not support attribute access", + ), + id="list:setattr", + ), + # setattr + pytest.param( + Expected( + create=lambda: OmegaConf.create([1, 2, 3]), + op=lambda cfg: getattr(cfg, "foo"), + exception_type=ConfigAttributeError, + key="foo", + full_key="[foo]", + msg="ListConfig does not support attribute access", + ), + id="list:setattr", + ), + # get node + pytest.param( + Expected( + create=lambda: OmegaConf.create([1, 2, 3]), + op=lambda cfg: cfg._get_node("foo"), + exception_type=KeyValidationError, + key="foo", + full_key="[foo]", + msg="ListConfig indices must be integers or slices, not str", + ref_type=Optional[List[Any]], + ), + id="list:get_nox_ex:invalid_index_type", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create([1, 2, 3]), + op=lambda cfg: cfg._get_node(20), + exception_type=IndexError, + msg="list index out of range", + key=20, + full_key="[20]", + ), + id="list:get_node_ex:index_out_of_range", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content=None), + op=lambda cfg: cfg._get_node(20), + exception_type=TypeError, + msg="Cannot get_node from a ListConfig object representing None", + key=20, + full_key="[20]", + ref_type=Optional[List[Any]], + ), + id="list:get_node_none", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content="???"), + op=lambda cfg: cfg._get_node(20), + exception_type=MissingMandatoryValue, + msg="Cannot get_node from a missing ListConfig", + key=20, + full_key="[20]", + ), + id="list:get_node_missing", + ), + # list:create + pytest.param( + Expected( + create=lambda: None, + op=lambda cfg: ListConfig(is_optional=False, content=None), + exception_type=ValidationError, + object_type=None, + msg="Non optional ListConfig cannot be constructed from None", + object_type_str=None, + ref_type_str=None, + ), + id="list:create:not_optional_with_none", + ), + # append + pytest.param( + Expected( + create=lambda: OmegaConf.create([]), + op=lambda cfg: cfg.append(IllegalType()), + exception_type=UnsupportedValueType, + msg="Value 'IllegalType' is not a supported primitive type", + key=0, + full_key="[0]", + ), + id="list:append_value_of_illegal_type", + ), + # pop + pytest.param( + Expected( + create=lambda: create_readonly([1, 2, 3]), + op=lambda cfg: cfg.pop(0), + exception_type=ReadonlyConfigError, + msg="Cannot pop from read-only ListConfig", + key=0, + full_key="[0]", + child_node=lambda cfg: cfg[0], + ), + id="list:readonly:pop", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create([1, 2, 3]), + op=lambda cfg: cfg.pop("Invalid_key_type"), + exception_type=ConfigTypeError, + msg="ListConfig indices must be integers or slices, not str", + key="Invalid_key_type", + full_key="[Invalid_key_type]", + ), + id="list:pop_invalid_key", + ), + pytest.param( + Expected( + create=lambda: create_struct({"foo": "bar"}), + op=lambda cfg: cfg.pop("foo"), + exception_type=ConfigTypeError, + msg="DictConfig in struct mode does not support pop", + key="foo", + child_node=lambda cfg: cfg.foo, + ), + id="dict,struct:pop", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.structured(ConcretePlugin), + op=lambda cfg: cfg.pop("name"), + exception_type=ConfigTypeError, + msg="ConcretePlugin (DictConfig) does not support pop", + key="name", + child_node=lambda cfg: cfg.name, + ), + id="dict,structured:pop", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content=None), + op=lambda cfg: cfg.pop(0), + exception_type=TypeError, + msg="Cannot pop from a ListConfig object representing None", + key=0, + full_key="[0]", + ), + id="list:pop_from_none", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content="???"), + op=lambda cfg: cfg.pop(0), + exception_type=MissingMandatoryValue, + msg="Cannot pop from a missing ListConfig", + key=0, + full_key="[0]", + ), + id="list:pop_from_missing", + ), + # getitem + pytest.param( + Expected( + create=lambda: OmegaConf.create(["???"]), + op=lambda cfg: cfg.__getitem__(slice(0, 1)), + exception_type=MissingMandatoryValue, + msg="Missing mandatory value: [0:1]", + key=slice(0, 1), + full_key="[0:1]", + child_node=lambda cfg: cfg._get_node(slice(0, 1)), + ), + id="list:subscript_slice_with_missing", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create([10, "???"]), + op=lambda cfg: cfg.__getitem__(1), + exception_type=MissingMandatoryValue, + msg="Missing mandatory value: [1]", + key=1, + full_key="[1]", + child_node=lambda cfg: cfg._get_node(1), + ), + id="list:subscript_index_with_missing", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create([1, 2, 3]), + op=lambda cfg: cfg.__getitem__(20), + exception_type=IndexError, + msg="list index out of range", + key=20, + full_key="[20]", + ), + id="list:subscript:index_out_of_range", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create([1, 2, 3]), + op=lambda cfg: cfg.__getitem__("foo"), + exception_type=KeyValidationError, + msg="ListConfig indices must be integers or slices, not str", + key="foo", + full_key="[foo]", + ), + id="list:getitem,illegal_key_type", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content=None), + op=lambda cfg: cfg.__getitem__(0), + exception_type=TypeError, + msg="ListConfig object representing None is not subscriptable", + key=0, + full_key="[0]", + ), + id="list:getitem,illegal_key_type", + ), + # setitem + pytest.param( + Expected( + create=lambda: OmegaConf.create([None]), + op=lambda cfg: cfg.__setitem__(0, IllegalType()), + exception_type=UnsupportedValueType, + msg="Value 'IllegalType' is not a supported primitive type", + key=0, + full_key="[0]", + ), + id="list:setitem,illegal_value_type", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create([1, 2, 3]), + op=lambda cfg: cfg.__setitem__("foo", 4), + exception_type=KeyValidationError, + msg="ListConfig indices must be integers or slices, not str", + key="foo", + full_key="[foo]", + ), + id="list:setitem,illegal_key_type", + ), + pytest.param( + Expected( + create=lambda: create_readonly([1, 2, 3]), + op=lambda cfg: cfg.__setitem__(0, 4), + exception_type=ReadonlyConfigError, + msg="ListConfig is read-only", + key=0, + full_key="[0]", + child_node=lambda cfg: cfg[0], + ), + id="list,readonly:setitem", + ), + # _set_value + pytest.param( + Expected( + create=lambda: ListConfig(is_optional=False, element_type=int, content=[]), + op=lambda cfg: cfg._set_value(None), + exception_type=ValidationError, + object_type=None, + msg="Non optional ListConfig cannot be constructed from None", + ref_type=List[int], + low_level=True, + ), + id="list:create_not_optional:_set_value(None)", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content=[1, 2]), + op=lambda cfg: cfg._set_value(True), + exception_type=ValidationError, + object_type=None, + msg="Invalid value assigned : bool is not a subclass of ListConfig or list", + ref_type=List[int], + low_level=True, + ), + id="list:create_not_optional:_set_value(True)", + ), + # assign + pytest.param( + Expected( + create=lambda: ListConfig(element_type=int, content=[1, 2, 3]), + op=lambda cfg: cfg.__setitem__(0, "foo"), + exception_type=ValidationError, + msg="Value 'foo' could not be converted to Integer", + key=0, + full_key="[0]", + child_node=lambda cfg: cfg[0], + ref_type=Optional[List[int]], + ), + id="list,int_elements:assigned_str_element", + ), + pytest.param( + Expected( + # make sure OmegaConf.create is not losing critical metadata. + create=lambda: OmegaConf.create( + ListConfig(element_type=int, content=[1, 2, 3]) + ), + op=lambda cfg: cfg.__setitem__(0, "foo"), + exception_type=ValidationError, + msg="Value 'foo' could not be converted to Integer", + key=0, + full_key="[0]", + child_node=lambda cfg: cfg[0], + ref_type=Optional[List[int]], + ), + id="list,int_elements:assigned_str_element", + ), + pytest.param( + Expected( + create=lambda: OmegaConf.create( + [IntegerNode(is_optional=False, value=0), 2, 3] + ), + op=lambda cfg: cfg.__setitem__(0, None), + exception_type=ValidationError, + msg="[0] is not optional and cannot be assigned None", + key=0, + full_key="[0]", + child_node=lambda cfg: cfg[0], + ref_type=Optional[List[Any]], + ), + id="list,not_optional:null_assignment", + ), + # index + pytest.param( + Expected( + create=lambda: create_readonly([1, 2, 3]), + op=lambda cfg: cfg.index(99), + exception_type=ConfigValueError, + msg="Item not found in ListConfig", + ), + id="list,readonly:index_not_found", + ), + # insert + pytest.param( + Expected( + create=lambda: create_readonly([1, 2, 3]), + op=lambda cfg: cfg.insert(1, 99), + exception_type=ReadonlyConfigError, + msg="Cannot insert into a read-only ListConfig", + key=1, + full_key="[1]", + child_node=lambda cfg: cfg[1], + ), + id="list,readonly:insert", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content=None), + op=lambda cfg: cfg.insert(1, 99), + exception_type=ConfigTypeError, + msg="Cannot insert into ListConfig object representing None", + key=1, + full_key="[1]", + ), + id="list:insert_into_none", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content="???"), + op=lambda cfg: cfg.insert(1, 99), + exception_type=MissingMandatoryValue, + msg="Cannot insert into missing ListConfig", + key=1, + full_key="[1]", + child_node=lambda _cfg: None, + ref_type=Optional[List[Any]], + ), + id="list:insert_into_missing", + ), + # get + pytest.param( + Expected( + create=lambda: ListConfig(content=None), + op=lambda cfg: cfg.get(0), + exception_type=TypeError, + msg="Cannot get from a ListConfig object representing None", + key=0, + full_key="[0]", + ref_type=Optional[List[Any]], + ), + id="list:get_from_none", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content="???"), + op=lambda cfg: cfg.get(0), + exception_type=MissingMandatoryValue, + msg="Cannot get from a missing ListConfig", + key=0, + full_key="[0]", + ), + id="list:get_from_missing", + ), + # sort + pytest.param( + Expected( + create=lambda: create_readonly([1, 2, 3]), + op=lambda cfg: cfg.sort(), + exception_type=ReadonlyConfigError, + msg="Cannot sort a read-only ListConfig", + ), + id="list:readonly:sort", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content=None), + op=lambda cfg: cfg.sort(), + exception_type=TypeError, + msg="Cannot sort a ListConfig object representing None", + ), + id="list:sort_from_none", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content="???"), + op=lambda cfg: cfg.sort(), + exception_type=MissingMandatoryValue, + msg="Cannot sort a missing ListConfig", + ), + id="list:sort_from_missing", + ), + # # iter + pytest.param( + Expected( + create=lambda: create_readonly([1, 2, 3]), + op=lambda cfg: cfg.sort(), + exception_type=ReadonlyConfigError, + msg="Cannot sort a read-only ListConfig", + ), + id="list:readonly:sort", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content=None), + op=lambda cfg: iter(cfg), + exception_type=TypeError, + msg="Cannot iterate a ListConfig object representing None", + ), + id="list:iter_none", + ), + pytest.param( + Expected( + create=lambda: ListConfig(content="???"), + op=lambda cfg: iter(cfg), + exception_type=MissingMandatoryValue, + msg="Cannot iterate a missing ListConfig", + ), + id="list:iter_missing", + ), + # delete + pytest.param( + Expected( + create=lambda: create_readonly([1, 2, 3]), + op=lambda cfg: cfg.__delitem__(0), + exception_type=ReadonlyConfigError, + msg="Cannot delete item from read-only ListConfig", + key=0, + full_key="[0]", + child_node=lambda cfg: cfg._get_node(0), + ), + id="list,readonly:del", + ), +] + + +def create_struct(cfg: Any) -> Any: + cfg = OmegaConf.create(cfg) + OmegaConf.set_struct(cfg, True) + return cfg + + +def create_readonly(cfg: Any) -> Any: + cfg = OmegaConf.create(cfg) + OmegaConf.set_readonly(cfg, True) + return cfg + + +@pytest.mark.parametrize( # type:ignore + "expected", params +) +def test_errors(expected: Expected, monkeypatch: Any) -> None: + monkeypatch.setenv("OC_CAUSE", "0") + cfg = expected.create() + expected.finalize(cfg) + msg = expected.msg + with pytest.raises(expected.exception_type, match=re.escape(msg)) as einfo: + try: + expected.op(cfg) + except Exception as e: + # helps in debugging + raise e + ex = einfo.value + + assert ex.object_type == expected.object_type + assert ex.key == expected.key + if not expected.low_level: + if isinstance(ex, OmegaConfBaseException): + assert str(ex).count("\n") == expected.num_lines + assert ex.parent_node == expected.parent_node(cfg) + assert ex.child_node == expected.child_node(cfg) + assert ex.full_key == expected.full_key + assert isinstance(expected.full_key, str) + + if expected.ref_type is not None: + assert ex.ref_type == expected.ref_type + + if expected.object_type is not None: + assert ex.object_type == expected.object_type + + with monkeypatch.context() as m: + m.setenv("OC_CAUSE", "1") + try: + expected.op(cfg) + except Exception as e: + assert e.__cause__ is not None + + with monkeypatch.context() as m: + m.setenv("OC_CAUSE", "0") + try: + expected.op(cfg) + except Exception as e: + assert e.__cause__ is None diff --git a/tests/test_get_full_key.py b/tests/test_get_full_key.py new file mode 100644 index 0000000000000000000000000000000000000000..1aef2a1041aaefbe485eb4b9139316cd2efe04ac --- /dev/null +++ b/tests/test_get_full_key.py @@ -0,0 +1,116 @@ +from typing import Any + +import pytest + +from omegaconf import DictConfig, IntegerNode, OmegaConf + +from . import Color + + +@pytest.mark.parametrize( # type: ignore + "cfg, select, key, expected", + [ + ({}, "", "a", "a"), + # 1 + # dict + ({"a": 1}, "", "a", "a"), + ({"a": 1}, "", "bad", "bad"), + # dict empty key + ({"a": 1}, "", "", ""), + ({"a": 1}, "", "bad", "bad"), + # list + ([1, 2, 3], "", "2", "[2]"), + ([1, 2, 3], "", "999", "[999]"), + # list empty key + ([1, 2, 3], "", "", ""), + ([1, 2, 3], "", "999", "[999]"), + # 2 + # dd + ({"a": 1, "b": {"c": 1}}, "b", "c", "b.c"), + ({"a": 1, "b": {"c": 1}}, "b", "bad", "b.bad"), + # dl + ({"a": [1, 2, 3]}, "a", 1, "a[1]"), + ({"a": [1, 2, 3]}, "a", 999, "a[999]"), + # ll + ([[1, 2, 3]], "0", "2", "[0][2]"), + ([[1, 2, 3]], "0", "999", "[0][999]"), + # ld + ([1, 2, {"a": 1}], "2", "a", "[2].a"), + ([1, 2, {"a": 1}], "2", "bad", "[2].bad"), + # dd empty key + ({"a": 1, "b": {"c": 1}}, "b", "", "b"), + ({"a": 1, "b": {"c": 1}}, "b", "bad", "b.bad"), + # 3 + # ddd + ({"a": {"b": {"c": 1}}}, "a.b", "c", "a.b.c"), + ({"a": {"b": {"c": 1}}}, "a.b", "bad", "a.b.bad"), + # ddl + ({"a": {"b": [0, 1]}}, "a.b", 0, "a.b[0]"), + ({"a": {"b": [0, 1]}}, "a.b", 999, "a.b[999]"), + # dll + ({"a": [1, [2]]}, "a.1", 0, "a[1][0]"), + ({"a": [1, [2]]}, "a.1", 999, "a[1][999]"), + # dld + ({"a": [{"b": 2}]}, "a.0", "b", "a[0].b"), + ({"a": [{"b": 2}]}, "a.0", "bad", "a[0].bad"), + # ldd + ([{"a": {"b": 1}}], "0.a", "b", "[0].a.b"), + ([{"a": {"b": 1}}], "0.a", "bad", "[0].a.bad"), + # ldl + ([{"a": [0]}], "0.a", 0, "[0].a[0]"), + ([{"a": [0]}], "0.a", 999, "[0].a[999]"), + # lld + ([[{"a": 1}]], "0.0", "a", "[0][0].a"), + ([[{"a": 1}]], "0.0", "bad", "[0][0].bad"), + # lll + ([[[0]]], "0.0", 0, "[0][0][0]"), + # lldddl + ([[{"a": {"a": [0]}}]], "0.0.a.a", 0, "[0][0].a.a[0]"), + # special cases + # parent_with_missing_item + ({"x": "???", "a": 1, "b": {"c": 1}}, "b", "c", "b.c"), + ({"foo": IntegerNode(value=10)}, "", "foo", "foo"), + ({"foo": {"bar": IntegerNode(value=10)}}, "foo", "bar", "foo.bar"), + # enum + pytest.param( + DictConfig(key_type=Color, element_type=str, content={Color.RED: "red"}), + "RED", + "", + "RED", + id="get_full_key_with_enum_key", + ), + pytest.param( + { + "foo": DictConfig( + key_type=Color, element_type=str, content={Color.RED: "red"} + ) + }, + "foo", + "RED", + "foo.RED", + id="get_full_key_with_nested_enum_key", + ), + # slice + ([1, 2, 3], "", slice(0, 1), "[0:1]"), + ([1, 2, 3], "", slice(0, 1, 2), "[0:1:2]"), + ], +) +def test_get_full_key_from_config( + cfg: Any, select: str, key: Any, expected: Any +) -> None: + c = OmegaConf.create(cfg) + _root, _last_key, node = c._select_impl( + select, throw_on_missing=True, throw_on_resolution_failure=True + ) + assert node is not None + assert node._get_full_key(key) == expected + + +def test_value_node_get_full_key() -> None: + cfg = OmegaConf.create({"foo": IntegerNode(value=10)}) + assert cfg._get_node("foo")._get_full_key(None) == "foo" # type: ignore + + node = IntegerNode(value=10) + assert node._get_full_key(None) == "" + node = IntegerNode(key="foo", value=10) + assert node._get_full_key(None) == "foo" diff --git a/tests/test_interpolation.py b/tests/test_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..7193e52f2cf374a724ae74e6c679e8a96c0addc7 --- /dev/null +++ b/tests/test_interpolation.py @@ -0,0 +1,433 @@ +import os +import random +import re +from typing import Any, Dict + +import pytest + +from omegaconf import ( + DictConfig, + IntegerNode, + ListConfig, + OmegaConf, + Resolver, + ValidationError, +) + + +def test_str_interpolation_dict_1() -> None: + # Simplest str_interpolation + c = OmegaConf.create(dict(a="${referenced}", referenced="bar")) + assert c.referenced == "bar" + assert c.a == "bar" + + +def test_str_interpolation_key_error_1() -> None: + # Test that a KeyError is thrown if an str_interpolation key is not available + c = OmegaConf.create(dict(a="${not_found}")) + + with pytest.raises(KeyError): + _ = c.a + + +def test_str_interpolation_key_error_2() -> None: + # Test that a KeyError is thrown if an str_interpolation key is not available + c = OmegaConf.create(dict(a="${not.found}")) + + with pytest.raises(KeyError): + c.a + + +def test_str_interpolation_3() -> None: + # Test that str_interpolation works with complex strings + c = OmegaConf.create(dict(a="the year ${year}", year="of the cat")) + + assert c.a == "the year of the cat" + + +def test_str_interpolation_4() -> None: + # Test that a string with multiple str_interpolations works + c = OmegaConf.create( + dict(a="${ha} ${ha} ${ha}, said Pennywise, ${ha} ${ha}... ${ha}!", ha="HA") + ) + + assert c.a == "HA HA HA, said Pennywise, HA HA... HA!" + + +def test_deep_str_interpolation_1() -> None: + # Test deep str_interpolation works + c = OmegaConf.create( + dict( + a="the answer to the universe and everything is ${nested.value}", + nested=dict(value=42), + ) + ) + + assert c.a == "the answer to the universe and everything is 42" + + +def test_deep_str_interpolation_2() -> None: + # Test that str_interpolation of a key that is nested works + c = OmegaConf.create( + dict( + out=42, + deep=dict(inside="the answer to the universe and everything is ${out}"), + ) + ) + + assert c.deep.inside == "the answer to the universe and everything is 42" + + +def test_simple_str_interpolation_inherit_type() -> None: + # Test that str_interpolation of a key that is nested works + c = OmegaConf.create( + dict( + inter1="${answer1}", + inter2="${answer2}", + inter3="${answer3}", + inter4="${answer4}", + answer1=42, + answer2=42.0, + answer3=False, + answer4="string", + ) + ) + + assert type(c.inter1) == int + assert type(c.inter2) == float + assert type(c.inter3) == bool + assert type(c.inter4) == str + + +def test_complex_str_interpolation_is_always_str_1() -> None: + c = OmegaConf.create(dict(two=2, four=4, inter1="${four}${two}", inter2="4${two}")) + + assert type(c.inter1) == str + assert c.inter1 == "42" + assert type(c.inter2) == str + assert c.inter2 == "42" + + +@pytest.mark.parametrize( # type: ignore + "input_,key,expected", + [ + (dict(a=10, b="${a}"), "b", 10), + (dict(a=10, b=[1, "${a}", 3, 4]), "b.1", 10), + (dict(a="${b.1}", b=[1, dict(c=10), 3, 4]), "a", dict(c=10)), + (dict(a="${b}", b=[1, 2]), "a", [1, 2]), + (dict(a="foo-${b}", b=[1, 2]), "a", "foo-[1, 2]"), + (dict(a="foo-${b}", b=dict(c=10)), "a", "foo-{'c': 10}"), + ], +) +def test_interpolation(input_: Dict[str, Any], key: str, expected: str) -> None: + c = OmegaConf.create(input_) + assert OmegaConf.select(c, key) == expected + + +def test_2_step_interpolation() -> None: + c = OmegaConf.create(dict(src="bar", copy_src="${src}", copy_copy="${copy_src}")) + assert c.copy_src == "bar" + assert c.copy_copy == "bar" + + +def test_env_interpolation1() -> None: + try: + os.environ["foobar"] = "1234" + c = OmegaConf.create({"path": "/test/${env:foobar}"}) + assert c.path == "/test/1234" + finally: + del os.environ["foobar"] + + +def test_env_interpolation_not_found() -> None: + c = OmegaConf.create({"path": "/test/${env:foobar}"}) + with pytest.raises( + ValidationError, match=re.escape("Environment variable 'foobar' not found") + ): + c.path + + +def test_env_default_str_interpolation_missing_env() -> None: + if os.getenv("foobar") is not None: + del os.environ["foobar"] + c = OmegaConf.create({"path": "/test/${env:foobar,abc}"}) + assert c.path == "/test/abc" + + +def test_env_default_interpolation_missing_env_default_with_slash() -> None: + if os.getenv("foobar") is not None: + del os.environ["foobar"] + c = OmegaConf.create({"path": "${env:DATA_PATH,a/b}"}) + assert c.path == "a/b" + + +def test_env_default_interpolation_env_exist() -> None: + os.environ["foobar"] = "1234" + c = OmegaConf.create({"path": "/test/${env:foobar,abc}"}) + assert c.path == "/test/1234" + + +@pytest.mark.parametrize( # type: ignore + "value,expected", + [ + # bool + ("false", False), + ("true", True), + # int + ("10", 10), + ("-10", -10), + # float + ("10.0", 10.0), + ("-10.0", -10.0), + # strings + ("off", "off"), + ("no", "no"), + ("on", "on"), + ("yes", "yes"), + (">1234", ">1234"), + (":1234", ":1234"), + ("/1234", "/1234"), + # yaml strings are not getting parsed by the env resolver + ("foo: bar", "foo: bar"), + ("foo: \n - bar\n - baz", "foo: \n - bar\n - baz"), + ], +) +def test_env_values_are_typed(value: Any, expected: Any) -> None: + try: + os.environ["my_key"] = value + c = OmegaConf.create(dict(my_key="${env:my_key}")) + assert c.my_key == expected + finally: + del os.environ["my_key"] + + +def test_register_resolver_twice_error(restore_resolvers: Any) -> None: + def foo() -> int: + return 10 + + OmegaConf.register_resolver("foo", foo) + with pytest.raises(AssertionError): + OmegaConf.register_resolver("foo", lambda: 10) + + +def test_clear_resolvers(restore_resolvers: Any) -> None: + assert OmegaConf.get_resolver("foo") is None + OmegaConf.register_resolver("foo", lambda x: int(x) + 10) + assert OmegaConf.get_resolver("foo") is not None + OmegaConf.clear_resolvers() + assert OmegaConf.get_resolver("foo") is None + + +def test_register_resolver_1(restore_resolvers: Any) -> None: + OmegaConf.register_resolver("plus_10", lambda x: int(x) + 10) + c = OmegaConf.create(dict(k="${plus_10:990}")) + + assert type(c.k) == int + assert c.k == 1000 + + +def test_resolver_cache_1(restore_resolvers: Any) -> None: + # resolvers are always converted to stateless idempotent functions + # subsequent calls to the same function with the same argument will always return the same value. + # this is important to allow embedding of functions like time() without having the value change during + # the program execution. + OmegaConf.register_resolver("random", lambda _: random.randint(0, 10000000)) + c = OmegaConf.create(dict(k="${random:_}")) + assert c.k == c.k + + +def test_resolver_cache_2(restore_resolvers: Any) -> None: + """ + Tests that resolver cache is not shared between different OmegaConf objects + """ + OmegaConf.register_resolver("random", lambda _: random.randint(0, 10000000)) + c1 = OmegaConf.create(dict(k="${random:_}")) + c2 = OmegaConf.create(dict(k="${random:_}")) + assert c1.k != c2.k + assert c1.k == c1.k + assert c2.k == c2.k + + +@pytest.mark.parametrize( # type: ignore + "resolver,name,key,result", + [ + (lambda *args: args, "arg_list", "${my_resolver:cat, dog}", ("cat", "dog")), + ( + lambda *args: args, + "escape_comma", + "${my_resolver:cat\\, do g}", + ("cat, do g",), + ), + ( + lambda *args: args, + "escape_whitespace", + "${my_resolver:cat\\, do g}", + ("cat, do g",), + ), + (lambda: "zero", "zero_arg", "${my_resolver:}", "zero"), + ], +) +def test_resolver_that_allows_a_list_of_arguments( + restore_resolvers: Any, resolver: Resolver, name: str, key: str, result: Any +) -> None: + OmegaConf.register_resolver("my_resolver", resolver) + c = OmegaConf.create({name: key}) + assert isinstance(c, DictConfig) + assert c[name] == result + + +def test_copy_cache(restore_resolvers: Any) -> None: + OmegaConf.register_resolver("random", lambda _: random.randint(0, 10000000)) + d = {"k": "${random:_}"} + c1 = OmegaConf.create(d) + assert c1.k == c1.k + + c2 = OmegaConf.create(d) + assert c2.k != c1.k + OmegaConf.set_cache(c2, OmegaConf.get_cache(c1)) + assert c2.k == c1.k + + c3 = OmegaConf.create(d) + + assert c3.k != c1.k + OmegaConf.copy_cache(c1, c3) + assert c3.k == c1.k + + +def test_clear_cache(restore_resolvers: Any) -> None: + OmegaConf.register_resolver("random", lambda _: random.randint(0, 10000000)) + c = OmegaConf.create(dict(k="${random:_}")) + old = c.k + OmegaConf.clear_cache(c) + assert old != c.k + + +def test_supported_chars() -> None: + supported_chars = "%_-abc123." + c = OmegaConf.create(dict(dir1="${copy:" + supported_chars + "}")) + + OmegaConf.register_resolver("copy", lambda x: x) + assert c.dir1 == supported_chars + + +def test_interpolation_in_list_key_error() -> None: + # Test that a KeyError is thrown if an str_interpolation key is not available + c = OmegaConf.create(["${10}"]) + assert isinstance(c, ListConfig) + + with pytest.raises(KeyError): + c[0] + + +def test_unsupported_interpolation_type() -> None: + c = OmegaConf.create(dict(foo="${wrong_type:ref}")) + + with pytest.raises(ValueError): + c.foo + + +def test_incremental_dict_with_interpolation() -> None: + conf = OmegaConf.create() + assert isinstance(conf, DictConfig) + conf.a = 1 + conf.b = OmegaConf.create() + assert isinstance(conf.b, DictConfig) + conf.b.c = "${a}" + assert conf.b.c == conf.a # type: ignore + + +@pytest.mark.parametrize( # type: ignore + "cfg,key,expected", + [ + ({"a": 10, "b": "${a}"}, "b", 10), + ({"a": 10, "b": "${a}", "c": "${b}"}, "c", 10), + ({"bar": 10, "foo": ["${bar}"]}, "foo.0", 10), + ({"foo": None, "bar": "${foo}"}, "bar", None), + ({"list": ["bar"], "foo": "${list.0}"}, "foo", "bar"), + ({"list": ["${ref}"], "ref": "bar"}, "list.0", "bar"), + ], +) +def test_interpolations(cfg: DictConfig, key: str, expected: Any) -> None: + c = OmegaConf.create(cfg) + assert OmegaConf.select(c, key) == expected + + +def test_interpolation_with_missing() -> None: + cfg = OmegaConf.create({"out_file": "${x.name}.txt", "x": {"name": "???"}}) + assert OmegaConf.is_missing(cfg, "out_file") + + +def test_assign_to_interpolation() -> None: + cfg = OmegaConf.create( + {"foo": 10, "bar": "${foo}", "typed_bar": IntegerNode("${foo}")} + ) + assert OmegaConf.is_interpolation(cfg, "bar") + assert cfg.bar == 10 + assert cfg.typed_bar == 10 + + # assign regular field + cfg.bar = 20 + assert not OmegaConf.is_interpolation(cfg, "bar") + + with pytest.raises(ValidationError): + cfg.typed_bar = "nope" + cfg.typed_bar = 30 + + assert cfg.foo == 10 + assert cfg.bar == 20 + assert cfg.typed_bar == 30 + + +def test_merge_with_interpolation() -> None: + cfg = OmegaConf.create( + {"foo": 10, "bar": "${foo}", "typed_bar": IntegerNode("${foo}")} + ) + + assert OmegaConf.merge(cfg, {"bar": 20}) == {"foo": 10, "bar": 20, "typed_bar": 10} + assert OmegaConf.merge(cfg, {"typed_bar": 30}) == { + "foo": 10, + "bar": 10, + "typed_bar": 30, + } + + with pytest.raises(ValidationError): + OmegaConf.merge(cfg, {"typed_bar": "nope"}) + + +def test_non_container_interpolation() -> None: + cfg = OmegaConf.create(dict(foo=0, bar="${foo.baz}")) + with pytest.raises(AssertionError): + cfg.bar + + +def test_indirect_interpolation() -> None: + d = { + "a": {"aa": 10}, + "b": "${a}", + "c": "${b.aa}", + } + + cfg = OmegaConf.create(d) + assert cfg.c == 10 + assert OmegaConf.to_container(cfg, resolve=True) == { + "a": {"aa": 10}, + "b": {"aa": 10}, + "c": 10, + } + + +def test_indirect_interpolation2() -> None: + d = { + "a": {"aa": 10}, + "b": "${a.aa}", + "c": "${b}", + } + + cfg = OmegaConf.create(d) + assert cfg.c == 10 + + assert OmegaConf.to_container(cfg, resolve=True) == { + "a": {"aa": 10}, + "b": 10, + "c": 10, + } diff --git a/tests/test_matrix.py b/tests/test_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..4cdc21dc243ddd990372f17c8b141ccf6ec34123 --- /dev/null +++ b/tests/test_matrix.py @@ -0,0 +1,379 @@ +import copy +import re +from typing import Any + +import pytest + +from omegaconf import ( + BooleanNode, + DictConfig, + EnumNode, + FloatNode, + IntegerNode, + ListConfig, + OmegaConf, + StringNode, + ValidationError, + ValueNode, +) + +from . import Color, Group + +SKIP = object() + + +def verify( + cfg: Any, + key: Any, + none: bool, + opt: bool, + missing: bool, + inter: bool, + exp: Any = SKIP, +) -> None: + target_node = cfg._get_node(key) + assert target_node._key() == key + assert target_node._is_none() == none + assert target_node._is_optional() == opt + assert target_node._is_missing() == missing + assert target_node._is_interpolation() == inter + + if exp is not SKIP: + assert cfg.get(key) == exp + + assert OmegaConf.is_missing(cfg, key) == missing + assert OmegaConf.is_none(cfg, key) == none + assert OmegaConf.is_optional(cfg, key) == opt + assert OmegaConf.is_interpolation(cfg, key) == inter + + +# for each type Node type : int, bool, str, float, Color (enum) and User (@dataclass), DictConfig, ListConfig +# for each MISSING, None, Optional and interpolation: +@pytest.mark.parametrize( + "node_type, values", + [ + (BooleanNode, [True, False]), + (FloatNode, [3.1415]), + (IntegerNode, [42]), + (StringNode, ["hello"]), + # EnumNode + ( + lambda value, is_optional, key=None: EnumNode( + enum_type=Color, value=value, is_optional=is_optional, key=key + ), + [Color.RED], + ), + # DictConfig + ( + lambda value, is_optional, key=None: DictConfig( + is_optional=is_optional, content=value, key=key + ), + [{}, {"foo": "bar"}], + ), + # ListConfig + ( + lambda value, is_optional, key=None: ListConfig( + is_optional=is_optional, content=value, key=key + ), + [[], [1, 2, 3]], + ), + # dataclass + ( + lambda value, is_optional, key=None: DictConfig( + ref_type=Group, is_optional=is_optional, content=value, key=key + ), + [Group, Group()], + ), + ], + ids=( + "BooleanNode", + "FloatNode", + "IntegerNode", + "StringNode", + "EnumNode", + "DictConfig", + "ListConfig", + "dataclass", + ), +) +class TestNodeTypesMatrix: + def test_none_assignment_and_merging_in_dict( + self, node_type: Any, values: Any + ) -> None: + values = copy.deepcopy(values) + for value in values: + node = node_type(value=value, is_optional=False) + data = {"node": node} + cfg = OmegaConf.create(obj=data) + verify(cfg, "node", none=False, opt=False, missing=False, inter=False) + msg = "child 'node' is not Optional" + with pytest.raises(ValidationError, match=re.escape(msg)): + cfg.node = None + + with pytest.raises(ValidationError): + OmegaConf.merge(cfg, {"node": None}) + + def test_dict_non_none_assignment(self, node_type: Any, values: Any) -> None: + values = copy.deepcopy(values) + for value in values: + value_backup = copy.deepcopy(value) + cfg = OmegaConf.create({"node": node_type(value=None, is_optional=True)}) + verify(cfg, "node", none=True, opt=True, missing=False, inter=False) + + cfg.node = value + assert cfg._get_node("node") == value + verify(cfg, "node", none=False, opt=True, missing=False, inter=False) + + cfg.node = "???" + verify(cfg, "node", none=False, opt=True, missing=True, inter=False) + + cfg.node = value_backup + assert cfg._get_node("node") == value_backup + verify(cfg, "node", none=False, opt=True, missing=False, inter=False) + + def test_none_assignment_in_list(self, node_type: Any, values: Any) -> None: + values = copy.deepcopy(values) + for value in values: + key = 0 + d = node_type(value=value, key=key, is_optional=False) + cfg = OmegaConf.create([d]) + verify(cfg, key, none=False, opt=False, missing=False, inter=False) + + with pytest.raises(ValidationError): + cfg[key] = None + + def test_list_non_none_assignment(self, node_type: Any, values: Any) -> None: + values = copy.deepcopy(values) + for value in values: + key = 0 + cfg = OmegaConf.create([node_type(value=None, key=key, is_optional=True)]) + verify(cfg, key, none=True, opt=True, missing=False, inter=False) + + cfg[key] = value + assert cfg[key] == value + verify(cfg, key, none=False, opt=True, missing=False, inter=False) + + def test_none_construction(self, node_type: Any, values: Any) -> None: + values = copy.deepcopy(values) + node = node_type(value=None, is_optional=True) + if isinstance(node, ValueNode): + assert node._value() is None + assert node._is_optional() + assert node.__eq__(None) + assert OmegaConf.is_none(node) + + for value in values: + node._set_value(value) + assert node.__eq__(value) + assert not node.__eq__(None) + assert not OmegaConf.is_none(node) + + with pytest.raises(ValidationError): + node_type(value=None, is_optional=False) + + def test_interpolation( + self, node_type: Any, values: Any, restore_resolvers: Any + ) -> None: + resolver_output = 9999 + OmegaConf.register_resolver("func", lambda: resolver_output) + values = copy.deepcopy(values) + for value in values: + node = { + "reg": node_type(value=value, is_optional=False), + "opt": node_type(value=value, is_optional=True), + } + cfg = OmegaConf.create( + { + "const": 10, + "primitive_missing": "???", + "resolver": StringNode(value="${func:}", is_optional=False), + "opt_resolver": StringNode(value="${func:}", is_optional=True), + "node": DictConfig(content=node, is_optional=False), + "opt_node": DictConfig(content=node, is_optional=True), + "reg": node_type(value=value, is_optional=False), + "opt": node_type(value=value, is_optional=True), + "opt_none": node_type(value=None, is_optional=True), + "missing": node_type(value="???", is_optional=False), + "opt_missing": node_type(value="???", is_optional=True), + # Interpolations + "int_reg": "${reg}", + "int_opt": "${opt}", + "int_opt_none": "${opt_none}", + "int_missing": "${missing}", + "int_opt_missing": "${opt_missing}", + "str_int_const": StringNode( + value="foo_${const}", is_optional=False + ), + "opt_str_int_const": StringNode( + value="foo_${const}", is_optional=True + ), + "str_int_with_primitive_missing": StringNode( + value="foo_${primitive_missing}", is_optional=False + ), + "opt_str_int_with_primitive_missing": StringNode( + value="foo_${primitive_missing}", is_optional=True + ), + "int_node": "${node}", + "int_opt_node": "${opt_node}", + "int_resolver": "${resolver}", + "int_opt_resolver": "${opt_resolver}", + } + ) + + verify( + cfg, "const", none=False, opt=True, missing=False, inter=False, exp=10 + ) + + verify( + cfg, + "resolver", + none=False, + # Note, resolvers are always optional because the underlying function may return None + opt=True, + missing=False, + inter=True, + exp=resolver_output, + ) + + verify( + cfg, + "opt_resolver", + none=False, + opt=True, + missing=False, + inter=True, + exp=resolver_output, + ) + + verify( + cfg, + "reg", + none=False, + opt=False, + missing=False, + inter=False, + exp=value, + ) + + verify( + cfg, "opt", none=False, opt=True, missing=False, inter=False, exp=value + ) + verify( + cfg, + "opt_none", + none=True, + opt=True, + missing=False, + inter=False, + exp=None, + ) + verify(cfg, "missing", none=False, opt=False, missing=True, inter=False) + verify(cfg, "opt_missing", none=False, opt=True, missing=True, inter=False) + + verify( + cfg, + "int_reg", + none=False, + opt=False, + missing=False, + inter=True, + exp=value, + ) + verify( + cfg, + "int_opt", + none=False, + opt=True, + missing=False, + inter=True, + exp=value, + ) + verify( + cfg, + "int_opt_none", + none=True, + opt=True, + missing=False, + inter=True, + exp=None, + ) + verify(cfg, "int_missing", none=False, opt=False, missing=True, inter=True) + verify( + cfg, "int_opt_missing", none=False, opt=True, missing=True, inter=True + ) + + verify( + cfg, + "str_int_const", + none=False, + opt=False, + missing=False, + inter=True, + exp="foo_10", + ) + verify( + cfg, + "opt_str_int_const", + none=False, + opt=True, + missing=False, + inter=True, + exp="foo_10", + ) + verify( + cfg, + "int_node", + none=False, + opt=False, + missing=False, + inter=True, + exp=node, + ) + + verify( + cfg, + "int_opt_node", + none=False, + opt=True, + missing=False, + inter=True, + exp=node, + ) + + verify( + cfg, + "int_resolver", + none=False, + opt=True, + missing=False, + inter=True, + exp=resolver_output, + ) + + verify( + cfg, + "int_opt_resolver", + none=False, + opt=True, + missing=False, + inter=True, + exp=resolver_output, + ) + + verify( + cfg, + "str_int_with_primitive_missing", + none=False, + opt=False, + missing=True, + inter=True, + ) + + verify( + cfg, + "opt_str_int_with_primitive_missing", + none=False, + opt=True, + missing=True, + inter=True, + ) diff --git a/tests/test_merge.py b/tests/test_merge.py new file mode 100644 index 0000000000000000000000000000000000000000..617dbf491ef6a66a8cc696b9381dc3cacab58b45 --- /dev/null +++ b/tests/test_merge.py @@ -0,0 +1,524 @@ +import sys +from typing import Any, Dict, List, MutableMapping, MutableSequence, Tuple, Union + +import pytest + +from omegaconf import ( + MISSING, + DictConfig, + ListConfig, + OmegaConf, + ReadonlyConfigError, + ValidationError, + nodes, +) +from omegaconf._utils import is_structured_config +from omegaconf.errors import ConfigKeyError + +from . import ( + A, + B, + C, + ConcretePlugin, + ConfWithMissingDict, + Group, + InterpolationDict, + InterpolationList, + MissingDict, + MissingList, + Package, + Plugin, + User, + Users, +) + + +@pytest.mark.parametrize( # type: ignore + "inputs, expected", + [ + # dictionaries + ([{}, {"a": 1}], {"a": 1}), + ([{"a": None}, {"b": None}], {"a": None, "b": None}), + ([{"a": 1}, {"b": 2}], {"a": 1, "b": 2}), + ([{"a": {"a1": 1, "a2": 2}}, {"a": {"a1": 2}}], {"a": {"a1": 2, "a2": 2}}), + ([{"a": 1, "b": 2}, {"b": 3}], {"a": 1, "b": 3}), + (({"a": 1, "b": 2}, {"b": {"c": 3}}), {"a": 1, "b": {"c": 3}}), + (({"b": {"c": 1}}, {"b": 1}), {"b": 1}), + (({"list": [1, 2, 3]}, {"list": [4, 5, 6]}), {"list": [4, 5, 6]}), + (({"a": 1}, {"a": nodes.IntegerNode(10)}), {"a": 10}), + (({"a": 1}, {"a": nodes.IntegerNode(10)}), {"a": nodes.IntegerNode(10)}), + (({"a": nodes.IntegerNode(10)}, {"a": 1}), {"a": 1}), + (({"a": nodes.IntegerNode(10)}, {"a": 1}), {"a": nodes.IntegerNode(1)}), + pytest.param( + ({"a": "???"}, {"a": {}}), {"a": {}}, id="dict_merge_into_missing" + ), + pytest.param( + ({"a": "???"}, {"a": {"b": 10}}), + {"a": {"b": 10}}, + id="dict_merge_into_missing", + ), + pytest.param( + ({"a": {"b": 10}}, {"a": "???"}), + {"a": "???"}, + id="dict_merge_missing_onto", + ), + # lists + (([1, 2, 3], [4, 5, 6]), [4, 5, 6]), + (([[1, 2, 3]], [[4, 5, 6]]), [[4, 5, 6]]), + (([1, 2, {"a": 10}], [4, 5, {"b": 20}]), [4, 5, {"b": 20}]), + pytest.param( + ({"a": "???"}, {"a": []}), {"a": []}, id="list_merge_into_missing" + ), + pytest.param( + ({"a": "???"}, {"a": [1, 2, 3]}), + {"a": [1, 2, 3]}, + id="list_merge_into_missing", + ), + pytest.param( + ({"a": [1, 2, 3]}, {"a": "???"}), + {"a": "???"}, + id="list_merge_missing_onto", + ), + pytest.param( + ([1, 2, 3], ListConfig(content=MISSING)), + ListConfig(content=MISSING), + id="list_merge_missing_onto2", + ), + # Interpolations + # value interpolation + pytest.param( + ({"d1": 1, "inter": "${d1}"}, {"d1": 2}), + {"d1": 2, "inter": 2}, + id="inter:updating_data", + ), + pytest.param( + ({"d1": 1, "d2": 2, "inter": "${d1}"}, {"inter": "${d2}"}), + {"d1": 1, "d2": 2, "inter": 2}, + id="inter:value_inter_over_value_inter", + ), + pytest.param( + ({"inter": "${d1}"}, {"inter": 123}), + {"inter": 123}, + id="inter:data_over_value_inter", + ), + pytest.param( + ({"inter": "${d1}", "d1": 1, "n1": {"foo": "bar"}}, {"inter": "${n1}"}), + {"inter": {"foo": "bar"}, "d1": 1, "n1": {"foo": "bar"}}, + id="inter:node_inter_over_value_inter", + ), + pytest.param( + ({"inter": 123}, {"inter": "${data}"}), + {"inter": "${data}"}, + id="inter:inter_over_data", + ), + # node interpolation + pytest.param( + ({"n": {"a": 10}, "i": "${n}"}, {"n": {"a": 20}}), + {"n": {"a": 20}, "i": {"a": 20}}, + id="node_inter:node_update", + ), + pytest.param( + ({"d": 20, "n": {"a": 10}, "i": "${n}"}, {"i": "${d}"}), + {"d": 20, "n": {"a": 10}, "i": 20}, + id="node_inter:value_inter_over_node_inter", + ), + pytest.param( + ({"n": {"a": 10}, "i": "${n}"}, {"i": 30}), + {"n": {"a": 10}, "i": 30}, + id="node_inter:data_over_node_inter", + ), + pytest.param( + ({"n1": {"a": 10}, "n2": {"b": 20}, "i": "${n1}"}, {"i": "${n2}"}), + {"n1": {"a": 10}, "n2": {"b": 20}, "i": {"b": 20}}, + id="node_inter:node_inter_over_node_inter", + ), + pytest.param( + ({"v": 10, "n": {"a": 20}}, {"v": "${n}"}), + {"v": {"a": 20}, "n": {"a": 20}}, + id="inter:node_inter_over_data", + ), + pytest.param( + ({"n": {"a": 10}, "i": "${n}"}, {"i": {"b": 20}}), + {"n": {"a": 10}, "i": {"a": 10, "b": 20}}, + id="inter:node_over_node_interpolation", + ), + # Structured configs + (({"user": User}, {}), {"user": User(name=MISSING, age=MISSING)}), + (({"user": User}, {"user": {}}), {"user": User(name=MISSING, age=MISSING)}), + ( + ({"user": User}, {"user": {"name": "Joe"}}), + {"user": User(name="Joe", age=MISSING)}, + ), + ( + ({"user": User}, {"user": {"name": "Joe", "age": 10}}), + {"user": User(name="Joe", age=10)}, + ), + ([{"users": Users}], {"users": {"name2user": {}}}), + ([Users], {"name2user": {}}), + ([Users, {"name2user": {}}], {"name2user": {}}), + ( + [Users, {"name2user": {"joe": User}}], + {"name2user": {"joe": {"name": MISSING, "age": MISSING}}}, + ), + ( + [Users, {"name2user": {"joe": User(name="joe")}}], + {"name2user": {"joe": {"name": "joe", "age": MISSING}}}, + ), + pytest.param( + [Users, {"name2user": {"joe": {"name": "joe"}}}], + {"name2user": {"joe": {"name": "joe", "age": MISSING}}}, + id="users_merge_with_missing_age", + ), + pytest.param( + [ConfWithMissingDict, {"dict": {"foo": "bar"}}], + {"dict": {"foo": "bar"}}, + id="conf_missing_dict", + ), + pytest.param( + [{}, ConfWithMissingDict], + {"dict": "???"}, + id="merge_missing_dict_into_missing_dict", + ), + ([{"user": User}, {"user": Group}], pytest.raises(ValidationError)), + ( + [{"user": DictConfig(ref_type=User, content=User)}, {"user": Group}], + pytest.raises(ValidationError), + ), + ([Plugin, ConcretePlugin], ConcretePlugin), + pytest.param( + [{"user": "???"}, {"user": Group}], + {"user": Group}, + id="merge_into_missing_node", + ), + ([{"user": User()}, {"user": {"foo": "bar"}}], pytest.raises(ConfigKeyError)), + # missing DictConfig + pytest.param( + [{"dict": DictConfig(content="???")}, {"dict": {"foo": "bar"}}], + {"dict": {"foo": "bar"}}, + id="merge_into_missing_DictConfig", + ), + # missing Dict[str, str] + pytest.param( + [MissingDict, {"dict": {"foo": "bar"}}], + {"dict": {"foo": "bar"}}, + id="merge_into_missing_Dict[str,str]", + ), + # missing ListConfig + pytest.param( + [{"list": ListConfig(content="???")}, {"list": [1, 2, 3]}], + {"list": [1, 2, 3]}, + id="merge_into_missing_ListConfig", + ), + # missing List[str] + pytest.param( + [MissingList, {"list": ["a", "b", "c"]}], + {"list": ["a", "b", "c"]}, + id="merge_into_missing_List[str]", + ), + # merging compatible dict into MISSING structured config expands it + # to ensure the resulting node follows the protocol set by the underlying type + pytest.param( + [B, {"x": {}}], {"x": {"a": 10}}, id="structured_merge_into_missing" + ), + pytest.param( + [B, {"x": {"a": 20}}], {"x": {"a": 20}}, id="structured_merge_into_missing" + ), + pytest.param([C, {"x": A}], {"x": {"a": 10}}, id="structured_merge_into_none"), + pytest.param([C, C], {"x": None}, id="none_not_expanding"), + # Merge into list with Structured Config + pytest.param( + [ListConfig(content=[], element_type=User), [{}]], + [User()], + id="list_sc_element_merge_dict", + ), + pytest.param( + [ListConfig(content=[], element_type=User), [{"name": "Bond", "age": 7}]], + [User(name="Bond", age=7)], + id="list_sc_element_merge_dict", + ), + pytest.param( + [ListConfig(content=[], element_type=User), [{"name": "Bond"}]], + [User(name="Bond", age=MISSING)], + id="list_sc_element_merge_dict", + ), + ], +) +def test_merge(inputs: Any, expected: Any) -> None: + configs = [OmegaConf.create(c) for c in inputs] + + if isinstance(expected, (MutableMapping, MutableSequence)) or is_structured_config( + expected + ): + merged = OmegaConf.merge(*configs) + assert merged == expected + # test input configs are not changed. + # Note that converting to container without resolving to avoid resolution errors while comparing + for i in range(len(inputs)): + input_i = OmegaConf.create(inputs[i]) + orig = OmegaConf.to_container(input_i, resolve=False) + merged2 = OmegaConf.to_container(configs[i], resolve=False) + assert orig == merged2 + else: + with expected: + OmegaConf.merge(*configs) + + +def test_merge_error_retains_type() -> None: + cfg = OmegaConf.structured(ConcretePlugin) + with pytest.raises(ValidationError): + cfg.merge_with({"params": {"foo": "error"}}) + assert OmegaConf.get_type(cfg) == ConcretePlugin + + +def test_primitive_dicts() -> None: + c1 = {"a": 10} + c2 = {"b": 20} + merged = OmegaConf.merge(c1, c2) + assert merged == {"a": 10, "b": 20} + + +@pytest.mark.parametrize( # type: ignore + "a_, b_, expected", [((1, 2, 3), (4, 5, 6), [4, 5, 6])] +) +def test_merge_no_eq_verify( + a_: Tuple[int], b_: Tuple[int], expected: Tuple[int] +) -> None: + a = OmegaConf.create(a_) + b = OmegaConf.create(b_) + c = OmegaConf.merge(a, b) + # verify merge result is expected + assert expected == c + + +@pytest.mark.parametrize( # type: ignore + "c1,c2,expected", + [({}, {"a": 1, "b": 2}, {"a": 1, "b": 2}), ({"a": 1}, {"b": 2}, {"a": 1, "b": 2})], +) +def test_merge_with(c1: Any, c2: Any, expected: Any) -> None: + a = OmegaConf.create(c1) + b = OmegaConf.create(c2) + a.merge_with(b) + assert a == expected + + +@pytest.mark.parametrize( # type: ignore + "c1,c2,expected", + [({}, {"a": 1, "b": 2}, {"a": 1, "b": 2}), ({"a": 1}, {"b": 2}, {"a": 1, "b": 2})], +) +def test_merge_with_c2_readonly(c1: Any, c2: Any, expected: Any) -> None: + a = OmegaConf.create(c1) + b = OmegaConf.create(c2) + OmegaConf.set_readonly(b, True) + a.merge_with(b) + assert a == expected + assert OmegaConf.is_readonly(a) + + +def test_3way_dict_merge() -> None: + c1 = OmegaConf.create("{a: 1, b: 2}") + c2 = OmegaConf.create("{b: 3}") + c3 = OmegaConf.create("{a: 2, c: 3}") + c4 = OmegaConf.merge(c1, c2, c3) + assert {"a": 2, "b": 3, "c": 3} == c4 + + +def test_merge_list_list() -> None: + a = OmegaConf.create([1, 2, 3]) + b = OmegaConf.create([4, 5, 6]) + a.merge_with(b) + assert a == b + + +@pytest.mark.parametrize( # type: ignore + "base, merge, exception", + [ + ({}, [], TypeError), + ([], {}, TypeError), + ([1, 2, 3], None, ValueError), + ({"a": 10}, None, ValueError), + (Package, {"modules": [{"foo": "var"}]}, ConfigKeyError), + ], +) +def test_merge_error(base: Any, merge: Any, exception: Any) -> None: + base = OmegaConf.create(base) + merge = None if merge is None else OmegaConf.create(merge) + with pytest.raises(exception): + OmegaConf.merge(base, merge) + + +@pytest.mark.parametrize( # type: ignore + "c1, c2", + [ + pytest.param({"foo": "bar"}, {"zoo": "foo"}, id="dict"), + pytest.param([1, 2, 3], [4, 5, 6], id="list"), + ], +) +def test_with_readonly_c1(c1: Any, c2: Any) -> None: + cfg1 = OmegaConf.create(c1) + cfg2 = OmegaConf.create(c2) + OmegaConf.set_readonly(cfg1, True) + cfg3 = OmegaConf.merge(cfg1, cfg2) + assert OmegaConf.is_readonly(cfg3) + + +@pytest.mark.parametrize( # type: ignore + "c1, c2", + [ + pytest.param({"foo": "bar"}, {"zoo": "foo"}, id="dict"), + pytest.param([1, 2, 3], [4, 5, 6], id="list"), + ], +) +def test_with_readonly_c2(c1: Any, c2: Any) -> None: + cfg1 = OmegaConf.create(c1) + cfg2 = OmegaConf.create(c1) + OmegaConf.set_readonly(cfg2, True) + cfg3 = OmegaConf.merge(cfg1, cfg2) + assert OmegaConf.is_readonly(cfg3) + + +@pytest.mark.parametrize( # type: ignore + "c1, c2", [({"foo": "bar"}, {"zoo": "foo"}), ([1, 2, 3], [4, 5, 6])] +) +def test_into_readonly(c1: Any, c2: Any) -> None: + cfg = OmegaConf.create(c1) + OmegaConf.set_readonly(cfg, True) + with pytest.raises(ReadonlyConfigError): + cfg.merge_with(c2) + + +@pytest.mark.parametrize( # type: ignore + "c1, c2, expected", + [ + ( + {"node": {"foo": "bar"}}, + {"node": {"zoo": "foo"}}, + {"node": {"foo": "bar", "zoo": "foo"}}, + ), + ], +) +def test_dict_merge_readonly_into_readwrite(c1: Any, c2: Any, expected: Any) -> None: + c1 = OmegaConf.create(c1) + c2 = OmegaConf.create(c2) + OmegaConf.set_readonly(c2.node, True) + with pytest.raises(ReadonlyConfigError): + c2.node.foo = 10 + assert OmegaConf.merge(c1, c2) == expected + c1.merge_with(c2) + assert c1 == expected + + +@pytest.mark.parametrize( # type: ignore + "c1, c2, expected", + [({"node": [1, 2, 3]}, {"node": [4, 5, 6]}, {"node": [4, 5, 6]})], +) +def test_list_merge_readonly_into_readwrite(c1: Any, c2: Any, expected: Any) -> None: + c1 = OmegaConf.create(c1) + c2 = OmegaConf.create(c2) + OmegaConf.set_readonly(c2.node, True) + with pytest.raises(ReadonlyConfigError): + c2.node.append(10) + assert OmegaConf.merge(c1, c2) == expected + c1.merge_with(c2) + assert c1 == expected + + +def test_parent_maintained() -> None: + c1 = OmegaConf.create({"a": {"b": 10}}) + c2 = OmegaConf.create({"aa": {"bb": 100}}) + c3 = OmegaConf.merge(c1, c2) + assert isinstance(c1, DictConfig) + assert isinstance(c2, DictConfig) + assert isinstance(c3, DictConfig) + assert id(c1.a._get_parent()) == id(c1) + assert id(c2.aa._get_parent()) == id(c2) + assert id(c3.a._get_parent()) == id(c3) + + +@pytest.mark.parametrize( # type:ignore + "cfg,overrides,expected", + [ + ([1, 2, 3], ["0=bar", "2.a=100"], ["bar", 2, dict(a=100)]), + ({}, ["foo=bar", "bar=100"], {"foo": "bar", "bar": 100}), + ({}, ["foo=bar=10"], {"foo": "bar=10"}), + ], +) +def test_merge_with_dotlist( + cfg: Union[List[Any], Dict[str, Any]], + overrides: List[str], + expected: Union[List[Any], Dict[str, Any]], +) -> None: + c = OmegaConf.create(cfg) + c.merge_with_dotlist(overrides) + assert c == expected + + +def test_merge_with_cli() -> None: + c = OmegaConf.create([1, 2, 3]) + sys.argv = ["app.py", "0=bar", "2.a=100"] + c.merge_with_cli() + assert c == ["bar", 2, dict(a=100)] + + +@pytest.mark.parametrize( # type:ignore + "dotlist, expected", + [([], {}), (["foo=1"], {"foo": 1}), (["foo=1", "bar"], {"foo": 1, "bar": None})], +) +def test_merge_empty_with_dotlist(dotlist: List[str], expected: Dict[str, Any]) -> None: + c = OmegaConf.create() + c.merge_with_dotlist(dotlist) + assert c == expected + + +@pytest.mark.parametrize("dotlist", ["foo=10", ["foo=1", 10]]) # type:ignore +def test_merge_with_dotlist_errors(dotlist: List[str]) -> None: + c = OmegaConf.create() + with pytest.raises(ValueError): + c.merge_with_dotlist(dotlist) + + +@pytest.mark.parametrize( # type:ignore + "dst, other, expected, node", + [ + pytest.param( + OmegaConf.structured(InterpolationList), + OmegaConf.create({"list": [0.1]}), + {"list": [0.1]}, + "list", + id="merge_interpolation_list_with_list", + ), + pytest.param( + OmegaConf.structured(InterpolationDict), + OmegaConf.create({"dict": {"a": 4}}), + {"dict": {"a": 4}}, + "dict", + id="merge_interpolation_dict_with_dict", + ), + ], +) +def test_merge_with_src_as_interpolation( + dst: Any, other: Any, expected: Any, node: Any +) -> None: + res = OmegaConf.merge(dst, other) + assert res == expected + + +@pytest.mark.parametrize( # type:ignore + "dst, other, node", + [ + pytest.param( + OmegaConf.structured(InterpolationDict), + OmegaConf.structured(InterpolationDict), + "dict", + id="merge_interpolation_dict_with_interpolation_dict", + ), + pytest.param( + OmegaConf.structured(InterpolationList), + OmegaConf.structured(InterpolationList), + "list", + id="merge_interpolation_list_with_interpolation_list", + ), + ], +) +def test_merge_with_other_as_interpolation(dst: Any, other: Any, node: Any) -> None: + res = OmegaConf.merge(dst, other) + assert OmegaConf.is_interpolation(res, node) diff --git a/tests/test_nodes.py b/tests/test_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..906a0c832bf7fb0c9f4c99be97739eb5d38c11ff --- /dev/null +++ b/tests/test_nodes.py @@ -0,0 +1,552 @@ +import copy +from enum import Enum +from typing import Any, Dict, Tuple, Type + +import pytest + +from omegaconf import ( + AnyNode, + BooleanNode, + DictConfig, + EnumNode, + FloatNode, + IntegerNode, + ListConfig, + OmegaConf, + StringNode, + ValueNode, +) +from omegaconf.errors import ValidationError + +from . import Color, IllegalType, User + + +# testing valid conversions +@pytest.mark.parametrize( # type: ignore + "type_,input_,output_", + [ + # string + (StringNode, "abc", "abc"), + (StringNode, 100, "100"), + # integer + (IntegerNode, 10, 10), + (IntegerNode, "10", 10), + (IntegerNode, -100, -100), + (IntegerNode, "-100", -100), + # float + (FloatNode, float("inf"), float("inf")), + # Yes, we treat nan as equal to nan in OmegaConf + (FloatNode, float("nan"), float("nan")), + (FloatNode, 10, 10.0), + (FloatNode, 10.1, 10.1), + (FloatNode, "10.2", 10.2), + (FloatNode, "10e-3", 10e-3), + # bool true + (BooleanNode, True, True), + (BooleanNode, "Y", True), + (BooleanNode, "true", True), + (BooleanNode, "Yes", True), + (BooleanNode, "On", True), + (BooleanNode, "1", True), + (BooleanNode, 100, True), + # bool false + (BooleanNode, False, False), + (BooleanNode, "N", False), + (BooleanNode, "false", False), + (BooleanNode, "No", False), + (BooleanNode, "Off", False), + (BooleanNode, None, None), + (BooleanNode, "0", False), + (BooleanNode, 0, False), + # any + (AnyNode, 3, 3), + (AnyNode, 3.14, 3.14), + (AnyNode, False, False), + (AnyNode, Color.RED, Color.RED), + (AnyNode, None, None), + # Enum node + (lambda v: EnumNode(enum_type=Color, value=v), Color.RED, Color.RED), + (lambda v: EnumNode(enum_type=Color, value=v), "Color.RED", Color.RED), + (lambda v: EnumNode(enum_type=Color, value=v), "RED", Color.RED), + (lambda v: EnumNode(enum_type=Color, value=v), 1, Color.RED), + ], +) +def test_valid_inputs(type_: type, input_: Any, output_: Any) -> None: + node = type_(input_) + assert node == output_ + assert node == node + assert not (node != output_) + assert not (node != node) + assert str(node) == str(output_) + + +# testing invalid conversions +@pytest.mark.parametrize( # type: ignore + "type_,input_", + [ + (IntegerNode, "abc"), + (IntegerNode, 10.1), + (IntegerNode, "-1132c"), + (FloatNode, "abc"), + (IntegerNode, "-abc"), + (BooleanNode, "Nope"), + (BooleanNode, "Yup"), + (StringNode, [1, 2]), + (StringNode, ListConfig([1, 2])), + (StringNode, {"foo": "var"}), + (FloatNode, DictConfig({"foo": "var"})), + (IntegerNode, [1, 2]), + (IntegerNode, ListConfig([1, 2])), + (IntegerNode, {"foo": "var"}), + (IntegerNode, DictConfig({"foo": "var"})), + (BooleanNode, [1, 2]), + (BooleanNode, ListConfig([1, 2])), + (BooleanNode, {"foo": "var"}), + (BooleanNode, DictConfig({"foo": "var"})), + (FloatNode, [1, 2]), + (FloatNode, ListConfig([1, 2])), + (FloatNode, {"foo": "var"}), + (FloatNode, DictConfig({"foo": "var"})), + (AnyNode, [1, 2]), + (AnyNode, ListConfig([1, 2])), + (AnyNode, {"foo": "var"}), + (AnyNode, DictConfig({"foo": "var"})), + (AnyNode, IllegalType()), + ], +) +def test_invalid_inputs(type_: type, input_: Any) -> None: + empty_node = type_() + + with pytest.raises(ValidationError): + empty_node._set_value(input_) + with pytest.raises(ValidationError): + type_(input_) + + +@pytest.mark.parametrize( # type: ignore + "input_, expected_type", + [ + ({}, DictConfig), + ([], ListConfig), + (5, AnyNode), + (5.0, AnyNode), + (True, AnyNode), + (False, AnyNode), + ("str", AnyNode), + ], +) +def test_assigned_value_node_type(input_: type, expected_type: Any) -> None: + c = OmegaConf.create() + assert isinstance(c, DictConfig) + c.foo = input_ + assert type(c._get_node("foo")) == expected_type + + +# dict +def test_dict_any() -> None: + c = OmegaConf.create() + assert isinstance(c, DictConfig) + # default type is Any + c.foo = 10 + c[Enum1.FOO] = "bar" + + assert c.foo == 10 + assert type(c._get_node("foo")) == AnyNode + c.foo = "string" + assert c.foo == "string" + + assert type(c._get_node(Enum1.FOO)) == AnyNode + + +def test_dict_integer_1() -> None: + c = OmegaConf.create() + assert isinstance(c, DictConfig) + c.foo = IntegerNode(10) + assert type(c._get_node("foo")) == IntegerNode + assert c.foo == 10 + + +# list +def test_list_any() -> None: + c = OmegaConf.create([]) + assert isinstance(c, ListConfig) + # default type is Any + c.append(10) + assert c[0] == 10 + assert type(c._get_node(0)) == AnyNode + c[0] = "string" + assert c[0] == "string" + + +def test_list_integer() -> None: + val = 10 + c = OmegaConf.create([]) + assert isinstance(c, ListConfig) + c.append(IntegerNode(val)) + assert type(c._get_node(0)) == IntegerNode + assert c.get(0) == val + + +def test_list_integer_rejects_string() -> None: + c = OmegaConf.create([]) + assert isinstance(c, ListConfig) + c.append(IntegerNode(10)) + assert c.get(0) == 10 + with pytest.raises(ValidationError): + c[0] = "string" + assert c[0] == 10 + assert type(c._get_node(0)) == IntegerNode + + +# Test merge raises validation error +@pytest.mark.parametrize( # type: ignore + "c1, c2", + [ + (dict(a=IntegerNode(10)), dict(a="str")), + (dict(a=IntegerNode(10)), dict(a=StringNode("str"))), + (dict(a=10, b=IntegerNode(10)), dict(a=20, b="str")), + (dict(foo=dict(bar=IntegerNode(10))), dict(foo=dict(bar="str"))), + ], +) +def test_merge_validation_error(c1: Dict[str, Any], c2: Dict[str, Any]) -> None: + conf1 = OmegaConf.create(c1) + conf2 = OmegaConf.create(c2) + with pytest.raises(ValidationError): + OmegaConf.merge(conf1, conf2) + # make sure that conf1 and conf2 were not modified + assert conf1 == OmegaConf.create(c1) + assert conf2 == OmegaConf.create(c2) + + +@pytest.mark.parametrize( # type: ignore + "type_,valid_value, invalid_value", + [ + (IntegerNode, 1, "invalid"), + (FloatNode, 3.1415, "invalid"), + (BooleanNode, True, "invalid"), + (AnyNode, "aaa", None), + (StringNode, "blah", None), + ], +) +def test_accepts_mandatory_missing( + type_: type, valid_value: Any, invalid_value: Any +) -> None: + node = type_() + node._set_value("???") + assert node._value() == "???" + + conf = OmegaConf.create({"foo": node}) + assert isinstance(conf, DictConfig) + assert "foo" not in conf + assert type(conf._get_node("foo")) == type_ + + conf.foo = valid_value + # make sure valid assignment does not change the type + assert type(conf._get_node("foo")) == type_ + assert "foo" in conf + assert conf.foo == valid_value + + if invalid_value is not None: + with pytest.raises(ValidationError): + conf.foo = invalid_value + + +class Enum1(Enum): + FOO = 1 + BAR = 2 + + +class Enum2(Enum): + NOT_FOO = 1 + NOT_BAR = 2 + + +@pytest.mark.parametrize( # type: ignore + "type_", [BooleanNode, EnumNode, FloatNode, IntegerNode, StringNode, AnyNode] +) +@pytest.mark.parametrize( # type: ignore + "values, success_map", + [ + ( + # True aliases + (True, "Y", "true", "yes", "on"), + { + "BooleanNode": True, # noqa F601 + "StringNode": str, # noqa F601 + "AnyNode": copy.copy, # noqa F601 + }, + ), + ( + ("1", 1, 10, -10), + { + "BooleanNode": True, # noqa F601 + "IntegerNode": int, # noqa F601 + "FloatNode": float, # noqa F601 + "StringNode": str, # noqa F601 + "AnyNode": copy.copy, # noqa F601 + }, + ), + ( + # Floaty things + ("1.0", 1.0, float("inf"), float("-inf"), "10e-3", 10e-3), + {"FloatNode": float, "StringNode": str, "AnyNode": copy.copy}, + ), + ( + # False aliases + (False, "N", "false", "no", "off"), + { + "BooleanNode": False, # noqa F601 + "StringNode": str, # noqa F601 + "AnyNode": copy.copy, # noqa F601 + }, + ), + ( + # Falsy integers + ("0", 0), + { + "BooleanNode": False, # noqa F601 + "IntegerNode": 0, # noqa F601 + "FloatNode": 0.0, # noqa F601 + "StringNode": str, # noqa F601 + "AnyNode": copy.copy, # noqa F601 + }, + ), + ], +) +def test_legal_assignment( + type_: type, values: Any, success_map: Dict[Any, Dict[str, Any]] +) -> None: + + if not isinstance(values, (list, tuple)): + values = [values] + + for value in values: + if type_.__name__ in success_map.keys(): + expected = success_map[type_.__name__] + if callable(expected): + expected = expected(value) + node = type_(value) + assert node._value() == expected + else: + with pytest.raises(ValidationError): + type_(value) + + +@pytest.mark.parametrize( # type: ignore + "node,value", + [ + (IntegerNode(), "foo"), + (BooleanNode(), "foo"), + (FloatNode(), "foo"), + (EnumNode(enum_type=Enum1), "foo"), + ], +) +def test_illegal_assignment(node: ValueNode, value: Any) -> None: + with pytest.raises(ValidationError): + node._set_value(value) + + +@pytest.mark.parametrize( # type: ignore + "node_type", [BooleanNode, EnumNode, FloatNode, IntegerNode, StringNode, AnyNode] +) +@pytest.mark.parametrize( # type: ignore + "enum_type, values, success_map", + [ + ( + Enum1, + (Enum1.FOO, "Enum1.FOO", "FOO", 1), + {EnumNode: Enum1.FOO, AnyNode: copy.copy, StringNode: str}, + ) + ], +) +def test_legal_assignment_enum( + node_type: Type[EnumNode], + enum_type: Type[Enum], + values: Tuple[Any], + success_map: Dict[Any, Any], +) -> None: + assert isinstance(values, (list, tuple)) + + for value in values: + if node_type in success_map.keys(): + expected = success_map[node_type] + if callable(expected): + expected = expected(value) + node = node_type(enum_type) + node._set_value(value) + assert node._value() == expected + else: + with pytest.raises(ValidationError): + node_type(enum_type) + + +class DummyEnum(Enum): + FOO = 1 + + +@pytest.mark.parametrize("is_optional", [True, False]) # type: ignore +@pytest.mark.parametrize( # type: ignore + "ref_type, type_, value, expected_type", + [ + (Any, Any, 10, AnyNode), + (DummyEnum, DummyEnum, DummyEnum.FOO, EnumNode), + (int, int, 42, IntegerNode), + (float, float, 3.1415, FloatNode), + (bool, bool, True, BooleanNode), + (str, str, "foo", StringNode), + ], +) +def test_node_wrap( + ref_type: type, type_: type, is_optional: bool, value: Any, expected_type: Any +) -> None: + from omegaconf.omegaconf import _node_wrap + + ret = _node_wrap( + ref_type=Any, + type_=type_, + value=value, + is_optional=is_optional, + parent=None, + key=None, + ) + assert ret._metadata.ref_type == ref_type + assert type(ret) == expected_type + assert ret == value + + if is_optional: + ret = _node_wrap( + ref_type=Any, + type_=type_, + value=None, + is_optional=is_optional, + parent=None, + key=None, + ) + assert type(ret) == expected_type + # noinspection PyComparisonWithNone + assert ret == None # noqa E711 + + +def test_node_wrap_illegal_type() -> None: + class UserClass: + pass + + from omegaconf.omegaconf import _node_wrap + + with pytest.raises(ValidationError): + _node_wrap( + type_=UserClass, value=UserClass(), is_optional=False, parent=None, key=None + ) + + +@pytest.mark.parametrize( # type: ignore + "obj", + [ + StringNode(), + StringNode(value="foo"), + StringNode(value="foo", is_optional=False), + BooleanNode(value=True), + IntegerNode(value=10), + FloatNode(value=10.0), + OmegaConf.create({}), + OmegaConf.create([]), + OmegaConf.create({"foo": "foo"}), + ], +) +def test_deepcopy(obj: Any) -> None: + cp = copy.deepcopy(obj) + assert cp == obj + assert id(cp) != id(obj) + assert obj.__dict__.keys() == cp.__dict__.keys() + for k in obj.__dict__.keys(): + assert obj.__dict__[k] == cp.__dict__[k] + + +@pytest.mark.parametrize( # type: ignore + "node, value, expected", + [ + (StringNode(), None, True), + (StringNode(), 100, False), + (StringNode("foo"), "foo", True), + (IntegerNode(), 1, False), + (IntegerNode(1), 1, True), + (IntegerNode(1), "foo", False), + (FloatNode(), 1, False), + (FloatNode(), None, True), + (FloatNode(1.0), None, False), + (FloatNode(1.0), 1.0, True), + (FloatNode(1), 1, True), + (FloatNode(1.0), "foo", False), + (BooleanNode(), True, False), + (BooleanNode(), False, False), + (BooleanNode(), None, True), + (BooleanNode(True), None, False), + (BooleanNode(True), False, False), + (BooleanNode(False), False, True), + (AnyNode(value=1, is_optional=True), AnyNode(value=1, is_optional=True), True), + ( + AnyNode(value=1, is_optional=True), + AnyNode(value=1, is_optional=False), + True, + ), + (EnumNode(enum_type=Enum1), Enum1.BAR, False), + (EnumNode(enum_type=Enum1), EnumNode(Enum1), True), + (EnumNode(enum_type=Enum1), "nope", False), + ( + EnumNode(enum_type=Enum1, value=Enum1.BAR), + EnumNode(enum_type=Enum1, value=Enum1.BAR), + True, + ), + (EnumNode(enum_type=Enum1, value=Enum1.BAR), Enum1.BAR, True), + ], +) +def test_eq(node: ValueNode, value: Any, expected: Any) -> None: + assert (node == value) == expected + assert (node != value) != expected + assert (value == node) == expected + assert (value != node) != expected + assert (node.__hash__() == value.__hash__()) == expected + + +@pytest.mark.parametrize("value", [1, 3.14, True, None, Enum1.FOO]) # type: ignore +def test_set_anynode_with_primitive_type(value: Any) -> None: + cfg = OmegaConf.create({"a": 5}) + a_before = cfg._get_node("a") + cfg.a = value + # changing anynode's value with a primitive type should set value + assert id(cfg._get_node("a")) == id(a_before) + assert cfg.a == value + + +@pytest.mark.parametrize( # type: ignore + "value, container_type", + [ + (ListConfig(content=[1, 2]), ListConfig), + ([1, 2], ListConfig), + (DictConfig(content={"foo": "var"}), DictConfig), + ({"foo": "var"}, DictConfig), + ], +) +def test_set_anynode_with_container(value: Any, container_type: Any) -> None: + cfg = OmegaConf.create({"a": 5}) + a_before = cfg._get_node("a") + cfg.a = value + # changing anynode's value with a container should wrap a new node + assert id(cfg._get_node("a")) != id(a_before) + assert isinstance(cfg.a, container_type) + assert cfg.a == value + + +def test_set_anynode_with_illegal_type() -> None: + cfg = OmegaConf.create({"a": 5}) + with pytest.raises(ValidationError): + cfg.a = IllegalType() + + +def test_set_valuenode() -> None: + cfg = OmegaConf.structured(User) + a_before = cfg._get_node("age") + cfg.age = 12 + assert id(cfg._get_node("age")) == id(a_before) + with pytest.raises(ValidationError): + cfg.age = [] diff --git a/tests/test_omegaconf.py b/tests/test_omegaconf.py new file mode 100644 index 0000000000000000000000000000000000000000..c941c7faff3f0b6835a971b5ae8c7be44a4cbf89 --- /dev/null +++ b/tests/test_omegaconf.py @@ -0,0 +1,379 @@ +from typing import Any + +import pytest +from pytest import raises + +from omegaconf import ( + MISSING, + BooleanNode, + DictConfig, + EnumNode, + FloatNode, + IntegerNode, + ListConfig, + MissingMandatoryValue, + OmegaConf, + StringNode, +) +from omegaconf.errors import UnsupportedInterpolationType + +from . import Color, ConcretePlugin, IllegalType, StructuredWithMissing, does_not_raise + + +@pytest.mark.parametrize( # type: ignore + "cfg, key, expected_is_missing, expectation", + [ + ({}, "foo", False, does_not_raise()), + ({"foo": True}, "foo", False, does_not_raise()), + ({"foo": MISSING}, "foo", True, raises(MissingMandatoryValue)), + ( + {"foo": "${bar}", "bar": MISSING}, + "foo", + True, + raises(MissingMandatoryValue), + ), + ( + {"foo": "${unknown_resolver:foo}"}, + "foo", + False, + raises(UnsupportedInterpolationType), + ), + ({"foo": StringNode(value="???")}, "foo", True, raises(MissingMandatoryValue)), + ( + {"foo": StringNode(value="???"), "inter": "${foo}"}, + "inter", + True, + raises(MissingMandatoryValue), + ), + (StructuredWithMissing, "num", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "opt_num", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "dict", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "opt_dict", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "list", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "opt_list", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "user", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "opt_user", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "inter_user", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "inter_opt_user", True, raises(MissingMandatoryValue)), + (StructuredWithMissing, "inter_num", True, raises(MissingMandatoryValue)), + ], +) +def test_is_missing( + cfg: Any, key: str, expected_is_missing: bool, expectation: Any +) -> None: + cfg = OmegaConf.create(cfg) + with expectation: + cfg.get(key) + + assert OmegaConf.is_missing(cfg, key) == expected_is_missing + OmegaConf.set_struct(cfg, True) + assert OmegaConf.is_missing(cfg, key) == expected_is_missing + OmegaConf.set_readonly(cfg, True) + assert OmegaConf.is_missing(cfg, key) == expected_is_missing + + +def test_is_missing_resets() -> None: + cfg = OmegaConf.structured(StructuredWithMissing) + assert OmegaConf.is_missing(cfg, "dict") + cfg.dict = {} + assert not OmegaConf.is_missing(cfg, "dict") + + assert OmegaConf.is_missing(cfg, "list") + cfg.list = [1, 2, 3] + assert not OmegaConf.is_missing(cfg, "list") + cfg.list = "???" + assert OmegaConf.is_missing(cfg, "list") + + +@pytest.mark.parametrize( # type: ignore + "cfg, expected", + [ + (None, False), + ({}, False), + ([], False), + ("aa", False), + (10, False), + (True, False), + (bool, False), + (StringNode("foo"), False), + (ConcretePlugin, False), + (ConcretePlugin(), False), + (OmegaConf.create({}), True), + (OmegaConf.create([]), True), + (OmegaConf.structured(ConcretePlugin), True), + (OmegaConf.structured(ConcretePlugin()), True), + ], +) +def test_is_config(cfg: Any, expected: bool) -> None: + assert OmegaConf.is_config(cfg) == expected + + +@pytest.mark.parametrize( # type: ignore + "cfg, expected", + [ + (None, False), + ({}, False), + ([], False), + ("aa", False), + (10, False), + (True, False), + (bool, False), + (StringNode("foo"), False), + (ConcretePlugin, False), + (ConcretePlugin(), False), + (OmegaConf.create({}), False), + (OmegaConf.create([]), True), + (OmegaConf.structured(ConcretePlugin), False), + (OmegaConf.structured(ConcretePlugin()), False), + ], +) +def test_is_list(cfg: Any, expected: bool) -> None: + assert OmegaConf.is_list(cfg) == expected + + +@pytest.mark.parametrize( # type: ignore + "cfg, expected", + [ + (None, False), + ({}, False), + ([], False), + ("aa", False), + (10, False), + (True, False), + (bool, False), + (StringNode("foo"), False), + (ConcretePlugin, False), + (ConcretePlugin(), False), + (OmegaConf.create({}), True), + (OmegaConf.create([]), False), + (OmegaConf.structured(ConcretePlugin), True), + (OmegaConf.structured(ConcretePlugin()), True), + ], +) +def test_is_dict(cfg: Any, expected: bool) -> None: + assert OmegaConf.is_dict(cfg) == expected + + +@pytest.mark.parametrize("is_optional", [True, False]) # type: ignore +@pytest.mark.parametrize( # type: ignore + "fac", + [ + ( + lambda is_optional, missing: StringNode( + value="foo" if not missing else "???", is_optional=is_optional + ) + ), + ( + lambda is_optional, missing: IntegerNode( + value=10 if not missing else "???", is_optional=is_optional + ) + ), + ( + lambda is_optional, missing: FloatNode( + value=10 if not missing else "???", is_optional=is_optional + ) + ), + ( + lambda is_optional, missing: BooleanNode( + value=True if not missing else "???", is_optional=is_optional + ) + ), + ( + lambda is_optional, missing: EnumNode( + enum_type=Color, + value=Color.RED if not missing else "???", + is_optional=is_optional, + ) + ), + ( + lambda is_optional, missing: ListConfig( + content=[1, 2, 3] if not missing else "???", is_optional=is_optional + ) + ), + ( + lambda is_optional, missing: DictConfig( + content={"foo": "bar"} if not missing else "???", + is_optional=is_optional, + ) + ), + ( + lambda is_optional, missing: DictConfig( + ref_type=ConcretePlugin, + content=ConcretePlugin() if not missing else "???", + is_optional=is_optional, + ) + ), + ], +) +def test_is_optional(fac: Any, is_optional: bool) -> None: + obj = fac(is_optional, False) + assert OmegaConf.is_optional(obj) == is_optional + + cfg = OmegaConf.create({"node": obj}) + assert OmegaConf.is_optional(cfg, "node") == is_optional + + obj = fac(is_optional, True) + assert OmegaConf.is_optional(obj) == is_optional + + cfg = OmegaConf.create({"node": obj}) + assert OmegaConf.is_optional(cfg, "node") == is_optional + + +@pytest.mark.parametrize("is_none", [True, False]) # type: ignore +@pytest.mark.parametrize( # type: ignore + "fac", + [ + (lambda none: StringNode(value="foo" if not none else None, is_optional=True)), + (lambda none: IntegerNode(value=10 if not none else None, is_optional=True)), + (lambda none: FloatNode(value=10 if not none else None, is_optional=True)), + (lambda none: BooleanNode(value=True if not none else None, is_optional=True)), + ( + lambda none: EnumNode( + enum_type=Color, + value=Color.RED if not none else None, + is_optional=True, + ) + ), + ( + lambda none: ListConfig( + content=[1, 2, 3] if not none else None, is_optional=True + ) + ), + ( + lambda none: DictConfig( + content={"foo": "bar"} if not none else None, is_optional=True + ) + ), + ( + lambda none: DictConfig( + ref_type=ConcretePlugin, + content=ConcretePlugin() if not none else None, + is_optional=True, + ) + ), + ], +) +def test_is_none(fac: Any, is_none: bool) -> None: + obj = fac(is_none) + assert OmegaConf.is_none(obj) == is_none + + cfg = OmegaConf.create({"node": obj}) + assert OmegaConf.is_none(cfg, "node") == is_none + + +@pytest.mark.parametrize( + "fac", # type: ignore + [ + ( + lambda inter: StringNode( + value="foo" if inter is None else inter, is_optional=True + ) + ), + ( + lambda inter: IntegerNode( + value=10 if inter is None else inter, is_optional=True + ) + ), + ( + lambda inter: FloatNode( + value=10 if inter is None else inter, is_optional=True + ) + ), + ( + lambda inter: BooleanNode( + value=True if inter is None else inter, is_optional=True + ) + ), + ( + lambda inter: EnumNode( + enum_type=Color, + value=Color.RED if inter is None else inter, + is_optional=True, + ) + ), + ( + lambda inter: ListConfig( + content=[1, 2, 3] if inter is None else inter, is_optional=True + ) + ), + ( + lambda inter: DictConfig( + content={"foo": "bar"} if inter is None else inter, is_optional=True + ) + ), + ( + lambda inter: DictConfig( + ref_type=ConcretePlugin, + content=ConcretePlugin() if inter is None else inter, + is_optional=True, + ) + ), + ], + ids=[ + "StringNode", + "IntegerNode", + "FloatNode", + "BooleanNode", + "EnumNode", + "ListConfig", + "DictConfig", + "ConcretePlugin", + ], +) +def test_is_interpolation(fac): + obj = fac(inter=None) + assert not OmegaConf.is_interpolation(obj) + cfg = OmegaConf.create({"node": obj}) + assert not OmegaConf.is_interpolation(cfg, "node") + + assert not OmegaConf.is_interpolation(cfg, "missing") + + for inter in ["${foo}", "http://${url}", "${resolver:value}"]: + obj = fac(inter=inter) + assert OmegaConf.is_interpolation(obj) + cfg = OmegaConf.create({"node": obj}) + assert OmegaConf.is_interpolation(cfg, "node") + + +@pytest.mark.parametrize( # type: ignore + "cfg, type_", + [ + ({"foo": 10}, int), + ({"foo": 10.0}, float), + ({"foo": True}, bool), + ({"foo": "bar"}, str), + ({"foo": None}, type(None)), + ({"foo": ConcretePlugin()}, ConcretePlugin), + ({"foo": ConcretePlugin}, ConcretePlugin), + ({"foo": {}}, dict), + ({"foo": OmegaConf.create()}, dict), + ({"foo": []}, list), + ({"foo": OmegaConf.create([])}, list), + ], +) +def test_get_type(cfg: Any, type_: Any) -> None: + cfg = OmegaConf.create(cfg) + assert OmegaConf.get_type(cfg, "foo") == type_ + + +@pytest.mark.parametrize( # type: ignore + "obj, type_", + [ + (10, int), + (10.0, float), + (True, bool), + ("foo", str), + (DictConfig(content={}), dict), + (ListConfig(content=[]), list), + (IllegalType, IllegalType), + (IllegalType(), IllegalType), + ], +) +def test_get_type_on_raw(obj: Any, type_: Any) -> None: + assert OmegaConf.get_type(obj) == type_ + + +def test_is_issubclass() -> None: + cfg = OmegaConf.structured(ConcretePlugin) + t = OmegaConf.get_type(cfg) + assert t is not None and issubclass(t, ConcretePlugin) diff --git a/tests/test_readonly.py b/tests/test_readonly.py new file mode 100644 index 0000000000000000000000000000000000000000..fbd1dff1932420ea9992632af09bebc19582842e --- /dev/null +++ b/tests/test_readonly.py @@ -0,0 +1,230 @@ +import re +from typing import Any, Callable, Dict, List, Union + +import pytest +from pytest import raises + +from omegaconf import DictConfig, ListConfig, OmegaConf, ReadonlyConfigError + + +@pytest.mark.parametrize( # type: ignore + "src, func, expectation", + [ + pytest.param( + {}, + lambda c: c.__setitem__("a", 1), + raises(ReadonlyConfigError, match="a"), + id="dict_setitem", + ), + pytest.param( + {"a": {"b": {"c": 1}}}, + lambda c: c.__getattr__("a").__getattr__("b").__setitem__("c", 1), + raises(ReadonlyConfigError, match="a.b.c"), + id="dict_nested_setitem", + ), + pytest.param( + {}, + lambda c: OmegaConf.update(c, "a.b", 10, merge=True), + raises(ReadonlyConfigError, match="a"), + id="dict_update", + ), + pytest.param( + {"a": 10}, + lambda c: c.__setattr__("a", 1), + raises(ReadonlyConfigError, match="a"), + id="dict_setattr", + ), + pytest.param( + {"a": 10}, + lambda c: c.pop("a"), + raises(ReadonlyConfigError, match="a"), + id="dict_pop", + ), + pytest.param( + {"a": 10}, + lambda c: c.__delitem__("a"), + raises(ReadonlyConfigError, match="a"), + id="dict_delitem", + ), + # list + pytest.param( + [], + lambda c: c.__setitem__(0, 1), + raises(ReadonlyConfigError, match="0"), + id="list_setitem", + ), + pytest.param( + [], + lambda c: OmegaConf.update(c, "0.b", 10, merge=True), + raises(ReadonlyConfigError, match="[0]"), + id="list_update", + ), + pytest.param( + [10], lambda c: c.pop(), raises(ReadonlyConfigError), id="list_pop" + ), + pytest.param( + [0], + lambda c: c.__delitem__(0), + raises(ReadonlyConfigError, match="[0]"), + id="list_delitem", + ), + ], +) +def test_readonly( + src: Union[Dict[str, Any], List[Any]], func: Callable[[Any], Any], expectation: Any +) -> None: + c = OmegaConf.create(src) + OmegaConf.set_readonly(c, True) + with expectation: + func(c) + assert c == src + + +@pytest.mark.parametrize("src", [{}, []]) # type: ignore +def test_readonly_flag(src: Union[Dict[str, Any], List[Any]]) -> None: + c = OmegaConf.create(src) + assert not OmegaConf.is_readonly(c) + OmegaConf.set_readonly(c, True) + assert OmegaConf.is_readonly(c) + OmegaConf.set_readonly(c, False) + assert not OmegaConf.is_readonly(c) + OmegaConf.set_readonly(c, None) + assert not OmegaConf.is_readonly(c) + + +def test_readonly_nested_list() -> None: + c = OmegaConf.create([[1]]) + assert isinstance(c, ListConfig) + assert not OmegaConf.is_readonly(c) + assert not OmegaConf.is_readonly(c[0]) + OmegaConf.set_readonly(c, True) + assert OmegaConf.is_readonly(c) + assert OmegaConf.is_readonly(c[0]) + OmegaConf.set_readonly(c, False) + assert not OmegaConf.is_readonly(c) + assert not OmegaConf.is_readonly(c[0]) + OmegaConf.set_readonly(c, None) + assert not OmegaConf.is_readonly(c) + assert not OmegaConf.is_readonly(c[0]) + OmegaConf.set_readonly(c[0], True) + assert not OmegaConf.is_readonly(c) + assert OmegaConf.is_readonly(c[0]) + + +def test_readonly_list_insert() -> None: + c = OmegaConf.create([]) + OmegaConf.set_readonly(c, True) + with raises(ReadonlyConfigError, match="[0]"): + c.insert(0, 10) + assert c == [] + + +def test_readonly_list_insert_deep() -> None: + src: List[Dict[str, Any]] = [dict(a=[dict(b=[])])] + c = OmegaConf.create(src) + assert isinstance(c, ListConfig) + OmegaConf.set_readonly(c, True) + with raises(ReadonlyConfigError, match=re.escape("[0].a[0].b[0]")): + c[0].a[0].b.insert(0, 10) + assert c == src + + +def test_readonly_list_append() -> None: + c = OmegaConf.create([]) + OmegaConf.set_readonly(c, True) + with raises(ReadonlyConfigError, match="[0]"): + c.append(10) + assert c == [] + + +def test_readonly_list_change_item() -> None: + c = OmegaConf.create([1, 2, 3]) + assert isinstance(c, ListConfig) + OmegaConf.set_readonly(c, True) + with raises(ReadonlyConfigError, match="[1]"): + c[1] = 10 + assert c == [1, 2, 3] + + +def test_readonly_list_pop() -> None: + c = OmegaConf.create([1, 2, 3]) + assert isinstance(c, ListConfig) + OmegaConf.set_readonly(c, True) + with raises(ReadonlyConfigError, match="[1]"): + c.pop(1) + assert c == [1, 2, 3] + + +def test_readonly_list_del() -> None: + c = OmegaConf.create([1, 2, 3]) + assert isinstance(c, ListConfig) + OmegaConf.set_readonly(c, True) + with raises(ReadonlyConfigError, match="[1]"): + del c[1] + assert c == [1, 2, 3] + + +def test_readonly_list_sort() -> None: + c = OmegaConf.create([3, 1, 2]) + assert isinstance(c, ListConfig) + OmegaConf.set_readonly(c, True) + with raises(ReadonlyConfigError): + c.sort() + assert c == [3, 1, 2] + + +def test_readonly_from_cli() -> None: + c = OmegaConf.create({"foo": {"bar": [1]}}) + assert isinstance(c, DictConfig) + OmegaConf.set_readonly(c, True) + cli = OmegaConf.from_dotlist(["foo.bar=[2]"]) + cfg2 = OmegaConf.merge(c, cli) + assert OmegaConf.is_readonly(c) + assert OmegaConf.is_readonly(cfg2) + + +@pytest.mark.parametrize( # type: ignore + "cfg1, cfg2", + [ + pytest.param({"foo": {"bar": 10}}, {"foo": {"bar": 20}}, id="override_value"), + pytest.param({"foo": {"bar": 10}}, {"foo": {"yup": 20}}, id="adding_key"), + pytest.param({"a": 1}, {"b": 2}, id="adding_key"), + pytest.param({"a": 1}, OmegaConf.create({"b": 2}), id="adding_key"), + ], +) +def test_merge_with_readonly(cfg1: Dict[str, Any], cfg2: Dict[str, Any]) -> None: + c = OmegaConf.create(cfg1) + OmegaConf.set_readonly(c, True) + with raises(ReadonlyConfigError): + c.merge_with(cfg2) + + +@pytest.mark.parametrize( # type: ignore + "readonly_key, cfg1, cfg2, expected", + [ + pytest.param( + "", + {"foo": {"bar": 10}}, + {"foo": {}}, + {"foo": {"bar": 10}}, + id="merge_empty_dict", + ), + pytest.param( + "foo", + {"foo": {"bar": 10}}, + {"xyz": 10}, + {"foo": {"bar": 10}, "xyz": 10}, + id="merge_different_node", + ), + ], +) +def test_merge_with_readonly_nop( + readonly_key: str, + cfg1: Dict[str, Any], + cfg2: Dict[str, Any], + expected: Dict[str, Any], +) -> None: + c = OmegaConf.create(cfg1) + OmegaConf.set_readonly(OmegaConf.select(c, readonly_key), True) + c.merge_with(cfg2) + assert c == OmegaConf.create(expected) diff --git a/tests/test_select.py b/tests/test_select.py new file mode 100644 index 0000000000000000000000000000000000000000..d396bf4c72c416ba681c76893a09e62da608daa5 --- /dev/null +++ b/tests/test_select.py @@ -0,0 +1,88 @@ +import re +from typing import Any, Optional + +import pytest +from pytest import raises + +from omegaconf import MissingMandatoryValue, OmegaConf + +from . import does_not_raise + + +@pytest.mark.parametrize("struct", [True, False, None]) # type: ignore +def test_select_key_from_empty(struct: Optional[bool]) -> None: + c = OmegaConf.create() + OmegaConf.set_struct(c, struct) + assert OmegaConf.select(c, "not_there") is None + + +@pytest.mark.parametrize( # type: ignore + "cfg, keys, expected, expectation", + [ + ({}, "nope", None, does_not_raise()), + ({}, "not.there", None, does_not_raise()), + ({}, "still.not.there", None, does_not_raise()), + ({"c": 1}, "c", 1, does_not_raise()), + ({"a": {"v": 1}}, "a", {"v": 1}, does_not_raise()), + ({"a": {"v": 1}}, "a.v", 1, does_not_raise()), + ({"missing": "???"}, "missing", None, does_not_raise()), + ([], "0", None, does_not_raise()), + ([1, "2"], ("0", "1"), (1, "2"), does_not_raise()), + ( + [1, {"a": 10, "c": ["foo", "bar"]}], + ("0", "1.a", "1.b", "1.c.0", "1.c.1"), + (1, 10, None, "foo", "bar"), + does_not_raise(), + ), + ([1, 2, 3], "a", None, raises(TypeError)), + ( + {"a": {"v": 1}, "b": {"v": 1}}, + "", + {"a": {"v": 1}, "b": {"v": 1}}, + does_not_raise(), + ), + ( + {"dict": {"one": 1}, "foo": "one=${dict.one}"}, + "foo", + "one=1", + does_not_raise(), + ), + ( + {"dict": {"foo": "one=${one}"}, "one": 1}, + "dict.foo", + "one=1", + does_not_raise(), + ), + ({"dict": {"foo": "one=${foo:1}"}}, "dict.foo", "one=_1_", does_not_raise()), + ], +) +def test_select( + restore_resolvers: Any, cfg: Any, keys: Any, expected: Any, expectation: Any +) -> None: + if not isinstance(keys, (tuple, list)): + keys = [keys] + if not isinstance(expected, (tuple, list)): + expected = [expected] + OmegaConf.register_resolver("foo", lambda x: f"_{x}_") + + c = OmegaConf.create(cfg) + with expectation: + for idx, key in enumerate(keys): + assert OmegaConf.select(c, key) == expected[idx] + + +def test_select_from_dict() -> None: + c = OmegaConf.create({"missing": "???"}) + with pytest.raises(MissingMandatoryValue): + OmegaConf.select(c, "missing", throw_on_missing=True) + assert OmegaConf.select(c, "missing", throw_on_missing=False) is None + assert OmegaConf.select(c, "missing") is None + + +def test_select_deprecated() -> None: + c = OmegaConf.create({"foo": "bar"}) + with pytest.warns( + expected_warning=UserWarning, + match=re.escape("select() is deprecated, use OmegaConf.select(). (Since 2.0)"), + ): + c.select("foo") diff --git a/tests/test_serialization.py b/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..24f5f8b9b8effaed123449c20a80e2e07515f16e --- /dev/null +++ b/tests/test_serialization.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- +import io +import os +import pathlib +import pickle +import tempfile +from pathlib import Path +from textwrap import dedent +from typing import Any, Dict, Type + +import pytest + +from omegaconf import MISSING, DictConfig, OmegaConf + +from . import PersonA, PersonD + + +def save_load_from_file(conf: Any, resolve: bool, expected: Any) -> None: + if expected is None: + expected = conf + try: + with tempfile.NamedTemporaryFile( + mode="wt", delete=False, encoding="utf-8" + ) as fp: + OmegaConf.save(conf, fp.file, resolve=resolve) # type: ignore + with io.open(os.path.abspath(fp.name), "rt", encoding="utf-8") as handle: + c2 = OmegaConf.load(handle) + assert c2 == expected + finally: + os.unlink(fp.name) + + +def save_load_from_filename( + conf: Any, resolve: bool, expected: Any, file_class: Type[Any] +) -> None: + if expected is None: + expected = conf + # note that delete=False here is a work around windows incompetence. + try: + with tempfile.NamedTemporaryFile(delete=False) as fp: + filepath = file_class(fp.name) + OmegaConf.save(conf, filepath, resolve=resolve) + c2 = OmegaConf.load(filepath) + assert c2 == expected + finally: + os.unlink(fp.name) + + +def test_load_from_invalid() -> None: + with pytest.raises(TypeError): + OmegaConf.load(3.1415) # type: ignore + + +@pytest.mark.parametrize( + "input_,resolve,expected,file_class", + [ + ({"a": 10}, False, None, str), + ({"foo": 10, "bar": "${foo}"}, False, None, str), + ({"foo": 10, "bar": "${foo}"}, False, None, pathlib.Path), + ({"foo": 10, "bar": "${foo}"}, False, {"foo": 10, "bar": 10}, str), + ([u"שלום"], False, None, str), + ], +) +class TestSaveLoad: + def test_save_load__from_file( + self, + input_: Dict[str, Any], + resolve: bool, + expected: Any, + file_class: Type[Any], + ) -> None: + cfg = OmegaConf.create(input_) + save_load_from_file(cfg, resolve, expected) + + def test_save_load__from_filename( + self, + input_: Dict[str, Any], + resolve: bool, + expected: Any, + file_class: Type[Any], + ) -> None: + cfg = OmegaConf.create(input_) + save_load_from_filename(cfg, resolve, expected, file_class) + + +@pytest.mark.parametrize( + "input_,resolve,expected,file_class", + [ + (PersonA, False, {"age": 18, "registered": True}, str), + (PersonD, False, {"age": 18, "registered": True}, str), + (PersonA(), False, {"age": 18, "registered": True}, str), + (PersonD(), False, {"age": 18, "registered": True}, str), + ], +) +class TestSaveLoadStructured: + def test_save_load__from_file( + self, + input_: Dict[str, Any], + resolve: bool, + expected: Any, + file_class: Type[Any], + ) -> None: + save_load_from_file(input_, resolve, expected) + + def test_save_load__from_filename( + self, + input_: Dict[str, Any], + resolve: bool, + expected: Any, + file_class: Type[Any], + ) -> None: + save_load_from_filename(input_, resolve, expected, file_class) + + +def test_save_illegal_type() -> None: + with pytest.raises(TypeError): + OmegaConf.save(OmegaConf.create(), 1000) # type: ignore + + +def test_pickle_dict() -> None: + with tempfile.TemporaryFile() as fp: + c = OmegaConf.create({"a": "b"}) + pickle.dump(c, fp) + fp.flush() + fp.seek(0) + c1 = pickle.load(fp) + assert c == c1 + + +def test_pickle_list() -> None: + with tempfile.TemporaryFile() as fp: + c = OmegaConf.create([1, 2, 3]) + pickle.dump(c, fp) + fp.flush() + fp.seek(0) + c1 = pickle.load(fp) + assert c == c1 + + +def test_load_duplicate_keys_top() -> None: + from yaml.constructor import ConstructorError + + try: + with tempfile.NamedTemporaryFile(delete=False) as fp: + content = dedent( + """\ + a: + b: 1 + a: + b: 2 + """ + ) + fp.write(content.encode("utf-8")) + with pytest.raises(ConstructorError): + OmegaConf.load(fp.name) + finally: + os.unlink(fp.name) + + +def test_load_duplicate_keys_sub() -> None: + from yaml.constructor import ConstructorError + + try: + with tempfile.NamedTemporaryFile(delete=False) as fp: + content = dedent( + """\ + a: + b: 1 + c: 2 + b: 3 + """ + ) + fp.write(content.encode("utf-8")) + with pytest.raises(ConstructorError): + OmegaConf.load(fp.name) + finally: + os.unlink(fp.name) + + +def test_load_empty_file(tmpdir: str) -> None: + empty = Path(tmpdir) / "test.yaml" + empty.touch() + + assert OmegaConf.load(empty) == {} + + +def test_pickle_missing() -> None: + cfg = DictConfig(content=MISSING) + with tempfile.TemporaryFile() as fp: + import pickle + + pickle.dump(cfg, fp) + fp.flush() + fp.seek(0) + cfg2 = pickle.load(fp) + assert cfg == cfg2 + + +def test_pickle_none() -> None: + cfg = DictConfig(content=None) + with tempfile.TemporaryFile() as fp: + import pickle + + pickle.dump(cfg, fp) + fp.flush() + fp.seek(0) + cfg2 = pickle.load(fp) + assert cfg == cfg2 diff --git a/tests/test_struct.py b/tests/test_struct.py new file mode 100644 index 0000000000000000000000000000000000000000..9a90a8e47c432a5b30dd26a999df00c828e450b0 --- /dev/null +++ b/tests/test_struct.py @@ -0,0 +1,60 @@ +import re +from typing import Any, Dict + +import pytest + +from omegaconf import OmegaConf +from omegaconf.errors import ConfigKeyError + + +def test_struct_default() -> None: + c = OmegaConf.create() + assert c.not_found is None + assert OmegaConf.is_struct(c) is None + + +def test_struct_set_on_dict() -> None: + c = OmegaConf.create({"a": {}}) + OmegaConf.set_struct(c, True) + # Throwing when it hits foo, so exception key is a.foo and not a.foo.bar + with pytest.raises(AttributeError, match=re.escape("a.foo")): + # noinspection PyStatementEffect + c.a.foo.bar + + +def test_struct_set_on_nested_dict() -> None: + c = OmegaConf.create(dict(a=dict(b=10))) + OmegaConf.set_struct(c, True) + with pytest.raises(AttributeError): + # noinspection PyStatementEffect + c.foo + + assert "a" in c + assert c.a.b == 10 + with pytest.raises(AttributeError, match=re.escape("a.foo")): + # noinspection PyStatementEffect + c.a.foo + + +def test_merge_dotlist_into_struct() -> None: + c = OmegaConf.create(dict(a=dict(b=10))) + OmegaConf.set_struct(c, True) + with pytest.raises(AttributeError, match=re.escape("foo")): + c.merge_with_dotlist(["foo=1"]) + + +@pytest.mark.parametrize("in_base, in_merged", [(dict(), dict(a=10))]) # type: ignore +def test_merge_config_with_struct( + in_base: Dict[str, Any], in_merged: Dict[str, Any] +) -> None: + base = OmegaConf.create(in_base) + merged = OmegaConf.create(in_merged) + OmegaConf.set_struct(base, True) + with pytest.raises(ConfigKeyError): + OmegaConf.merge(base, merged) + + +def test_struct_contain_missing() -> None: + c = OmegaConf.create(dict()) + OmegaConf.set_struct(c, True) + assert "foo" not in c diff --git a/tests/test_to_yaml.py b/tests/test_to_yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..55b70d283864d5aed22f33f1a4950eccf38a6f39 --- /dev/null +++ b/tests/test_to_yaml.py @@ -0,0 +1,159 @@ +import re +from textwrap import dedent +from typing import Any + +import pytest + +from omegaconf import DictConfig, EnumNode, ListConfig, OmegaConf, _utils + +from . import Enum1, User + + +@pytest.mark.parametrize( # type: ignore + "input_, expected", + [ + (["item1", "item2", {"key3": "value3"}], "- item1\n- item2\n- key3: value3\n"), + ({"hello": "world", "list": [1, 2]}, "hello: world\nlist:\n- 1\n- 2\n"), + ], +) +def test_to_yaml(input_: Any, expected: str) -> None: + c = OmegaConf.create(input_) + assert expected == OmegaConf.to_yaml(c) + assert OmegaConf.create(OmegaConf.to_yaml(c)) == c + + +@pytest.mark.parametrize( # type: ignore + "input_, expected", + [ + (["item一", "item二", dict(key三="value三")], "- item一\n- item二\n- key三: value三\n"), + (dict(你好="世界", list=[1, 2]), "你好: 世界\nlist:\n- 1\n- 2\n"), + ], +) +def test_to_yaml_unicode(input_: Any, expected: str) -> None: + c = OmegaConf.create(input_) + assert expected == OmegaConf.to_yaml(c) + assert OmegaConf.create(OmegaConf.to_yaml(c)) == c + + +@pytest.mark.parametrize( # type: ignore + "input_, expected, type_", + [ + (["1", 1], "- '1'\n- 1\n", int), + (["10e2", "1.0", 1.0], "- '10e2'\n- '1.0'\n- 1.0\n", float), + (_utils.YAML_BOOL_TYPES, None, bool), + ], +) +def test_to_yaml_string_primitive_types_list( + input_: Any, expected: str, type_: type +) -> None: + if type_ == bool: + for t in input_: + c = OmegaConf.create([t, 1]) + expected = "- '%s'\n- 1\n" % t + assert OmegaConf.to_yaml(c) == expected + + else: + c = OmegaConf.create(input_) + assert OmegaConf.to_yaml(c) == expected + + +@pytest.mark.parametrize( # type: ignore + "input_, expected, type_", + [ + ({"b": "1", "a": 1}, "b: '1'\na: 1\n", int), + ({"b": "10e2", "a": "1.0", "c": 1.0}, "b: '10e2'\na: '1.0'\nc: 1.0\n", float), + (_utils.YAML_BOOL_TYPES, None, bool), + ], +) +def test_to_yaml_string_primitive_types_dict( + input_: Any, expected: str, type_: type +) -> None: + if type_ == bool: + for t in input_: + c = OmegaConf.create({"b": t, "a": 1}) + assert OmegaConf.to_yaml(c) == "b: '%s'\na: 1\n" % t + else: + c = OmegaConf.create(input_) + assert OmegaConf.to_yaml(c) == expected + + +@pytest.mark.parametrize( # type: ignore + "input_, resolve, expected", + [ + (dict(a1="${ref}", ref="bar"), True, "bar"), + (dict(a1="${ref}", ref="bar"), False, "changed"), + ([100, "${0}"], True, 100), + ([100, "${0}"], False, 1000), + ], +) +def test_to_yaml_resolve(input_: Any, resolve: bool, expected: int) -> None: + c = OmegaConf.create(input_) + # without resolve, references are preserved + yaml_str = OmegaConf.to_yaml(c, resolve=resolve) + c2 = OmegaConf.create(yaml_str) + assert isinstance(c2, ListConfig) or isinstance(c2, DictConfig) + if isinstance(c2, DictConfig): + assert c2.a1 == "bar" + c2.ref = "changed" + assert c2.a1 == expected + else: + c2[0] = 1000 + assert c2[1] == expected + + +def test_to_yaml_sort_keys() -> None: + c = OmegaConf.create({"b": 2, "a": 1}) + # keys are not sorted by default + assert OmegaConf.to_yaml(c) == "b: 2\na: 1\n" + c = OmegaConf.create({"b": 2, "a": 1}) + assert OmegaConf.to_yaml(c, sort_keys=True) == "a: 1\nb: 2\n" + + +def test_to_yaml_with_enum() -> None: + cfg = OmegaConf.create() + assert isinstance(cfg, DictConfig) + cfg.foo = EnumNode(Enum1) + cfg.foo = Enum1.FOO + + expected = """foo: FOO +""" + s = OmegaConf.to_yaml(cfg) + assert s == expected + assert ( + OmegaConf.merge({"foo": EnumNode(Enum1, value="???")}, OmegaConf.create(s)) + == cfg + ) + + +def test_pretty_deprecated() -> None: + c = OmegaConf.create({"foo": "bar"}) + with pytest.warns( + expected_warning=UserWarning, + match=re.escape( + dedent( + """\ + cfg.pretty() is deprecated and will be removed in a future version. + Use OmegaConf.to_yaml(cfg) + """, + ) + ), + ): + assert c.pretty() == "foo: bar\n" + + +@pytest.mark.parametrize( # type: ignore + "user", + [ + User(name="Bond", age=7), + OmegaConf.structured(User(name="Bond", age=7)), + {"name": "Bond", "age": 7}, + ], +) +def test_structured_configs(user: User) -> None: + expected = dedent( + """\ + name: Bond + age: 7 + """ + ) + assert OmegaConf.to_yaml(user) == expected diff --git a/tests/test_update.py b/tests/test_update.py new file mode 100644 index 0000000000000000000000000000000000000000..5b4d0e3cb0cfa6f94b1d2ce894ed7b1894e0a8db --- /dev/null +++ b/tests/test_update.py @@ -0,0 +1,199 @@ +import re +from textwrap import dedent +from typing import Any + +import pytest +from pytest import raises + +from omegaconf import ListConfig, OmegaConf, ValidationError +from omegaconf._utils import _ensure_container, is_primitive_container +from tests import Package + + +@pytest.mark.parametrize( # type: ignore + "cfg,key,value,expected", + [ + # dict + pytest.param({"a": "b"}, "a", "c", {"a": "c"}, id="replace:string"), + pytest.param({"a": "b"}, "c", "d", {"a": "b", "c": "d"}, id="add:string"), + pytest.param({"a": "b"}, "c", None, {"a": "b", "c": None}, id="none_value"), + pytest.param({}, "a", {}, {"a": {}}, id="dict:value:empty_dict"), + pytest.param({}, "a", {"b": 1}, {"a": {"b": 1}}, id="value:dict"), + pytest.param({}, "a.b", 1, {"a": {"b": 1}}, id="dict:deep"), + pytest.param( + {"a": "b"}, "a.b", {"c": 1}, {"a": {"b": {"c": 1}}}, id="dict:deep:map" + ), + pytest.param({}, "a", 1, {"a": 1}, id="dict:value"), + pytest.param({}, "a.b", 1, {"a": {"b": 1}}, id="dict:deep:value"), + pytest.param({"a": 1}, "b.c", 2, {"a": 1, "b": {"c": 2}}, id="dict:deep:value"), + pytest.param( + {"a": {"b": {"c": 1}}}, + "a.b.d", + 2, + {"a": {"b": {"c": 1, "d": 2}}}, + id="deep_map_update", + ), + pytest.param({"a": "???"}, "a", 123, {"a": 123}, id="update_missing"), + pytest.param({"a": None}, "a", None, {"a": None}, id="same_value"), + pytest.param({"a": 123}, "a", 123, {"a": 123}, id="same_value"), + pytest.param({}, "a", {}, {"a": {}}, id="dict_value"), + pytest.param({}, "a", {"b": 1}, {"a": {"b": 1}}, id="dict_value"), + pytest.param({"a": {"b": 2}}, "a", {"b": 1}, {"a": {"b": 1}}, id="dict_value"), + # dict value (merge or set) + pytest.param( + {"a": None}, + "a", + {"c": 2}, + {"a": {"c": 2}}, + id="dict_value:merge", + ), + pytest.param( + {"a": {"b": 1}}, + "a", + {"c": 2}, + {"a": {"b": 1, "c": 2}}, + id="dict_value:merge", + ), + # list + pytest.param({"a": [1, 2]}, "a", [2, 3], {"a": [2, 3]}, id="list:replace"), + pytest.param([1, 2, 3], "1", "abc", [1, "abc", 3], id="list:update"), + pytest.param([1, 2, 3], "-1", "abc", [1, 2, "abc"], id="list:update"), + pytest.param( + {"a": {"b": [1, 2, 3]}}, + "a.b.1", + "abc", + {"a": {"b": [1, "abc", 3]}}, + id="list:nested:update", + ), + pytest.param( + {"a": {"b": [1, 2, 3]}}, + "a.b.-1", + "abc", + {"a": {"b": [1, 2, "abc"]}}, + id="list:nested:update", + ), + pytest.param([{"a": 1}], "0", {"b": 2}, [{"a": 1, "b": 2}], id="list:merge"), + pytest.param( + {"list": [{"a": 1}]}, + "list", + [{"b": 2}], + {"list": [{"b": 2}]}, + id="list:merge", + ), + ], +) +def test_update(cfg: Any, key: str, value: Any, expected: Any) -> None: + cfg = _ensure_container(cfg) + OmegaConf.update(cfg, key, value, merge=True) + assert cfg == expected + + +@pytest.mark.parametrize( # type: ignore + "cfg,key,value,merge,expected", + [ + pytest.param( + {"a": {"b": 1}}, + "a", + {"c": 2}, + True, + {"a": {"b": 1, "c": 2}}, + id="dict_value:merge", + ), + pytest.param( + {"a": {"b": 1}}, + "a", + {"c": 2}, + False, + {"a": {"c": 2}}, + id="dict_value:set", + ), + # merging lists is replacing. + # this is useful when we mix it Structured Configs + pytest.param( + {"a": {"b": [1, 2]}}, + "a.b", + [3, 4], + True, + {"a": {"b": [3, 4]}}, + id="list:merge", + ), + pytest.param( + {"a": {"b": [1, 2]}}, + "a.b", + [3, 4], + False, + {"a": {"b": [3, 4]}}, + id="list:set", + ), + pytest.param( + Package, + "modules", + [{"name": "foo"}], + True, + {"modules": [{"name": "foo", "classes": "???"}]}, + id="structured_list:merge", + ), + pytest.param( + Package, + "modules", + [{"name": "foo"}], + False, + pytest.raises(ValidationError), + id="structured_list:set", + ), + ], +) +def test_update_merge_set( + cfg: Any, key: str, value: Any, merge: bool, expected: Any +) -> None: + cfg = _ensure_container(cfg) + if is_primitive_container(expected): + OmegaConf.update(cfg, key, value, merge=merge) + assert cfg == expected + else: + with expected: + OmegaConf.update(cfg, key, value, merge=merge) + + +def test_update_list_make_dict() -> None: + c = OmegaConf.create([None, None]) + assert isinstance(c, ListConfig) + OmegaConf.update(c, "0.a.a", "aa", merge=True) + OmegaConf.update(c, "0.a.b", "ab", merge=True) + OmegaConf.update(c, "1.b.a", "ba", merge=True) + OmegaConf.update(c, "1.b.b", "bb", merge=True) + assert c == [{"a": {"a": "aa", "b": "ab"}}, {"b": {"a": "ba", "b": "bb"}}] + + +def test_update_node_deprecated() -> None: + c = OmegaConf.create() + with pytest.warns( + expected_warning=UserWarning, + match=re.escape( + "update_node() is deprecated, use OmegaConf.update(). (Since 2.0)" + ), + ): + c.update_node("foo", "bar") + assert c.foo == "bar" + + +def test_update_list_index_error() -> None: + c = OmegaConf.create([1, 2, 3]) + assert isinstance(c, ListConfig) + with raises(IndexError): + OmegaConf.update(c, "4", "abc", merge=True) + + assert c == [1, 2, 3] + + +def test_merge_deprecation() -> None: + cfg = OmegaConf.create({"a": {"b": 10}}) + msg = dedent( + """\ + update() merge flag is is not specified, defaulting to False. + For more details, see https://github.com/omry/omegaconf/issues/367""" + ) + + with pytest.warns(UserWarning, match=re.escape(msg)): + OmegaConf.update(cfg, "a", {"c": 20}) # default to set, and issue a warning. + assert cfg == {"a": {"c": 20}} diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..da48b4993e0d8713121725edc4ee398a4965651d --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,513 @@ +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, List, Optional, Union + +import attr +import pytest + +from omegaconf import DictConfig, ListConfig, Node, OmegaConf, _utils +from omegaconf._utils import is_dict_annotation, is_list_annotation +from omegaconf.errors import KeyValidationError, ValidationError +from omegaconf.nodes import ( + AnyNode, + BooleanNode, + EnumNode, + FloatNode, + IntegerNode, + StringNode, +) +from omegaconf.omegaconf import _node_wrap + +from . import Color, ConcretePlugin, IllegalType, Plugin, does_not_raise + + +@pytest.mark.parametrize( # type: ignore + "target_type, value, expected", + [ + # Any + pytest.param(Any, "foo", AnyNode("foo"), id="any"), + pytest.param(Any, True, AnyNode(True), id="any"), + pytest.param(Any, 1, AnyNode(1), id="any"), + pytest.param(Any, 1.0, AnyNode(1.0), id="any"), + pytest.param(Any, Color.RED, AnyNode(Color.RED), id="any"), + pytest.param(Any, {}, DictConfig(content={}), id="any_as_dict"), + pytest.param(Any, [], ListConfig(content=[]), id="any_as_list"), + # int + pytest.param(int, "foo", ValidationError, id="int"), + pytest.param(int, True, ValidationError, id="int"), + pytest.param(int, 1, IntegerNode(1), id="int"), + pytest.param(int, 1.0, ValidationError, id="int"), + pytest.param(int, Color.RED, ValidationError, id="int"), + # float + pytest.param(float, "foo", ValidationError, id="float"), + pytest.param(float, True, ValidationError, id="float"), + pytest.param(float, 1, FloatNode(1), id="float"), + pytest.param(float, 1.0, FloatNode(1.0), id="float"), + pytest.param(float, Color.RED, ValidationError, id="float"), + # # bool + pytest.param(bool, "foo", ValidationError, id="bool"), + pytest.param(bool, True, BooleanNode(True), id="bool"), + pytest.param(bool, 1, BooleanNode(True), id="bool"), + pytest.param(bool, 0, BooleanNode(False), id="bool"), + pytest.param(bool, 1.0, ValidationError, id="bool"), + pytest.param(bool, Color.RED, ValidationError, id="bool"), + pytest.param(bool, "true", BooleanNode(True), id="bool"), + pytest.param(bool, "false", BooleanNode(False), id="bool"), + pytest.param(bool, "on", BooleanNode(True), id="bool"), + pytest.param(bool, "off", BooleanNode(False), id="bool"), + # str + pytest.param(str, "foo", StringNode("foo"), id="str"), + pytest.param(str, True, StringNode("True"), id="str"), + pytest.param(str, 1, StringNode("1"), id="str"), + pytest.param(str, 1.0, StringNode("1.0"), id="str"), + pytest.param(str, Color.RED, StringNode("Color.RED"), id="str"), + # Color + pytest.param(Color, "foo", ValidationError, id="Color"), + pytest.param(Color, True, ValidationError, id="Color"), + pytest.param(Color, 1, EnumNode(enum_type=Color, value=Color.RED), id="Color"), + pytest.param(Color, 1.0, ValidationError, id="Color"), + pytest.param( + Color, Color.RED, EnumNode(enum_type=Color, value=Color.RED), id="Color" + ), + pytest.param( + Color, "RED", EnumNode(enum_type=Color, value=Color.RED), id="Color" + ), + pytest.param( + Color, "Color.RED", EnumNode(enum_type=Color, value=Color.RED), id="Color" + ), + # bad type + pytest.param(IllegalType, "nope", ValidationError, id="bad_type"), + # DictConfig + pytest.param( + dict, {"foo": "bar"}, DictConfig(content={"foo": "bar"}), id="DictConfig" + ), + pytest.param( + Plugin, Plugin(), DictConfig(content=Plugin()), id="DictConfig[Plugin]" + ), + # ListConfig + pytest.param(list, [1, 2, 3], ListConfig(content=[1, 2, 3]), id="ListConfig"), + ], +) +def test_node_wrap(target_type: Any, value: Any, expected: Any) -> None: + from omegaconf.omegaconf import _maybe_wrap + + if isinstance(expected, Node): + res = _node_wrap( + type_=target_type, key="foo", value=value, is_optional=False, parent=None + ) + assert type(res) == type(expected) + assert res == expected + assert res._key() == "foo" + else: + with pytest.raises(expected): + _maybe_wrap( + ref_type=target_type, + key=None, + value=value, + is_optional=False, + parent=None, + ) + + +class _TestEnum(Enum): + A = 1 + B = 2 + + +@dataclass +class _TestDataclass: + x: int = 10 + s: str = "foo" + b: bool = True + f: float = 3.14 + e: _TestEnum = _TestEnum.A + list1: List[int] = field(default_factory=list) + dict1: Dict[str, int] = field(default_factory=dict) + + +@attr.s(auto_attribs=True) +class _TestAttrsClass: + x: int = 10 + s: str = "foo" + b: bool = True + f: float = 3.14 + e: _TestEnum = _TestEnum.A + list1: List[int] = [] + dict1: Dict[str, int] = {} + + +class _TestUserClass: + pass + + +@pytest.mark.parametrize( # type: ignore + "type_, expected", + [ + (int, True), + (float, True), + (bool, True), + (str, True), + (Any, True), + (_TestEnum, True), + (_TestUserClass, False), + # Nesting structured configs in contain + (_TestAttrsClass, True), + (_TestDataclass, True), + ], +) +def test_valid_value_annotation_type(type_: type, expected: bool) -> None: + from omegaconf._utils import valid_value_annotation_type + + assert valid_value_annotation_type(type_) == expected + + +@pytest.mark.parametrize( # type: ignore + "test_cls_or_obj, expectation", + [ + (_TestDataclass, does_not_raise()), + (_TestDataclass(), does_not_raise()), + (_TestAttrsClass, does_not_raise()), + (_TestAttrsClass(), does_not_raise()), + ("invalid", pytest.raises(ValueError)), + ], +) +def test_get_structured_config_data(test_cls_or_obj: Any, expectation: Any) -> None: + with expectation: + d = _utils.get_structured_config_data(test_cls_or_obj) + assert d["x"] == 10 + assert d["s"] == "foo" + assert d["b"] == bool(True) + assert d["f"] == 3.14 + assert d["e"] == _TestEnum.A + assert d["list1"] == [] + assert d["dict1"] == {} + + +def test_is_dataclass(mocker: Any) -> None: + @dataclass + class Foo: + pass + + assert _utils.is_dataclass(Foo) + assert _utils.is_dataclass(Foo()) + assert not _utils.is_dataclass(10) + + mocker.patch("omegaconf._utils.dataclasses", None) + assert not _utils.is_dataclass(10) + + +def test_is_attr_class(mocker: Any) -> None: + @attr.s + class Foo: + pass + + assert _utils.is_attr_class(Foo) + assert _utils.is_attr_class(Foo()) + + assert not _utils.is_attr_class(10) + mocker.patch("omegaconf._utils.attr", None) + assert not _utils.is_attr_class(10) + + +def test_is_structured_config_frozen_with_invalid_obj() -> None: + assert not _utils.is_structured_config_frozen(10) + + +@dataclass +class Dataclass: + pass + + +@pytest.mark.parametrize( # type: ignore + "value,kind", + [ + ("foo", _utils.ValueKind.VALUE), + (1, _utils.ValueKind.VALUE), + (1.0, _utils.ValueKind.VALUE), + (True, _utils.ValueKind.VALUE), + (False, _utils.ValueKind.VALUE), + (Color.GREEN, _utils.ValueKind.VALUE), + (Dataclass, _utils.ValueKind.VALUE), + ("???", _utils.ValueKind.MANDATORY_MISSING), + ("${foo.bar}", _utils.ValueKind.INTERPOLATION), + ("ftp://${host}/path", _utils.ValueKind.STR_INTERPOLATION), + ("${func:foo}", _utils.ValueKind.INTERPOLATION), + ("${func:a/b}", _utils.ValueKind.INTERPOLATION), + ("${func:c:\\a\\b}", _utils.ValueKind.INTERPOLATION), + ("${func:c:\\a\\b}", _utils.ValueKind.INTERPOLATION), + ], +) +def test_value_kind(value: Any, kind: _utils.ValueKind) -> None: + assert _utils.get_value_kind(value) == kind + + +def test_re_parent() -> None: + def validate(cfg1: DictConfig) -> None: + assert cfg1._get_parent() is None + assert cfg1._get_node("str")._get_parent() == cfg1 # type:ignore + assert cfg1._get_node("list")._get_parent() == cfg1 # type:ignore + assert cfg1.list._get_node(0)._get_parent() == cfg1.list + + cfg = OmegaConf.create({}) + assert isinstance(cfg, DictConfig) + cfg.str = StringNode("str") + cfg.list = [1] + + validate(cfg) + + cfg._get_node("str")._set_parent(None) # type:ignore + cfg._get_node("list")._set_parent(None) # type:ignore + cfg.list._get_node(0)._set_parent(None) # type: ignore + # noinspection PyProtectedMember + cfg._re_parent() + validate(cfg) + + +def test_get_class() -> None: + name = "tests.examples.test_dataclass_example.SimpleTypes" + assert _utils._get_class(name).__name__ == "SimpleTypes" + with pytest.raises(ValueError): + _utils._get_class("not_found") + + with pytest.raises(ModuleNotFoundError): + _utils._get_class("foo.not_found") + + with pytest.raises(ImportError): + _utils._get_class("tests.examples.test_dataclass_example.not_found") + + +@pytest.mark.parametrize( # type: ignore + "key_type,expected_key_type", + [ + (int, KeyValidationError), + (str, str), + (Color, Color), + (Any, None), + (None, KeyValidationError), + ], +) +@pytest.mark.parametrize( # type: ignore + "value_type,expected_value_type", + [(int, int), (str, str), (Color, Color), (Any, None), (None, type(None))], +) +def test_get_key_value_types( + key_type: Any, expected_key_type: Any, value_type: Any, expected_value_type: Any +) -> None: + dt = Dict[key_type, value_type] # type: ignore + if expected_key_type is not None and issubclass(expected_key_type, Exception): + with pytest.raises(expected_key_type): + _utils.get_dict_key_value_types(dt) + + else: + assert _utils.get_dict_key_value_types(dt) == ( + expected_key_type, + expected_value_type, + ) + + +@pytest.mark.parametrize( # type: ignore + "type_, is_primitive", + [ + (int, True), + (float, True), + (bool, True), + (str, True), + (type(None), True), + (Color, True), + (list, False), + (ListConfig, False), + (dict, False), + (DictConfig, False), + ], +) +def test_is_primitive_type(type_: Any, is_primitive: bool) -> None: + assert _utils.is_primitive_type(type_) == is_primitive + + +@pytest.mark.parametrize("optional", [False, True]) # type: ignore +@pytest.mark.parametrize( # type: ignore + "type_, expected", + [ + (int, "int"), + (bool, "bool"), + (float, "float"), + (str, "str"), + (Color, "Color"), + (DictConfig, "DictConfig"), + (ListConfig, "ListConfig"), + (Dict[str, str], "Dict[str, str]"), + (Dict[Color, int], "Dict[Color, int]"), + (Dict[str, Plugin], "Dict[str, Plugin]"), + (Dict[str, List[Plugin]], "Dict[str, List[Plugin]]"), + (List[str], "List[str]"), + (List[Color], "List[Color]"), + (List[Dict[str, Color]], "List[Dict[str, Color]]"), + ], +) +def test_type_str(type_: Any, expected: str, optional: bool) -> None: + if optional: + assert _utils.type_str(Optional[type_]) == f"Optional[{expected}]" + else: + assert _utils.type_str(type_) == expected + + +def test_type_str_none() -> None: + assert _utils.type_str(None) == "NoneType" + + +@pytest.mark.parametrize( # type: ignore + "type_, expected", + [ + (Optional[int], "Optional[int]"), + (Union[str, int, Color], "Union[str, int, Color]"), + (Optional[Union[int]], "Optional[int]"), + (Optional[Union[int, str]], "Union[int, str, NoneType]"), + ], +) +def test_type_str_union(type_: Any, expected: str) -> None: + assert _utils.type_str(type_) == expected + + +@pytest.mark.parametrize( # type: ignore + "type_, expected", + [ + (Dict[str, int], True), + (Dict[str, float], True), + (Dict[IllegalType, bool], True), + (Dict[str, IllegalType], True), + (Dict[int, Color], True), + (Dict[Plugin, Plugin], True), + (Dict[IllegalType, int], True), + (Dict, True), + (List, False), + (dict, False), + (DictConfig, False), + ], +) +def test_is_dict_annotation(type_: Any, expected: Any) -> Any: + assert is_dict_annotation(type_=type_) == expected + + +@pytest.mark.parametrize( # type: ignore + "type_, expected", + [ + (List[int], True), + (List[float], True), + (List[bool], True), + (List[str], True), + (List[Color], True), + (List[Plugin], True), + (List[IllegalType], True), + (Dict, False), + (List, True), + (list, False), + (tuple, False), + (ListConfig, False), + ], +) +def test_is_list_annotation(type_: Any, expected: Any) -> Any: + assert is_list_annotation(type_=type_) == expected + + +@pytest.mark.parametrize( # type: ignore + "obj, expected", + [ + # Unwrapped values + pytest.param(10, Optional[int], id="int"), + pytest.param(10.0, Optional[float], id="float"), + pytest.param(True, Optional[bool], id="bool"), + pytest.param("bar", Optional[str], id="str"), + pytest.param(None, type(None), id="NoneType"), + pytest.param({}, Optional[Dict[Union[str, Enum], Any]], id="dict"), + pytest.param([], Optional[List[Any]], id="List[Any]"), + pytest.param(tuple(), Optional[List[Any]], id="List[Any]"), + pytest.param(ConcretePlugin(), Optional[ConcretePlugin], id="ConcretePlugin"), + pytest.param(ConcretePlugin, Optional[ConcretePlugin], id="ConcretePlugin"), + # Optional value nodes + pytest.param(IntegerNode(10), Optional[int], id="IntegerNode"), + pytest.param(FloatNode(10.0), Optional[float], id="FloatNode"), + pytest.param(BooleanNode(True), Optional[bool], id="BooleanNode"), + pytest.param(StringNode("bar"), Optional[str], id="StringNode"), + pytest.param( + EnumNode(enum_type=Color, value=Color.RED), + Optional[Color], + id="EnumNode[Color]", + ), + # Non-optional value nodes: + pytest.param(IntegerNode(10, is_optional=False), int, id="IntegerNode"), + pytest.param(FloatNode(10.0, is_optional=False), float, id="FloatNode"), + pytest.param(BooleanNode(True, is_optional=False), bool, id="BooleanNode"), + pytest.param(StringNode("bar", is_optional=False), str, id="StringNode"), + pytest.param( + EnumNode(enum_type=Color, value=Color.RED, is_optional=False), + Color, + id="EnumNode[Color]", + ), + # DictConfig + pytest.param(DictConfig(content={}), Any, id="DictConfig"), + pytest.param( + DictConfig(key_type=int, element_type=Color, content={}), + Optional[Dict[int, Color]], + id="DictConfig[int,Color]", + ), + pytest.param( + DictConfig(key_type=Color, element_type=int, content={}), + Optional[Dict[Color, int]], + id="DictConfig[Color,int]", + ), + pytest.param( + DictConfig(ref_type=Any, content=ConcretePlugin), + Any, + id="DictConfig[ConcretePlugin]_Any_reftype", + ), + pytest.param( + DictConfig(content="???"), + Optional[Dict[Union[str, Enum], Any]], + id="DictConfig[Union[str, Enum], Any]_missing", + ), + pytest.param( + DictConfig(content="???", element_type=int, key_type=str), + Optional[Dict[str, int]], + id="DictConfig[str, int]_missing", + ), + pytest.param( + DictConfig(ref_type=Plugin, content=ConcretePlugin), + Optional[Plugin], + id="DictConfig[Plugin]", + ), + pytest.param( + DictConfig(ref_type=Plugin, content=ConcretePlugin), + Optional[Plugin], + id="Plugin", + ), + # Non optional DictConfig + pytest.param( + DictConfig(ref_type=Plugin, content=ConcretePlugin, is_optional=False), + Plugin, + id="Plugin", + ), + # ListConfig + pytest.param(ListConfig([]), Optional[List[Any]], id="ListConfig[Any]"), + pytest.param( + ListConfig([], element_type=int), Optional[List[int]], id="ListConfig[int]" + ), + pytest.param( + ListConfig(content="???"), Optional[List[Any]], id="ListConfig_missing" + ), + pytest.param( + ListConfig(content="???", element_type=int), + Optional[List[int]], + id="ListConfig[int]_missing", + ), + pytest.param( + ListConfig(content=None), Optional[List[Any]], id="ListConfig_none" + ), + pytest.param( + ListConfig(content=None, element_type=int), + Optional[List[int]], + id="ListConfig[int]_none", + ), + ], +) +def test_get_ref_type(obj: Any, expected: Any) -> None: + assert _utils.get_ref_type(obj) == expected