[英]how can I use assertRaises() in python's unittest to catch syntaxerror?
[英]How can I get Python's unittest to not catch exceptions?
我正在一个Django项目,但我认为这是一个纯Python unittest
的问题。
通常,当您运行测试时,测试运行程序将捕获异常并进行相应处理。
出于调试目的,我想禁用此行为,即:
python -i manage.py test
像往常一样,会在异常上闯入交互式Python shell。
怎么做?
编辑:基于到目前为止的答案,似乎这更像是一个特定于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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.