Added all original pyside unit tests to the shiboken version.

This commit is contained in:
Hugo Lima 2009-09-21 14:51:26 -03:00
commit 9af36fbb64
160 changed files with 6616 additions and 12 deletions

View file

@ -0,0 +1,107 @@
''' Test case for QObject.signalsBlocked() and blockSignal()'''
import unittest
import os
from tempfile import mkstemp
from PySide.QtCore import QObject, SIGNAL, QFile
class TestSignalsBlockedBasic(unittest.TestCase):
'''Basic test case for signalsBlocked'''
def testBasic(self):
'''QObject.signalsBlocked() and blockSignals()
The signals aren't blocked by default.
blockSignals returns the previous value'''
obj = QObject()
self.assert_(not obj.signalsBlocked())
self.assert_(not obj.blockSignals(True))
self.assert_(obj.signalsBlocked())
self.assert_(obj.blockSignals(False))
class TestSignalsBlocked(unittest.TestCase):
'''Test case to check if the signals are really blocked'''
def setUp(self):
#Set up the basic resources needed
self.obj = QObject()
self.args = tuple()
self.called = False
def tearDown(self):
#Delete used resources
del self.obj
del self.args
def callback(self, *args):
#Default callback
if args == self.args:
self.called = True
else:
raise TypeError("Invalid arguments")
def testShortCircuitSignals(self):
#Blocking of Python short-circuit signals
QObject.connect(self.obj, SIGNAL('mysignal'), self.callback)
self.obj.emit(SIGNAL('mysignal'))
self.assert_(self.called)
self.called = False
self.obj.blockSignals(True)
self.obj.emit(SIGNAL('mysignal'))
self.assert_(not self.called)
def testPythonSignals(self):
#Blocking of Python typed signals
QObject.connect(self.obj, SIGNAL('mysignal(int,int)'), self.callback)
self.args = (1, 3)
self.obj.emit(SIGNAL('mysignal(int,int)'), *self.args)
self.assert_(self.called)
self.called = False
self.obj.blockSignals(True)
self.obj.emit(SIGNAL('mysignal(int,int)'), *self.args)
self.assert_(not self.called)
class TestQFileSignalBlocking(unittest.TestCase):
'''Test case for blocking the signal QIODevice.aboutToClose()'''
def setUp(self):
#Set up the needed resources - A temp file and a QFile
self.called = False
handle, self.filename = mkstemp()
os.close(handle)
self.qfile = QFile(self.filename)
def tearDown(self):
#Release acquired resources
os.remove(self.filename)
del self.qfile
def callback(self):
#Default callback
self.called = True
def testAboutToCloseBlocking(self):
#QIODevice.aboutToClose() blocking
QObject.connect(self.qfile, SIGNAL('aboutToClose()'), self.callback)
self.assert_(self.qfile.open(QFile.ReadOnly))
self.qfile.close()
self.assert_(self.called)
self.called = False
self.qfile.blockSignals(True)
self.assert_(self.qfile.open(QFile.ReadOnly))
self.qfile.close()
self.assert_(not self.called)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,55 @@
#!/usr/bin/python
'''Test case for QObject.childEvent and QTimer.childEvent overloading'''
import unittest
from time import sleep
from PySide.QtCore import QObject, QTimer, QCoreApplication
from helper import UsesQCoreApplication
class ExtQObject(QObject):
def __init__(self):
QObject.__init__(self)
self.child_event_received = False
def childEvent(self, event):
QObject.childEvent(self, event)
self.child_event_received = True
class ExtQTimer(QTimer):
def __init__(self):
QTimer.__init__(self)
self.child_event_received = False
def childEvent(self, event):
QTimer.childEvent(self, event)
self.child_event_received = True
class TestChildEvent(UsesQCoreApplication):
'''Test case for QObject::childEvent and QTimer::childEvent'''
def setUp(self):
UsesQCoreApplication.setUp(self)
def tearDown(self):
UsesQCoreApplication.tearDown(self)
def testQObject(self):
parent = ExtQObject()
child = QObject()
child.setParent(parent)
print "parent seted"
#self.assert_(parent.child_event_received)
"""
def testQTimer(self):
parent = ExtQTimer()
child = QObject()
child.setParent(parent)
self.assert_(parent.child_event_received)
"""
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,56 @@
#!/usr/bin/python
'''Test case for duck puching new implementations of C++ virtual methods into object instances.'''
import unittest
import new
from PySide.QtCore import QObject
from helper import UsesQCoreApplication
class Duck(QObject):
def __init__(self):
QObject.__init__(self)
def childEvent(self, event):
QObject.childEvent(self, event)
class TestDuckPunchingOnQObjectInstance(UsesQCoreApplication):
'''Test case for duck puching new implementations of C++ virtual methods into object instances.'''
def setUp(self):
#Acquire resources
self.duck_childEvent_called = False
UsesQCoreApplication.setUp(self)
def tearDown(self):
#Release resources
del self.duck_childEvent_called
UsesQCoreApplication.tearDown(self)
def testChildEventMonkeyPatch(self):
#Test if the new childEvent injected on QObject instance is called from C++
parent = QObject()
def childEvent(obj, event):
self.duck_childEvent_called = True
QObject.childEvent(obj, event)
parent.event = new.instancemethod(childEvent, parent, QObject)
child = QObject()
child.setParent(parent)
self.assert_(self.duck_childEvent_called)
def testChildEventMonkeyPatchWithInheritance(self):
#Test if the new childEvent injected on a QObject's extension class instance is called from C++
parent = Duck()
def childEvent(obj, event):
QObject.childEvent(obj, event)
self.duck_childEvent_called = True
child = QObject()
child.setParent(parent)
parent.event = new.instancemethod(childEvent, parent, QObject)
child = QObject()
child.setParent(parent)
self.assert_(self.duck_childEvent_called)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,16 @@
'''(Very) Simple test case for missing names from QtCore'''
import unittest
from PySide import QtCore
class MissingClasses(unittest.TestCase):
def testQSettings(self): # Bug 232
getattr(QtCore, 'QSettings')
def testQtTrNoop(self): # Bug 220
getattr(QtCore, 'QT_TR_NOOP')
if __name__ == '__main__':
unittest.main()

100
tests/qtcore/qbitarray_test.py Executable file
View file

