2016-11-08 38 views
1

我有一个wxpython对话框,在单击确定按钮时引发TypeError异常。我想用unittest测试异常的发生,但测试不能按预期工作。输出显示引发异常。总之单元测试通知测试失败:unittest:wxpython的事件方法会引发异常,但assertRaises不会检测到它

"C:\Program Files (x86)\Python\python.exe" test.py 
Traceback (most recent call last): 
    File "test.py", line 22, in on_ok 
    raise TypeError('TypeError raised') 
TypeError: TypeError raised 
F 
====================================================================== 
FAIL: test_should_raise (__main__.CDlgTest) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "test.py", line 34, in test_should_raise 
    self._dut.m_button_ok.GetEventHandler().ProcessEvent(event) 
AssertionError: TypeError not raised 

---------------------------------------------------------------------- 
Ran 1 test in 0.005s 

FAILED (failures=1) 

这里是我的代码缩减样本:

import unittest 
import wx 

class CDlgBase (wx.Dialog): 
    """The UI""" 
    def __init__(self, parent): 
     wx.Dialog.__init__ (self, parent) 
     bSizerTest = wx.BoxSizer(wx.VERTICAL) 
     self.m_button_ok = wx.Button(self, wx.ID_ANY) 
     bSizerTest.Add(self.m_button_ok, 0) 
     self.SetSizer(bSizerTest) 
     # Connect Events 
     self.m_button_ok.Bind(wx.EVT_BUTTON, self.on_ok) 
    def on_ok(self, event): 
     event.Skip() 

class CDlg(CDlgBase) : 
    """The dialog""" 
    def __init__(self, parent): 
     super(CDlg, self).__init__(parent) 
    def on_ok(self, event): 
     # The exception should be verified in the test `test_should_raise()`. 
     raise TypeError('TypeError raised') 

class CDlgTest(unittest.TestCase) : 
    """The test class""" 
    def setUp(self): 
     self._dut = CDlg(None) 
    def test_should_raise(self): 
     """The test to verify raising the TypeError exception in the event 
     method `on_ok()`. this is the test method wich works not as expected.""" 
     event = wx.CommandEvent(wx.EVT_BUTTON.evtType[0]) 
     event.SetEventObject(self._dut.m_button_ok) 
     with self.assertRaises(TypeError) : 
      """Simulate an "OK" click. `on_ok()` will be executed 
      and raises the TypeError exception.""" 
      self._dut.m_button_ok.GetEventHandler().ProcessEvent(event) 

if __name__ == '__main__': 
    app = wx.App() 
    tests = [ unittest.TestLoader().loadTestsFromTestCase(CDlgTest) ] 
    unittest.TextTestRunner(verbosity=2, failfast=True).run(unittest.TestSuite(tests)) 

有人可以帮我找出我做错了什么?

+0

我很好奇这个解决方案。据我的理解,这个异常在另一个线程中引发,并被wx框架捕获,可能它的踪迹被转储到'stdout'。 –

+0

从另一个python论坛我收到以下答案:这是测试GUI中的一个普遍问题。事件处理程序中抛出的异常不应该影响整个程序。这是调度程序捕获它们并且不会将它们转发到测试例程的原因。事件处理程序应该不超过应该在没有GUI的情况下单独测试的薄层。 – Humbalan

回答

2

参见:https://wiki.wxpython.org/CppAndPythonSandwich

例外不向上传递虽然C++层调用堆栈。当控制从Python返回到C++时,它会检查是否有未被捕获的Python异常,如果是,则打印并清除错误。

在单元测试中处理此问题的一种方法是在事件处理程序中捕获异常并设置一个标志。然后回到测试代码中,您可以检查是否设置了该标志。

+0

我试过你的建议,它适用于我。非常感谢。无论如何,我正在考虑重新分配我的验证器,使其无异常工作。 – Humbalan

相关问题