From ab918abc1e103e0ca86939f7d057e8a44ac8a4ef Mon Sep 17 00:00:00 2001 From: Renato Filho Date: Mon, 7 Jun 2010 14:43:45 -0300 Subject: Created new unittest model. Separete unittest for module. Only run unittest for compiled modules. Reviewer: Marcelo Lira , Luciano Wolf --- tests/QtCore/CMakeLists.txt | 71 +++++ tests/QtCore/blocking_signals_test.py | 107 +++++++ tests/QtCore/buffer_test.py | 13 + tests/QtCore/child_event_test.py | 55 ++++ tests/QtCore/deletelater_test.py | 22 ++ tests/QtCore/duck_punching_test.py | 56 ++++ tests/QtCore/missing_symbols_test.py | 16 + tests/QtCore/qabs_test.py | 20 ++ tests/QtCore/qabstracttransition_test.py | 156 ++++++++++ tests/QtCore/qanimationgroup_test.py | 24 ++ tests/QtCore/qbitarray_test.py | 119 ++++++++ tests/QtCore/qbytearray_buffer_protocol_test.py | 20 ++ .../qbytearray_concatenation_operator_test.py | 46 +++ tests/QtCore/qbytearray_operator_iadd_test.py | 73 +++++ tests/QtCore/qbytearray_operator_test.py | 82 +++++ tests/QtCore/qbytearray_test.py | 98 ++++++ tests/QtCore/qchar_test.py | 59 ++++ tests/QtCore/qcoreapplication_instance_test.py | 20 ++ tests/QtCore/qdatastream_test.py | 330 +++++++++++++++++++++ tests/QtCore/qdate_test.py | 28 ++ tests/QtCore/qenum_test.py | 45 +++ tests/QtCore/qevent_test.py | 24 ++ tests/QtCore/qfile_test.py | 31 ++ tests/QtCore/qfileinfo_test.py | 17 ++ tests/QtCore/qflags_test.py | 56 ++++ tests/QtCore/qhandle_test.py | 16 + tests/QtCore/qlatin1string_test.py | 21 ++ tests/QtCore/qlinef_test.py | 20 ++ tests/QtCore/qlocale_test.py | 40 +++ tests/QtCore/qmetaobject_test.py | 51 ++++ tests/QtCore/qmodelindex_internalpointer_test.py | 50 ++++ tests/QtCore/qobject_children_segfault_test.py | 29 ++ tests/QtCore/qobject_connect_notify_test.py | 70 +++++ tests/QtCore/qobject_event_filter_test.py | 80 +++++ tests/QtCore/qobject_inherits_test.py | 43 +++ tests/QtCore/qobject_parent_test.py | 234 +++++++++++++++ tests/QtCore/qobject_property_test.py | 71 +++++ tests/QtCore/qobject_protected_methods_test.py | 38 +++ tests/QtCore/qobject_test.py | 43 +++ tests/QtCore/qobject_timer_event_test.py | 44 +++ tests/QtCore/qobject_tr_as_instance_test.py | 55 ++++ tests/QtCore/qpoint_test.py | 21 ++ tests/QtCore/qprocess_test.py | 16 + tests/QtCore/qrect_test.py | 102 +++++++ tests/QtCore/qresource_test.py | 31 ++ tests/QtCore/qsize_test.py | 26 ++ tests/QtCore/qslot_object_test.py | 47 +++ tests/QtCore/qsrand_test.py | 16 + tests/QtCore/qstate_test.py | 35 +++ tests/QtCore/qstatemachine_test.py | 68 +++++ tests/QtCore/qstring_buffer_protocol_test.py | 20 ++ tests/QtCore/qstring_operator_test.py | 161 ++++++++++ tests/QtCore/qstring_test.py | 192 ++++++++++++ tests/QtCore/qstringlist_test.py | 171 +++++++++++ tests/QtCore/qtext_codec_test.py | 20 ++ tests/QtCore/qtextstream_test.py | 95 ++++++ tests/QtCore/qthread_prod_cons_test.py | 107 +++++++ tests/QtCore/qthread_signal_test.py | 64 ++++ tests/QtCore/qthread_test.py | 76 +++++ tests/QtCore/qtimer_singleshot_test.py | 49 +++ tests/QtCore/qtimer_timeout_test.py | 57 ++++ tests/QtCore/qtnamespace_test.py | 19 ++ tests/QtCore/quoteEnUS.txt | 1 + tests/QtCore/qurl_test.py | 91 ++++++ tests/QtCore/qvariant_pyobject_test.py | 71 +++++ tests/QtCore/qvariant_test.py | 141 +++++++++ tests/QtCore/resources.qrc | 6 + tests/QtCore/resources_mc.py | 39 +++ tests/QtCore/static_method_test.py | 55 ++++ tests/QtCore/static_protected_methods_test.py | 30 ++ tests/QtCore/thread_signals.py | 33 +++ tests/QtCore/translation_test.py | 62 ++++ tests/QtCore/translations/trans_latin.ts | 11 + tests/QtCore/translations/trans_russian.ts | 11 + tests/QtCore/unaryoperator_test.py | 38 +++ tests/QtCore/unicode_test.py | 33 +++ 76 files changed, 4508 insertions(+) create mode 100644 tests/QtCore/CMakeLists.txt create mode 100644 tests/QtCore/blocking_signals_test.py create mode 100644 tests/QtCore/buffer_test.py create mode 100644 tests/QtCore/child_event_test.py create mode 100644 tests/QtCore/deletelater_test.py create mode 100644 tests/QtCore/duck_punching_test.py create mode 100644 tests/QtCore/missing_symbols_test.py create mode 100644 tests/QtCore/qabs_test.py create mode 100644 tests/QtCore/qabstracttransition_test.py create mode 100644 tests/QtCore/qanimationgroup_test.py create mode 100755 tests/QtCore/qbitarray_test.py create mode 100755 tests/QtCore/qbytearray_buffer_protocol_test.py create mode 100755 tests/QtCore/qbytearray_concatenation_operator_test.py create mode 100644 tests/QtCore/qbytearray_operator_iadd_test.py create mode 100644 tests/QtCore/qbytearray_operator_test.py create mode 100644 tests/QtCore/qbytearray_test.py create mode 100644 tests/QtCore/qchar_test.py create mode 100755 tests/QtCore/qcoreapplication_instance_test.py create mode 100644 tests/QtCore/qdatastream_test.py create mode 100644 tests/QtCore/qdate_test.py create mode 100644 tests/QtCore/qenum_test.py create mode 100644 tests/QtCore/qevent_test.py create mode 100644 tests/QtCore/qfile_test.py create mode 100644 tests/QtCore/qfileinfo_test.py create mode 100644 tests/QtCore/qflags_test.py create mode 100644 tests/QtCore/qhandle_test.py create mode 100644 tests/QtCore/qlatin1string_test.py create mode 100644 tests/QtCore/qlinef_test.py create mode 100644 tests/QtCore/qlocale_test.py create mode 100644 tests/QtCore/qmetaobject_test.py create mode 100644 tests/QtCore/qmodelindex_internalpointer_test.py create mode 100644 tests/QtCore/qobject_children_segfault_test.py create mode 100644 tests/QtCore/qobject_connect_notify_test.py create mode 100644 tests/QtCore/qobject_event_filter_test.py create mode 100644 tests/QtCore/qobject_inherits_test.py create mode 100644 tests/QtCore/qobject_parent_test.py create mode 100644 tests/QtCore/qobject_property_test.py create mode 100644 tests/QtCore/qobject_protected_methods_test.py create mode 100644 tests/QtCore/qobject_test.py create mode 100644 tests/QtCore/qobject_timer_event_test.py create mode 100644 tests/QtCore/qobject_tr_as_instance_test.py create mode 100644 tests/QtCore/qpoint_test.py create mode 100644 tests/QtCore/qprocess_test.py create mode 100644 tests/QtCore/qrect_test.py create mode 100644 tests/QtCore/qresource_test.py create mode 100644 tests/QtCore/qsize_test.py create mode 100644 tests/QtCore/qslot_object_test.py create mode 100644 tests/QtCore/qsrand_test.py create mode 100644 tests/QtCore/qstate_test.py create mode 100644 tests/QtCore/qstatemachine_test.py create mode 100755 tests/QtCore/qstring_buffer_protocol_test.py create mode 100644 tests/QtCore/qstring_operator_test.py create mode 100644 tests/QtCore/qstring_test.py create mode 100644 tests/QtCore/qstringlist_test.py create mode 100644 tests/QtCore/qtext_codec_test.py create mode 100644 tests/QtCore/qtextstream_test.py create mode 100644 tests/QtCore/qthread_prod_cons_test.py create mode 100755 tests/QtCore/qthread_signal_test.py create mode 100644 tests/QtCore/qthread_test.py create mode 100644 tests/QtCore/qtimer_singleshot_test.py create mode 100644 tests/QtCore/qtimer_timeout_test.py create mode 100644 tests/QtCore/qtnamespace_test.py create mode 100644 tests/QtCore/quoteEnUS.txt create mode 100644 tests/QtCore/qurl_test.py create mode 100644 tests/QtCore/qvariant_pyobject_test.py create mode 100644 tests/QtCore/qvariant_test.py create mode 100644 tests/QtCore/resources.qrc create mode 100644 tests/QtCore/resources_mc.py create mode 100755 tests/QtCore/static_method_test.py create mode 100644 tests/QtCore/static_protected_methods_test.py create mode 100644 tests/QtCore/thread_signals.py create mode 100644 tests/QtCore/translation_test.py create mode 100644 tests/QtCore/translations/trans_latin.ts create mode 100644 tests/QtCore/translations/trans_russian.ts create mode 100755 tests/QtCore/unaryoperator_test.py create mode 100644 tests/QtCore/unicode_test.py (limited to 'tests/QtCore') diff --git a/tests/QtCore/CMakeLists.txt b/tests/QtCore/CMakeLists.txt new file mode 100644 index 000000000..536d40861 --- /dev/null +++ b/tests/QtCore/CMakeLists.txt @@ -0,0 +1,71 @@ +PYSIDE_TEST(blocking_signals_test.py) +PYSIDE_TEST(buffer_test.py) +PYSIDE_TEST(child_event_test.py) +PYSIDE_TEST(deletelater_test.py) +PYSIDE_TEST(duck_punching_test.py) +PYSIDE_TEST(missing_symbols_test.py) +PYSIDE_TEST(qabs_test.py) +PYSIDE_TEST(qabstracttransition_test.py) +PYSIDE_TEST(qanimationgroup_test.py) +PYSIDE_TEST(qbitarray_test.py) +PYSIDE_TEST(qbytearray_buffer_protocol_test.py) +PYSIDE_TEST(qbytearray_concatenation_operator_test.py) +PYSIDE_TEST(qbytearray_operator_iadd_test.py) +PYSIDE_TEST(qbytearray_operator_test.py) +PYSIDE_TEST(qbytearray_test.py) +PYSIDE_TEST(qchar_test.py) +PYSIDE_TEST(qcoreapplication_instance_test.py) +PYSIDE_TEST(qdatastream_test.py) +PYSIDE_TEST(qdate_test.py) +PYSIDE_TEST(qenum_test.py) +PYSIDE_TEST(qevent_test.py) +PYSIDE_TEST(qfileinfo_test.py) +PYSIDE_TEST(qfile_test.py) +PYSIDE_TEST(qflags_test.py) +PYSIDE_TEST(qhandle_test.py) +PYSIDE_TEST(qlatin1string_test.py) +PYSIDE_TEST(qlinef_test.py) +PYSIDE_TEST(qlocale_test.py) +PYSIDE_TEST(qmetaobject_test.py) +PYSIDE_TEST(qmodelindex_internalpointer_test.py) +PYSIDE_TEST(qobject_children_segfault_test.py) +PYSIDE_TEST(qobject_connect_notify_test.py) +PYSIDE_TEST(qobject_event_filter_test.py) +PYSIDE_TEST(qobject_inherits_test.py) +PYSIDE_TEST(qobject_parent_test.py) +PYSIDE_TEST(qobject_property_test.py) +PYSIDE_TEST(qobject_protected_methods_test.py) +PYSIDE_TEST(qobject_test.py) +PYSIDE_TEST(qobject_timer_event_test.py) +PYSIDE_TEST(qobject_tr_as_instance_test.py) +PYSIDE_TEST(qpoint_test.py) +PYSIDE_TEST(qprocess_test.py) +PYSIDE_TEST(qrect_test.py) +PYSIDE_TEST(qresource_test.py) +PYSIDE_TEST(qsize_test.py) +PYSIDE_TEST(qslot_object_test.py) +PYSIDE_TEST(qsrand_test.py) +PYSIDE_TEST(qstatemachine_test.py) +PYSIDE_TEST(qstate_test.py) +PYSIDE_TEST(qstring_buffer_protocol_test.py) +PYSIDE_TEST(qstringlist_test.py) +PYSIDE_TEST(qstring_operator_test.py) +PYSIDE_TEST(qstring_test.py) +PYSIDE_TEST(qtext_codec_test.py) +PYSIDE_TEST(qtextstream_test.py) +PYSIDE_TEST(qthread_prod_cons_test.py) +PYSIDE_TEST(qthread_signal_test.py) +PYSIDE_TEST(qthread_test.py) +PYSIDE_TEST(qtimer_singleshot_test.py) +PYSIDE_TEST(qtimer_timeout_test.py) +PYSIDE_TEST(qtnamespace_test.py) +PYSIDE_TEST(qurl_test.py) +PYSIDE_TEST(qvariant_pyobject_test.py) +PYSIDE_TEST(qvariant_test.py) +PYSIDE_TEST(resources_mc.py) +PYSIDE_TEST(static_method_test.py) +PYSIDE_TEST(static_protected_methods_test.py) +PYSIDE_TEST(thread_signals.py) +PYSIDE_TEST(translation_test.py) +PYSIDE_TEST(unaryoperator_test.py) +PYSIDE_TEST(unicode_test.py) diff --git a/tests/QtCore/blocking_signals_test.py b/tests/QtCore/blocking_signals_test.py new file mode 100644 index 000000000..96582f6cc --- /dev/null +++ b/tests/QtCore/blocking_signals_test.py @@ -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() diff --git a/tests/QtCore/buffer_test.py b/tests/QtCore/buffer_test.py new file mode 100644 index 000000000..2917232a1 --- /dev/null +++ b/tests/QtCore/buffer_test.py @@ -0,0 +1,13 @@ +#!/usr/bin/python + +import unittest +from PySide.QtCore import QString + +class BufferTest(unittest.TestCase): + def testQByteArray(self): + data = buffer("PySide") + str = QString(data) + self.assertEqual(data, str) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/child_event_test.py b/tests/QtCore/child_event_test.py new file mode 100644 index 000000000..ccc27c848 --- /dev/null +++ b/tests/QtCore/child_event_test.py @@ -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() + diff --git a/tests/QtCore/deletelater_test.py b/tests/QtCore/deletelater_test.py new file mode 100644 index 000000000..3b2f7d9e3 --- /dev/null +++ b/tests/QtCore/deletelater_test.py @@ -0,0 +1,22 @@ +#!/usr/bin/python + +'''Test cases for QTimer.singleShot''' + +import unittest + +from PySide.QtCore import QObject, QTimer, QCoreApplication, SIGNAL +from helper import UsesQCoreApplication + +class TestDeleteLater(UsesQCoreApplication): + '''Test case for function DeleteLater''' + + def testCase(self): + o = QObject() + o.deleteLater() + del o + QTimer.singleShot(100, self.app.quit) + self.app.exec_() + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/duck_punching_test.py b/tests/QtCore/duck_punching_test.py new file mode 100644 index 000000000..e20c0c1b1 --- /dev/null +++ b/tests/QtCore/duck_punching_test.py @@ -0,0 +1,56 @@ +#!/usr/bin/python + +'''Test case for duck punching new implementations of C++ virtual methods into object instances.''' + +import unittest +import types +from PySide.QtCore import QObject, QEvent +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 punching 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.childEvent = types.MethodType(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.childEvent = types.MethodType(childEvent, parent, QObject) + child = QObject() + child.setParent(parent) + self.assert_(self.duck_childEvent_called) + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/missing_symbols_test.py b/tests/QtCore/missing_symbols_test.py new file mode 100644 index 000000000..f535c53d3 --- /dev/null +++ b/tests/QtCore/missing_symbols_test.py @@ -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() diff --git a/tests/QtCore/qabs_test.py b/tests/QtCore/qabs_test.py new file mode 100644 index 000000000..1727ae6d5 --- /dev/null +++ b/tests/QtCore/qabs_test.py @@ -0,0 +1,20 @@ + +import unittest + +from PySide import QtCore + + +class QAbsTest(unittest.TestCase): + '''Tests for QtCore.qAbs''' + + def testBasic(self): + def check(x): + self.assertEqual(QtCore.qAbs(x), abs(x)) + + check(0) + check(-10) + check(10) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qabstracttransition_test.py b/tests/QtCore/qabstracttransition_test.py new file mode 100644 index 000000000..510b8ef64 --- /dev/null +++ b/tests/QtCore/qabstracttransition_test.py @@ -0,0 +1,156 @@ +#!/usr/bin/python +import unittest +from sys import getrefcount +from PySide.QtCore import QObject, SIGNAL, QCoreApplication, QTimer, QVariant +from PySide.QtCore import QState, QFinalState, QStateMachine, QParallelAnimationGroup, QEventTransition + +def addStates(transition): + sx = QState() + sy = QState() + transition.setTargetStates([sx, sy]) + +def addAnimation(transition): + animation = QParallelAnimationGroup() + transition.addAnimation(animation) + +class QAbstractTransitionTest(unittest.TestCase): + + def testBasic(self): + app = QCoreApplication([]) + + o = QObject() + o.setProperty("text", QVariant("INdT")) + + machine = QStateMachine() + s1 = QState() + s1.assignProperty(o, "text", QVariant("Rocks")) + + s2 = QFinalState() + t = s1.addTransition(o, SIGNAL("change()"), s2) + + self.assertEqual(t.targetStates(), [s2]) + + addStates(t) + self.assertEqual(len(t.targetStates()), 2) + + animation = QParallelAnimationGroup() + t.addAnimation(animation) + + self.assertEqual(t.animations(), [animation]) + + addAnimation(t) + self.assertEqual(t.animations()[0].parent(), None) + + machine.addState(s1) + machine.addState(s2) + machine.setInitialState(s1) + machine.start() + + QTimer.singleShot(100, app.quit) + app.exec_() + + def testRefCountOfTargetState(self): + transition = QEventTransition() + state1 = QState() + refcount1 = getrefcount(state1) + + transition.setTargetState(state1) + + self.assertEqual(transition.targetState(), state1) + self.assertEqual(getrefcount(transition.targetState()), refcount1 + 1) + + state2 = QState() + refcount2 = getrefcount(state2) + + transition.setTargetState(state2) + + self.assertEqual(transition.targetState(), state2) + self.assertEqual(getrefcount(transition.targetState()), refcount2 + 1) + self.assertEqual(getrefcount(state1), refcount1) + + del transition + + self.assertEqual(getrefcount(state2), refcount2) + + def testRefCountOfTargetStates(self): + transition = QEventTransition() + state1 = QState() + state2 = QState() + states = [state1, state2] + refcount1 = getrefcount(state1) + refcount2 = getrefcount(state2) + + transition.setTargetStates(states) + + self.assertEqual(transition.targetStates(), states) + self.assertEqual(transition.targetState(), state1) + self.assertEqual(getrefcount(transition.targetStates()[0]), refcount1 + 1) + self.assertEqual(getrefcount(transition.targetStates()[1]), refcount2 + 1) + + del states + del transition + + self.assertEqual(getrefcount(state1), refcount1) + self.assertEqual(getrefcount(state2), refcount2) + + def testRefCountOfTargetStatesAfterSingleTargetState(self): + transition = QEventTransition() + state0 = QState() + refcount0 = getrefcount(state0) + + transition.setTargetState(state0) + + self.assertEqual(transition.targetState(), state0) + self.assertEqual(getrefcount(transition.targetState()), refcount0 + 1) + + state1 = QState() + state2 = QState() + states = [state1, state2] + refcount1 = getrefcount(state1) + refcount2 = getrefcount(state2) + + transition.setTargetStates(states) + + self.assertEqual(getrefcount(state0), refcount0) + self.assertEqual(transition.targetStates(), states) + self.assertEqual(transition.targetState(), state1) + self.assertEqual(getrefcount(transition.targetStates()[0]), refcount1 + 1) + self.assertEqual(getrefcount(transition.targetStates()[1]), refcount2 + 1) + + del states + del transition + + self.assertEqual(getrefcount(state1), refcount1) + self.assertEqual(getrefcount(state2), refcount2) + + def testRefCountOfTargetStatesBeforeSingleTargetState(self): + transition = QEventTransition() + state1 = QState() + state2 = QState() + states = [state1, state2] + refcount1 = getrefcount(state1) + refcount2 = getrefcount(state2) + + transition.setTargetStates(states) + + self.assertEqual(transition.targetStates(), states) + self.assertEqual(transition.targetState(), state1) + self.assertEqual(getrefcount(transition.targetStates()[0]), refcount1 + 1) + self.assertEqual(getrefcount(transition.targetStates()[1]), refcount2 + 1) + + state3 = QState() + refcount3 = getrefcount(state3) + + transition.setTargetState(state3) + + self.assertEqual(transition.targetState(), state3) + self.assertEqual(getrefcount(transition.targetState()), refcount3 + 1) + + del states + + self.assertEqual(getrefcount(state1), refcount1) + self.assertEqual(getrefcount(state2), refcount2) + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/qanimationgroup_test.py b/tests/QtCore/qanimationgroup_test.py new file mode 100644 index 000000000..05bd81e10 --- /dev/null +++ b/tests/QtCore/qanimationgroup_test.py @@ -0,0 +1,24 @@ +#!/usr/bin/python +import unittest +from PySide.QtCore import QObject, QState, QFinalState, SIGNAL, QCoreApplication, QTimer, QStateMachine, QSignalTransition, QVariant, QParallelAnimationGroup, QSequentialAnimationGroup, QAnimationGroup + +class QAnimationGroupTest(unittest.TestCase): + + def testBasic(self): + app = QCoreApplication([]) + + panim = QParallelAnimationGroup() + sanim = QSequentialAnimationGroup() + panim.addAnimation(sanim) + + self.assertEqual(sanim.parent(), panim) + + panim.clear() + + self.assertRaises(RuntimeError, lambda :sanim.parent()) + + QTimer.singleShot(100, app.quit) + app.exec_() + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qbitarray_test.py b/tests/QtCore/qbitarray_test.py new file mode 100755 index 000000000..0ae6e1d2f --- /dev/null +++ b/tests/QtCore/qbitarray_test.py @@ -0,0 +1,119 @@ +#!/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) + + +class QBitArrayGetItemTest(unittest.TestCase): + '''Test case for []/__getitem__ operator''' + + def create_bitarray(self, values): + '''helper function to create a bit array''' + obj = QBitArray(len(values)) + for i, value in enumerate(values): + obj.setBit(i, value) + return obj + + def testSequenceProtocol(self): + '''QBitArray sequence protocol''' + data = [True, False, True] + obj = self.create_bitarray(data) + for reference, value in zip(data, obj): + self.assertEqual(reference, value) + + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/qbytearray_buffer_protocol_test.py b/tests/QtCore/qbytearray_buffer_protocol_test.py new file mode 100755 index 000000000..117e50b93 --- /dev/null +++ b/tests/QtCore/qbytearray_buffer_protocol_test.py @@ -0,0 +1,20 @@ +#!/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 + isdir(QByteArray('/tmp')) + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/qbytearray_concatenation_operator_test.py b/tests/QtCore/qbytearray_concatenation_operator_test.py new file mode 100755 index 000000000..b9a01ff63 --- /dev/null +++ b/tests/QtCore/qbytearray_concatenation_operator_test.py @@ -0,0 +1,46 @@ +#!/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 + qba = QByteArray('foo') + result = qba + 'bar' + self.assert_(isinstance(result, QByteArray)) + self.assertEqual(result, 'foobar') + # 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 = 'bar' + qba + self.assert_(isinstance(result, QByteArray)) + self.assertEqual(result, 'barfoo') + + # NOTICE: Does not makes sense concat a unicode string with a QByteArray, because the + # user does not know nothing about the internal representation of the unicode string. + #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() + diff --git a/tests/QtCore/qbytearray_operator_iadd_test.py b/tests/QtCore/qbytearray_operator_iadd_test.py new file mode 100644 index 000000000..168f22de9 --- /dev/null +++ b/tests/QtCore/qbytearray_operator_iadd_test.py @@ -0,0 +1,73 @@ + +import unittest +import new + +from PySide.QtCore import QByteArray, QString +from helper.docmodifier import DocModifier + +class BaseQByteArrayOperatorIAdd(object): + '''Base class for QByteArray += operator tests. + + Implementing classes should inherit from unittest.TestCase and implement + setUp, setting self.obj and self.orig_obj to the target QByteArray and original + one, respectively''' + + __metaclass__ = DocModifier + + def testSingleString(self): + '''QByteArray += string of size 1''' + s = '0' + self.obj += s + self.assertEqual(self.obj, self.orig_obj + s) + self.assertEqual(self.obj.size(), self.orig_obj.size() + len(s)) + + def testString(self): + '''QByteArray += string of size > 1''' + s = 'dummy' + self.obj += s + self.assertEqual(self.obj, self.orig_obj + s) + self.assertEqual(self.obj.size(), self.orig_obj.size() + len(s)) + + def testQByteArray(self): + '''QByteArray += QByteArray''' + s = QByteArray('array') + self.obj += s + self.assertEqual(self.obj, self.orig_obj + s) + + def testChar(self): + '''QByteArray += char (number < 256)''' + s = ord('a') + self.obj += s + self.assertEqual(self.obj, self.orig_obj + s) + self.assertEqual(self.obj.size(), self.orig_obj.size() + 1) + + def testQString(self): + '''QByteArray += QString''' + s = QString('dummy') + self.obj += s + self.assertEqual(self.obj, self.orig_obj + s) + self.assertEqual(self.obj.size(), self.orig_obj.size() + s.size()) + +class NullQByteArrayOperatorIAdd(unittest.TestCase, BaseQByteArrayOperatorIAdd): + '''Test case for operator QByteArray += on null QByteArrays''' + + doc_prefix = 'Null object' + doc_filter = lambda x: x.startswith('test') + + def setUp(self): + self.obj = QByteArray() + self.orig_obj = QByteArray() + + +class ValidQByteArrayOperatorIAdd(unittest.TestCase, BaseQByteArrayOperatorIAdd): + '''Test case for operator QByteArray += on valid QByteArrays''' + + doc_prefix = 'Valid object' + doc_filter = lambda x: x.startswith('test') + + def setUp(self): + self.obj = QByteArray('some byte array') + self.orig_obj = QByteArray('some byte array') + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qbytearray_operator_test.py b/tests/QtCore/qbytearray_operator_test.py new file mode 100644 index 000000000..4a20c04c5 --- /dev/null +++ b/tests/QtCore/qbytearray_operator_test.py @@ -0,0 +1,82 @@ +#!/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)]) + + +class QByteArrayOperatorLen(unittest.TestCase): + '''Test case for __len__ operator of QByteArray''' + + def testBasic(self): + '''QByteArray __len__''' + self.assertEqual(len(QByteArray()), 0) + self.assertEqual(len(QByteArray('')), 0) + self.assertEqual(len(QByteArray(' ')), 1) + self.assertEqual(len(QByteArray('yabadaba')), 8) + + +class QByteArrayOperatorStr(unittest.TestCase): + '''Test case for __str__ operator of QByteArray''' + + def testBasic(self): + '''QByteArray __str__''' + self.assertEqual(QByteArray().__str__(), '') + self.assertEqual(QByteArray('').__str__(), '') + self.assertEqual(QByteArray('aaa').__str__(), 'aaa') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qbytearray_test.py b/tests/QtCore/qbytearray_test.py new file mode 100644 index 000000000..20bba1400 --- /dev/null +++ b/tests/QtCore/qbytearray_test.py @@ -0,0 +1,98 @@ +#!/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, True), obj.toInt()) + + def testToNumberUShort(self): + obj = QByteArray('37') + self.assertEqual((37, True), obj.toUShort()) + + def testToNumberFloat(self): + obj = QByteArray('37.109') + self.assertEqual((ctypes.c_float(37.109).value, True), + obj.toFloat()) + + def testToNumberDouble(self): + obj = QByteArray('37.109') + self.assertEqual((ctypes.c_double(37.109).value, True), + obj.toDouble()) + +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/") + +class QByteArrayOperatorAtSetter(unittest.TestCase): + '''Test case for operator QByteArray[] - __setitem__''' + + def testSetterString(self): + '''QByteArray[x] = pythonstring''' + obj = QByteArray('123456') + obj[1] = '0' + self.assertEqual(obj, QByteArray('103456')) + + def testSetterStringLarge(self): + '''QByteArray[x] = pythonstring (larget than 1 char)''' + obj = QByteArray('123456') + obj[3] = 'abba' + self.assertEqual(obj, QByteArray('123abba56')) + + def testSetterQByteArray(self): + '''QByteArray[x] = qbytearray''' + obj = QByteArray('123456') + obj[3] = QByteArray('array') + self.assertEqual(obj, QByteArray('123array56')) + + +class QByteArrayOperatorAtSetterNegativeIndex(unittest.TestCase): + '''Test case for QByteArray[] - __setitem__ - for negative index''' + + def testSetterNegativeIndex(self): + '''QByteArray[x] = string - negative index''' + obj = QByteArray('123456') + obj[-3] = 'array' + self.assertEqual(obj, QByteArray('123array56')) + + +class QByteArrayOperatorAtSetterLargeIndex(unittest.TestCase): + '''Test case for QByteArray[] - __setitem__ - for 'overflown' index''' + + def testSetterLargeIndexEmpty(self): + '''QByteArray[x] = somestring - Overflow index on empty string''' + # should pad with spaces if the index is larger + obj = QByteArray('') + obj[2] = 'a' + self.assertEqual(obj, QByteArray(' a')) + + def testSetterLargeIndexNormal(self): + '''QByteArray[x] = somestring - Overflow index on normal string''' + # should pad with spaces if the index is larger + obj = QByteArray('mystring') + obj[10] = 'normal' + self.assertEqual(obj, QByteArray('mystring normal')) + + + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qchar_test.py b/tests/QtCore/qchar_test.py new file mode 100644 index 000000000..a40724b0e --- /dev/null +++ b/tests/QtCore/qchar_test.py @@ -0,0 +1,59 @@ + +'''Test cases for QChar''' + +import unittest + +from PySide.QtCore import QString, QChar, QTextStream, QLatin1Char + + +class EqualTest(unittest.TestCase): + '''Tests for '__equal__''' + + def testEqualQChar(self): + '''QChar == QChar''' + self.assertEqual(QChar('a'), QChar('a')) + + def testEqualPyString(self): + '''QChar == Python string''' + self.assertEqual(QChar('a'), 'a') + + +class ImplicitConvQLatin1Char(unittest.TestCase): + '''Tests for implicit conversion from QLatin1Char to QChar''' + + def testQLatin1CharToChar(self): + '''QLatin1Char implicitly convertible to QChar''' + stream = QTextStream() + stream.setPadChar(QLatin1Char('-')) + self.assertEqual(QChar('-'), stream.padChar()) + + +class QCharCtorBigNumber(unittest.TestCase): + '''QChar constructors receiving ints''' + + def testInt(self): + '''QChar(int)''' + codepoint = 512 + qchar = QChar(codepoint) + reference = unichr(codepoint) + self.assertEqual(qchar.unicode(), codepoint) + + +class QCharCtorString(unittest.TestCase): + '''QChar constructor receiving strings''' + + def testBasic(self): + '''QChar(char)''' + reference = 'a' + qchar = QChar(reference) + self.assertEqual(ord(reference), ord(qchar.toAscii())) + + def testError(self): + '''QChar(char)''' + reference = 'aaaaaa' + self.assertRaises(TypeError, QChar, reference) + + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/qcoreapplication_instance_test.py b/tests/QtCore/qcoreapplication_instance_test.py new file mode 100755 index 000000000..365148d34 --- /dev/null +++ b/tests/QtCore/qcoreapplication_instance_test.py @@ -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() + diff --git a/tests/QtCore/qdatastream_test.py b/tests/QtCore/qdatastream_test.py new file mode 100644 index 000000000..d71ed2f24 --- /dev/null +++ b/tests/QtCore/qdatastream_test.py @@ -0,0 +1,330 @@ +#!/usr/bin/python +'''Unit tests for QDataStream''' + +import unittest + +from PySide.QtCore import QDataStream, QString, QIODevice, QByteArray +from PySide.QtCore import QBitArray, QDate, QTime, QDateTime, QLine, QChar + +def create_bitarray(string): + array = QBitArray(len(string)) + for i, char in enumerate(string): + array.setBit(i, char != '0') + return array + +class QDataStreamWrite(unittest.TestCase): + '''Test case for QDatastream write* functions''' + + def setUp(self): + self.ba = QByteArray() + self.read = QDataStream(self.ba, QIODevice.ReadOnly) + self.write = QDataStream(self.ba, QIODevice.WriteOnly) + + def testWriteUInt8(self): + '''QDataStream.writeUInt8 (accepting str of size 1)''' + x = 0xFF + self.write.writeUInt8(chr(x)) + y = self.read.readUInt8() + self.assertEqual(x, y) + + self.assertRaises(TypeError, self.write.writeUInt8, 'aaaaa') + + def testWriteInt8(self): + '''QDataStream.writeInt8 (accepting str of size 1)''' + x = 65 + self.write.writeInt8(chr(x)) + y = self.read.readInt8() + self.assertEqual(x, y) + + self.assertRaises(TypeError, self.write.writeInt8, 'aaaaa') + + def testWriteUInt8Int(self): + '''QDataStream.writeUInt8 (accepting integer)''' + x = 0xFF + self.write.writeUInt8(x) + y = self.read.readUInt8() + self.assertEqual(x, y) + + def testWriteInt8Int(self): + '''QDataStream.writeInt8 (accepting integer)''' + x = 65 + self.write.writeInt8(x) + y = self.read.readInt8() + self.assertEqual(x, y) + + def testWriteUInt16(self): + '''QDataStream.writeUInt16''' + x = 0x4423 + self.write.writeUInt16(x) + y = int(self.read.readUInt16()) + self.assertEqual(x, y) + + def testWriteUInt32(self): + '''QDataStream.writeUInt32''' + x = 0xdeadbeef + self.write.writeUInt32(x) + y = int(self.read.readUInt32()) + self.assertEqual(x, y) + + +class QDataStreamShift(unittest.TestCase): + '''Test case for << and >> operators''' + + def setUp(self): + self.ba = QByteArray() + self.stream = QDataStream(self.ba, QIODevice.WriteOnly) + self.read_stream = QDataStream(self.ba, QIODevice.ReadOnly) + + def testQCharValid(self): + '''QDataStream <<>> QChar - valid''' + self.stream << QChar(42) + + res = QChar() + + self.read_stream >> res + self.assertEqual(res, QChar(42)) + + def testQCharNull(self): + '''QDataStream <<>> QChar - null''' + self.stream << QChar() + + res = QChar() + + self.read_stream >> res + self.assertEqual(res, QChar()) + self.assert_(res.isNull()) + + def testQByteArrayValid(self): + '''QDataStream <<>> QByteArray - valid''' + self.stream << QByteArray("hello") + + res = QByteArray() + + self.read_stream >> res + self.assertEqual(res, QByteArray("hello")) + + def testQByteArrayEmpty(self): + '''QDataStream <<>> QByteArray - empty''' + self.stream << QByteArray("") + + res = QByteArray() + + self.read_stream >> res + self.assertEqual(res, QByteArray("")) + self.assert_(res.isEmpty()) + self.assert_(not res.isNull()) + + def testQByteArrayNull(self): + '''QDataStream <<>> QByteArray - null''' + self.stream << QByteArray() + + res = QByteArray() + + self.read_stream >> res + self.assertEqual(res, QByteArray()) + self.assert_(res.isEmpty()) + self.assert_(res.isNull()) + + def testQStringValid(self): + '''QDataStream <<>> QString - valid''' + self.stream << QString('Ka-boom') + + res = QString() + + self.read_stream >> res + self.assertEqual(res, QString('Ka-boom')) + + def testQStringEmpty(self): + '''QDataStream <<>> QString - empty''' + self.stream << QString('') + + res = QString() + + self.read_stream >> res + self.assertEqual(res, QString("")) + self.assert_(res.isEmpty()) + self.assert_(not res.isNull()) + + def testQStringNull(self): + '''QDataStream <<>> QString - null''' + self.stream << QString() + + res = QString() + + self.read_stream >> res + self.assertEqual(res, QString()) + self.assert_(res.isEmpty()) + self.assert_(res.isNull()) + + + def testQBitArrayNull(self): + '''QDataStream <<>> QBitArray - null''' + self.stream << QBitArray() + + res = QBitArray() + + self.read_stream >> res + self.assertEqual(res, QBitArray()) + + def testQBitArrayValid(self): + '''QDataStream <<>> QBitArray - valid''' + self.stream << create_bitarray('01010101') + + res = QBitArray() + + self.read_stream >> res + self.assertEqual(res, create_bitarray('01010101')) + + def testQDateNull(self): + '''QDataStream <<>> QDate - null''' + self.stream << QDate() + + res = QDate() + + self.read_stream >> res + self.assertEqual(res, QDate()) + self.assert_(not res.isValid()) + self.assert_(res.isNull()) + + def testQDateValid(self): + '''QDataStream <<>> QDate - valid''' + self.stream << QDate(2012, 12, 21) + + res = QDate() + + self.read_stream >> res + self.assertEqual(res, QDate(2012, 12, 21)) + self.assert_(res.isValid()) + self.assert_(not res.isNull()) + + + def testQTimeNull(self): + '''QDataStream <<>> QTime - null''' + self.stream << QTime() + + res = QTime() + + self.read_stream >> res + self.assertEqual(res, QTime()) + self.assert_(not res.isValid()) + self.assert_(res.isNull()) + + def testQTimeValid(self): + '''QDataStream <<>> QTime - valid''' + self.stream << QTime(12, 12, 21) + + res = QTime() + + self.read_stream >> res + self.assertEqual(res, QTime(12, 12, 21)) + self.assert_(res.isValid()) + self.assert_(not res.isNull()) + + def testQDateTimeNull(self): + '''QDataStream <<>> QDateTime - null''' + + self.stream << QDateTime() + + res = QDateTime() + + self.read_stream >> res + self.assertEqual(res, QDateTime()) + self.assert_(not res.isValid()) + self.assert_(res.isNull()) + + def testQDateTimeValid(self): + '''QDataStream <<>> QDateTime - valid''' + time = QTime(23, 23, 23) + date = QDate(2009, 01, 01) + + self.stream << QDateTime(date, time) + + res = QDateTime() + + self.read_stream >> res + self.assertEqual(res, QDateTime(date, time)) + self.assert_(res.isValid()) + self.assert_(not res.isNull()) + + +class QDataStreamShiftBitArray(unittest.TestCase): + + def _check_bitarray(self, data_set): + '''Check the >> operator for the given data set''' + + for data, expectedStatus, expectedString in data_set: + stream = QDataStream(data, QIODevice.ReadOnly) + string = QBitArray() + stream >> string + + self.assertEqual(stream.status(), expectedStatus) + self.assertEqual(string.size(), expectedString.size()) + self.assertEqual(string, expectedString) + + def testOk(self): + '''QDataStream with valid QBitArray''' + data = [] + + data.append((QByteArray('\x00\x00\x00\x00'), QDataStream.Ok, + QBitArray())) + data.append((QByteArray('\x00\x00\x00\x01\x00'), QDataStream.Ok, + create_bitarray('0'))) + data.append((QByteArray('\x00\x00\x00\x01\x01'), QDataStream.Ok, + create_bitarray('1'))) + data.append((QByteArray('\x00\x00\x00\x02\x03'), QDataStream.Ok, + create_bitarray('11'))) + data.append((QByteArray('\x00\x00\x00\x03\x07'), QDataStream.Ok, + create_bitarray('111'))) + data.append((QByteArray('\x00\x00\x00\x04\x0f'), QDataStream.Ok, + create_bitarray('1111'))) + data.append((QByteArray('\x00\x00\x00\x05\x1f'), QDataStream.Ok, + create_bitarray('11111'))) + data.append((QByteArray('\x00\x00\x00\x06\x3f'), QDataStream.Ok, + create_bitarray('111111'))) + data.append((QByteArray('\x00\x00\x00\x07\x7f'), QDataStream.Ok, + create_bitarray('1111111'))) + data.append((QByteArray('\x00\x00\x00\x07\x7e'), QDataStream.Ok, + create_bitarray('0111111'))) + data.append((QByteArray('\x00\x00\x00\x07\x00'), QDataStream.Ok, + create_bitarray('0000000'))) + data.append((QByteArray('\x00\x00\x00\x07\x39'), QDataStream.Ok, + create_bitarray('1001110'))) + + self._check_bitarray(data) + + def testPastEnd(self): + '''QDataStream >> QBitArray reading past the end of the data''' + data = [] + + data.append((QByteArray(), QDataStream.ReadPastEnd, + QBitArray())) + data.append((QByteArray('\x00'), QDataStream.ReadPastEnd, + QBitArray())) + data.append((QByteArray('\x00\x00'), QDataStream.ReadPastEnd, + QBitArray())) + data.append((QByteArray('\x00\x00\x00'), QDataStream.ReadPastEnd, + QBitArray())) + data.append((QByteArray('\x00\x00\x00\x01'), QDataStream.ReadPastEnd, + QBitArray())) + data.append((QByteArray('\x00\x00\x00\x02'), QDataStream.ReadPastEnd, + QBitArray())) + data.append((QByteArray('\x00\x00\x00\x03'), QDataStream.ReadPastEnd, + QBitArray())) + data.append((QByteArray('\x00\x00\x00\x04'), QDataStream.ReadPastEnd, + QBitArray())) + + self._check_bitarray(data) + + def testCorruptData(self): + '''QDataStream reading corrupt data''' + data = [] + + data.append((QByteArray('\x00\x00\x00\x01\x02'), + QDataStream.ReadCorruptData, + QBitArray())) + + self._check_bitarray(data) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qdate_test.py b/tests/QtCore/qdate_test.py new file mode 100644 index 000000000..49234486f --- /dev/null +++ b/tests/QtCore/qdate_test.py @@ -0,0 +1,28 @@ +#!/usr/bin/python +'''Test cases for QDate''' + +import unittest + +from PySide.QtCore import * + +class TestQDate (unittest.TestCase): + def testGetDate(self): + date = QDate(2009, 22, 9) + tuple_ = date.getDate() + self.assertEquals(tuple, tuple_.__class__) + (y, m, d) = tuple_ + self.assertEqual(date.year(), y) + self.assertEqual(date.month(), m) + self.assertEqual(date.day(), d) + + def testGetWeekNumber(self): + date = QDate(2000, 1, 1) + tuple_ = date.weekNumber() + self.assertEquals(tuple, tuple_.__class__) + (week, yearNumber) = tuple_ + self.assertEqual(week, 52) + self.assertEqual(yearNumber, 1999) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qenum_test.py b/tests/QtCore/qenum_test.py new file mode 100644 index 000000000..e3f963869 --- /dev/null +++ b/tests/QtCore/qenum_test.py @@ -0,0 +1,45 @@ +#!/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.NotOpen + + self.assertEqual(om, QIODevice.NotOpen) + self.assertTrue(om == 0) + + self.assertTrue(om != QIODevice.ReadOnly) + self.assertTrue(om != 1) + + def testToIntInFunction(self): + om = QIODevice.WriteOnly + self.assertEqual(int(om), 2) + + def testNonExtensibleEnums(self): + try: + om = QIODevice.OpenMode(QIODevice.WriteOnly) + self.assertFail() + except: + pass + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qevent_test.py b/tests/QtCore/qevent_test.py new file mode 100644 index 000000000..07f23f098 --- /dev/null +++ b/tests/QtCore/qevent_test.py @@ -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() diff --git a/tests/QtCore/qfile_test.py b/tests/QtCore/qfile_test.py new file mode 100644 index 000000000..adbdd68b7 --- /dev/null +++ b/tests/QtCore/qfile_test.py @@ -0,0 +1,31 @@ + +import unittest + +import os +import tempfile + +from PySide.QtCore import QFile, QIODevice + +class GetCharTest(unittest.TestCase): + '''Test case for QIODevice.getChar in QFile''' + + def setUp(self): + '''Acquire resources''' + handle, self.filename = tempfile.mkstemp() + os.write(handle, 'a') + os.close(handle) + + def tearDown(self): + '''release resources''' + os.remove(self.filename) + + def testBasic(self): + '''QFile.getChar''' + obj = QFile(self.filename) + obj.open(QIODevice.ReadOnly) + self.assertEqual(obj.getChar(), (True, 'a')) + self.assert_(not obj.getChar()[0]) + obj.close() + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qfileinfo_test.py b/tests/QtCore/qfileinfo_test.py new file mode 100644 index 000000000..580b5a7d5 --- /dev/null +++ b/tests/QtCore/qfileinfo_test.py @@ -0,0 +1,17 @@ + +import unittest + +import os +import tempfile + +from PySide.QtCore import QFile, QFileInfo + +class QFileConstructor(unittest.TestCase): + '''QFileInfo constructor with qfile''' + + def testBasic(self): + '''QFileInfo(QFile)''' + obj = QFileInfo(QFile()) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qflags_test.py b/tests/QtCore/qflags_test.py new file mode 100644 index 000000000..1346c11ef --- /dev/null +++ b/tests/QtCore/qflags_test.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +'''Test cases for QFlags''' + +import unittest +from PySide.QtCore import QIODevice, Qt, QFile + +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) + f.close() + + +class QFlagOperatorTest(unittest.TestCase): + '''Test case for operators in QFlags''' + + def testInvert(self): + '''QFlags ~ (invert) operator''' + self.assert_(isinstance(~QIODevice.ReadOnly, QIODevice.OpenMode)) + + def testOr(self): + '''QFlags | (or) operator''' + self.assert_(isinstance(QIODevice.ReadOnly | QIODevice.WriteOnly, QIODevice.OpenMode)) + + def testAnd(self): + '''QFlags & (and) operator''' + self.assert_(isinstance(QIODevice.ReadOnly & QIODevice.WriteOnly, QIODevice.OpenMode)) + + def testIOr(self): + '''QFlags |= (ior) operator''' + flag = Qt.WindowFlags() + self.assert_(flag & Qt.Widget == 0) + flag |= Qt.WindowMinimizeButtonHint + self.assert_(flag & Qt.WindowMinimizeButtonHint) + + def testInvertOr(self): + '''QFlags ~ (invert) operator over the result of an | (or) operator''' + self.assert_(isinstance(~(Qt.ItemIsSelectable | Qt.ItemIsEditable), Qt.ItemFlags)) + + def testEqual(self): + '''QFlags == operator''' + flags = Qt.Window + flags |= Qt.WindowMinimizeButtonHint + flag_type = (flags & Qt.WindowType_Mask) + self.assertEqual(flag_type, Qt.Window) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qhandle_test.py b/tests/QtCore/qhandle_test.py new file mode 100644 index 000000000..bcf6dea3d --- /dev/null +++ b/tests/QtCore/qhandle_test.py @@ -0,0 +1,16 @@ +#!/usr/bin/python +'''Test cases for QEnum and QFlags''' + +import unittest + +from PySide.QtCore import QThread, Qt + +class TestHANDLE(unittest.TestCase): + def testIntConversion(self): + i = 0 + h = QThread.currentThreadId() + i = 0 + int(h) + self.assertEqual(i, int(h)) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qlatin1string_test.py b/tests/QtCore/qlatin1string_test.py new file mode 100644 index 000000000..fdcf6ec98 --- /dev/null +++ b/tests/QtCore/qlatin1string_test.py @@ -0,0 +1,21 @@ + +'''Test cases for QLatin1String''' + +import unittest + +from PySide.QtCore import QString, QLatin1String, QObject + + +class ImplicitConvQLatin1String(unittest.TestCase): + '''Tests for implicit conversion from QLatin1String to QString''' + + def testQLatin1String(self): + '''QString implicit convertion from QLatin1String''' + obj = QObject() + obj.setObjectName(QLatin1String('dummy')) + + self.assertEqual(QString('dummy'), obj.objectName()) + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/qlinef_test.py b/tests/QtCore/qlinef_test.py new file mode 100644 index 000000000..31b5db955 --- /dev/null +++ b/tests/QtCore/qlinef_test.py @@ -0,0 +1,20 @@ +#!/usr/bin/python +'''Test cases for QLineF''' + +import unittest +import os + +from PySide.QtCore import * + +class TestQLineF (unittest.TestCase): + def testIntersect(self): + l1 = QLineF(0, 0, 1, 0) + l2 = QLineF(1, -1, 1, 1) + tuple_ = l1.intersect(l2) + self.assertEquals(tuple, tuple_.__class__) + (value, p) = tuple_ + self.assertEquals(QLineF.BoundedIntersection, value) + self.assertEqual(QPointF(1, 0), p) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qlocale_test.py b/tests/QtCore/qlocale_test.py new file mode 100644 index 000000000..f1bff8e82 --- /dev/null +++ b/tests/QtCore/qlocale_test.py @@ -0,0 +1,40 @@ +#!/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, True), obj.toInt('37')) + + def testToNumberFloat(self): + obj = QLocale(QLocale.C) + self.assertEqual((ctypes.c_float(37.109).value, True), + obj.toFloat('37.109')) + + def testToNumberDouble(self): + obj = QLocale(QLocale.C) + self.assertEqual((ctypes.c_double(37.109).value, True), + obj.toDouble('37.109')) + + def testToNumberShort(self): + obj = QLocale(QLocale.C) + self.assertEqual((ctypes.c_short(37).value, True), + obj.toShort('37')) + + def testToNumberULongLong(self): + obj = QLocale(QLocale.C) + self.assertEqual((ctypes.c_ulonglong(37).value, True), + obj.toULongLong('37')) + + def testToNumberULongLongNegative(self): + obj = QLocale(QLocale.C) + self.assert_(not obj.toULongLong('-37')[1]) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qmetaobject_test.py b/tests/QtCore/qmetaobject_test.py new file mode 100644 index 000000000..667e763ad --- /dev/null +++ b/tests/QtCore/qmetaobject_test.py @@ -0,0 +1,51 @@ +#!/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 DynObject(QObject): + def slot(self): + 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") + f = QFile() + fm = f.metaObject() + self.assertEqual(m.methodCount(), fm.methodCount()) + + def test_DynamicSlotSignal(self): + o = DynObject() + o2 = QObject() + + method_count_base = o.metaObject().methodCount() + + o.connect(o2, SIGNAL("bar()"), o.slot) + slot_index = o.metaObject().indexOfMethod("slot()") + + o.connect(o, SIGNAL("foo()"), o2, SIGNAL("bar()")) + signal_index = o.metaObject().indexOfMethod("foo()"); + + self.assert_(slot_index != signal_index) + + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/qmodelindex_internalpointer_test.py b/tests/QtCore/qmodelindex_internalpointer_test.py new file mode 100644 index 000000000..015d1c926 --- /dev/null +++ b/tests/QtCore/qmodelindex_internalpointer_test.py @@ -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() + diff --git a/tests/QtCore/qobject_children_segfault_test.py b/tests/QtCore/qobject_children_segfault_test.py new file mode 100644 index 000000000..930a082cf --- /dev/null +++ b/tests/QtCore/qobject_children_segfault_test.py @@ -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() diff --git a/tests/QtCore/qobject_connect_notify_test.py b/tests/QtCore/qobject_connect_notify_test.py new file mode 100644 index 000000000..441037585 --- /dev/null +++ b/tests/QtCore/qobject_connect_notify_test.py @@ -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() diff --git a/tests/QtCore/qobject_event_filter_test.py b/tests/QtCore/qobject_event_filter_test.py new file mode 100644 index 000000000..8018fcda0 --- /dev/null +++ b/tests/QtCore/qobject_event_filter_test.py @@ -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() diff --git a/tests/QtCore/qobject_inherits_test.py b/tests/QtCore/qobject_inherits_test.py new file mode 100644 index 000000000..9e02b0a46 --- /dev/null +++ b/tests/QtCore/qobject_inherits_test.py @@ -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() diff --git a/tests/QtCore/qobject_parent_test.py b/tests/QtCore/qobject_parent_test.py new file mode 100644 index 000000000..4699fc60c --- /dev/null +++ b/tests/QtCore/qobject_parent_test.py @@ -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() diff --git a/tests/QtCore/qobject_property_test.py b/tests/QtCore/qobject_property_test.py new file mode 100644 index 000000000..33df2ac9b --- /dev/null +++ b/tests/QtCore/qobject_property_test.py @@ -0,0 +1,71 @@ + +'''Test cases for QObject property and setProperty''' + +import unittest + +from PySide.QtCore import QObject, QVariant, QString + +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 testQStringProperty(self): + obj = QObject() + self.assert_(not obj.setProperty('dummy', QString('data'))) + prop = obj.property('dummy') + + self.assert_(isinstance(prop, QVariant)) + self.assert_(prop.isValid()) + self.assertEqual(obj.property('dummy').toString(), QString('data')) + + def testImplicitQVariantProperty(self): + obj = QObject() + self.assert_(not obj.setProperty('dummy', 'data')) + prop = obj.property('dummy') + + self.assert_(isinstance(prop, QVariant)) + self.assert_(prop.isValid()) + self.assertEqual(obj.property('dummy').toString(), 'data') + + def testInvalidProperty(self): + #QObject.property() for invalid properties + obj = QObject() + + prop = obj.property('dummy') + self.assert_(not prop.isValid()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qobject_protected_methods_test.py b/tests/QtCore/qobject_protected_methods_test.py new file mode 100644 index 000000000..530b870a2 --- /dev/null +++ b/tests/QtCore/qobject_protected_methods_test.py @@ -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()")), 0) + + 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()")), 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qobject_test.py b/tests/QtCore/qobject_test.py new file mode 100644 index 000000000..a1749babc --- /dev/null +++ b/tests/QtCore/qobject_test.py @@ -0,0 +1,43 @@ +#!/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 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() diff --git a/tests/QtCore/qobject_timer_event_test.py b/tests/QtCore/qobject_timer_event_test.py new file mode 100644 index 000000000..b46207d88 --- /dev/null +++ b/tests/QtCore/qobject_timer_event_test.py @@ -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() diff --git a/tests/QtCore/qobject_tr_as_instance_test.py b/tests/QtCore/qobject_tr_as_instance_test.py new file mode 100644 index 000000000..5aa70530b --- /dev/null +++ b/tests/QtCore/qobject_tr_as_instance_test.py @@ -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() + diff --git a/tests/QtCore/qpoint_test.py b/tests/QtCore/qpoint_test.py new file mode 100644 index 000000000..dfce76939 --- /dev/null +++ b/tests/QtCore/qpoint_test.py @@ -0,0 +1,21 @@ + +'''Test cases for QPoint and QPointF''' + +import unittest + +from PySide.QtCore import QPoint, QPointF + + +class QPointTest(unittest.TestCase): + + def testQPointCtor(self): + point = QPoint(QPoint(10,20)) + +class QPointFTest(unittest.TestCase): + + def testQPointFCtor(self): + pointf = QPointF(QPoint(10,20)) + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/qprocess_test.py b/tests/QtCore/qprocess_test.py new file mode 100644 index 000000000..b01c68ba3 --- /dev/null +++ b/tests/QtCore/qprocess_test.py @@ -0,0 +1,16 @@ +#!/usr/bin/python +'''Test cases for QProcess''' + +import unittest +import os + +from PySide.QtCore import * + +class TestQProcess (unittest.TestCase): + def testStartDetached(self): + value, pid = QProcess.startDetached("dir", [], os.getcwd()) + self.assert_(isinstance(value, bool)) + self.assert_(isinstance(pid, long)) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qrect_test.py b/tests/QtCore/qrect_test.py new file mode 100644 index 000000000..3c5f5be05 --- /dev/null +++ b/tests/QtCore/qrect_test.py @@ -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() diff --git a/tests/QtCore/qresource_test.py b/tests/QtCore/qresource_test.py new file mode 100644 index 000000000..8f3350a60 --- /dev/null +++ b/tests/QtCore/qresource_test.py @@ -0,0 +1,31 @@ +# -*- 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): + f = open(os.path.join(os.path.dirname(__file__), '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() + diff --git a/tests/QtCore/qsize_test.py b/tests/QtCore/qsize_test.py new file mode 100644 index 000000000..4fb060b74 --- /dev/null +++ b/tests/QtCore/qsize_test.py @@ -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() + diff --git a/tests/QtCore/qslot_object_test.py b/tests/QtCore/qslot_object_test.py new file mode 100644 index 000000000..ad0ea3a14 --- /dev/null +++ b/tests/QtCore/qslot_object_test.py @@ -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()") + QtCore.QObject.connect(timer, 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() diff --git a/tests/QtCore/qsrand_test.py b/tests/QtCore/qsrand_test.py new file mode 100644 index 000000000..97d0a3b0b --- /dev/null +++ b/tests/QtCore/qsrand_test.py @@ -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() diff --git a/tests/QtCore/qstate_test.py b/tests/QtCore/qstate_test.py new file mode 100644 index 000000000..d7c9a4c44 --- /dev/null +++ b/tests/QtCore/qstate_test.py @@ -0,0 +1,35 @@ +#!/usr/bin/python +import unittest +from PySide.QtCore import QObject, QState, QFinalState, SIGNAL, QCoreApplication, QTimer, QStateMachine, QSignalTransition, QVariant + + +class QStateTest(unittest.TestCase): + def testBasic(self): + app = QCoreApplication([]) + + o = QObject() + o.setProperty("text", QVariant("INdT")) + + machine = QStateMachine() + s1 = QState() + s1.assignProperty(o, "text", QVariant("Rocks")); + + s2 = QFinalState() + t = s1.addTransition(o, SIGNAL("change()"), s2); + self.assert_(isinstance(t, QSignalTransition)) + + machine.addState(s1) + machine.addState(s2) + machine.setInitialState(s1) + machine.start() + + o.emit(SIGNAL("change()")) + + QTimer.singleShot(100, app.quit) + app.exec_() + + txt = o.property("text").toString() + self.assert_(txt, "Rocks") + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qstatemachine_test.py b/tests/QtCore/qstatemachine_test.py new file mode 100644 index 000000000..ce2449d15 --- /dev/null +++ b/tests/QtCore/qstatemachine_test.py @@ -0,0 +1,68 @@ +#!/usr/bin/python +import unittest +from PySide.QtCore import QObject, QState, QFinalState, SIGNAL +from PySide.QtCore import QTimer, QStateMachine +from PySide.QtCore import QParallelAnimationGroup + +from helper import UsesQCoreApplication + + +class StateMachineTest(unittest.TestCase): + '''Check presence of State Machine classes''' + + def testBasic(self): + '''State machine classes''' + import PySide.QtCore + PySide.QtCore.QSignalTransition + PySide.QtCore.QPropertyAnimation + + + +class QStateMachineTest(UsesQCoreApplication): + + def cb(self, *args): + self.assertEqual(self.machine.defaultAnimations(), [self.anim]) + + def testBasic(self): + self.machine = QStateMachine() + s1 = QState() + s2 = QState() + s3 = QFinalState() + + QObject.connect(self.machine, SIGNAL("started()"), self.cb) + + self.anim = QParallelAnimationGroup() + + self.machine.addState(s1) + self.machine.addState(s2) + self.machine.addState(s3) + self.machine.setInitialState(s1) + self.machine.addDefaultAnimation(self.anim) + self.machine.start() + + QTimer.singleShot(100, self.app.quit) + self.app.exec_() + + +class QSetConverterTest(UsesQCoreApplication): + '''Test converter of QSet toPython using QStateAnimation.configuration''' + + def testBasic(self): + '''QStateMachine.configuration converting QSet to python set''' + machine = QStateMachine() + s1 = QState() + machine.addState(s1) + machine.setInitialState(s1) + machine.start() + + QTimer.singleShot(100, self.app.quit) + self.app.exec_() + + configuration = machine.configuration() + + self.assert_(isinstance(configuration, set)) + self.assert_(s1 in configuration) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qstring_buffer_protocol_test.py b/tests/QtCore/qstring_buffer_protocol_test.py new file mode 100755 index 000000000..f8475d093 --- /dev/null +++ b/tests/QtCore/qstring_buffer_protocol_test.py @@ -0,0 +1,20 @@ +#!/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 + isdir(QString('/tmp')) + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/qstring_operator_test.py b/tests/QtCore/qstring_operator_test.py new file mode 100644 index 000000000..6d7ae314d --- /dev/null +++ b/tests/QtCore/qstring_operator_test.py @@ -0,0 +1,161 @@ +#!/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 QStringOperatorAtSetter(unittest.TestCase): + '''Test case for operator QString[] - __setitem__''' + + def testSetterString(self): + '''QString[x] = pythonstring''' + obj = QString('123456') + obj[1] = '0' + self.assertEqual(obj, QString('103456')) + + def testSetterStringLarge(self): + '''QString[x] = pythonstring (larget than 1 char)''' + obj = QString('123456') + obj[3] = 'abba' + self.assertEqual(obj, QString('123abba56')) + + def testSetterQString(self): + '''QString[x] = QString''' + obj = QString('123456') + obj[3] = QString('string') + self.assertEqual(obj, QString('123string56')) + + def testSetterQByteArray(self): + '''QString[x] = qbytearray''' + obj = QString('123456') + obj[3] = QByteArray('array') + self.assertEqual(obj, QString('123array56')) + + +class QStringOperatorAtSetterNegativeIndex(unittest.TestCase): + '''Test case for QString[] - __setitem__ - for negative index''' + + def testSetterNegativeIndex(self): + '''QString[x] = string - negative index''' + obj = QString('123456') + obj[-3] = 'array' + self.assertEqual(obj, QString('123array56')) + + +class QStringOperatorAtSetterLargeIndex(unittest.TestCase): + '''Test case for QString[] - __setitem__ - for 'overflown' index''' + + def testSetterLargeIndexEmpty(self): + '''QString[x] = somestring - Overflow index on empty string''' + # should pad with spaces if the index is larger + obj = QString('') + obj[2] = 'a' + self.assertEqual(obj, QString(' a')) + + def testSetterLargeIndexNormal(self): + '''QString[x] = somestring - Overflow index on normal string''' + # should pad with spaces if the index is larger + obj = QString('mystring') + obj[10] = 'normal' + self.assertEqual(obj, QString('mystring normal')) + + +class QStringOperatorAt(unittest.TestCase): + '''TestCase for operator QString[] - __getitem__''' + + 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() diff --git a/tests/QtCore/qstring_test.py b/tests/QtCore/qstring_test.py new file mode 100644 index 000000000..3f0fb4931 --- /dev/null +++ b/tests/QtCore/qstring_test.py @@ -0,0 +1,192 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +'''Test cases for QString''' + +import unittest +import ctypes +import sys + +from PySide.QtCore import QString, QByteArray, QObject + +class QStringToNumber(unittest.TestCase): + def testReturnValueTypes(self): + obj = QString('37') + val, ok = obj.toInt() + self.assertEqual(type(val), int) + self.assertEqual(type(ok), bool) + + def testToNumberInt(self): + obj = QString('37') + self.assertEqual((37, True), obj.toInt()) + + def testToNumberLong(self): + obj = QString('3700000') + self.assertEqual((3700000, True), obj.toInt()) + + def testToNumberShort(self): + obj = QString('33') + self.assertEqual((ctypes.c_short(33).value, True), obj.toShort()) + + def testToNumberShortNegative(self): + obj = QString('-4') + self.assertEqual((ctypes.c_short(-4).value, True), obj.toShort()) + + def testToNumberShortOverflow(self): + obj = QString('1000000') + self.assertEqual(False, obj.toShort()[1]) + + def testToNumberUInt(self): + obj = QString('33') + self.assertEqual((ctypes.c_uint(33).value, True), obj.toUInt()) + + def testToNumberUIntNegative(self): + obj = QString('-4') + self.assertEqual(False, obj.toUInt()[1]) + + def testToNumberUIntOverflow(self): + obj = QString('10000000000000') + self.assertEqual(False, obj.toUInt()[1]) + + def testToNumberULong(self): + obj = QString('33') + self.assertEqual((ctypes.c_ulong(33).value, True), obj.toULong()) + + def testToNumberULongNegative(self): + obj = QString('-4') + self.assertEqual(False, obj.toULong()[1]) + + def testToNumberUShort(self): + obj = QString('33') + self.assertEqual((ctypes.c_ushort(33).value, True), obj.toUShort()) + + def testToNumberUShortLarge(self): + obj = QString('128') + self.assertEqual((ctypes.c_ushort(128).value, True), obj.toUShort()) + + def testToNumberUShortOverflow(self): + obj = QString('205000') + self.assertEqual(False, obj.toUShort()[1]) + + def testToNumberUShortNegative(self): + obj = QString('-4') + self.assertEqual(False, obj.toUShort()[1]) + + def testToNumberIntUsingHex(self): + obj = QString('2A') + self.assertEquals((0, False), obj.toInt()) + self.assertEqual((int(str(obj), 16), True), obj.toInt(16)) + + def testToNumberIntUsingHex(self): + obj = QString('101010') + self.assertEqual((int(str(obj), 2), True), obj.toInt(2)) + + 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 testNullQString(self): + s = QString(None) + self.assertTrue(s.isNull()) + + 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) + + +class QStringImplicitConvertion(unittest.TestCase): + '''Implicit conversions for QString''' + + def testQByteArray(self): + '''QString implicitly conversion: QByteArray''' + obj = QObject() + obj.setObjectName(QByteArray('foobar')) + self.assertEqual(obj.objectName(), QString('foobar')) + +class QStringHash(unittest.TestCase): + def testHash(self): + self.assertEqual(hash("key"), hash(QString("key"))) + self.assertEqual(hash(u"aéióu"), hash(QString(u"aéióu"))) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qstringlist_test.py b/tests/QtCore/qstringlist_test.py new file mode 100644 index 000000000..031051684 --- /dev/null +++ b/tests/QtCore/qstringlist_test.py @@ -0,0 +1,171 @@ + +# -*- 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()) + + def testShiftOperator(self): + #QStringList lshift + a = QStringList() + b = ["1", 2, "3"] + self.assertRaises(TypeError, a.__lshift__, b) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qtext_codec_test.py b/tests/QtCore/qtext_codec_test.py new file mode 100644 index 000000000..2bd7f8139 --- /dev/null +++ b/tests/QtCore/qtext_codec_test.py @@ -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() diff --git a/tests/QtCore/qtextstream_test.py b/tests/QtCore/qtextstream_test.py new file mode 100644 index 000000000..13dc6516c --- /dev/null +++ b/tests/QtCore/qtextstream_test.py @@ -0,0 +1,95 @@ + +'''Unit tests for QTextStream''' + +import unittest + +from PySide.QtCore import QTextStream, QIODevice, QString, QByteArray +from PySide.QtCore import QTextCodec, QFile + +class QTextStreamShiftTest(unittest.TestCase): + + def setUp(self): + self.ba = QByteArray() + self.read = QTextStream(self.ba, QIODevice.ReadOnly) + self.write = QTextStream(self.ba, QIODevice.WriteOnly) + + def testNumber(self): + '''QTextStream << number''' + + self.write << QString('4') + self.write.flush() + res = self.read.readLine() + self.assert_(isinstance(res, QString)) + self.assertEqual(res, QString('4')) + + def testString(self): + self.write << QString('Test_it!') + self.write.flush() + res = QString() + self.read >> res + self.assertEqual(res, QString('Test_it!')) + +class QTextStreamGetSet(unittest.TestCase): + + def setUp(self): + self.obj = QTextStream() + + + def testCodec(self): + '''QTextStream set/get Codec''' + + codec = QTextCodec.codecForName('ISO8859-1') + self.obj.setCodec(codec) + self.assertEqual(codec, self.obj.codec()) + + def testDevice(self): + '''QTextStream get/set Device''' + device = QFile() + self.obj.setDevice(device) + self.assertEqual(device, self.obj.device()) + self.obj.setDevice(None) + self.assertEqual(None, self.obj.device()) + +class QTextStreamInitialization(unittest.TestCase): + + def testConstruction(self): + '''QTextStream construction''' + obj = QTextStream() + + self.assertEqual(obj.codec(), QTextCodec.codecForLocale()) + self.assertEqual(obj.device(), None) + self.assertEqual(obj.string(), None) + + self.assert_(obj.atEnd()) + self.assertEqual(obj.readAll(), '') + +class QTextStreamReadLinesFromDevice(unittest.TestCase): + + def _check_data(self, data_set): + + for data, lines in data_set: + stream = QTextStream(data) + + res = [] + while not stream.atEnd(): + res.append(stream.readLine()) + + self.assertEqual(res, lines) + + def testLatin1(self): + '''QTextStream readLine for simple Latin1 strings''' + + data = [] + + data.append((QByteArray(), [])) + data.append((QByteArray('\n'), [''])) + data.append((QByteArray('\r\n'), [''])) + data.append((QByteArray('ole'), ['ole'])) + data.append((QByteArray('ole\n'), ['ole'])) + data.append((QByteArray('ole\r\n'), ['ole'])) + data.append((QByteArray('ole\r\ndole\r\ndoffen'), ['ole', 'dole', 'doffen'])) + + self._check_data(data) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qthread_prod_cons_test.py b/tests/QtCore/qthread_prod_cons_test.py new file mode 100644 index 000000000..fc634dd88 --- /dev/null +++ b/tests/QtCore/qthread_prod_cons_test.py @@ -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() diff --git a/tests/QtCore/qthread_signal_test.py b/tests/QtCore/qthread_signal_test.py new file mode 100755 index 000000000..edd7d77f4 --- /dev/null +++ b/tests/QtCore/qthread_signal_test.py @@ -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() diff --git a/tests/QtCore/qthread_test.py b/tests/QtCore/qthread_test.py new file mode 100644 index 000000000..410afb908 --- /dev/null +++ b/tests/QtCore/qthread_test.py @@ -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() diff --git a/tests/QtCore/qtimer_singleshot_test.py b/tests/QtCore/qtimer_singleshot_test.py new file mode 100644 index 000000000..96107ecce --- /dev/null +++ b/tests/QtCore/qtimer_singleshot_test.py @@ -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() + diff --git a/tests/QtCore/qtimer_timeout_test.py b/tests/QtCore/qtimer_timeout_test.py new file mode 100644 index 000000000..8dfe39529 --- /dev/null +++ b/tests/QtCore/qtimer_timeout_test.py @@ -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() + diff --git a/tests/QtCore/qtnamespace_test.py b/tests/QtCore/qtnamespace_test.py new file mode 100644 index 000000000..3343a276b --- /dev/null +++ b/tests/QtCore/qtnamespace_test.py @@ -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() diff --git a/tests/QtCore/quoteEnUS.txt b/tests/QtCore/quoteEnUS.txt new file mode 100644 index 000000000..909b4fa17 --- /dev/null +++ b/tests/QtCore/quoteEnUS.txt @@ -0,0 +1 @@ +Fine! Dishonor! Dishonor on you, dishonor on ya cow! diff --git a/tests/QtCore/qurl_test.py b/tests/QtCore/qurl_test.py new file mode 100644 index 000000000..14243a11a --- /dev/null +++ b/tests/QtCore/qurl_test.py @@ -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() diff --git a/tests/QtCore/qvariant_pyobject_test.py b/tests/QtCore/qvariant_pyobject_test.py new file mode 100644 index 000000000..82da5556f --- /dev/null +++ b/tests/QtCore/qvariant_pyobject_test.py @@ -0,0 +1,71 @@ + +'''QVariant handling of PyObjects, including pure-python or derived from Qt''' + +import unittest + +from PySide.QtCore import QSize, QVariant, QString + + +class Dummy(object): + '''Pure python sample class''' + pass + + +class MySize(QSize): + '''Extended class''' + pass + + +class QVariantPurePython(unittest.TestCase): + '''QVariant + pure python classes''' + + def testTypeNamePythonClasses(self): + '''QVariant of pure python classes''' + d = Dummy() + obj = QVariant(d) + # inherited type name from other binding + self.assertEqual('PyQt_PyObject', obj.typeName()) + + +class QVariantInheritedPython(unittest.TestCase): + '''QVariant + classes inherited from C++''' + + # This works only on PyQt4 4.5.x, not on PyQt4 4.4.x or PySide + def testSubClassConvertion(self): + '''QVariant(QSize subclass) type is UserType and returns same object''' + mysize = MySize(0, 0) + variant = QVariant(mysize) + + self.assertEqual(variant.type(), QVariant.UserType) + self.assertTrue(variant.toPyObject() is mysize) + + +class QVariantToPyObject(unittest.TestCase): + '''QVariant.toPyObject tests''' + + def testQVariantPyList(self): + '''QVariant(QVariantList).toPyObject() equals original list''' + obj = QVariant([1, 'two', 3]) + self.assertEqual(obj.toPyObject(), [1, 'two', 3]) + + def testPyObject(self): + '''QVariant(pure PyObject).toPyObject should return the same object''' + d = Dummy() + obj = QVariant(d) + self.assert_(d is obj.toPyObject()) + + def testNoneToPyObject(self): + '''QVariant().toPyObject() should return None''' + obj = QVariant() + self.assertEqual(None, obj.toPyObject()) + + def testQStringToPyObject(self): + '''QVariant(python string).toPyObject() return an equal QString''' + d = 'abc' + obj = QVariant('abc') + self.assert_(isinstance(obj.toPyObject(), QString)) + self.assertEqual(d, obj.toPyObject()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/qvariant_test.py b/tests/QtCore/qvariant_test.py new file mode 100644 index 000000000..5c23b4049 --- /dev/null +++ b/tests/QtCore/qvariant_test.py @@ -0,0 +1,141 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +'''Test cases for QVariant''' + +import unittest +import sys + +from PySide.QtCore import QSize, QVariant, QByteArray, QStringList, QString + + +class QVariantToNumber(unittest.TestCase): + '''QVariant of number types''' + + def testToNumberInt(self): + '''QVariant(int).toInt()''' + obj = QVariant('37') + self.assertEqual((37, True), obj.toInt()) + + def testToNumberLongLong(self): + '''QVariant(int).toLongLong()''' + obj = QVariant('37') + self.assertEqual((37, True), obj.toLongLong()) + + def testToNumberUInt(self): + '''QVariant(int).toUInt()''' + obj = QVariant('37') + self.assertEqual((37, True), obj.toUInt()) + + def testToNumberUIntNegative(self): + '''QVariant(negative int).toUInt()''' + obj = QVariant('-37') + self.assert_(not obj.toUInt()[1]) + + def testToNumberULongLong(self): + '''QVariant(int).toULongLong()''' + obj = QVariant('37') + self.assertEqual((37, True), obj.toULongLong()) + + def testToNumberULongLongNegative(self): + '''QVariant(negative int).toULongLong()''' + obj = QVariant('-37') + self.assert_(not obj.toULongLong()[1]) + + def testToNumberFloat(self): + '''QVariant(double).toFloat()''' + obj = QVariant('37.109') + self.assertEqual((37.109, True), obj.toDouble()) + + +class QVariantTypeName(unittest.TestCase): + '''QVariant.typeName()''' + + def testTypeNameQString(self): + '''QVariant(QString).typeName()''' + obj = QVariant(QString('aaaa')) + self.assertEqual('QString', obj.typeName()) + + def testTypeNameString(self): + '''QVariant(PyString).typeName()''' + obj = QVariant('aaaa') + self.assertEqual('QString', obj.typeName()) + + def testTypeNameInt(self): + '''QVariant(int).typeName()''' + obj = QVariant(34) + self.assertEqual('int', obj.typeName()) + + def testTypeNameDouble(self): + '''QVariant(double).typeName()''' + obj = QVariant(3.14) + self.assertEqual('double', obj.typeName()) + + def testTypeNameBool(self): + '''QVariant(bool).typeName()''' + obj = QVariant(True) + self.assertEqual('bool', obj.typeName()) + + def testTypeNameQByteArray(self): + '''QVariant(QByteArray).typeName()''' + obj = QVariant(QByteArray('aaaa')) + self.assertEqual('QByteArray', obj.typeName()) + + def testTypeNameNone(self): + '''QVariant().typeName()''' + obj = QVariant() + self.assertEqual(None, obj.typeName()) + + def testTypeNameQVariantList(self): + '''QVariant(QVariantList).typeName()''' + obj = QVariant([1, 2, 3, 4]) + self.assertEqual('QVariantList', obj.typeName()) + + obj = QVariant([1.0, 2.2, 3.3, 4.2]) + self.assertEqual('QVariantList', obj.typeName()) + + obj = QVariant(['aaa', 'bbb', 'ccc', 'dddd']) + self.assertEqual('QVariantList', obj.typeName()) + + obj = QVariant([QString('aaa'), QString('bbb'), + QString('ccc'), QString('dddd')]) + self.assertEqual('QVariantList', obj.typeName()) + + def testTypeNameQStringList(self): + '''QVariant(QStringList).typeName()''' + obj = QVariant(QStringList()) + self.assertEqual('QStringList', obj.typeName()) + obj = QVariant(QStringList(['aaa', 'bbb', 'ccc'])) + self.assertEqual('QStringList', obj.typeName()) + + +class QVariantConstructor(unittest.TestCase): + '''More qvariant constructions''' + + def testCopyConstructor(self): + '''QVariant copy constructor''' + obj = QVariant(1) + cpy = QVariant(obj) + + self.assertEqual(obj.type(), cpy.type()) + + def testQStringConstructor(self): + '''QVariant(PyString).type == QVariant.string''' + obj = QVariant("PySide") + self.assertEqual(obj.type(), QVariant.String) + + def testQSizeConstructor(self): + '''QVariant(QSize).type == QVariant.Size''' + mysize = QSize(0, 0) + variant = QVariant(mysize) + + self.assertEqual(variant.type(), QVariant.Size) + self.assertEqual(variant.toSize(), mysize) + + def testToList(self): + v = QVariant((1,2,3)) + self.assertEqual(v.toList(), (1, 2, 3)) + v = QVariant([0,1,2]) + self.assertEqual(v.toList(), [0, 1, 2]) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/resources.qrc b/tests/QtCore/resources.qrc new file mode 100644 index 000000000..cea17b440 --- /dev/null +++ b/tests/QtCore/resources.qrc @@ -0,0 +1,6 @@ + + + quoteEnUS.txt + + + diff --git a/tests/QtCore/resources_mc.py b/tests/QtCore/resources_mc.py new file mode 100644 index 000000000..132c8db12 --- /dev/null +++ b/tests/QtCore/resources_mc.py @@ -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() diff --git a/tests/QtCore/static_method_test.py b/tests/QtCore/static_method_test.py new file mode 100755 index 000000000..1f9de78f7 --- /dev/null +++ b/tests/QtCore/static_method_test.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +'''Test cases for overloads involving static and non-static versions of a method.''' + +import os +import unittest + +from PySide.QtCore import QFile + +class StaticNonStaticMethodsTest(unittest.TestCase): + '''Test cases for overloads involving static and non-static versions of a method.''' + + def setUp(self): + filename = 'somefile%d.txt' % os.getpid() + self.existing_filename = os.path.join(os.path.curdir, filename) + self.delete_file = False + if not os.path.exists(self.existing_filename): + f = open(self.existing_filename, 'w') + for line in range(10): + f.write('sbrubbles\n') + f.close() + self.delete_file = True + + self.non_existing_filename = os.path.join(os.path.curdir, 'inexistingfile.txt') + i = 0 + while os.path.exists(self.non_existing_filename): + i += 1 + filename = 'inexistingfile-%d.txt' % i + self.non_existing_filename = os.path.join(os.path.curdir, filename) + + def tearDown(self): + if self.delete_file: + os.remove(self.existing_filename) + + def testCallingStaticMethodWithClass(self): + '''Call static method using class.''' + self.assert_(QFile.exists(self.existing_filename)) + self.assertFalse(QFile.exists(self.non_existing_filename)) + + def testCallingStaticMethodWithInstance(self): + '''Call static method using instance of class.''' + f = QFile(self.non_existing_filename) + self.assert_(f.exists(self.existing_filename)) + self.assertFalse(f.exists(self.non_existing_filename)) + + def testCallingInstanceMethod(self): + '''Call instance method.''' + f1 = QFile(self.non_existing_filename) + self.assertFalse(f1.exists()) + f2 = QFile(self.existing_filename) + self.assert_(f2.exists()) + + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/static_protected_methods_test.py b/tests/QtCore/static_protected_methods_test.py new file mode 100644 index 000000000..9d920a438 --- /dev/null +++ b/tests/QtCore/static_protected_methods_test.py @@ -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() diff --git a/tests/QtCore/thread_signals.py b/tests/QtCore/thread_signals.py new file mode 100644 index 000000000..9eea82907 --- /dev/null +++ b/tests/QtCore/thread_signals.py @@ -0,0 +1,33 @@ + +''' Test case for QObject.signalsBlocked() and blockSignal()''' + +import unittest +import os +from tempfile import mkstemp + +from PySide.QtCore import QObject, SIGNAL, QFile, QThread, QTimer, Qt +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.app.quit() + + def testThread(self): + t = MyThread() + QObject.connect(t, SIGNAL("test(const QString&)"), self._callback); + t.start() + + self.app.exec_() + self.assert_(self.__called__); + +if __name__ == '__main__': + unittest.main() diff --git a/tests/QtCore/translation_test.py b/tests/QtCore/translation_test.py new file mode 100644 index 000000000..870c8c50f --- /dev/null +++ b/tests/QtCore/translation_test.py @@ -0,0 +1,62 @@ +#!/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, QString + +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'привет мир!') + + def testUtf8(self): + translator = QTranslator() + translator.load(os.path.join(self.trdir, 'trans_russian.qm')) + self.app.installTranslator(translator) + + obj = QObject() + obj.setObjectName(obj.trUtf8('Hello World!')) + self.assertEqual(obj.objectName(), u'привет мир!') + + def testTranslateWithNoneDisambiguation(self): + value = 'String here' + obj = QCoreApplication.translate('context', value, None, QCoreApplication.UnicodeUTF8) + self.assert_(isinstance(obj, QString)) + self.assertEqual(obj, value) + +if __name__ == '__main__': + unittest.main() + diff --git a/tests/QtCore/translations/trans_latin.ts b/tests/QtCore/translations/trans_latin.ts new file mode 100644 index 000000000..b9fcf41be --- /dev/null +++ b/tests/QtCore/translations/trans_latin.ts @@ -0,0 +1,11 @@ + + + + + QObject + + Hello World! + Orbis, te saluto! + + + diff --git a/tests/QtCore/translations/trans_russian.ts b/tests/QtCore/translations/trans_russian.ts new file mode 100644 index 000000000..d1ba49bd2 --- /dev/null +++ b/tests/QtCore/translations/trans_russian.ts @@ -0,0 +1,11 @@ + + + + + QObject + + Hello World! + привет мир! + + + diff --git a/tests/QtCore/unaryoperator_test.py b/tests/QtCore/unaryoperator_test.py new file mode 100755 index 000000000..94db1feec --- /dev/null +++ b/tests/QtCore/unaryoperator_test.py @@ -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() + diff --git a/tests/QtCore/unicode_test.py b/tests/QtCore/unicode_test.py new file mode 100644 index 000000000..f0bb883ed --- /dev/null +++ b/tests/QtCore/unicode_test.py @@ -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() + -- cgit v1.2.3