[英]unittest: wxpython's event method raises exception but assertRaises does not detect it
我有一個wxpython對話框,單擊“確定”按鈕時會引發TypeError異常。 我想用unittest測試異常的發生,但是測試不能按預期工作。 輸出顯示引發了異常。 無論如何,unittest都會通知測試失敗:
"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) )
有人可以幫我找出我做錯了什么嗎?
參見: https : //wiki.wxpython.org/CppAndPythonSandwich
異常不會通過C ++層傳遞到調用堆棧。 當控件從Python返回C ++時,它將檢查是否存在未被捕獲的Python異常,如果是,則打印並清除錯誤。
在單元測試中處理此問題的一種方法是在事件處理程序中捕獲異常,並設置一個標志。 然后返回測試代碼,您可以檢查是否設置了該標志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.