from PyQt4 import Qt
import gc
import sys
import unittest
import weakref



#===================================================================================================
# Stub
#===================================================================================================
class Stub(object):
    '''
    Stub class just to create an instance of something in the test.
    '''
    pass



#===================================================================================================
# Test
#===================================================================================================
class Test(unittest.TestCase):
    
    
    def SlotRaiseError(self):
        '''
        This slot raises a RuntimeError.
        We create a local variable which must be deleted on the error condition.
        '''
        # Local variable.
        stub = Stub()
        
        # Getting a weak ref here for test purposes.
        self.stub = weakref.ref(stub)
        
        # Raise the error.
        raise RuntimeError('Error. All local variables must be removed.')
    
    
    def testExceptionBehavior(self):
        '''
        Checks the Qt's behavior when an error happens.
        On error conditions, all local variable must be released.
        '''
        _app = Qt.QApplication([])
        
        widget = Qt.QWidget()
        exception_button = Qt.QPushButton(widget)
        exception_button.connect(exception_button, Qt.SIGNAL('clicked()'), self.SlotRaiseError)
        
        widget.show()
        
        exception_button.click()
        exception_button.disconnect(exception_button, Qt.SIGNAL('clicked()'), self.SlotRaiseError)
        
        sys.exc_clear()
        gc.collect()
        
        # The SlotRaiseError's  local variable stub must be garbage collect after
        # the error condition the Slot keeps a strong reference of the instance.
        self.assertEquals(self.stub(), None)



#===================================================================================================
# main
#===================================================================================================
if __name__ == '__main__':
    unittest.main()