@ -0,0 +1,100 @@
#!/usr/bin/python
'''Tests if QBitArray class is iterable and also '~' (__invert__) and bitwise operators'''
import unittest
from PySide.QtCore import QBitArray
def bool_list_from_qbitarray(qbitarray):
'''This function is used instead of a list comprehension because
the QBitArray is being tested also to check if it is providing
the iterable protocol.
'''
qbitarray_values = []
for i in range(qbitarray.size()):
qbitarray_values.append(qbitarray.at(i))
return qbitarray_values
class QBitArrayIsIterableTest(unittest.TestCase):
'''Tests if QBitArray class is iterable and also '~' (__invert__) and bitwise operators'''
def setUp(self):
#Acquire resources
self.qbitarray = QBitArray(3)
self.qbitarray_values = [True, False, False]
# WARNING: do not pythonify the following loop
for i in range(len(self.qbitarray_values)):
self.qbitarray.setBit(i, self.qbitarray_values[i])
self.inverted_qbitarray_values = [not bit for bit in self.qbitarray_values]
self.other_qbitarray = QBitArray(3)
self.other_qbitarray_values = [True, True, False]
# WARNING: do not pythonify the following loop
for i in range(len(self.other_qbitarray_values)):
self.other_qbitarray.setBit(i, self.other_qbitarray_values[i])
def tearDown(self):
#Release resources
del self.qbitarray
del self.other_qbitarray
del self.qbitarray_values
del self.other_qbitarray_values
del self.inverted_qbitarray_values
def testQBitArrayIsIterable(self):
#Tests if QBitArray class is iterable
qbitarray_is_iterable = True
try:
bitarray = [bit for bit in self.qbitarray]
except:
qbitarray_is_iterable = False
self.assertTrue(qbitarray_is_iterable)
def testQBitArrayInvertOperator(self):
#Tests QBitArray '~' (__invert__) operator
inverted_qbitarray = ~self.qbitarray
# WARNING: do not pythonify the following loop, the
# iterability of QBitArray class is tested in another place
inverted_qbitarray_values = bool_list_from_qbitarray(inverted_qbitarray)
self.assertEqual(self.inverted_qbitarray_values, inverted_qbitarray_values)
def testQBitArrayOrBitwiseOperator(self):
#Tests QBitArray '|' (or) operator
has_or_bitwise_operator = True
ored_qbitarray, ored_bool_list = None, None
try:
ored_qbitarray = self.qbitarray | self.other_qbitarray
ored_bool_list = [b1 | b2 for b1, b2 in zip(self.qbitarray_values, self.other_qbitarray_values)]
except:
has_or_bitwise_operator = False
self.assertTrue(has_or_bitwise_operator)
self.assertEqual(bool_list_from_qbitarray(ored_qbitarray), ored_bool_list)
def testQBitArrayAndBitwiseOperator(self):
#Tests QBitArray '&' (and) operator
has_and_bitwise_operator = True
anded_qbitarray, anded_bool_list = None, None
try:
anded_qbitarray = self.qbitarray | self.other_qbitarray
anded_bool_list = [b1 | b2 for b1, b2 in zip(self.qbitarray_values, self.other_qbitarray_values)]
except:
has_and_bitwise_operator = False
self.assertTrue(has_and_bitwise_operator)
self.assertEqual(bool_list_from_qbitarray(anded_qbitarray), anded_bool_list)
def testQBitArrayXorBitwiseOperator(self):
#Tests QBitArray '^' (xor) operator
has_xor_bitwise_operator = True
xored_qbitarray, xored_bool_list = None, None
try:
xored_qbitarray = self.qbitarray | self.other_qbitarray
xored_bool_list = [b1 | b2 for b1, b2 in zip(self.qbitarray_values, self.other_qbitarray_values)]
except:
has_xor_bitwise_operator = False
self.assertTrue(has_xor_bitwise_operator)
self.assertEqual(bool_list_from_qbitarray(xored_qbitarray), xored_bool_list)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,25 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Tests QByteArray implementation of Python buffer protocol'''
import unittest
from os.path import isdir
from PySide.QtCore import QByteArray
class QByteArrayBufferProtocolTest(unittest.TestCase):
'''Tests QByteArray implementation of Python buffer protocol'''
def testQByteArrayBufferProtocol(self):
#Tests QByteArray implementation of Python buffer protocol using the os.path.isdir
#function which an unicode object or other object implementing the Python buffer protocol
os_path_isdir_function_correctly_called_with_a_qbytearray = True
try:
isdir(QByteArray('/tmp'))
except:
os_path_isdir_function_correctly_called_with_a_qbytearray = False
self.assertTrue(os_path_isdir_function_correctly_called_with_a_qbytearray)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,52 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Test cases for QByteArray concatenation with '+' operator'''
import unittest
from PySide.QtCore import QByteArray
class QByteArrayConcatenationOperatorTest(unittest.TestCase):
'''Test cases for QByteArray concatenation with '+' operator'''
def testConcatQByteArrayAndPythonString(self):
#Test concatenation of a QByteArray with a Python string, in this order
concat_qbytearray_add_python_string_worked = True
qba = QByteArray('foo')
result = None
try:
result = qba + 'bar'
except:
concat_qbytearray_add_python_string_worked = False
self.assertTrue(concat_qbytearray_add_python_string_worked)
# NOTICE: the standard behavior of PyQt is to return a QString object
# for this case. As this is a minor issue the assertion will be left commented.
#self.assertEqual(result.__class__.__name__, 'QString')
def testConcatPythonStringAndQByteArray(self):
#Test concatenation of a Python string with a QByteArray, in this order
concat_python_string_add_qbytearray_worked = True
qba = QByteArray('foo')
result = None
try:
result = 'bar' + qba
except:
concat_python_string_add_qbytearray_worked = False
self.assertTrue(concat_python_string_add_qbytearray_worked)
self.assertEqual(result.__class__.__name__, 'QByteArray')
def testConcatPythonUnicodeAndQByteArray(self):
#Test concatenation of a Python unicode object with a QByteArray, in this order
concat_python_unicode_add_qbytearray_worked = True
qba = QByteArray('foo')
result = None
try:
result = u'ümlaut' + qba
except:
concat_python_unicode_add_qbytearray_worked = False
self.assertTrue(concat_python_unicode_add_qbytearray_worked)
self.assertEqual(result.__class__.__name__, 'unicode')
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,61 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Test cases for QByteArray operators'''
import unittest
from PySide.QtCore import QByteArray, QString
class QByteArrayOperatorEqual(unittest.TestCase):
'''TestCase for operator QByteArray == QByteArray'''
def testDefault(self):
#QByteArray() == QByteArray()
obj1 = QByteArray()
obj2 = QByteArray()
self.assertEqual(obj1, obj2)
def testSimple(self):
#QByteArray(some_string) == QByteArray(some_string)
string = 'egg snakes'
self.assertEqual(QByteArray(string), QByteArray(string))
def testPyString(self):
#QByteArray(string) == string
string = 'my test string'
self.assertEqual(QByteArray(string), string)
def testQString(self):
#QByteArray(string) == QString(string)
string = 'another test string'
self.assertEqual(QByteArray(string), QString(string))
class QByteArrayOperatorAt(unittest.TestCase):
'''TestCase for operator QByteArray[]'''
def testInRange(self):
#QByteArray[x] where x is a valid index
string = 'abcdefgh'
obj = QByteArray(string)
for i in range(len(string)):
self.assertEqual(obj[i], string[i])
def testInRangeReverse(self):
#QByteArray[x] where x is a valid index (reverse order)
string = 'abcdefgh'
obj = QByteArray(string)
for i in range(len(string)-1, 0, -1):
self.assertEqual(obj[i], string[i])
def testOutOfRange(self):
#QByteArray[x] where x is out of index
string = '1234567'
obj = QByteArray(string)
self.assertRaises(IndexError, lambda :obj[len(string)])
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,43 @@
#!/usr/bin/python
'''Unit tests for QByteArray'''
import unittest
import ctypes
import sys
from PySide.QtCore import QByteArray
class QByteArrayTestToNumber(unittest.TestCase):
def testToNumberInt(self):
obj = QByteArray('37')
self.assertEqual(37, obj.toInt()[0])
def testToNumberFloat(self):
obj = QByteArray('37.109')
self.assertEqual(ctypes.c_float(37.109).value,
obj.toFloat()[0])
def testToNumberDouble(self):
obj = QByteArray('37.109')
self.assertEqual(ctypes.c_double(37.109).value,
obj.toDouble()[0])
class QByteArraySplit(unittest.TestCase):
'''Test case for QByteArray.split'''
def testPathSeparator(self):
#QByteArray.split('/')
obj = QByteArray(unittest.__file__)
self.assertEqual(obj.split('/'), unittest.__file__.split('/'))
class QByteArrayData(unittest.TestCase):
'''Test case for QByteArray.data'''
def testData(self):
url = QByteArray("http://web.openbossa.org/")
self.assertEqual(url.data(), "http://web.openbossa.org/")
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,20 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Test cases for QCoreApplication.instance static method'''
import unittest
from PySide.QtCore import QCoreApplication
class QCoreApplicationInstanceTest(unittest.TestCase):
'''Test cases for QCoreApplication.instance static method'''
def testQCoreApplicationInstance(self):
#Tests QCoreApplication.instance()
self.assertEqual(QCoreApplication.instance(), None)
app = QCoreApplication([])
self.assertEqual(QCoreApplication.instance(), app)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,20 @@
#!/usr/bin/python
'''Unit tests for QDataStream'''
import unittest
from PySide.QtCore import QDataStream, QBuffer
class QDataStreamTest(unittest.TestCase):
'''Test case for QByteArray.split'''
def testWriteFunction(self):
b = QBuffer()
b.open(QBuffer.ReadWrite)
ds = QDataStream(b)
ds.writeUInt8(chr(True))
self.assertEqual(b.buffer().at(0), chr(True))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,43 @@
#!/usr/bin/python
'''Test cases for QEnum and QFlags'''
import unittest
from PySide.QtCore import QIODevice, QString, Qt, QVariant
class TestEnum(unittest.TestCase):
def testToInt(self):
self.assertEqual(QIODevice.NotOpen, 0)
self.assertEqual(QIODevice.ReadOnly, 1)
self.assertEqual(QIODevice.WriteOnly, 2)
self.assertEqual(QIODevice.ReadWrite, 1 | 2)
self.assertEqual(QIODevice.Append, 4)
self.assertEqual(QIODevice.Truncate, 8)
self.assertEqual(QIODevice.Text, 16)
self.assertEqual(QIODevice.Unbuffered, 32)
def testToIntInFunction(self):
self.assertEqual(QString.number(QIODevice.WriteOnly), "2")
class TestQFlags(unittest.TestCase):
def testToItn(self):
om = QIODevice.OpenMode(QIODevice.NotOpen)
self.assertEqual(om, QIODevice.NotOpen)
self.assertTrue(om == 0)
self.assertTrue(om != QIODevice.ReadOnly)
self.assertTrue(om != 1)
def testToIntInFunction(self):
om = QIODevice.OpenMode(QIODevice.WriteOnly)
self.assertEqual(QString.number(int(om)), "2")
class TestDuplicatedValues(unittest.TestCase):
def testQVariant(self):
self.assertEqual(QVariant.LastCoreType, QVariant.Hash)
self.assertEqual(QVariant.LastGuiType, QVariant.Transform)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,24 @@
#!/usr/bin/python
'''Test cases for QtCore.QEvent'''
import unittest
from PySide.QtCore import QEvent
class QEventTypeFlag(unittest.TestCase):
'''Test case for usage of QEvent.Type flags'''
def testFlagAccess(self):
#QEvent.Type flags usage
event = QEvent(QEvent.Timer)
self.assertEqual(event.type(), QEvent.Timer)
event = QEvent(QEvent.Close)
self.assertEqual(event.type(), QEvent.Close)
event = QEvent(QEvent.IconTextChange)
self.assertEqual(event.type(), QEvent.IconTextChange)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,23 @@
#!/usr/bin/python
'''Test cases for QFlags'''
import unittest
from PySide.QtCore import *
class QFLagTest(unittest.TestCase):
'''Test case for usage of flags'''
def testCallFunction(self):
f = QFile("/tmp/t0");
self.assertEqual(f.open(QIODevice.Truncate | QIODevice.Text | QIODevice.ReadWrite), True)
om = f.openMode()
self.assertEqual(om & QIODevice.Truncate, QIODevice.Truncate)
self.assertEqual(om & QIODevice.Text, QIODevice.Text)
self.assertEqual(om & QIODevice.ReadWrite, QIODevice.ReadWrite)
self.assert_(om == QIODevice.Truncate | QIODevice.Text | QIODevice.ReadWrite)
print (om != QIODevice.ReadOnly)
f.close()
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,26 @@
#!/usr/bin/python
'''Unit tests for QLocale'''
import unittest
import ctypes
import sys
from PySide.QtCore import QLocale
class QLocaleTestToNumber(unittest.TestCase):
def testToNumberInt(self):
obj = QLocale(QLocale.C)
self.assertEqual(37, obj.toInt('37')[0])
def testToNumberFloat(self):
obj = QLocale(QLocale.C)
self.assertEqual(ctypes.c_float(37.109).value,
obj.toFloat('37.109')[0])
def testToNumberDouble(self):
obj = QLocale(QLocale.C)
self.assertEqual(ctypes.c_double(37.109).value,
obj.toDouble('37.109')[0])
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,31 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Tests for static methos conflicts with class methods'''
import unittest
from PySide.QtCore import *
class Foo(QFile):
pass
class qmetaobject_test(unittest.TestCase):
def test_QMetaObject(self):
qobj = QObject()
qobj_metaobj = qobj.metaObject()
self.assertEqual(qobj_metaobj.className(), "QObject")
obj = QFile()
m = obj.metaObject()
self.assertEqual(m.className(), "QFile")
self.assertNotEqual(m.methodCount(), qobj_metaobj.methodCount())
obj = Foo()
m = obj.metaObject()
self.assertEqual(m.className(), "Foo")
self.assertEqual(m.methodCount(), QFile().metaObject().methodCount())
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
''' Test case for QAbstractListModel.createIndex and QModelIndex.internalPointer'''
import sys
import unittest
from PySide.QtCore import *
class MyModel (QAbstractListModel):
pass
class TestQModelIndexInternalPointer(unittest.TestCase):
''' Test case for QAbstractListModel.createIndex and QModelIndex.internalPointer'''
def setUp(self):
#Acquire resources
self.model = MyModel()
def tearDown(self):
#Release resources
del self.model
def testInternalPointer(self):
#Test QAbstractListModel.createIndex and
#QModelIndex.internalPointer with regular
#Python objects
idx = self.model.createIndex(0, 0, "Hello")
self.assertEqual("Hello", idx.internalPointer())
a = [1, 2, 3]
idx = self.model.createIndex(0, 0, a)
self.assertEqual(a, idx.internalPointer())
def testReferenceCounting(self):
#Test reference counting when retrieving data with
#QModelIndex.internalPointer
a = [1, 2, 3]
a_refcnt = sys.getrefcount(a)
idx = self.model.createIndex(0, 0, a)
ptr = idx.internalPointer()
self.assertEqual(sys.getrefcount(a), a_refcnt + 1)
def testIndexForDefaultDataArg(self):
#Test QAbstractListModel.createIndex with a default
#value for data argument
idx = self.model.createIndex(0, 0)
self.assertEqual(None, idx.internalPointer())
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,29 @@
'''Test cases for parent-child relationship'''
import unittest
from PySide.QtCore import QObject, QCoreApplication
class ChildrenCoreApplication(unittest.TestCase):
'''Test case for calling QObject.children after creating a QCoreApp'''
def testQCoreAppChildren(self):
#QObject.children() after creating a QCoreApplication
# Minimal test:
# 1- Create QCoreApp
# 2- Create parent and childrens
# 3- While keeping the children alive, call parent.children()
# 4- Delete parent
app = QCoreApplication([])
parent = QObject()
children = [QObject(parent) for x in range(25)]
# Uncomment the lines below to make the test pass
# del children
# del child2
del parent # XXX Segfaults here
self.assert_(True)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,70 @@
# -*- coding: utf-8 -*-
''' Test case for QObject::connectNotify()'''
import unittest
from PySide.QtCore import *
from helper import UsesQCoreApplication
def cute_slot():
pass
class Obj(QObject):
def __init__(self):
QObject.__init__(self)
self.con_notified = False
self.dis_notified = False
def connectNotify(self, signal):
self.con_notified = True
def disconnectNotify(self, signal):
self.dis_notified = True
def reset(self):
self.con_notified = False
self.dis_notified = False
class TestQObjectConnectNotify(UsesQCoreApplication):
'''Test case for QObject::connectNotify'''
def setUp(self):
UsesQCoreApplication.setUp(self)
self.called = False
def tearDown(self):
UsesQCoreApplication.tearDown(self)
def testBasic(self):
sender = Obj()
receiver = QObject()
sender.connect(SIGNAL("destroyed()"), receiver, SLOT("deleteLater()"))
self.assert_(sender.con_notified)
sender.disconnect(SIGNAL("destroyed()"), receiver, SLOT("deleteLater()"))
self.assert_(sender.dis_notified)
def testPySignal(self):
sender = Obj()
receiver = QObject()
sender.connect(SIGNAL("foo()"), receiver, SLOT("deleteLater()"))
self.assert_(sender.con_notified)
sender.disconnect(SIGNAL("foo()"), receiver, SLOT("deleteLater()"))
self.assert_(sender.dis_notified)
def testPySlots(self):
sender = Obj()
receiver = QObject()
sender.connect(SIGNAL("destroyed()"), cute_slot)
self.assert_(sender.con_notified)
sender.disconnect(SIGNAL("destroyed()"), cute_slot)
self.assert_(sender.dis_notified)
def testpyAll(self):
sender = Obj()
receiver = QObject()
sender.connect(SIGNAL("foo()"), cute_slot)
self.assert_(sender.con_notified)
sender.disconnect(SIGNAL("foo()"), cute_slot)
self.assert_(sender.dis_notified)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,80 @@
'''Test cases for QObject.eventFilter'''
import unittest
from PySide.QtCore import QObject, QTimerEvent
from helper import UsesQCoreApplication
class FilterObject(QObject):
'''Filter object for the basic test'''
def __init__(self, obj=None, event_type=None, *args):
#Creates a new filter object
QObject.__init__(self, *args)
self.obj = obj
self.event_type = event_type
self.events_handled = 0
self.events_bypassed = 0
def setTargetObject(self, obj):
#Sets the object that will be filtered
self.obj = obj
def eventFilter(self, obj, event):
'''Just checks if is the correct object and event type
incrementing counter until reaching the limit. After that it
stops filtering the events for the object.'''
if (self.obj == obj):
if isinstance(event, self.event_type) and self.events_handled < 5:
self.events_handled += 1
return True
else:
self.events_bypassed += 1
return False
else:
return QObject.eventFilter(self, obj, event)
class FilteredObject(QObject):
'''Class that will be filtered. Quits the app after 5 timer events'''
def __init__(self, app, *args):
QObject.__init__(self, *args)
self.app = app
self.times_called = 0
def timerEvent(self, evt):
#Overriden method
self.times_called += 1
if self.times_called == 5:
self.app.quit()
class TestQObjectEventFilterPython(UsesQCoreApplication):
'''QObject.eventFilter - Reimplemented in python
Filters 5 TimerEvents and then bypasses the other events to the
timerEvent method. After 5 runs, the timerEvent method will ask
the core application to exit'''
def setUp(self):
#Acquire resources
UsesQCoreApplication.setUp(self)
self.obj_filter = FilterObject(event_type=QTimerEvent)
def tearDown(self):
#Release resources
del self.obj_filter
UsesQCoreApplication.tearDown(self)
def testEventFilter(self):
#QObject.eventFilter reimplemented in python
filtered = FilteredObject(self.app)
filtered.installEventFilter(self.obj_filter)
self.obj_filter.setTargetObject(filtered)
filtered.startTimer(0)
self.app.exec_()
self.assertEqual(filtered.times_called, 5)
self.assertEqual(self.obj_filter.events_handled, 5)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,43 @@
'''Test cases for QObject methods'''
import unittest
from PySide.QtCore import QObject
class InheritsCase(unittest.TestCase):
'''Test case for QObject.inherits'''
def testCppInheritance(self):
#QObject.inherits() for c++ classes
#An class inherits itself
self.assert_(QObject().inherits('QObject'))
def testPythonInheritance(self):
#QObject.inherits() for python classes
class Dummy(QObject):
#Dummy class
pass
self.assert_(Dummy().inherits('QObject'))
self.assert_(Dummy().inherits('Dummy'))
self.assert_(not Dummy().inherits('FooBar'))
def testPythonMultiInheritance(self):
#QObject.inherits() for multiple inheritance
# QObject.inherits(classname) should fail if classname isn't a
# QObject subclass
class Parent(object):
#Dummy parent
pass
class Dummy(QObject, Parent):
#Dummy class
pass
self.assert_(Dummy().inherits('QObject'))
self.assert_(not Dummy().inherits('Parent'))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,234 @@
'''Test cases for parent-child relationship'''
import unittest
from sys import getrefcount
from PySide.QtCore import QObject, QTimer
class ParentRefCountCase(unittest.TestCase):
'''Test case for the refcount changes of setParent'''
def setUp(self):
#Acquire resources
self.parent = QObject()
self.child = QObject()
def tearDown(self):
#Release resources
del self.child
del self.parent
def testSetParent(self):
#QObject.setParent() refcount changes
self.assertEqual(getrefcount(self.child), 2)
self.child.setParent(self.parent)
self.assertEqual(getrefcount(self.child), 3)
def testConstructor(self):
#QObject(QObject) refcount changes
child = QObject(self.parent)
self.assertEqual(getrefcount(child), 3)
class ParentCase(unittest.TestCase):
'''Small collection of tests related to parent-child relationship'''
def testSetParent(self):
#QObject.setParent()
parent = QObject()
child = QObject()
child.setParent(parent)
self.assertEqual(parent, child.parent())
def testParentConstructor(self):
#QObject(parent)
parent = QObject()
child = QObject(parent)
self.assertEqual(parent, child.parent())
orig_repr = repr(child)
del child
self.assertEqual(orig_repr, repr(parent.children()[0]))
def testChildren(self):
#QObject.children()
parent = QObject()
children = [QObject(parent) for x in range(25)]
self.assertEqual(parent.children(), children)
def testFindChild(self):
#QObject.findChild() with all QObject
parent = QObject()
name = 'object%d'
children = [QObject(parent) for i in range(20)]
for i, child in enumerate(children):
child.setObjectName(name % i)
for i, child in enumerate(children):
self.assertEqual(child, parent.findChild(QObject, name % i))
def testFindChildren(self):
#QObject.findChildren() with all QObject
parent = QObject()
target_name = 'foo'
children = [QTimer(parent) for i in range(20)]
children.extend([QObject(parent) for i in range(20)])
for i, child in enumerate(children):
if i % 5 == 0:
child.setObjectName(target_name)
else:
child.setObjectName(str(i))
# Emulates findChildren with the intended outcome
target_children = [x for x in children if x.objectName() == target_name]
test_children = parent.findChildren(QObject, target_name)
self.assertEqual(sorted(target_children), sorted(test_children))
def testParentEquality(self):
#QObject.parent() == parent
parent = QObject()
child = QObject(parent)
self.assertEqual(parent, child.parent())
class TestParentOwnership(unittest.TestCase):
'''Test case for Parent/Child object ownership'''
def testParentDestructor(self):
parent = QObject()
self.assertEqual(getrefcount(parent), 2)
child = QObject(parent)
self.assertEqual(getrefcount(child), 3)
self.assertEqual(getrefcount(parent), 2)
del parent
self.assertEqual(getrefcount(child), 2)
# this will fail because parent deleted child cpp object
self.assertRaises(RuntimeError, lambda :child.objectName())
# test parent with multiples children
def testMultipleChildren(self):
o = QObject()
self.assertEqual(getrefcount(o), 2)
c = QObject(o)
self.assertEqual(getrefcount(c), 3)
self.assertEqual(getrefcount(o), 2)
c2 = QObject(o)
self.assertEqual(getrefcount(o), 2)
self.assertEqual(getrefcount(c), 3)
self.assertEqual(getrefcount(c2), 3)
del o
self.assertEqual(getrefcount(c), 2)
self.assertEqual(getrefcount(c2), 2)
# this will fail because parent deleted child cpp object
self.assertRaises(RuntimeError, lambda :c.objectName())
self.assertRaises(RuntimeError, lambda :c2.objectName())
# test recursive parent
def testRecursiveParent(self):
o = QObject()
self.assertEqual(getrefcount(o), 2)
c = QObject(o)
self.assertEqual(getrefcount(c), 3)
self.assertEqual(getrefcount(o), 2)
c2 = QObject(c)
self.assertEqual(getrefcount(o), 2)
self.assertEqual(getrefcount(c), 3)
self.assertEqual(getrefcount(c2), 3)
del o
self.assertEqual(getrefcount(c), 2)
self.assertEqual(getrefcount(c2), 2)
# this will fail because parent deleted child cpp object
self.assertRaises(RuntimeError, lambda :c.objectName())
self.assertRaises(RuntimeError, lambda :c2.objectName())
# test parent transfer
def testParentTransfer(self):
o = QObject()
self.assertEqual(getrefcount(o), 2)
c = QObject()
self.assertEqual(getrefcount(c), 2)
c.setParent(o)
self.assertEqual(getrefcount(c), 3)
c.setParent(None)
self.assertEqual(getrefcount(c), 2)
del c
del o
class ExtQObject(QObject):
def __init__(self):
QObject.__init__(self)
class ReparentingTest(unittest.TestCase):
'''Test cases for reparenting'''
def testParentedQObjectIdentity(self):
object_list = []
parent = QObject()
for i in range(3):
obj = QObject()
object_list.append(obj)
obj.setParent(parent)
for child in parent.children():
self.assert_(child in object_list)
def testParentedExtQObjectType(self):
object_list = []
parent = QObject()
for i in range(3):
obj = ExtQObject()
object_list.append(obj)
obj.setParent(parent)
for orig, child in zip(object_list, parent.children()):
self.assertEqual(type(orig), type(child))
def testReparentedQObjectIdentity(self):
object_list = []
old_parent = QObject()
new_parent = QObject()
for i in range(3):
obj = QObject()
object_list.append(obj)
obj.setParent(old_parent)
for obj in object_list:
obj.setParent(new_parent)
for child in new_parent.children():
self.assert_(child in object_list)
def testReparentedExtQObjectType(self):
object_list = []
old_parent = QObject()
new_parent = QObject()
for i in range(3):
obj = ExtQObject()
object_list.append(obj)
obj.setParent(old_parent)
for obj in object_list:
obj.setParent(new_parent)
for orig, child in zip(object_list, new_parent.children()):
self.assertEqual(type(orig), type(child))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,54 @@
'''Test cases for QObject property and setProperty'''
import unittest
from PySide.QtCore import QObject, QVariant
class PropertyCase(unittest.TestCase):
'''Test case for QObject properties'''
def testObjectNameProperty(self):
#QObject.setProperty() for existing C++ property
obj = QObject()
self.assert_(obj.setProperty('objectName', QVariant('dummy')))
self.assertEqual(obj.objectName(), 'dummy')
self.assert_(obj.setProperty('objectName', QVariant('foobar')))
self.assertEqual(obj.objectName(), 'foobar')
def testDynamicProperty(self):
#QObject.setProperty() for dynamic properties
obj = QObject()
# Should return false when creating a new dynamic property
self.assert_(not obj.setProperty('dummy', QVariant('mydata')))
prop = obj.property('dummy')
self.assert_(isinstance(prop, QVariant))
self.assert_(prop.isValid())
self.assertEqual(obj.property('dummy').toString(), 'mydata')
self.assert_(not obj.setProperty('dummy', QVariant('zigzag')))
prop = obj.property('dummy')
self.assert_(isinstance(prop, QVariant))
self.assert_(prop.isValid())
self.assertEqual(obj.property('dummy').toString(), 'zigzag')
self.assert_(not obj.setProperty('dummy', QVariant(42)))
prop = obj.property('dummy')
self.assert_(isinstance(prop, QVariant))
self.assert_(prop.isValid())
# QVariant.toInt has a bool* arg in C++, so returns a tuple
self.assertEqual(obj.property('dummy').toInt(), (42, True))
def testInvalidProperty(self):
#QObject.property() for invalid properties
obj = QObject()
prop = obj.property('dummy')
self.assert_(not prop.isValid())
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,38 @@
#!/usr/bin/python
'''Test cases for QObject protected methods'''
import unittest
from PySide.QtCore import QObject, QThread, SIGNAL
class Dummy(QObject):
'''Dummy class'''
pass
class QObjectReceivers(unittest.TestCase):
'''Test case for QObject.receivers()'''
def cb(self, *args):
#Dummy callback
pass
def testQObjectReceiversExtern(self):
#QObject.receivers() - Protected method external access
obj = Dummy()
self.assertEqual(obj.receivers(SIGNAL("destroyed()")), 0)
QObject.connect(obj, SIGNAL("destroyed()"), self.cb)
self.assertEqual(obj.receivers(SIGNAL("destroyed()")), 1)
def testQThreadReceiversExtern(self):
#QThread.receivers() - Inherited protected method
obj = QThread()
self.assertEqual(obj.receivers(SIGNAL('destroyed()')), 0)
QObject.connect(obj, SIGNAL("destroyed()"), self.cb)
self.assertEqual(obj.receivers(SIGNAL("destroyed()")), 1)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,49 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Test cases for QObject methods'''
import unittest
from PySide.QtCore import QObject
class ObjectNameCase(unittest.TestCase):
'''Tests related to QObject object name'''
def testSimple(self):
#QObject.objectName(string)
name = 'object1'
obj = QObject()
obj.setObjectName(name)
self.assertEqual(name, obj.objectName())
def testEmpty(self):
#QObject.objectName('')
name = ''
obj = QObject()
obj.setObjectName(name)
self.assertEqual(name, obj.objectName())
def testNone(self):
#QObject.objectName(None)
obj = QObject()
self.assertRaises(TypeError, obj.setObjectName, None)
def testDefault(self):
#QObject.objectName() default
obj = QObject()
self.assertEqual('', obj.objectName())
def testUnicode(self):
#QObject.setObjectName(unicode)
name = u'diseño'
#FIXME Strange error on upstream when using equal(name, obj)
obj = QObject()
obj.setObjectName(name)
self.assertEqual(obj.objectName(), name)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,44 @@
#!/usr/bin/python
'''Test case for QObject.timerEvent overloading'''
import unittest
from time import sleep
from PySide.QtCore import QObject, QCoreApplication
from helper import UsesQCoreApplication
class Dummy(QObject):
def __init__(self, app):
super(Dummy, self).__init__()
self.times_called = 0
self.app = app
def timerEvent(self, event):
QObject.timerEvent(self, event)
event.accept()
self.times_called += 1
if self.times_called == 5:
self.app.exit(0)
class QObjectTimerEvent(UsesQCoreApplication):
def setUp(self):
#Acquire resources
super(QObjectTimerEvent, self).setUp()
def tearDown(self):
#Release resources
super(QObjectTimerEvent, self).tearDown()
def testTimerEvent(self):
#QObject.timerEvent overloading
obj = Dummy(self.app)
timer_id = obj.startTimer(200)
self.app.exec_()
obj.killTimer(timer_id)
self.assertEqual(obj.times_called, 5)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,55 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Unit tests for QObject's tr and trUtf8 static methods.'''
import os
import unittest
from PySide.QtCore import QObject
#from helper import UsesQCoreApplication
class QObjectTrTest(unittest.TestCase):
'''Test case to check if QObject tr and trUtf8 static methods could be treated as instance methods.'''
def setUp(self):
self.obj = QObject()
def tearDown(self):
del self.obj
def testTrCommonCase(self):
#Test common case for QObject.tr
invar1 = 'test1'
outvar1 = self.obj.tr(invar1)
invar2 = 'test2'
outvar2 = self.obj.tr(invar2, 'test comment')
self.assertEqual((invar1, invar2), (outvar1, outvar2))
def testTrAsInstanceMethod(self):
#Test QObject.tr as instance
invar1 = 'test1'
outvar1 = QObject.tr(self.obj, invar1)
invar2 = 'test2'
outvar2 = QObject.tr(self.obj, invar2, 'test comment')
self.assertEqual((invar1, invar2), (outvar1, outvar2))
def testTrUtf8CommonCase(self):
#Test common case for QObject.trUtf8
invar1 = 'test1'
outvar1 = self.obj.trUtf8(invar1)
invar2 = 'test2'
outvar2 = self.obj.trUtf8(invar2, 'test comment')
self.assertEqual((invar1, invar2), (outvar1, outvar2))
def testTrUtf8AsInstanceMethod(self):
#Test QObject.trUtf8 as instance
invar1 = 'test1'
outvar1 = QObject.trUtf8(self.obj, invar1)
invar2 = 'test2'
outvar2 = QObject.trUtf8(self.obj, invar2, 'test comment')
self.assertEqual((invar1, invar2), (outvar1, outvar2))
if __name__ == '__main__':
unittest.main()

