我正在运行一个单元测试,我意识到有一个异常被抛出。然而,我只是不知道到底是什么抛出。
from pt_hil.utilities.PT_HIL_Interface_Utils.widgets import PathPicker
import unittest
import wx
class TestUM(unittest.TestCase):
@classmethod
def setUpClass(cls):
print 'setUpClass called'
cls.path_picker = PathPicker()
print 'path_picker has been declared'
def test_PathPicker(self):
self.assertRaises(NotImplementedError, wx.UIActionSimulator.MouseClick(self.path_picker.browse))
if __name__ == '__main__':
unittest.main()PathPicker类:
class PathPicker(Widget):
def __init__(self, parent=None, name="PathPicker"):
print 'hi1'
try:
Widget.__init__(self, name, parent)
except Exception as e:
print 'hello'
return logging.error(traceback.format_exc())
print 'hi2'当我运行单元测试时得到的输出是:
setUpClass called
hi1
Process finished with exit code 1很明显,Widget.__init__(self, name, parent)出了点问题,但我看不出是什么。有什么办法可以让这个打印出什么异常或错误被抛出吗?
编辑:下面是要与其一起使用的Widget类:
class Widget(QWidget):
def __init__(self, name, parent=None):
print 'hey2'
try:
super(Widget, self).__init__()
except BaseException as e:
print 'hello'
return logging.error(traceback.format_exc())
print 'hey3'现在它给了我:
setUpClass called
hi1
hey2
Process finished with exit code 1发布于 2017-08-03 19:36:19
我需要在脚本中添加app = QApplication(sys.argv)和sys.exit(app.exec_()),并使用class TestUM(unittest.TestCase):
因此上面的脚本应该如下所示:
from pt_hil.utilities.PT_HIL_Interface_Utils.widgets import PathPicker
import unittest
import wx
class TestUM(unittest.TestCase):
@classmethod
def setUpClass(cls):
print 'setUpClass called'
cls.path_picker = PathPicker()
print 'path_picker has been declared'
def test_PathPicker(self):
self.assertRaises(NotImplementedError, wx.UIActionSimulator.MouseClick(self.path_picker.browse))
if __name__ == '__main__':
app = QApplication(sys.argv)
unittest.main()
sys.exit(app.exec_())注意,这并不能解决我抛出所需异常的问题(因为没有任何异常是可见的)。但它确实解决了问题,脚本就会运行。谢谢!
发布于 2017-08-03 15:31:24
正如您可以看到的这里,python (2.x)中最重要的例外是:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
....因此,在您的示例中,通过捕获异常,您将丢失一些其他异常(罕见的异常,但可能发生在您的示例中):SystemExit、KeyboardInterrupt和GeneratorExit。尝试将您的into子句更改为:
except BaseException as e:这样,您将确保捕获所有异常,并检测您的问题。
编辑:
但是,PyQT在里面会很有趣。正如提到的那样,这里:
在PyQt v5.5中,未处理的Python异常将导致对Qt的qFatal()函数的调用。默认情况下,这将调用abort(),应用程序将终止。请注意,安装的应用程序异常钩子仍然优先。
因此,一个无可挑剔的异常(在C++代码中可能由于许多原因而发生,参数不佳.)可以静默地停止应用程序。然而,最后一部分听起来很有用,如果您安装了一个异常钩子,它将在默认中止之前被调用。让我们尝试添加一个异常钩子:
sys._excepthook = sys.excepthook # always save before overriding
def application_exception_hook(exctype, value, traceback):
# Let's try to write the problem
print "Exctype : %s, value : %s traceback : %s"%(exctype, value, traceback)
# Call the normal Exception hook after (this will probably abort application)
sys._excepthook(exctype, value, traceback)
sys.exit(1)
# Do not forget to our exception hook
sys.excepthook = application_exception_hookhttps://stackoverflow.com/questions/45488531
复制相似问题