Python unittest’s assertDictContainsSubset recommended alternative [duplicate]

On Python 3.9+, use the dictionary union operator.

Change

assertDictContainsSubset(a, b)

to

assertEqual(b, b | a)

On older versions of Python, change it to

assertEqual(b, {**b, **a})

Note the order of the arguments, assertDictContainsSubset put the “larger” dictionary (b) second and the subset (a) first, but it makes more sense to put the larger dictionary (b) first (which is why assertDictContainsSubset was removed in the first place).

This creates a copy of b then iterates over a, setting any keys to their value in a and then compares that result against the original b. If you can add all the keys/values of a to b and still have the same dictionary, it means a doesn’t contain any keys that aren’t in b and all the keys it contains have the same values as they do in b, i.e. a is a subset of b.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)