Python unittest - opposite of assertRaises?

前端 未结 10 658
甜味超标
甜味超标 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 05:46

    def _assertNotRaises(self, exception, obj, attr):                                                                                                                              
         try:                                                                                                                                                                       
             result = getattr(obj, attr)                                                                                                                                            
             if hasattr(result, '__call__'):                                                                                                                                        
                 result()                                                                                                                                                           
         except Exception as e:                                                                                                                                                     
             if isinstance(e, exception):                                                                                                                                           
                raise AssertionError('{}.{} raises {}.'.format(obj, attr, exception)) 
    

    could be modified if you need to accept parameters.

    call like

    self._assertNotRaises(IndexError, array, 'sort')
    

提交回复
热议问题