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

后端 未结 7 1743
醉酒成梦
醉酒成梦 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:08

    I would define my own assertNumpyArraysEqual() method that explicitly makes the comparison that you want to use. That way, your production code is unchanged but you can still make reasonable assertions in your unit tests. Make sure to define it in a module that includes __unittest = True so that it will not be included in stack traces:

    import numpy
    __unittest = True
    
    def assertNumpyArraysEqual(self, other):
        if self.shape != other.shape:
            raise AssertionError("Shapes don't match")
        if not numpy.allclose(self, other)
            raise AssertionError("Elements don't match!")
    
    0 讨论(0)
提交回复
热议问题