Skip to content

Commit

Permalink
Create isSubDict test method (facebook#3147)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
Daniel Cohen authored and facebook-github-bot committed Dec 4, 2024
1 parent 3302a6c commit 25c887e
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions ax/utils/common/testutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,33 @@ def assertDictsAlmostEqual(
else:
self.assertEqual(a_field, b_field, msg=msg)

def assertIsSubDict(
self,
subdict: dict[str, Any],
superdict: dict[str, Any],
almost_equal: bool = False,
consider_nans_equal: bool = False,
) -> None:
"""Testing utility that checks that all keys and values of `subdict` are
contained in `dict`.
Args:
subdict: A smaller dictionary.
superdict: A larger dictionary which should contain all keys of subdict
and the same values as subdict for the corresponding keys.
"""
intersection_dict = {k: superdict[k] for k in subdict}
if consider_nans_equal and not almost_equal:
raise ValueError(
"`consider_nans_equal` can only be used with `almost_equal`"
)
if almost_equal:
self.assertDictsAlmostEqual(
subdict, intersection_dict, consider_nans_equal=consider_nans_equal
)
else:
self.assertEqual(subdict, intersection_dict)

@staticmethod
@contextlib.contextmanager
def silence_stderr() -> Generator[None, None, None]:
Expand Down

0 comments on commit 25c887e

Please sign in to comment.