Python unittest - opposite of assertRaises?

前端 未结 10 681
甜味超标
甜味超标 2020-12-04 05:36

I want to write a test to establish that an Exception is not raised in a given circumstance.

It\'s straightforward to test if an Exception is raise

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 06:04

    I've found it useful to monkey-patch unittest as follows:

    def assertMayRaise(self, exception, expr):
      if exception is None:
        try:
          expr()
        except:
          info = sys.exc_info()
          self.fail('%s raised' % repr(info[0]))
      else:
        self.assertRaises(exception, expr)
    
    unittest.TestCase.assertMayRaise = assertMayRaise
    

    This clarifies intent when testing for the absence of an exception:

    self.assertMayRaise(None, does_not_raise)
    

    This also simplifies testing in a loop, which I often find myself doing:

    # ValueError is raised only for op(x,x), op(y,y) and op(z,z).
    for i,(a,b) in enumerate(itertools.product([x,y,z], [x,y,z])):
      self.assertMayRaise(None if i%4 else ValueError, lambda: op(a, b))
    

提交回复
热议问题