1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
|
"""
This file compares DictConfig methods with the corresponding
methods of standard python's dict.
The following methods are compared:
__contains__
__delitem__
__eq__
__getitem__
__setitem__
get
pop
keys
values
items
We have separate test classes for the following cases:
TestUntypedDictConfig: for DictConfig without a set key_type
TestPrimitiveTypeDunderMethods: for DictConfig where key_type is primitive
TestEnumTypeDunderMethods: for DictConfig where key_type is Enum
"""
from copy import deepcopy
from enum import Enum
from typing import Any, Dict, Optional
from pytest import fixture, mark, param, raises
from omegaconf import DictConfig, OmegaConf
from omegaconf.errors import ConfigKeyError, ConfigTypeError, KeyValidationError
from tests import Enum1
@fixture(
params=[
"str",
b"abc",
1,
3.1415,
True,
Enum1.FOO,
]
)
def key(request: Any) -> Any:
"""A key to test indexing into DictConfig."""
return request.param
@fixture
def python_dict(data: Dict[Any, Any]) -> Dict[Any, Any]:
"""Just a standard python dictionary, to be used in comparison with DictConfig."""
return deepcopy(data)
@fixture(params=[None, False, True])
def struct_mode(request: Any) -> Optional[bool]:
struct_mode: Optional[bool] = request.param
return struct_mode
@mark.parametrize(
"data",
[
param({"a": 10}, id="str"),
param({b"abc": 10}, id="bytes"),
param({1: "a"}, id="int"),
param({123.45: "a"}, id="float"),
param({True: "a"}, id="bool"),
param({Enum1.FOO: "foo"}, id="Enum1"),
],
)
class TestUntypedDictConfig:
"""Compare DictConfig with python dict in the case where key_type is not set."""
@fixture
def cfg(self, python_dict: Any, struct_mode: Optional[bool]) -> DictConfig:
"""Create a DictConfig instance from the given data"""
cfg: DictConfig = DictConfig(content=python_dict)
OmegaConf.set_struct(cfg, struct_mode)
return cfg
def test__setitem__(
self, python_dict: Any, cfg: DictConfig, key: Any, struct_mode: Optional[bool]
) -> None:
"""Ensure that __setitem__ has same effect on python dict and on DictConfig."""
if struct_mode and key not in cfg:
with raises(ConfigKeyError):
cfg[key] = "sentinel"
else:
python_dict[key] = "sentinel"
cfg[key] = "sentinel"
assert python_dict == cfg
def test__getitem__(self, python_dict: Any, cfg: DictConfig, key: Any) -> None:
"""Ensure that __getitem__ has same result with python dict as with DictConfig."""
try:
result = python_dict[key]
except KeyError:
with raises(ConfigKeyError):
cfg[key]
else:
assert result == cfg[key]
@mark.parametrize("struct_mode", [False, None])
def test__delitem__(self, python_dict: Any, cfg: DictConfig, key: Any) -> None:
"""Ensure that __delitem__ has same result with python dict as with DictConfig."""
try:
del python_dict[key]
assert key not in python_dict
except KeyError:
with raises(ConfigKeyError):
del cfg[key]
else:
del cfg[key]
assert key not in cfg
@mark.parametrize("struct_mode", [True])
def test__delitem__struct_mode(
self, python_dict: Any, cfg: DictConfig, key: Any
) -> None:
"""Ensure that __delitem__ fails in struct_mode"""
with raises(ConfigTypeError):
del cfg[key]
def test__contains__(self, python_dict: Any, cfg: Any, key: Any) -> None:
"""Ensure that __contains__ has same result with python dict as with DictConfig."""
assert (key in python_dict) == (key in cfg)
def test__eq__(self, python_dict: Any, cfg: Any, key: Any) -> None:
assert python_dict == cfg
def test_get(self, python_dict: Any, cfg: DictConfig, key: Any) -> None:
"""Ensure that __getitem__ has same result with python dict as with DictConfig."""
assert python_dict.get(key) == cfg.get(key)
def test_get_with_default(
self, python_dict: Any, cfg: DictConfig, key: Any
) -> None:
"""Ensure that __getitem__ has same result with python dict as with DictConfig."""
assert python_dict.get(key, "DEFAULT") == cfg.get(key, "DEFAULT")
@mark.parametrize("struct_mode", [False, None])
def test_pop(
self,
python_dict: Any,
cfg: DictConfig,
key: Any,
) -> None:
"""Ensure that pop has same result with python dict as with DictConfig."""
try:
result = python_dict.pop(key)
except KeyError:
with raises(ConfigKeyError):
cfg.pop(key)
else:
assert result == cfg.pop(key)
assert python_dict.keys() == cfg.keys()
@mark.parametrize("struct_mode", [True])
def test_pop_struct_mode(
self,
python_dict: Any,
cfg: DictConfig,
key: Any,
) -> None:
"""Ensure that pop fails in struct mode."""
with raises(ConfigTypeError):
cfg.pop(key)
@mark.parametrize("struct_mode", [False, None])
def test_pop_with_default(
self,
python_dict: Any,
cfg: DictConfig,
key: Any,
) -> None:
"""Ensure that pop(..., DEFAULT) has same result with python dict as with DictConfig."""
assert python_dict.pop(key, "DEFAULT") == cfg.pop(key, "DEFAULT")
assert python_dict.keys() == cfg.keys()
@mark.parametrize("struct_mode", [True])
def test_pop_with_default_struct_mode(
self,
python_dict: Any,
cfg: DictConfig,
key: Any,
) -> None:
"""Ensure that pop(..., DEFAULT) fails in struct mode."""
with raises(ConfigTypeError):
cfg.pop(key, "DEFAULT")
def test_keys(self, python_dict: Any, cfg: Any) -> None:
assert python_dict.keys() == cfg.keys()
def test_values(self, python_dict: Any, cfg: Any) -> None:
assert list(python_dict.values()) == list(cfg.values())
def test_items(self, python_dict: Any, cfg: Any) -> None:
assert list(python_dict.items()) == list(cfg.items())
@fixture
def cfg_typed(
python_dict: Any, cfg_key_type: Any, struct_mode: Optional[bool]
) -> DictConfig:
"""Create a DictConfig instance that has strongly-typed keys"""
cfg_typed: DictConfig = DictConfig(content=python_dict, key_type=cfg_key_type)
OmegaConf.set_struct(cfg_typed, struct_mode)
return cfg_typed
@mark.parametrize(
"cfg_key_type,data",
[
(str, {"a": 10}),
(bytes, {b"abc": "a"}),
(int, {1: "a"}),
(float, {123.45: "a"}),
(bool, {True: "a"}),
],
)
class TestPrimitiveTypeDunderMethods:
"""Compare DictConfig with python dict in the case where key_type is a primitive type."""
def test__setitem__primitive_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
struct_mode: Optional[bool],
) -> None:
"""When DictConfig keys are strongly typed,
ensure that __setitem__ has same effect on python dict and on DictConfig."""
if struct_mode and key not in cfg_typed:
if isinstance(key, cfg_key_type) or (
cfg_key_type == bool and key in (0, 1)
):
with raises(ConfigKeyError):
cfg_typed[key] = "sentinel"
else:
with raises(KeyValidationError):
cfg_typed[key] = "sentinel"
else:
python_dict[key] = "sentinel"
if isinstance(key, cfg_key_type) or (
cfg_key_type == bool and key in (0, 1)
):
cfg_typed[key] = "sentinel"
assert python_dict == cfg_typed
else:
with raises(KeyValidationError):
cfg_typed[key] = "sentinel"
def test__getitem__primitive_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
) -> None:
"""When Dictconfig keys are strongly typed,
ensure that __getitem__ has same result with python dict as with DictConfig."""
try:
result = python_dict[key]
except KeyError:
if isinstance(key, cfg_key_type) or (
cfg_key_type == bool and key in (0, 1)
):
with raises(ConfigKeyError):
cfg_typed[key]
else:
with raises(KeyValidationError):
cfg_typed[key]
else:
assert result == cfg_typed[key]
@mark.parametrize("struct_mode", [False, None])
def test__delitem__primitive_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
) -> None:
"""When Dictconfig keys are strongly typed,
ensure that __delitem__ has same result with python dict as with DictConfig."""
try:
del python_dict[key]
assert key not in python_dict
except KeyError:
if isinstance(key, cfg_key_type) or (
cfg_key_type == bool and key in (0, 1)
):
with raises(ConfigKeyError):
del cfg_typed[key]
else:
with raises(KeyValidationError):
del cfg_typed[key]
else:
del cfg_typed[key]
assert key not in cfg_typed
@mark.parametrize("struct_mode", [True])
def test__delitem__primitive_typed_struct_mode(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
) -> None:
"""Ensure ensure that struct-mode __delitem__ raises ConfigTypeError or KeyValidationError"""
if isinstance(key, cfg_key_type) or (cfg_key_type == bool and key in (0, 1)):
with raises(ConfigTypeError):
del cfg_typed[key]
else:
with raises(KeyValidationError):
del cfg_typed[key]
def test__contains__primitive_typed(
self, python_dict: Any, cfg_typed: Any, key: Any
) -> None:
"""Ensure that __contains__ has same result with python dict as with DictConfig."""
assert (key in python_dict) == (key in cfg_typed)
def test__eq__primitive_typed(
self, python_dict: Any, cfg_typed: Any, key: Any
) -> None:
assert python_dict == cfg_typed
def test_get_primitive_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that __getitem__ has same result with python dict as with DictConfig."""
if isinstance(key, cfg_key_type) or (cfg_key_type == bool and key in (0, 1)):
assert python_dict.get(key) == cfg_typed.get(key)
else:
with raises(KeyValidationError):
cfg_typed.get(key)
def test_get_with_default_primitive_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that __getitem__ has same result with python dict as with DictConfig."""
if isinstance(key, cfg_key_type) or (cfg_key_type == bool and key in (0, 1)):
assert python_dict.get(key, "DEFAULT") == cfg_typed.get(key, "DEFAULT")
else:
with raises(KeyValidationError):
cfg_typed.get(key, "DEFAULT")
@mark.parametrize("struct_mode", [False, None])
def test_pop_primitive_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that pop has same result with python dict as with DictConfig."""
if isinstance(key, cfg_key_type) or (cfg_key_type == bool and key in (0, 1)):
try:
result = python_dict.pop(key)
except KeyError:
with raises(ConfigKeyError):
cfg_typed.pop(key)
else:
assert result == cfg_typed.pop(key)
assert python_dict.keys() == cfg_typed.keys()
else:
with raises(KeyValidationError):
cfg_typed.pop(key)
@mark.parametrize("struct_mode", [True])
def test_pop_primitive_typed_struct_mode(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that pop fails in struct mode."""
with raises(ConfigTypeError):
cfg_typed.pop(key)
@mark.parametrize("struct_mode", [False, None])
def test_pop_with_default_primitive_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that pop(..., DEFAULT) has same result with python dict as with DictConfig."""
if isinstance(key, cfg_key_type) or (cfg_key_type == bool and key in (0, 1)):
assert python_dict.pop(key, "DEFAULT") == cfg_typed.pop(key, "DEFAULT")
assert python_dict.keys() == cfg_typed.keys()
else:
with raises(KeyValidationError):
cfg_typed.pop(key, "DEFAULT")
@mark.parametrize("struct_mode", [True])
def test_pop_with_default_primitive_typed_struct_mode(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that pop(..., DEFAULT) fails in struct mode"""
with raises(ConfigTypeError):
cfg_typed.pop(key)
def test_keys_primitive_typed(self, python_dict: Any, cfg_typed: Any) -> None:
assert python_dict.keys() == cfg_typed.keys()
def test_values_primitive_typed(self, python_dict: Any, cfg_typed: Any) -> None:
assert list(python_dict.values()) == list(cfg_typed.values())
def test_items_primitive_typed(self, python_dict: Any, cfg_typed: Any) -> None:
assert list(python_dict.items()) == list(cfg_typed.items())
@mark.parametrize("cfg_key_type,data", [(Enum1, {Enum1.FOO: "foo"})])
class TestEnumTypeDunderMethods:
"""Compare DictConfig with python dict in the case where key_type is an Enum type."""
@fixture
def key_coerced(self, key: Any, cfg_key_type: Any) -> Any:
"""
This handles key coersion in the special case where DictConfig key_type
is a subclass of Enum: keys of type `str` or `int` are coerced to `key_type`.
See https://github.com/omry/omegaconf/pull/484#issuecomment-765772019
"""
assert issubclass(cfg_key_type, Enum)
if type(key) == str and key in [e.name for e in cfg_key_type]:
return cfg_key_type[key]
elif type(key) == int and key in [e.value for e in cfg_key_type]:
return cfg_key_type(key)
else:
return key
def test__setitem__enum_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
struct_mode: Optional[bool],
) -> None:
"""When DictConfig keys are strongly typed,
ensure that __setitem__ has same effect on python dict and on DictConfig."""
if struct_mode and key_coerced not in cfg_typed:
if isinstance(key_coerced, cfg_key_type):
with raises(ConfigKeyError):
cfg_typed[key] = "sentinel"
else:
with raises(KeyValidationError):
cfg_typed[key] = "sentinel"
else:
python_dict[key_coerced] = "sentinel"
if isinstance(key_coerced, cfg_key_type):
cfg_typed[key] = "sentinel"
assert python_dict == cfg_typed
else:
with raises(KeyValidationError):
cfg_typed[key] = "sentinel"
def test__getitem__enum_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
) -> None:
"""When Dictconfig keys are strongly typed,
ensure that __getitem__ has same result with python dict as with DictConfig."""
try:
result = python_dict[key_coerced]
except KeyError:
if isinstance(key_coerced, cfg_key_type):
with raises(ConfigKeyError):
cfg_typed[key]
else:
with raises(KeyValidationError):
cfg_typed[key]
else:
assert result == cfg_typed[key]
@mark.parametrize("struct_mode", [False, None])
def test__delitem__enum_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
) -> None:
"""When Dictconfig keys are strongly typed,
ensure that __delitem__ has same result with python dict as with DictConfig."""
try:
del python_dict[key_coerced]
assert key_coerced not in python_dict
except KeyError:
if isinstance(key_coerced, cfg_key_type):
with raises(ConfigKeyError):
del cfg_typed[key]
else:
with raises(KeyValidationError):
del cfg_typed[key]
else:
del cfg_typed[key]
assert key not in cfg_typed
@mark.parametrize("struct_mode", [True])
def test__delitem__enum_typed_struct_mode(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that __delitem__ errors in struct mode"""
if isinstance(key_coerced, cfg_key_type):
with raises(ConfigTypeError):
del cfg_typed[key]
else:
with raises(KeyValidationError):
del cfg_typed[key]
def test__contains__enum_typed(
self, python_dict: Any, cfg_typed: Any, key: Any, key_coerced: Any
) -> None:
"""Ensure that __contains__ has same result with python dict as with DictConfig."""
assert (key_coerced in python_dict) == (key in cfg_typed)
def test__eq__enum_typed(self, python_dict: Any, cfg_typed: Any, key: Any) -> None:
assert python_dict == cfg_typed
def test_get_enum_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that __getitem__ has same result with python dict as with DictConfig."""
if isinstance(key_coerced, cfg_key_type):
assert python_dict.get(key_coerced) == cfg_typed.get(key)
else:
with raises(KeyValidationError):
cfg_typed.get(key)
def test_get_with_default_enum_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that __getitem__ has same result with python dict as with DictConfig."""
if isinstance(key_coerced, cfg_key_type):
assert python_dict.get(key_coerced, "DEFAULT") == cfg_typed.get(
key, "DEFAULT"
)
else:
with raises(KeyValidationError):
cfg_typed.get(key, "DEFAULT")
@mark.parametrize("struct_mode", [False, None])
def test_pop_enum_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that pop has same result with python dict as with DictConfig."""
if isinstance(key_coerced, cfg_key_type):
try:
result = python_dict.pop(key_coerced)
except KeyError:
with raises(ConfigKeyError):
cfg_typed.pop(key)
else:
assert result == cfg_typed.pop(key)
assert python_dict.keys() == cfg_typed.keys()
else:
with raises(KeyValidationError):
cfg_typed.pop(key)
@mark.parametrize("struct_mode", [True])
def test_pop_enum_typed_struct_mode(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that pop fails in struct mode"""
with raises(ConfigTypeError):
cfg_typed.pop(key)
@mark.parametrize("struct_mode", [False, None])
def test_pop_with_default_enum_typed(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that pop(..., DEFAULT) has same result with python dict as with DictConfig."""
if isinstance(key_coerced, cfg_key_type):
assert python_dict.pop(key_coerced, "DEFAULT") == cfg_typed.pop(
key, "DEFAULT"
)
assert python_dict.keys() == cfg_typed.keys()
else:
with raises(KeyValidationError):
cfg_typed.pop(key, "DEFAULT")
@mark.parametrize("struct_mode", [True])
def test_pop_with_default_enum_typed_struct_mode(
self,
python_dict: Any,
cfg_typed: DictConfig,
key: Any,
key_coerced: Any,
cfg_key_type: Any,
) -> None:
"""Ensure that pop(..., DEFAULT) errors in struct mode"""
with raises(ConfigTypeError):
cfg_typed.pop(key)
def test_keys_enum_typed(self, python_dict: Any, cfg_typed: Any) -> None:
assert python_dict.keys() == cfg_typed.keys()
def test_values_enum_typed(self, python_dict: Any, cfg_typed: Any) -> None:
assert list(python_dict.values()) == list(cfg_typed.values())
def test_items_enum_typed(self, python_dict: Any, cfg_typed: Any) -> None:
assert list(python_dict.items()) == list(cfg_typed.items())
|