Skip to content

Commit 25c887e

Browse files
Daniel Cohenfacebook-github-bot
authored andcommitted
Create isSubDict test method (facebook#3147)
Summary: Pull Request resolved: facebook#3147 Utility method for checking dicts have at least certain fields defined with certain values, where extra fields will not break functionality. Breaking this out as an OSS change. Reviewed By: ItsMrLin Differential Revision: D66770059 fbshipit-source-id: 5e1bbaa69b1f597ef21540bd5c21ad158ef6c716
1 parent 3302a6c commit 25c887e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

ax/utils/common/testutils.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,33 @@ def assertDictsAlmostEqual(
485485
else:
486486
self.assertEqual(a_field, b_field, msg=msg)
487487

488+
def assertIsSubDict(
489+
self,
490+
subdict: dict[str, Any],
491+
superdict: dict[str, Any],
492+
almost_equal: bool = False,
493+
consider_nans_equal: bool = False,
494+
) -> None:
495+
"""Testing utility that checks that all keys and values of `subdict` are
496+
contained in `dict`.
497+
498+
Args:
499+
subdict: A smaller dictionary.
500+
superdict: A larger dictionary which should contain all keys of subdict
501+
and the same values as subdict for the corresponding keys.
502+
"""
503+
intersection_dict = {k: superdict[k] for k in subdict}
504+
if consider_nans_equal and not almost_equal:
505+
raise ValueError(
506+
"`consider_nans_equal` can only be used with `almost_equal`"
507+
)
508+
if almost_equal:
509+
self.assertDictsAlmostEqual(
510+
subdict, intersection_dict, consider_nans_equal=consider_nans_equal
511+
)
512+
else:
513+
self.assertEqual(subdict, intersection_dict)
514+
488515
@staticmethod
489516
@contextlib.contextmanager
490517
def silence_stderr() -> Generator[None, None, None]:

0 commit comments

Comments
 (0)