102
tests/qtcore/qrect_test.py Normal file
View file

@ -0,0 +1,102 @@
#!/usr/bin/python
'''Test cases for QRect'''
import unittest
from PySide.QtCore import QPoint, QRect
class RectConstructor(unittest.TestCase):
def testDefault(self):
#QRect()
obj = QRect()
self.assert_(obj.isNull())
def testConstructorQPoint(self):
topLeft = QPoint(3, 0)
bottomRight = QPoint(0, 3)
rect1 = QRect(topLeft, bottomRight)
rect2 = QRect(topLeft, bottomRight)
self.assertEqual(rect1, rect2)
class RectOperator(unittest.TestCase):
'''Test case for QRect operators'''
def testEqual(self):
'''QRect == QRect
Note: operator == must be working as it's the main check
for correctness'''
rect1 = QRect()
rect2 = QRect()
self.assertEqual(rect1, rect2)
rect1 = QRect(0, 4, 100, 300)
rect2 = QRect(0, 4, 100, 300)
self.assertEqual(rect1, rect2)
def testNullRectIntersection(self):
#QRect & QRect for null rects
rect1 = QRect()
rect2 = QRect()
rect3 = rect1 & rect2
self.assertEqual(rect3, rect1)
self.assertEqual(rect3, rect2)
def testNoIntersect(self):
'''QRect & QRect for non-intersecting QRects
Non-intersecting QRects return a 'null' QRect for operator &'''
rect1 = QRect(10, 10, 5, 5)
rect2 = QRect(20, 20, 5, 5)
rect3 = rect1 & rect2
self.assertEqual(rect3, QRect())
def testIntersectPartial(self):
#QRect & QRect for partial intersections
rect1 = QRect(10, 10, 10, 10)
rect2 = QRect(15, 15, 10, 10)
rect3 = rect1 & rect2
self.assertEqual(rect3, QRect(15, 15, 5, 5))
def testIntersetEnclosed(self):
#QRect & QRect for a qrect inside another
rect1 = QRect(10, 10, 20, 20)
rect2 = QRect(15, 15, 5, 5)
rect3 = rect1 & rect2
self.assertEqual(rect3, rect2)
def testNullRectIntersectBounding(self):
#QRect | QRect for null rects
rect1 = QRect()
rect2 = QRect()
rect3 = rect1 & rect2
self.assertEqual(rect3, rect1)
self.assertEqual(rect3, rect2)
def testNoIntersectBounding(self):
'''QRect | QRect for non-intersecting QRects
Non-intersecting QRects return a greater QRect for operator |'''
rect1 = QRect(10, 10, 5, 5)
rect2 = QRect(20, 20, 5, 5)
rect3 = rect1 | rect2
self.assertEqual(rect3, QRect(10, 10, 15, 15))
def testBoundingPartialIntersection(self):
#QRect | QRect for partial intersections
rect1 = QRect(10, 10, 10, 10)
rect2 = QRect(15, 15, 10, 10)
rect3 = rect1 | rect2
self.assertEqual(rect3, QRect(10, 10, 15, 15))
def testBoundingEnclosed(self):
#QRect | QRect for a qrect inside another
rect1 = QRect(10, 10, 20, 20)
rect2 = QRect(15, 15, 5, 5)
rect3 = rect1 | rect2
self.assertEqual(rect3, rect1)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,35 @@
# -*- coding: utf-8 -*-
'''Test cases for QResource usage'''
import unittest
import os
from PySide.QtCore import QFile, QIODevice
import resources_mc
class ResourcesUsage(unittest.TestCase):
'''Test case for resources usage'''
def setUp(self):
try:
f = open('quoteEnUS.txt')
except IOError:
f = open(os.path.join('qtcore', 'quoteEnUS.txt'))
self.text = f.read()
f.close()
def tearDown(self):
self.text = None
def testPhrase(self):
#Test loading of quote.txt resource
f = QFile(':/quote.txt')
f.open(QIODevice.ReadOnly|QIODevice.Text)
content = f.readAll()
f.close()
self.assertEqual(self.text, content)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,26 @@
#!/usr/bin/python
'''Unit tests for QSize'''
import unittest
from PySide.QtCore import QSize
class QSizeOperator(unittest.TestCase):
def testOperatorMultiply(self):
#QSize operator * float
# bug 131
a = QSize(1, 1)
x = a * 3.4
self.assertEqual(QSize(3, 3), x)
def testOperatorRevertedMultiply(self):
#QSize operator * float, reverted
# bug 132
a = QSize(1, 1)
x = 3.4 * a
self.assertEqual(QSize(3, 3), x)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,47 @@
#!/usr/bin/python
import unittest
from PySide import QtCore
global qApp
class objTest(QtCore.QObject):
def __init__(self, parent=None):
QtCore.QObject.__init__(self, parent)
self.ok = False
def slot(self):
global qApp
self.ok = True
qApp.quit()
class slotTest(unittest.TestCase):
def quit_app(self):
global qApp
qApp.quit()
def testBasic(self):
global qApp
timer = QtCore.QTimer()
timer.setInterval(100)
my_obj = objTest()
my_slot = QtCore.SLOT("slot()")
timer.connect(QtCore.SIGNAL("timeout()"), my_obj, my_slot)
timer.start(100)
QtCore.QTimer.singleShot(1000, self.quit_app)
qApp.exec_()
self.assert_(my_obj.ok)
if __name__ == '__main__':
global qApp
qApp = QtCore.QCoreApplication([])
unittest.main()

