Python unittest - opposite of assertRaises?

前端 未结 10 660
甜味超标
甜味超标 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:00

    One straight forward way to ensure the object is initialized without any error is to test the object's type instance.

    Here is an example :

    p = SomeClass(param1=_param1_value)
    self.assertTrue(isinstance(p, SomeClass))
    
    0 讨论(0)
  • 2020-12-04 06:02

    you can try like that. try: self.assertRaises(None,function,arg1, arg2) except: pass if you don't put code inside try block it will through exception' AssertionError: None not raised " and test case will be failed. Test case will be pass if put inside try block which is expected behaviour.

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2020-12-04 06:07

    Just call the function. If it raises an exception, the unit test framework will flag this as an error. You might like to add a comment, e.g.:

    sValidPath=AlwaysSuppliesAValidPath()
    # Check PathIsNotAValidOne not thrown
    MyObject(sValidPath)
    
    0 讨论(0)
提交回复
热议问题