Compare (assert equality of) two complex data structures containing numpy arrays in unittest

后端 未结 7 1766
醉酒成梦
醉酒成梦 2020-12-06 16:25

I use Python\'s unittest module and want to check if two complex data structures are equal. The objects can be lists of dicts with all sorts of values: numbers,

7条回答
  •  不知归路
    2020-12-06 16:44

    I've run into the same issue, and developed a function to compare equality based on creating a fixed hash for the object. This has the added advantage that you can test that an object is as expected by comparing it's hash against a fixed has shored in code.

    The code (a stand-alone python file, is here). There are two functions: fixed_hash_eq, which solves your problem, and compute_fixed_hash, which makes a hash from the structure. Tests are here

    Here's a test:

    obj1 = [1, 'd', {'a': 4, 'b': np.arange(10)}, (7, [1, 2, 3, 4, 5])]
    obj2 = [1, 'd', {'a': 4, 'b': np.arange(10)}, (7, [1, 2, 3, 4, 5])]
    obj3 = [1, 'd', {'a': 4, 'b': np.arange(10)}, (7, [1, 2, 3, 4, 5])]
    obj3[2]['b'][4] = 0
    assert fixed_hash_eq(obj1, obj2)
    assert not fixed_hash_eq(obj1, obj3)
    

提交回复
热议问题