View file

@ -0,0 +1,16 @@
import gc
import unittest
from PySide.QtCore import qsrand
class OverflowExceptionCollect(unittest.TestCase):
'''Test case for OverflowError exception during garbage collection. See bug #147'''
def testOverflow(self):
# NOTE: PyQt4 raises TypeError, but boost.python raises OverflowError
self.assertRaises(OverflowError, qsrand, 42415335332353253)
# should not abort if bug #147 is fixed
gc.collect()
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,25 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Tests QString implementation of Python buffer protocol'''
import unittest
from os.path import isdir
from PySide.QtCore import QString
class QStringBufferProtocolTest(unittest.TestCase):
'''Tests QString implementation of Python buffer protocol'''
def testQStringBufferProtocol(self):
#Tests QString implementation of Python buffer protocol using the os.path.isdir
#function which an unicode object or other object implementing the Python buffer protocol
os_path_isdir_function_correctly_called_with_a_qstring = True
try:
isdir(QString('/tmp'))
except:
os_path_isdir_function_correctly_called_with_a_qstring = False
self.assertTrue(os_path_isdir_function_correctly_called_with_a_qstring)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,104 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Test cases for QString operators'''
import unittest
from PySide.QtCore import QString, QByteArray
class QStringOperatorEqual(unittest.TestCase):
'''TestCase for operator QString == QString'''
def testDefault(self):
#QString() == QString()
obj1 = QString()
obj2 = QString()
self.assertEqual(obj1, obj2)
def testSimple(self):
#QString(some_string) == QString(some_string)
string = 'egg snakes'
self.assertEqual(QString(string), QString(string))
def testUnicode(self):
#QString(unicode) == QString(unicode)
string = u'àâãá'
self.assertEqual(QString(string), QString(string))
def testPyString(self):
#QString(string) == string
string = 'my test string'
self.assertEqual(QString(string), string)
self.assertEqual(string, QString(string))
def testPyUnicodeString(self):
#QString(unicode) == unicode
string = u'àâãá'
self.assertEqual(QString(string), string)
self.assertEqual(string, unicode(QString(string)))
def testQByteArray(self):
#QString(string) == QByteArray(string)
string = 'another test string'
self.assertEqual(QString(string), QByteArray(string))
class QStringOperatorAt(unittest.TestCase):
'''TestCase for operator QString[]'''
def testInRange(self):
#QString[x] where x is a valid index
string = 'abcdefgh'
obj = QString(string)
for i in range(len(string)):
self.assertEqual(obj[i], string[i])
def testInRangeReverse(self):
#QString[x] where x is a valid index (reverse order)
string = 'abcdefgh'
obj = QString(string)
for i in range(len(string)-1, 0, -1):
self.assertEqual(obj[i], string[i])
def testInRangeUnicode(self):
#QString[x] where x is a valid index (unicode)
string = u'àâãá'
obj = QString(string)
for i in range(len(string)):
self.assertEqual(obj[i], string[i])
def testInRangeUnicodeReverse(self):
#QString[x] where x is a valid index (unicode) (reverse order)
string = u'àâãá'
obj = QString(string)
for i in range(len(string)-1, 0, -1):
self.assertEqual(obj[i], string[i])
def testOutOfRange(self):
#QString[x] where x is out of index
string = '1234567'
obj = QString(string)
self.assertRaises(IndexError, lambda :obj[len(string)])
def testReturnQString(self):
#QString[x] must return a QString
string = QString('123456')
data = string[0]
self.assert_(isinstance(data, QString))
class QStringOperatorAdd(unittest.TestCase):
'''TestCase for operator QString[]'''
def testOperatorAdd(self):
str1 = '123'
str2 = QString('456')
self.assertEquals('123456', str1 + str2)
self.assertEquals('456123', str2 + str1)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,18 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Tests QString using QKeySequence parameter'''
import unittest
from PySide.QtCore import QString
from PySide.QtGui import QKeySequence
class QStringQKeySequenceTest(unittest.TestCase):
'''Tests QString using QKeySequence parameter'''
def testQStringQKeySequence(self):
a = QString(QKeySequence("Ctrl+A"))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,106 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Test cases for QString'''
import unittest
import ctypes
import sys
from PySide.QtCore import QString, QByteArray
class QStringToNumber(unittest.TestCase):
def testToNumberInt(self):
obj = QString('37')
self.assertEqual(37, obj.toInt()[0])
def testToNumberFloat(self):
obj = QString('37.109')
self.assertEqual(ctypes.c_float(37.109).value,
obj.toFloat()[0])
def testToNumberDouble(self):
obj = QString('37.109')
self.assertEqual(ctypes.c_double(37.109).value,
obj.toDouble()[0])
def testToULongLong(self):
obj = QString('37109')
self.assertEqual(ctypes.c_ulong(37109).value,
obj.toULongLong()[0])
class QStringConstructor(unittest.TestCase):
'''Test case for QString constructors'''
def testQStringDefault(self):
#QString()
obj1 = QString()
obj2 = QString()
self.assertEqual(obj1, obj2)
def testQStringFromPy(self):
#QString(const char*)
sample = 'a new string'
obj1 = QString(sample)
obj2 = QString(sample)
self.assertEqual(obj1, obj2)
def testQStringFromUnicode(self):
sample = u'áâãà'
obj1 = QString(sample)
obj2 = QString(sample)
self.assertEqual(obj1, obj2)
self.assertEqual(obj1, sample)
self.assertEqual(obj2, sample)
def testQStringFromByteArray(self):
# QByteArray(const char *) must be working
sample = QByteArray('foo')
obj1 = QString(sample)
obj2 = QString(sample)
self.assertEqual(obj1, obj2)
def testQStringArg(self):
a = QString("%1 %2 %3").arg(1).arg("two").arg(3.14)
self.assertEquals("1 two 3.14", str(a))
def testQStringArgNegative(self):
a = QString("%1").arg(-20)
self.assertEquals("-20", str(a))
class QStringComparison(unittest.TestCase):
'''Test case for comparison to python strings'''
def testComparePyString(self):
#Compare QStrings and Python strings.
py = ''
qstr = QString()
self.assertEqual(py, qstr)
py = 'The quick brown fox jumps over the lazy dog'
qstr = QString(py)
self.assertEqual(py, qstr)
class QStringRange(unittest.TestCase):
'''Test case for ranges in python strings'''
def testSimpleRange(self):
#Test open start and open end intervals
py = 'The quick brown fox jumps over the lazy dog'
qstr = QString(py)
self.assertEqual(py[5:], qstr[5:])
self.assertEqual(py[:7], qstr[:7])
class QStringIndexOf(unittest.TestCase):
def testEmpty(self):
string = QString()
self.assertEqual(string.indexOf(QString("aaa")), -1)
self.assertEqual(string.indexOf(QString()), 0)
def testString(self):
string = QString("the quick brown fox")
self.assertEqual(string.indexOf("quick", 0), 4)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,165 @@
# -*- coding: utf-8 -*-
'''Test cases for QStringList'''
import unittest
from random import shuffle
from PySide.QtCore import QStringList, QString
from helper import random_string
class UsesManyStrings(unittest.TestCase):
'''Helper class to setup a list of strings and QStrings'''
def setUp(self):
#Creates a list of strings and python strings
self.size = 10
# List of Python strings
self.samples = [random_string() for x in range(self.size)]
# List of QStrings
self.strings = map(QString, self.samples)
self.obj = QStringList(self.strings)
class TestConstructorBasic(unittest.TestCase):
'''Basic constructor test'''
def testEmpty(self):
#QStringList() - default constructor
obj = QStringList()
self.assert_(isinstance(obj, QStringList))
def testQString(self):
#QStringList(QString)
qstr = QString('aaaa')
obj = QStringList(qstr)
self.assert_(isinstance(obj, QStringList))
def testPyString(self):
#QStringList(python_string) constructor
string = 'forty two'
obj = QStringList(string)
self.assert_(isinstance(obj, QStringList))
def testPyStringUnicode(self):
#QStringList(unicode python_string) constructor
string = 'Nação Zumbi'
obj = QStringList(string)
self.assert_(isinstance(obj, QStringList))
class TestConstructorList(UsesManyStrings):
'''Test case for QStringList(List) constructor'''
def testListQString(self):
#QStringList([QString]) constructor
obj = QStringList(self.strings)
self.assert_(isinstance(obj, QStringList))
def testListPyString(self):
#QStringList([python_string]) constructor
obj = QStringList(self.samples)
self.assert_(isinstance(obj, QStringList))
def testListMixed(self):
#QStringList([python_string and QString]) mixed constructor
mixed = self.samples + self.strings
shuffle(mixed)
obj = QStringList(mixed)
self.assert_(isinstance(obj, QStringList))
def testCopyList(self):
#QStringList(QStringList(list)) - copy constructor
obj = QStringList(self.strings)
obj2 = QStringList(obj)
self.assert_(isinstance(obj2, QStringList))
self.assertEqual(obj, obj2)
class TestComparison(unittest.TestCase):
'''Test case for comparison of QStringLists'''
def testEqual(self):
#QStringList == QStringList
string = QString('aaaabvbbcccedde')
obj1 = QStringList(string)
obj2 = QStringList(string)
self.assertEqual(obj1, obj2)
class TestIndexing(unittest.TestCase):
'''Test case for indexing through []'''
def testInvalidIndexEmpty(self):
#QStringList[x] for empty list
obj = QStringList()
self.assertRaises(IndexError, lambda:obj[0])
def testInvalidIndexQString(self):
#QStringList[1] raising IndexError for QStringList(QString)
obj = QStringList(QString('aaaaa'))
self.assertRaises(IndexError, lambda:obj[1])
def testValidIndexQString(self):
#QStringList[0] not raising IndexError for QStringList(QString)
string = QString('abcdefg')
obj = QStringList(string)
self.assertEqual(obj[0], string)
def testNegativeIndexing(self):
#QStringList[-1] not raising IndexError for QStringList(QString)
string = QString('abcdefg')
obj = QStringList(string)
self.assertEqual(obj[-1], string)
class TestListIndexing(UsesManyStrings):
'''Test case for indexing QStringList longer than 1 string'''
def testValid(self):
#QStringList[] for valid indexes
for i in range(self.size):
self.assertEqual(self.strings[i], self.obj[i])
def testNegativeValid(self):
#QStringList[] for valid indexes
for i in range(-1, -self.size, -1):
self.assertEqual(self.strings[i], self.obj[i])
def testInvalid(self):
#QStringList[] for invalid negative indexes
self.assertRaises(IndexError, lambda : self.obj[self.size])
self.assertRaises(IndexError, lambda : self.obj[-(self.size+1)])
class TestSlicing(UsesManyStrings):
'''Test case for slicing a QStringList'''
def testSlicing(self):
#QStringList slicing
for i in range(self.size):
self.assertEqual(self.obj[i:], self.strings[i:])
self.assertEqual(self.obj[:i], self.strings[:i])
for j in range(i):
self.assertEqual(self.obj[j:i], self.strings[j:i])
for i in range(-1, -self.size, -1):
self.assertEqual(self.obj[:i], self.strings[:i])
class TestShiftOperator(UsesManyStrings):
'''Test case for QStringList lshift operator'''
def testShiftOperator(self):
#QStringList lshift
a = QStringList()
a << "a" << "b" << "c";
self.assertEquals(3, a.count())
b = ["1", "2", "3"]
c = ["4", "5", "6"]
a << b << c
self.assertEquals(9, a.count())
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,20 @@
import gc
import unittest
from PySide.QtCore import QTextCodec
class TestCodecGetters(unittest.TestCase):
def testCodecsNames(self):
for codec_name in QTextCodec.availableCodecs():
codec = QTextCodec.codecForName(codec_name)
self.assert_(type(codec), QTextCodec)
def testCodecsMibs(self):
for codec_num in QTextCodec.availableMibs():
codec = QTextCodec.codecForMib(codec_num)
self.assert_(type(codec), QTextCodec)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,107 @@
#!/usr/bin/python
'''Producer-Consumer test/example with QThread'''
import unittest
from random import random
import logging
logging.basicConfig(level=logging.WARNING)
from PySide.QtCore import QThread, QCoreApplication, QObject, SIGNAL
class Bucket(QObject):
'''Dummy class to hold the produced values'''
def __init__(self, max_size=10, *args):
#Constructor which receives the max number of produced items
super(Bucket, self).__init__(*args)
self.data = []
self.max_size = 10
def pop(self):
#Retrieves an item
return self.data.pop(0)
def push(self, data):
#Pushes an item
self.data.append(data)
class Producer(QThread):
'''Producer thread'''
def __init__(self, bucket, *args):
#Constructor. Receives the bucket
super(Producer, self).__init__(*args)
self.runs = 0
self.bucket = bucket
self.production_list = []
def run(self):
#Produces at most bucket.max_size items
while self.runs < self.bucket.max_size:
value = int(random()*10) % 10
self.bucket.push(value)
self.production_list.append(value)
logging.debug('PRODUCER - pushed %d' % value)
self.runs += 1
self.msleep(5)
class Consumer(QThread):
'''Consumer thread'''
def __init__(self, bucket, *args):
#Constructor. Receives the bucket
super(Consumer, self).__init__(*args)
self.runs = 0
self.bucket = bucket
self.consumption_list = []
def run(self):
#Consumes at most bucket.max_size items
while self.runs < self.bucket.max_size:
try:
value = self.bucket.pop()
self.consumption_list.append(value)
logging.debug('CONSUMER - got %d' % value)
self.runs += 1
except IndexError:
logging.debug('CONSUMER - empty bucket')
self.msleep(5)
class ProducerConsumer(unittest.TestCase):
'''Basic test case for producer-consumer QThread'''
def setUp(self):
#Create fixtures
self.app = QCoreApplication([])
def tearDown(self):
#Destroy fixtures
del self.app
def finishCb(self):
#Quits the application
self.app.exit(0)
def testProdCon(self):
#QThread producer-consumer example
bucket = Bucket()
prod = Producer(bucket)
cons = Consumer(bucket)
prod.start()
cons.start()
QObject.connect(prod, SIGNAL('finished()'), self.finishCb)
QObject.connect(cons, SIGNAL('finished()'), self.finishCb)
self.app.exec_()
prod.wait()
cons.wait()
self.assertEqual(prod.production_list, cons.consumption_list)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,64 @@
'''Test cases for connecting signals between threads'''
import unittest
from PySide.QtCore import QThread, QObject, SIGNAL, QCoreApplication
thread_run = False
class Source(QObject):
def __init__(self, *args):
QObject.__init__(self, *args)
def emit_sig(self):
self.emit(SIGNAL('source()'))
class Target(QObject):
def __init__(self, *args):
QObject.__init__(self, *args)
self.called = False
def myslot(self):
self.called = True
class ThreadJustConnects(QThread):
def __init__(self, source, *args):
QThread.__init__(self, *args)
self.source = source
self.target = Target()
def run(self):
global thread_run
thread_run = True
QObject.connect(self.source, SIGNAL('source()'), self.target.myslot)
while not self.target.called:
pass
class BasicConnection(unittest.TestCase):
def testEmitOutsideThread(self):
global thread_run
app = QCoreApplication([])
source = Source()
thread = ThreadJustConnects(source)
QObject.connect(thread, SIGNAL('finished()'), lambda: app.exit(0))
thread.start()
while not thread_run:
pass
source.emit_sig()
app.exec_()
thread.wait()
self.assert_(thread.target.called)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,76 @@
#!/usr/bin/python
'''Test cases for QThread'''
import unittest
from PySide.QtCore import QThread, QCoreApplication, QObject, SIGNAL, QMutex, QTimer
from PySide.QtCore import QEventLoop
from helper import UsesQCoreApplication
mutex = QMutex()
class Dummy(QThread):
'''Dummy thread'''
def __init__(self, *args):
super(Dummy, self).__init__(*args)
self.called = False
def run(self):
#Start-quit sequence
mutex.lock()
self.called = True
mutex.unlock()
class QThreadSimpleCase(UsesQCoreApplication):
def setUp(self):
UsesQCoreApplication.setUp(self)
self.called = False
def tearDown(self):
UsesQCoreApplication.tearDown(self)
def testThread(self):
#Basic QThread test
obj = Dummy()
obj.start()
obj.wait()
self.assert_(obj.called)
def cb(self, *args):
self.called = True
#self.exit_app_cb()
def abort_application(self):
self._thread.terminate()
self.app.quit()
def testSignalFinished(self):
#QThread.finished() (signal)
obj = Dummy()
QObject.connect(obj, SIGNAL('finished()'), self.cb)
mutex.lock()
obj.start()
mutex.unlock()
self._thread = obj
QTimer.singleShot(1000, self.abort_application)
self.app.exec_()
self.assert_(self.called)
def testSignalStarted(self):
#QThread.started() (signal)
obj = Dummy()
QObject.connect(obj, SIGNAL('started()'), self.cb)
obj.start()
self._thread = obj
QTimer.singleShot(1000, self.abort_application)
self.app.exec_()
self.assert_(self.called)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,49 @@
#!/usr/bin/python
'''Test cases for QTimer.singleShot'''
import unittest
from PySide.QtCore import QObject, QTimer, QCoreApplication, SIGNAL
from helper import UsesQCoreApplication
class WatchDog(QObject):
'''Exits the QCoreApplication main loop after sometime.'''
def __init__(self, watched):
QObject.__init__(self)
self.times_called = 0
self.watched = watched
def timerEvent(self, evt):
self.times_called += 1
if self.times_called == 20:
self.watched.exit_app_cb()
class TestSingleShot(UsesQCoreApplication):
'''Test case for QTimer.singleShot'''
def setUp(self):
#Acquire resources
UsesQCoreApplication.setUp(self)
self.watchdog = WatchDog(self)
self.called = False
def tearDown(self):
#Release resources
del self.watchdog
del self.called
UsesQCoreApplication.tearDown(self)
def callback(self):
self.called = True
self.app.quit()
def testSingleShot(self):
timer = QTimer.singleShot(100, self.callback)
self.app.exec_()
self.assert_(self.called)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,57 @@
'''Test case for timeout() signals from QTimer object.'''
import unittest
import os
from tempfile import mkstemp
from PySide.QtCore import QObject, QTimer, SIGNAL
from helper import UsesQCoreApplication
class WatchDog(QObject):
'''Exits the QCoreApplication main loop after sometime.'''
def __init__(self, watched):
QObject.__init__(self)
self.times_called = 0
self.watched = watched
def timerEvent(self, evt):
self.times_called += 1
if self.times_called == 20:
self.watched.exit_app_cb()
class TestTimeoutSignal(UsesQCoreApplication):
'''Test case to check if the signals are really being caught'''
def setUp(self):
#Acquire resources
UsesQCoreApplication.setUp(self)
self.watchdog = WatchDog(self)
self.timer = QTimer()
self.called = False
def tearDown(self):
#Release resources
del self.watchdog
del self.timer
del self.called
UsesQCoreApplication.tearDown(self)
def callback(self, *args):
#Default callback
self.called = True
def testTimeoutSignal(self):
#Test the QTimer timeout() signal
QObject.connect(self.timer, SIGNAL('timeout()'), self.callback)
self.timer.start(4)
self.watchdog.startTimer(10)
self.app.exec_()
self.assert_(self.called)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,19 @@
#!/usr/bin/python
'''Test suite for QtCore.Qt namespace'''
import unittest
from PySide.QtCore import Qt
class QtNamespace(unittest.TestCase):
'''Test case for accessing attributes from Qt namespace'''
def testBasic(self):
#Access to Qt namespace
getattr(Qt, 'Horizontal')
getattr(Qt, 'WindowMaximizeButtonHint')
self.assert_(True)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1 @@
Fine! Dishonor! Dishonor on you, dishonor on ya cow!

