@@ -357,6 +357,62 @@ def assert_dict_equal(first, second, key_msg_fmt="{msg}",
357357 assert_equal (first_value , second_value , msg_fmt = msg )
358358
359359
360+ def assert_dict_superset (first , second , key_msg_fmt = "{msg}" ,
361+ value_msg_fmt = "{msg}" ):
362+ """Fail unless second dictionary is a superset of the first.
363+
364+ The second dictionary must contain all keys of the first and their
365+ values are equal (or a superset in case of dicts). But the second
366+ dictionary can contain additional keys.
367+
368+ >>> assert_equal({"foo": 5}, {"foo": 5, "bar": 10})
369+ >>> assert_equal({"foo": 5}, {})
370+ Traceback (most recent call last):
371+ ...
372+ AssertionError: key 'foo' missing from right dict
373+
374+ The following key_msg_fmt arguments are supported, if the keys do not
375+ match:
376+ * msg - the default error message
377+ * first - the first dict
378+ * second - the second dict
379+ * missing_keys - list of keys missing from right
380+
381+ The following value_msg_fmt arguments are supported, if a value does not
382+ match:
383+ * msg - the default error message
384+ * first - the first dict
385+ * second - the second dict
386+ * key - the key where the value does not match
387+ * first_value - the value in the first dict
388+ * second_value - the value in the second dict
389+ """
390+ first_keys = set (first .keys ())
391+ second_keys = set (second .keys ())
392+ missing_keys = list (first_keys - second_keys )
393+ if missing_keys :
394+ if len (missing_keys ) == 1 :
395+ msg = "key {!r} missing from right dict" .format (missing_keys [0 ])
396+ else :
397+ keys = ", " .join (sorted (repr (k ) for k in missing_keys ))
398+ msg = "keys {} missing from right dict" .format (keys )
399+ if key_msg_fmt :
400+ msg = key_msg_fmt .format (
401+ msg = msg , first = first , second = second , missing_keys = missing_keys )
402+ raise AssertionError (msg )
403+ for key in first :
404+ first_value = first [key ]
405+ second_value = second [key ]
406+ msg = "key '{}' differs: {!r} != {!r}" .format (
407+ key , first_value , second_value )
408+ if value_msg_fmt :
409+ msg = value_msg_fmt .format (
410+ msg = msg , first = first , second = second ,
411+ key = key , first_value = first_value , second_value = second_value )
412+ msg = msg .replace ("{" , "{{" ).replace ("}" , "}}" )
413+ assert_equal (first_value , second_value , msg_fmt = msg )
414+
415+
360416def assert_less (first , second , msg_fmt = "{msg}" ):
361417 """Fail if first is not less than second.
362418
0 commit comments