我正在研究一個Django項目,但我認爲這是一個純Python unittest
的問題。我怎樣才能得到Python的單元測試不捕捉異常?
通常,當您運行測試時,異常將被測試運行器捕獲並進行相應處理。
出於調試目的,我要禁用此行爲,即讓:
python -i manage.py test
將打入交互式Python外殼上個例外,因爲正常的。
如何做到這一點?
編輯:根據迄今爲止的答案,它似乎更像是一個特定於Django的問題,而不是我意識到的!
我正在研究一個Django項目,但我認爲這是一個純Python unittest
的問題。我怎樣才能得到Python的單元測試不捕捉異常?
通常,當您運行測試時,異常將被測試運行器捕獲並進行相應處理。
出於調試目的,我要禁用此行爲,即讓:
python -i manage.py test
將打入交互式Python外殼上個例外,因爲正常的。
如何做到這一點?
編輯:根據迄今爲止的答案,它似乎更像是一個特定於Django的問題,而不是我意識到的!
您可以使用django-nose測試運行器,它可以與unittest
測試一起使用,並運行您的測試,如python manage.py test -v2 --pdb
。鼻子會爲你運行pdb。
一個新的應用程序django-pdb使這個更好,支持在常規代碼中打破測試失敗或未捕獲異常的模式。
你可以嘗試在一個模塊中像這樣你的包內,然後用CondCatches(
你的例外,在你的代碼)
:
# System Imports
import os
class NoSuchException(Exception):
""" Null Exception will not match any exception."""
pass
def CondCatches(conditional, *args):
"""
Depending on conditional either returns the arguments or NoSuchException.
Use this to check have a caught exception that is suppressed some of the
time. e.g.:
from DisableableExcept import CondCatches
import os
try:
# Something like:
print "Do something bad!"
print 23/0
except CondCatches(os.getenv('DEBUG'), Exception), e:
#handle the exception in non DEBUG
print 'Somthing has a problem!', e
"""
if conditional:
return (NoSuchException,)
else:
return args
if __name__ == '__main__':
# Do SOMETHING if file is called on it's own.
try:
print 'To Suppress Catching this exception set DEBUG=anything'
print 1/0
except CondCatches(os.getenv('DEBUG'), ValueError, ZeroDivisionError), e:
print "Caught Exception", e
感謝。我聽說鼻子提到了很多好處,比如這個,它在我的待辦清單上學習,但現在,我希望有一種方法可以在沒有它的情況下做到這一點。你知道標準測試跑步者絕對不可能嗎? – Ghopper21
這不是很好,但你可以在你的代碼中捕獲異常並運行pdb。 –
僅供參考,我試圖弄清楚如何安裝django-nose,它看起來很棒。它給我的麻煩到目前爲止...請參閱http://stackoverflow.com/questions/12215520/how-to-get-django-nose-installed-correctly – Ghopper21