91
tests/qtcore/qurl_test.py Normal file
View file

@ -0,0 +1,91 @@
#!/usr/bin/python
'''Test suite for QtCore.QUrl'''
import unittest
from PySide.QtCore import QUrl
class QUrlBasicConstructor(unittest.TestCase):
'''Tests the basic constructors'''
def testBasic(self):
#Default constructor for QUrl
url = QUrl()
self.assertEqual(url.toString(), "")
def testSetAttributes(self):
#Construct QUrl by set* methods
url = QUrl()
url.setScheme('ftp')
self.assertEqual(url.toString(), 'ftp:')
url.setHost('www.google.com')
self.assertEqual(url.toString(), 'ftp://www.google.com')
url.setPort(8080)
self.assertEqual(url.toString(), 'ftp://www.google.com:8080')
url.setPath('mail/view')
self.assertEqual(url.toString(),
'ftp://www.google.com:8080/mail/view')
url.setUserName('john')
self.assertEqual(url.toString(),
'ftp://john@www.google.com:8080/mail/view')
url.setPassword('abc123')
self.assertEqual(url.toString(),
'ftp://john:abc123@www.google.com:8080/mail/view')
class QueryItemsTest(unittest.TestCase):
'''Test query item management'''
def testQueryItems(self):
#QUrl.queryItems
url = QUrl('http://www.google.com/search?q=python&hl=en')
valid_data = [(('q'), ('python')), (('hl'), ('en'))]
self.assertEqual(sorted(url.queryItems()), sorted(valid_data))
def testEncodedQueryItems(self):
#QUrl.encodedQueryItems
url = QUrl('http://www.google.com/search?q=python&hl=en')
valid_data = [(('q'), ('python')), (('hl'), ('en'))]
self.assertEqual(sorted(url.encodedQueryItems()), sorted(valid_data))
def testSetQueryItems(self):
#QUrl.setQueryItems
urla = QUrl('http://www.google.com/search?q=python&hl=en')
urlb = QUrl('http://www.google.com/search')
urlb.setQueryItems(urla.queryItems())
self.assertEqual(urla, urlb)
def testAddQueryItem(self):
#QUrl.addQueryItem
url = QUrl()
valid_data = [('hl', 'en'), ('user', 'konqui')]
url.addQueryItem(*valid_data[0])
self.assertEqual(url.queryItems()[0], valid_data[0])
url.addQueryItem(*valid_data[1])
self.assertEqual(sorted(url.queryItems()), sorted(valid_data))
def testAllEncodedQueryItemsValues(self):
#QUrl.allEncodedQueryItemValues
url = QUrl()
key = 'key'
valid_data = ['data', 'valid', 'test']
for i, data in enumerate(valid_data):
url.addQueryItem(key, data)
self.assertEqual(url.allEncodedQueryItemValues(key),
list(valid_data[:i+1]))
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,115 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Test cases for QVariant'''
import unittest
import sys
from PySide.QtCore import QSize, QVariant, QByteArray, QStringList
class Dummy(object):
pass
class MySize(QSize):
pass
class QVariantToNumber(unittest.TestCase):
def testToNumberInt(self):
obj = QVariant('37')
self.assertEqual(37, obj.toInt()[0])
def testToNumberFloat(self):
obj = QVariant('37.109')
self.assertEqual(37.109, obj.toDouble()[0])
class QVariantTypeName(unittest.TestCase):
def testTypeNameQString(self):
#QVariant.typeName()
obj = QVariant('aaaa')
self.assertEqual('QString', obj.typeName())
def testTypeNameInt(self):
obj = QVariant(34)
self.assertEqual('int', obj.typeName())
def testTypeNameDouble(self):
obj = QVariant(3.14)
self.assertEqual('double', obj.typeName())
def testTypeNameBool(self):
obj = QVariant(True)
self.assertEqual('bool', obj.typeName())
def testTypeNameQByteArray(self):
obj = QVariant(QByteArray('aaaa'))
self.assertEqual('QByteArray', obj.typeName())
def testTypeNameNone(self):
obj = QVariant()
self.assertEqual(None, obj.typeName())
def testTypeNameQVariantList(self):
obj = QVariant([1,Dummy(),3,4])
self.assertEqual('QVariantList', obj.typeName())
def testTypeNameQStringList(self):
obj = QVariant(QStringList())
self.assertEqual('QStringList', obj.typeName())
def testTypeNamePythonClasses(self):
## QVariant of python classes
d = Dummy()
obj = QVariant(d)
self.assertEqual('PyQt_PyObject', obj.typeName())
# This works only on PyQt4 4.5.x, not on PyQt4 4.4.x or PySide
def testSubClassConvertion(self):
mysize = MySize(0, 0)
variant = QVariant(mysize)
assert(variant.type() != QVariant.Size)
assert(variant.toPyObject() is mysize)
class QVariantConstructor(unittest.TestCase):
def testCopyConstructor(self):
obj = QVariant(1)
cpy = QVariant(obj)
self.assertEqual(obj.type(), cpy.type())
def testQStringConstructor(self):
obj = QVariant("PySide")
self.assertEqual(obj.type(), QVariant.String)
class QVariantToPyObject(unittest.TestCase):
def testQVariantPyList(self):
obj = QVariant([1, 'two', 3])
self.assertEqual(obj.toPyObject(), [1, 'two', 3])
def testPyObject(self):
d = Dummy()
obj = QVariant(d)
self.assertEqual(d, obj.toPyObject())
def atestNoneToPyObject(self):
# XXX Do not run by default because segfaults with PyQt4
obj = QVariant()
self.assertEqual(None, obj.toPyObject())
def testQStringToPyObject(self):
d = 'abc'
obj = QVariant('abc')
self.assertEqual(d, obj.toPyObject())
class QVartiantTypeTest(unittest.TestCase):
def testQSize(self):
class MySize(QSize):
pass
mysize = MySize(5, 5)
variant = QVariant(mysize)
self.assert_(variant.type() != QVariant.Size)
self.assert_(variant.toPyObject() is mysize)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,6 @@
<RCC>
<qresource prefix="/">
<file alias="quote.txt">quoteEnUS.txt</file>
</qresource>
</RCC>

View file

@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: Thu Mar 26 11:08:45 2009
# by: The Resource Compiler for PyQt (Qt v4.5.0)
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore
qt_resource_data = "\
\x00\x00\x00\x35\
\x46\
\x69\x6e\x65\x21\x20\x44\x69\x73\x68\x6f\x6e\x6f\x72\x21\x20\x44\
\x69\x73\x68\x6f\x6e\x6f\x72\x20\x6f\x6e\x20\x79\x6f\x75\x2c\x20\
\x64\x69\x73\x68\x6f\x6e\x6f\x72\x20\x6f\x6e\x20\x79\x61\x20\x63\
\x6f\x77\x21\x0a\
"
qt_resource_name = "\
\x00\x09\
\x06\xa8\xaa\x74\
\x00\x71\
\x00\x75\x00\x6f\x00\x74\x00\x65\x00\x2e\x00\x74\x00\x78\x00\x74\
"
qt_resource_struct = "\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()

Binary file not shown.

View file

@ -0,0 +1,18 @@
#!/usr/bin/python
'''Tests for static methos conflicts with class methods'''
import unittest
from PySide import QtCore
class static_function_test(unittest.TestCase):
def testMemberQFileExists(self):
f = QtCore.QFile("/tmp/foo.txt")
self.assertEqual(f.exists(), False)
def testStatocQFileExists(self):
self.assertEqual(QtCore.QFile.fileExists("/tmp/foo.txt"), False)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,30 @@
#!/usr/bin/python
'''Unit tests for static protected methods'''
import unittest, time
from PySide.QtCore import QThread
class Test (QThread):
def run(self):
start = time.time()
self.sleep(1)
self.time_elapsed = time.time() - start
class QStaticProtectedCall(unittest.TestCase):
'''Test case for static protected method call'''
def setUp(self):
pass
def tearDown(self):
pass
def testPathSeparator(self):
thread = Test()
thread.start()
thread.wait()
self.assertTrue(thread.time_elapsed <= 1.1) # tolarance of 100ms
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,39 @@
''' Test case for QObject.signalsBlocked() and blockSignal()'''
import unittest
import os
from tempfile import mkstemp
from PySide.QtCore import QObject, SIGNAL, QFile, QThread, QTimer
from helper import UsesQCoreApplication
class MyThread(QThread):
def run(self):
self.emit(SIGNAL("test(const QString&)"),
"INdT - PySide");
class TestThreadSignal(UsesQCoreApplication):
__called__ = True
def _callback(self, msg):
self.assertEqual(msg, "INdT - PySide")
self.__called__ = True
self._quit()
def _quit(self):
self.app.quit()
def testThread(self):
t = MyThread()
QObject.connect(t, SIGNAL("test(const QString&)"),
self._callback);
t.start()
QTimer.singleShot(100, self._quit)
self.app.exec_()
self.assert_(self.__called__);
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,48 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Unit tests to test QTranslator and translation in general.'''
import os
import unittest
from PySide.QtCore import QObject, QTranslator, QCoreApplication
from helper import UsesQCoreApplication
class TranslationTest(UsesQCoreApplication):
'''Test case for Qt translation facilities.'''
def setUp(self):
super(TranslationTest, self).setUp()
self.trdir = os.path.join(os.path.dirname(__file__), 'translations')
# os.system is probably not the best way to do it
os.system('lrelease %s/*.ts > /dev/null' % self.trdir)
def tearDown(self):
os.system('rm %s/*.qm > /dev/null' % self.trdir)
super(TranslationTest, self).tearDown()
def testLatin(self):
#Set string value to Latin
translator = QTranslator()
translator.load(os.path.join(self.trdir, 'trans_latin.qm'))
self.app.installTranslator(translator)
obj = QObject()
obj.setObjectName(obj.tr('Hello World!'))
self.assertEqual(obj.objectName(), u'Orbis, te saluto!')
def testRussian(self):
#Set string value to Russian
translator = QTranslator()
translator.load(os.path.join(self.trdir, 'trans_russian.qm'))
self.app.installTranslator(translator)
obj = QObject()
obj.setObjectName(obj.tr('Hello World!'))
self.assertEqual(obj.objectName(), u'привет мир!')
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS><TS version="1.1" language="lt">
<defaultcodec></defaultcodec>
<context>
<name>QObject</name>
<message>
<source>Hello World!</source>
<translation>Orbis, te saluto!</translation>
</message>
</context>
</TS>

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS><TS version="1.1" language="ru">
<defaultcodec></defaultcodec>
<context>
<name>QObject</name>
<message>
<source>Hello World!</source>
<translation>привет мир!</translation>
</message>
</context>
</TS>

