2016-11-08 10 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

相關問題