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

后端 未结 7 1763
醉酒成梦
醉酒成梦 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 17:05

    Building on @dbw (with thanks), the following method inserted within the test-case subclass worked well for me:

     def assertNumpyArraysEqual(self,this,that,msg=''):
        '''
        modified from http://stackoverflow.com/a/15399475/5459638
        '''
        if this.shape != that.shape:
            raise AssertionError("Shapes don't match")
        if not np.allclose(this,that):
            raise AssertionError("Elements don't match!")
    

    I had it called as self.assertNumpyArraysEqual(this,that) inside my test case methods and worked like a charm.

提交回复
热议问题