View file

@ -0,0 +1,38 @@
#!/usr/bin/python
'''Tests the presence of unary operator __neg__ on the QPoint class'''
import unittest
from PySide.QtCore import QPoint
class NegUnaryOperatorTest(unittest.TestCase):
'''Tests the presence of unary operator __neg__ on the QPoint class'''
def setUp(self):
#Acquire resources
self.x, self.y = 10, 20
self.neg_x, self.neg_y = -self.x, -self.y
self.qpoint = QPoint(self.x, self.y)
def tearDown(self):
#Release resources
del self.qpoint
del self.x
del self.y
del self.neg_x
del self.neg_y
def testNegUnaryOperator(self):
#Test __neg__ unary operator on QPoint class
__neg__method_exists = True
try:
neg_qpoint = -self.qpoint
except:
__neg__method_exists = False
self.assertTrue(__neg__method_exists)
self.assertEqual(self.qpoint, -neg_qpoint)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,33 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''Unit tests for QString conversion to/from Python Unicode'''
import unittest
from PySide.QtCore import QObject
class UnicodeConversion(unittest.TestCase):
'''Test case for QString to/from Python Unicode conversion'''
def setUp(self):
pass
def tearDown(self):
pass
def testSetRegularStringRetrieveUnicode(self):
#Set regular Python string retrieve unicode
obj = QObject()
obj.setObjectName('test')
self.assertEqual(obj.objectName(), u'test')
def testSetUnicodeRetrieveUnicode(self):
#Set Python unicode string and retrieve unicode
obj = QObject()
obj.setObjectName(u'ümlaut')
self.assertEqual(obj.objectName(), u'ümlaut')
if __name__ == '__main__':
unittest.main()