2012-09-20 128 views
1

我要檢查在Python單元測試異常,符合下列要求:Python的單元測試:報告異常的故障

  • 需要上報的失敗,而不是錯誤
  • 不得吞原始異常

我見過很多形式的解決方案:

try: 
    something() 
except: 
    self.fail("It failed") 

不幸的是,這些解決方案吞下了原始的異常。任何方式來保留原來的異常?

我結束了使用皮埃爾GM的回答的變體:

try: 
    something() 
except: 
    self.fail("Failed with %s" % traceback.format_exc()) 

回答

2

至於建議,你可以使用的上下文一般例外:

except Exception, error: 
    self.fail("Failed with %s" % error) 

您還可以檢索相對於exc主器件接收通過sys.exc_info()

try: 
    1./0 
except: 
    (etype, evalue, etrace) = sys.exc_info() 
    self.fail("Failed with %s" % evalue) 

元組(etype, evalue, etrace)在這裏(<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('float division',), <traceback object at 0x7f6f2c02fa70>)

0

您可以使用的東西捕捉變量異常喜歡

except Exception, e: 
     // fail with str(e)