summaryrefslogtreecommitdiffstats
path: root/tests/auto/corelib/kernel
diff options
context:
space:
mode:
Diffstat (limited to 'tests/auto/corelib/kernel')
-rw-r--r--tests/auto/corelib/kernel/.prev_CMakeLists.txt44
-rw-r--r--tests/auto/corelib/kernel/CMakeLists.txt30
-rw-r--r--tests/auto/corelib/kernel/kernel.pro51
-rw-r--r--tests/auto/corelib/kernel/qapplicationstatic/CMakeLists.txt17
-rw-r--r--tests/auto/corelib/kernel/qapplicationstatic/tst_qapplicationstatic.cpp40
-rw-r--r--tests/auto/corelib/kernel/qchronotimer/.gitignore1
-rw-r--r--tests/auto/corelib/kernel/qchronotimer/CMakeLists.txt33
-rw-r--r--tests/auto/corelib/kernel/qchronotimer/tst_qchronotimer.cpp1266
-rw-r--r--tests/auto/corelib/kernel/qcoreapplication/.prev_CMakeLists.txt29
-rw-r--r--tests/auto/corelib/kernel/qcoreapplication/CMakeLists.txt34
-rw-r--r--tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro9
-rw-r--r--tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp197
-rw-r--r--tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h38
-rw-r--r--tests/auto/corelib/kernel/qdeadlinetimer/BLACKLIST2
-rw-r--r--tests/auto/corelib/kernel/qdeadlinetimer/CMakeLists.txt13
-rw-r--r--tests/auto/corelib/kernel/qdeadlinetimer/qdeadlinetimer.pro5
-rw-r--r--tests/auto/corelib/kernel/qdeadlinetimer/tst_qdeadlinetimer.cpp544
-rw-r--r--tests/auto/corelib/kernel/qelapsedtimer/CMakeLists.txt11
-rw-r--r--tests/auto/corelib/kernel/qelapsedtimer/qelapsedtimer.pro5
-rw-r--r--tests/auto/corelib/kernel/qelapsedtimer/tst_qelapsedtimer.cpp59
-rw-r--r--tests/auto/corelib/kernel/qeventdispatcher/CMakeLists.txt33
-rw-r--r--tests/auto/corelib/kernel/qeventdispatcher/qeventdispatcher.pro4
-rw-r--r--tests/auto/corelib/kernel/qeventdispatcher/tst_qeventdispatcher.cpp314
-rw-r--r--tests/auto/corelib/kernel/qeventloop/BLACKLIST2
-rw-r--r--tests/auto/corelib/kernel/qeventloop/CMakeLists.txt19
-rw-r--r--tests/auto/corelib/kernel/qeventloop/qeventloop.pro8
-rw-r--r--tests/auto/corelib/kernel/qeventloop/tst_qeventloop.cpp83
-rw-r--r--tests/auto/corelib/kernel/qjniarray/CMakeLists.txt13
-rw-r--r--tests/auto/corelib/kernel/qjniarray/tst_qjniarray.cpp165
-rw-r--r--tests/auto/corelib/kernel/qjnienvironment/CMakeLists.txt23
-rw-r--r--tests/auto/corelib/kernel/qjnienvironment/testdata/src/org/qtproject/qt/android/testdata/QtJniEnvironmentTestClass.java60
-rw-r--r--tests/auto/corelib/kernel/qjnienvironment/tst_qjnienvironment.cpp379
-rw-r--r--tests/auto/corelib/kernel/qjniobject/CMakeLists.txt23
-rw-r--r--tests/auto/corelib/kernel/qjniobject/testdata/src/org/qtproject/qt/android/testdata/QtJniObjectTestClass.java345
-rw-r--r--tests/auto/corelib/kernel/qjniobject/tst_qjniobject.cpp2108
-rw-r--r--tests/auto/corelib/kernel/qjnitypes/CMakeLists.txt13
-rw-r--r--tests/auto/corelib/kernel/qjnitypes/tst_qjnitypes.cpp284
-rw-r--r--tests/auto/corelib/kernel/qmath/CMakeLists.txt11
-rw-r--r--tests/auto/corelib/kernel/qmath/qmath.pro4
-rw-r--r--tests/auto/corelib/kernel/qmath/tst_qmath.cpp189
-rw-r--r--tests/auto/corelib/kernel/qmetacontainer/CMakeLists.txt16
-rw-r--r--tests/auto/corelib/kernel/qmetacontainer/qmetacontainer.pro7
-rw-r--r--tests/auto/corelib/kernel/qmetacontainer/tst_qmetacontainer.cpp274
-rw-r--r--tests/auto/corelib/kernel/qmetaenum/CMakeLists.txt11
-rw-r--r--tests/auto/corelib/kernel/qmetaenum/qmetaenum.pro4
-rw-r--r--tests/auto/corelib/kernel/qmetaenum/tst_qmetaenum.cpp38
-rw-r--r--tests/auto/corelib/kernel/qmetamethod/CMakeLists.txt13
-rw-r--r--tests/auto/corelib/kernel/qmetamethod/qmetamethod.pro4
-rw-r--r--tests/auto/corelib/kernel/qmetamethod/tst_qmetamethod.cpp136
-rw-r--r--tests/auto/corelib/kernel/qmetaobject/CMakeLists.txt33
-rw-r--r--tests/auto/corelib/kernel/qmetaobject/forwarddeclared.cpp17
-rw-r--r--tests/auto/corelib/kernel/qmetaobject/forwarddeclared.h12
-rw-r--r--tests/auto/corelib/kernel/qmetaobject/qmetaobject.pro5
-rw-r--r--tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp1203
-rw-r--r--tests/auto/corelib/kernel/qmetaobjectbuilder/CMakeLists.txt13
-rw-r--r--tests/auto/corelib/kernel/qmetaobjectbuilder/qmetaobjectbuilder.pro4
-rw-r--r--tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp339
-rw-r--r--tests/auto/corelib/kernel/qmetaproperty/CMakeLists.txt11
-rw-r--r--tests/auto/corelib/kernel/qmetaproperty/qmetaproperty.pro4
-rw-r--r--tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp67
-rw-r--r--tests/auto/corelib/kernel/qmetatype/.prev_CMakeLists.txt38
-rw-r--r--tests/auto/corelib/kernel/qmetatype/CMakeLists.txt63
-rw-r--r--tests/auto/corelib/kernel/qmetatype/lib1.cpp5
-rw-r--r--tests/auto/corelib/kernel/qmetatype/lib2.cpp5
-rw-r--r--tests/auto/corelib/kernel/qmetatype/lib_common.cpp13
-rw-r--r--tests/auto/corelib/kernel/qmetatype/qmetatype.pro27
-rw-r--r--tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp1746
-rw-r--r--tests/auto/corelib/kernel/qmetatype/tst_qmetatype.h568
-rw-r--r--tests/auto/corelib/kernel/qmetatype/tst_qmetatype2.cpp733
-rw-r--r--tests/auto/corelib/kernel/qmetatype/tst_qmetatype3.cpp14
-rw-r--r--tests/auto/corelib/kernel/qmetatype/tst_qmetatype_common.h269
-rw-r--r--tests/auto/corelib/kernel/qmetatype/tst_qmetatype_libs.h24
-rw-r--r--tests/auto/corelib/kernel/qmimedata/CMakeLists.txt13
-rw-r--r--tests/auto/corelib/kernel/qmimedata/qmimedata.pro4
-rw-r--r--tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp57
-rw-r--r--tests/auto/corelib/kernel/qobject/.prev_CMakeLists.txt19
-rw-r--r--tests/auto/corelib/kernel/qobject/CMakeLists.txt18
-rw-r--r--tests/auto/corelib/kernel/qobject/qobject.pro4
-rw-r--r--tests/auto/corelib/kernel/qobject/signalbug/CMakeLists.txt5
-rw-r--r--tests/auto/corelib/kernel/qobject/signalbug/signalbug.cpp29
-rw-r--r--tests/auto/corelib/kernel/qobject/signalbug/signalbug.h29
-rw-r--r--tests/auto/corelib/kernel/qobject/signalbug/signalbug.pro6
-rw-r--r--tests/auto/corelib/kernel/qobject/test.pro10
-rw-r--r--tests/auto/corelib/kernel/qobject/tst_qobject.cpp1036
-rw-r--r--tests/auto/corelib/kernel/qpermission/.gitignore1
-rw-r--r--tests/auto/corelib/kernel/qpermission/CMakeLists.txt19
-rw-r--r--tests/auto/corelib/kernel/qpermission/tst_qpermission.cpp284
-rw-r--r--tests/auto/corelib/kernel/qpointer/CMakeLists.txt21
-rw-r--r--tests/auto/corelib/kernel/qpointer/qpointer.pro5
-rw-r--r--tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp151
-rw-r--r--tests/auto/corelib/kernel/qproperty/CMakeLists.txt13
-rw-r--r--tests/auto/corelib/kernel/qproperty/qproperty.pro4
-rw-r--r--tests/auto/corelib/kernel/qproperty/tst_qproperty.cpp1784
-rw-r--r--tests/auto/corelib/kernel/qsharedmemory/.prev_CMakeLists.txt23
-rw-r--r--tests/auto/corelib/kernel/qsharedmemory/CMakeLists.txt24
-rw-r--r--tests/auto/corelib/kernel/qsharedmemory/producerconsumer/CMakeLists.txt12
-rw-r--r--tests/auto/corelib/kernel/qsharedmemory/producerconsumer/main.cpp198
-rw-r--r--tests/auto/corelib/kernel/qsharedmemory/producerconsumer/producerconsumer.pro5
-rw-r--r--tests/auto/corelib/kernel/qsharedmemory/qsharedmemory.pro6
-rw-r--r--tests/auto/corelib/kernel/qsharedmemory/test.pro8
-rw-r--r--tests/auto/corelib/kernel/qsharedmemory/tst_qsharedmemory.cpp822
-rw-r--r--tests/auto/corelib/kernel/qsignalblocker/CMakeLists.txt11
-rw-r--r--tests/auto/corelib/kernel/qsignalblocker/qsignalblocker.pro5
-rw-r--r--tests/auto/corelib/kernel/qsignalblocker/tst_qsignalblocker.cpp44
-rw-r--r--tests/auto/corelib/kernel/qsignalmapper/CMakeLists.txt11
-rw-r--r--tests/auto/corelib/kernel/qsignalmapper/qsignalmapper.pro4
-rw-r--r--tests/auto/corelib/kernel/qsignalmapper/tst_qsignalmapper.cpp33
-rw-r--r--tests/auto/corelib/kernel/qsocketnotifier/BLACKLIST3
-rw-r--r--tests/auto/corelib/kernel/qsocketnotifier/CMakeLists.txt22
-rw-r--r--tests/auto/corelib/kernel/qsocketnotifier/qsocketnotifier.pro8
-rw-r--r--tests/auto/corelib/kernel/qsocketnotifier/tst_qsocketnotifier.cpp107
-rw-r--r--tests/auto/corelib/kernel/qsystemsemaphore/CMakeLists.txt14
-rw-r--r--tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/CMakeLists.txt12
-rw-r--r--tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/acquirerelease.pro5
-rw-r--r--tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/main.cpp101
-rw-r--r--tests/auto/corelib/kernel/qsystemsemaphore/qsystemsemaphore.pro3
-rw-r--r--tests/auto/corelib/kernel/qsystemsemaphore/test.pro7
-rw-r--r--tests/auto/corelib/kernel/qsystemsemaphore/tst_qsystemsemaphore.cpp292
-rw-r--r--tests/auto/corelib/kernel/qtimer/BLACKLIST2
-rw-r--r--tests/auto/corelib/kernel/qtimer/CMakeLists.txt43
-rw-r--r--tests/auto/corelib/kernel/qtimer/qtimer.pro7
-rw-r--r--tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp514
-rw-r--r--tests/auto/corelib/kernel/qtranslator/CMakeLists.txt27
-rw-r--r--tests/auto/corelib/kernel/qtranslator/android_testdata.qrc8
-rw-r--r--tests/auto/corelib/kernel/qtranslator/qtranslator.pro9
-rw-r--r--tests/auto/corelib/kernel/qtranslator/qtranslator.qrc6
-rw-r--r--tests/auto/corelib/kernel/qtranslator/tst_qtranslator.cpp165
-rw-r--r--tests/auto/corelib/kernel/qvariant/.prev_CMakeLists.txt44
-rw-r--r--tests/auto/corelib/kernel/qvariant/CMakeLists.txt40
-rw-r--r--tests/auto/corelib/kernel/qvariant/qvariant.pro18
-rw-r--r--tests/auto/corelib/kernel/qvariant/qvariant.qrc6
-rw-r--r--tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp2364
-rw-r--r--tests/auto/corelib/kernel/qwineventnotifier/CMakeLists.txt13
-rw-r--r--tests/auto/corelib/kernel/qwineventnotifier/qwineventnotifier.pro4
-rw-r--r--tests/auto/corelib/kernel/qwineventnotifier/tst_qwineventnotifier.cpp35
-rw-r--r--tests/auto/corelib/kernel/qwinregistrykey/.gitignore1
-rw-r--r--tests/auto/corelib/kernel/qwinregistrykey/CMakeLists.txt15
-rw-r--r--tests/auto/corelib/kernel/qwinregistrykey/tst_qwinregistrykey.cpp242
138 files changed, 15407 insertions, 5672 deletions
diff --git a/tests/auto/corelib/kernel/.prev_CMakeLists.txt b/tests/auto/corelib/kernel/.prev_CMakeLists.txt
deleted file mode 100644
index 154cc8e766..0000000000
--- a/tests/auto/corelib/kernel/.prev_CMakeLists.txt
+++ /dev/null
@@ -1,44 +0,0 @@
-# Generated from kernel.pro.
-
-add_subdirectory(qcoreapplication)
-add_subdirectory(qdeadlinetimer)
-add_subdirectory(qelapsedtimer)
-add_subdirectory(qeventdispatcher)
-add_subdirectory(qmath)
-add_subdirectory(qmetacontainer)
-add_subdirectory(qmetaobject)
-add_subdirectory(qmetaobjectbuilder)
-add_subdirectory(qmetamethod)
-add_subdirectory(qmetaproperty)
-add_subdirectory(qmetatype)
-add_subdirectory(qmetaenum)
-add_subdirectory(qpointer)
-add_subdirectory(qsignalblocker)
-add_subdirectory(qsignalmapper)
-add_subdirectory(qtimer)
-add_subdirectory(qtranslator)
-add_subdirectory(qvariant)
-if(TARGET Qt::Network)
- add_subdirectory(qeventloop)
-endif()
-if(TARGET Qt::Gui)
- add_subdirectory(qmimedata)
-endif()
-if(TARGET Qt::Network AND NOT ANDROID AND NOT UIKIT)
- add_subdirectory(qobject)
-endif()
-if(QT_FEATURE_private_tests AND NOT ANDROID AND NOT UIKIT)
- add_subdirectory(qsharedmemory)
-endif()
-if(QT_FEATURE_private_tests AND TARGET Qt::Network)
- add_subdirectory(qsocketnotifier)
-endif()
-if(QT_FEATURE_systemsemaphore AND NOT ANDROID AND NOT UIKIT)
- add_subdirectory(qsystemsemaphore)
-endif()
-if(win32_x_)
- add_subdirectory(qwineventnotifier)
-endif()
-if(QT_FEATURE_private_tests)
- add_subdirectory(qproperty)
-endif()
diff --git a/tests/auto/corelib/kernel/CMakeLists.txt b/tests/auto/corelib/kernel/CMakeLists.txt
index 85d80e7a3d..c2feb38641 100644
--- a/tests/auto/corelib/kernel/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/CMakeLists.txt
@@ -1,9 +1,11 @@
-# Generated from kernel.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+add_subdirectory(qapplicationstatic)
+add_subdirectory(qchronotimer)
add_subdirectory(qcoreapplication)
add_subdirectory(qdeadlinetimer)
add_subdirectory(qelapsedtimer)
-add_subdirectory(qeventdispatcher)
add_subdirectory(qmath)
add_subdirectory(qmetacontainer)
add_subdirectory(qmetaobject)
@@ -11,34 +13,42 @@ add_subdirectory(qmetaobjectbuilder)
add_subdirectory(qmetamethod)
add_subdirectory(qmetaproperty)
add_subdirectory(qmetaenum)
-add_subdirectory(qpointer)
add_subdirectory(qsignalblocker)
add_subdirectory(qsignalmapper)
add_subdirectory(qtimer)
add_subdirectory(qtranslator)
+# QTBUG-88135
+if(NOT ANDROID)
+ add_subdirectory(qeventdispatcher)
+endif()
if(TARGET Qt::Network)
add_subdirectory(qeventloop)
endif()
if(TARGET Qt::Gui)
add_subdirectory(qmetatype)
add_subdirectory(qmimedata)
+ add_subdirectory(qpointer)
add_subdirectory(qvariant)
endif()
if(TARGET Qt::Network AND NOT ANDROID AND NOT UIKIT)
add_subdirectory(qobject)
endif()
-if(QT_FEATURE_private_tests AND NOT ANDROID AND NOT UIKIT)
- add_subdirectory(qsharedmemory)
-endif()
if(QT_FEATURE_private_tests AND TARGET Qt::Network)
add_subdirectory(qsocketnotifier)
endif()
-if(QT_FEATURE_systemsemaphore AND NOT ANDROID AND NOT UIKIT)
- add_subdirectory(qsystemsemaphore)
-endif()
-if(win32_x_)
+if(WIN32)
add_subdirectory(qwineventnotifier)
+ add_subdirectory(qwinregistrykey)
+endif()
+if(QT_FEATURE_permissions)
+ add_subdirectory(qpermission)
endif()
if(QT_FEATURE_private_tests)
add_subdirectory(qproperty)
endif()
+if(ANDROID)
+ add_subdirectory(qjnienvironment)
+ add_subdirectory(qjniobject)
+ add_subdirectory(qjnitypes)
+ add_subdirectory(qjniarray)
+endif()
diff --git a/tests/auto/corelib/kernel/kernel.pro b/tests/auto/corelib/kernel/kernel.pro
deleted file mode 100644
index 627407b0e4..0000000000
--- a/tests/auto/corelib/kernel/kernel.pro
+++ /dev/null
@@ -1,51 +0,0 @@
-TEMPLATE=subdirs
-SUBDIRS=\
- qcoreapplication \
- qdeadlinetimer \
- qelapsedtimer \
- qeventdispatcher \
- qeventloop \
- qmath \
- qmetacontainer \
- qmetaobject \
- qmetaobjectbuilder \
- qmetamethod \
- qmetaproperty \
- qmetatype \
- qmetaenum \
- qmimedata \
- qobject \
- qpointer \
- qsharedmemory \
- qsignalblocker \
- qsignalmapper \
- qsocketnotifier \
- qsystemsemaphore \
- qtimer \
- qtranslator \
- qvariant \
- qwineventnotifier \
- qproperty
-
-!qtHaveModule(gui): SUBDIRS -= \
- qmimedata \
- qvariant \
- qmetatype
-
-!qtHaveModule(network): SUBDIRS -= \
- qeventloop \
- qobject \
- qsocketnotifier
-
-!qtConfig(private_tests): SUBDIRS -= \
- qsocketnotifier \
- qsharedmemory \
- qproperty
-
-# This test is only applicable on Windows
-!win32*: SUBDIRS -= qwineventnotifier
-
-android|uikit: SUBDIRS -= qobject qsharedmemory qsystemsemaphore
-
-!qtConfig(systemsemaphore): SUBDIRS -= \
- qsystemsemaphore
diff --git a/tests/auto/corelib/kernel/qapplicationstatic/CMakeLists.txt b/tests/auto/corelib/kernel/qapplicationstatic/CMakeLists.txt
new file mode 100644
index 0000000000..9332b6ecd0
--- /dev/null
+++ b/tests/auto/corelib/kernel/qapplicationstatic/CMakeLists.txt
@@ -0,0 +1,17 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+#####################################################################
+## tst_qapplicationstatic Test:
+#####################################################################
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qapplicationstatic LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qapplicationstatic
+ SOURCES
+ tst_qapplicationstatic.cpp
+ )
diff --git a/tests/auto/corelib/kernel/qapplicationstatic/tst_qapplicationstatic.cpp b/tests/auto/corelib/kernel/qapplicationstatic/tst_qapplicationstatic.cpp
new file mode 100644
index 0000000000..dd9a415a52
--- /dev/null
+++ b/tests/auto/corelib/kernel/qapplicationstatic/tst_qapplicationstatic.cpp
@@ -0,0 +1,40 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
+#include <QPointer>
+#include "QtCore/qapplicationstatic.h"
+
+Q_APPLICATION_STATIC(QObject, tstObject)
+
+class tst_qapplicationstatic : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void testCreateMultipleApplications() const;
+};
+
+void tst_qapplicationstatic::testCreateMultipleApplications() const
+{
+ for (int i = 0; i < 5; i++) {
+ int argc = 1;
+ char *argv[] = { (char *)"tst_qapplicationstatic" };
+ auto app = new QCoreApplication(argc, argv);
+
+ QVERIFY(tstObject);
+
+ QPointer<QObject> tstObjectPointer(tstObject);
+ QVERIFY(tstObjectPointer.get());
+
+ QVERIFY2(tstObject->objectName().isEmpty(), "Got QObject from previous iteration, not correctly recreated");
+ tstObject->setObjectName(QStringLiteral("tstObject"));
+ QVERIFY(!tstObject->objectName().isEmpty());
+
+ delete app;
+ QVERIFY2(!tstObjectPointer.get(), "QObject wasn't destroyed on QCoreApplication destruction");
+ }
+}
+
+QTEST_APPLESS_MAIN(tst_qapplicationstatic)
+#include "tst_qapplicationstatic.moc"
diff --git a/tests/auto/corelib/kernel/qchronotimer/.gitignore b/tests/auto/corelib/kernel/qchronotimer/.gitignore
new file mode 100644
index 0000000000..254f7a0281
--- /dev/null
+++ b/tests/auto/corelib/kernel/qchronotimer/.gitignore
@@ -0,0 +1 @@
+tst_qchronotimer
diff --git a/tests/auto/corelib/kernel/qchronotimer/CMakeLists.txt b/tests/auto/corelib/kernel/qchronotimer/CMakeLists.txt
new file mode 100644
index 0000000000..43164858c5
--- /dev/null
+++ b/tests/auto/corelib/kernel/qchronotimer/CMakeLists.txt
@@ -0,0 +1,33 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qchronotimer LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+if (NOT QT_FEATURE_thread)
+ return()
+endif()
+
+function(addChronoTimerTest test)
+ qt_internal_add_test(${test}
+ SOURCES
+ tst_qchronotimer.cpp
+ LIBRARIES
+ Qt::CorePrivate
+ Qt::TestPrivate
+ )
+endfunction()
+
+addChronoTimerTest(tst_qchronotimer)
+
+if(QT_FEATURE_glib AND UNIX)
+ addChronoTimerTest(tst_qchronotimer_no_glib)
+ qt_internal_extend_target(tst_qchronotimer_no_glib
+ DEFINES
+ DISABLE_GLIB
+ tst_QChronoTimer=tst_QChronoTimer_no_glib # Class name in the unittest
+ )
+endif()
diff --git a/tests/auto/corelib/kernel/qchronotimer/tst_qchronotimer.cpp b/tests/auto/corelib/kernel/qchronotimer/tst_qchronotimer.cpp
new file mode 100644
index 0000000000..62c402ae24
--- /dev/null
+++ b/tests/auto/corelib/kernel/qchronotimer/tst_qchronotimer.cpp
@@ -0,0 +1,1266 @@
+// Copyright (C) 2020 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#ifdef QT_GUI_LIB
+# include <QtGui/QGuiApplication>
+#else
+# include <QtCore/QCoreApplication>
+#endif
+
+#include <QtCore/private/qglobal_p.h>
+#include <QTest>
+#include <QSignalSpy>
+#include <QtTest/private/qpropertytesthelper_p.h>
+
+#include <qbasictimer.h>
+#include <qchronotimer.h>
+#include <qthread.h>
+#include <qtimer.h>
+#include <qelapsedtimer.h>
+#include <qproperty.h>
+
+#if defined Q_OS_UNIX
+#include <unistd.h>
+#endif
+
+using namespace std::chrono_literals;
+
+#ifdef DISABLE_GLIB
+static bool glibDisabled = []() {
+ qputenv("QT_NO_GLIB", "1");
+ return true;
+}();
+#endif
+
+class tst_QChronoTimer : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void zeroTimer();
+ void singleShotTimeout(); // Non-static singleShot()
+ void timeout();
+ void sequentialTimers_data();
+ void sequentialTimers();
+ void remainingTime();
+ void remainingTimeInitial_data();
+ void remainingTimeInitial();
+ void remainingTimeDuringActivation_data();
+ void remainingTimeDuringActivation();
+ void basic_chrono();
+ void livelock_data();
+ void livelock();
+ void timerInfiniteRecursion_data();
+ void timerInfiniteRecursion();
+ void recurringTimer_data();
+ void recurringTimer();
+ void deleteLaterOnQChronoTimer(); // long name, don't want to shadow QObject::deleteLater()
+ void moveToThread();
+ void restartedTimerFiresTooSoon();
+ void timerFiresOnlyOncePerProcessEvents_data();
+ void timerFiresOnlyOncePerProcessEvents();
+ void timerIdPersistsAfterThreadExit();
+ void cancelLongTimer();
+ void recurseOnTimeoutAndStopTimer();
+ void timerOrder();
+ void timerOrder_data();
+ void timerOrderBackgroundThread();
+ void timerOrderBackgroundThread_data() { timerOrder_data(); }
+ void timerPrecision();
+
+ void dontBlockEvents();
+ void postedEventsShouldNotStarveTimers();
+ void callOnTimeout();
+
+ void bindToTimer();
+ void bindTimer();
+ void automatedBindingTests();
+
+ void negativeInterval();
+};
+
+void tst_QChronoTimer::zeroTimer()
+{
+ QChronoTimer timer;
+ QVERIFY(!timer.isSingleShot());
+ timer.setInterval(0ns);
+ timer.setSingleShot(true);
+ QVERIFY(timer.isSingleShot());
+
+ QSignalSpy timeoutSpy(&timer, &QChronoTimer::timeout);
+ timer.start();
+
+ // Pass timeout to work round glib issue, see QTBUG-84291.
+ QCoreApplication::processEvents(QEventLoop::AllEvents, INT_MAX);
+
+ QCOMPARE(timeoutSpy.size(), 1);
+}
+
+void tst_QChronoTimer::singleShotTimeout()
+{
+ QChronoTimer timer;
+ QVERIFY(!timer.isSingleShot());
+ timer.setSingleShot(true);
+ QVERIFY(timer.isSingleShot());
+
+ QSignalSpy timeoutSpy(&timer, &QChronoTimer::timeout);
+ timer.setInterval(100ms);
+ timer.start();
+
+ QVERIFY(timeoutSpy.wait(500ms));
+ QCOMPARE(timeoutSpy.size(), 1);
+ QTest::qWait(500ms);
+ QCOMPARE(timeoutSpy.size(), 1);
+}
+
+static constexpr auto Timeout_Interval = 200ms;
+
+void tst_QChronoTimer::timeout()
+{
+ QChronoTimer timer{100ms};
+ QSignalSpy timeoutSpy(&timer, &QChronoTimer::timeout);
+ timer.start();
+
+ QCOMPARE(timeoutSpy.size(), 0);
+
+ QTRY_VERIFY_WITH_TIMEOUT(timeoutSpy.size() > 0, Timeout_Interval);
+ const qsizetype oldCount = timeoutSpy.size();
+
+ QTRY_VERIFY_WITH_TIMEOUT(timeoutSpy.size() > oldCount, Timeout_Interval);
+}
+
+void tst_QChronoTimer::sequentialTimers_data()
+{
+#ifdef Q_OS_WIN
+ QSKIP("The API used by QEventDispatcherWin32 doesn't respect the order");
+#endif
+ QTest::addColumn<QList<std::chrono::milliseconds>>("timeouts");
+ auto addRow = [](const QList<std::chrono::milliseconds> &l) {
+ Q_ASSERT_X(std::is_sorted(l.begin(), l.end()),
+ "tst_QChronoTimer", "input list must be sorted");
+ QByteArray name;
+ for (auto msec : l)
+ name += QByteArray::number(msec.count()) + ',';
+ name.chop(1);
+ QTest::addRow("%s", name.constData()) << l;
+ };
+ // PreciseTimers
+ addRow({0ms, 0ms, 0ms, 0ms, 0ms, 0ms});
+ addRow({0ms, 1ms, 2ms});
+ addRow({1ms, 1ms, 1ms, 2ms, 2ms, 2ms, 2ms});
+ addRow({1ms, 2ms, 3ms});
+ addRow({19ms, 19ms, 19ms});
+ // CoarseTimer for setinterval
+ addRow({20ms, 20ms, 20ms, 20ms, 20ms});
+ addRow({25ms, 25ms, 25ms, 25ms, 25ms, 25ms, 50ms});
+}
+
+void tst_QChronoTimer::sequentialTimers()
+{
+ QFETCH(const QList<std::chrono::milliseconds>, timeouts);
+ QByteArray result, expected;
+ std::vector<std::unique_ptr<QChronoTimer>> timers;
+ expected.resize(timeouts.size());
+ result.reserve(timeouts.size());
+ timers.reserve(timeouts.size());
+ for (int i = 0; i < timeouts.size(); ++i) {
+ auto timer = std::make_unique<QChronoTimer>(timeouts[i]);
+ timer->setSingleShot(true);
+
+ char c = 'A' + i;
+ expected[i] = c;
+ QObject::connect(timer.get(), &QChronoTimer::timeout, this, [&result, c = c]() {
+ result.append(c);
+ });
+ timers.push_back(std::move(timer));
+ }
+
+ // start the timers
+ for (auto &timer : timers)
+ timer->start();
+
+ QTestEventLoop::instance().enterLoop(timeouts.last() * 2 + 10ms);
+
+ QCOMPARE(result, expected);
+}
+
+void tst_QChronoTimer::remainingTime()
+{
+ QChronoTimer tested;
+ tested.setTimerType(Qt::PreciseTimer);
+
+ QChronoTimer tester;
+ tester.setTimerType(Qt::PreciseTimer);
+ tester.setSingleShot(true);
+
+ constexpr auto tested_interval = 200ms;
+ constexpr auto tester_interval = 50ms;
+ constexpr auto expectedRemainingTime = tested_interval - tester_interval;
+
+ int testIteration = 0;
+ const int desiredTestCount = 2;
+
+ // We let tested (which isn't a single-shot) run repeatedly, to verify
+ // it *does* repeat, and check that the single-shot tester, starting
+ // at the same time, does finish first each time, by about the right duration.
+ auto connection = QObject::connect(&tested, &QChronoTimer::timeout,
+ &tester, &QChronoTimer::start);
+
+ QObject::connect(&tester, &QChronoTimer::timeout, this, [&]() {
+ const std::chrono::nanoseconds remainingTime = tested.remainingTime();
+ // We expect that remainingTime is at most 150 and not overdue.
+ const bool remainingTimeInRange = remainingTime > 0ns
+ && remainingTime <= expectedRemainingTime;
+ if (remainingTimeInRange)
+ ++testIteration;
+ else
+ testIteration = desiredTestCount; // We are going to fail on QVERIFY2()
+ // below, so we don't want to iterate
+ // anymore and quickly exit the QTRY_...()
+ // with this failure.
+ if (testIteration == desiredTestCount)
+ QObject::disconnect(connection); // Last iteration, don't start tester again.
+ QVERIFY2(remainingTimeInRange, qPrintable("Remaining time "
+ + QByteArray::number(remainingTime.count()) + "ms outside expected range (0ns, "
+ + QByteArray::number(expectedRemainingTime.count()) + "ms]"));
+ });
+
+ tested.setInterval(tested_interval);
+ tested.start();
+ tester.setInterval(tester_interval);
+ tester.start(); // Start tester for the 1st time.
+
+ // Test it desiredTestCount times, give it reasonable amount of time
+ // (twice as much as needed).
+ const auto tryTimeout = tested_interval * desiredTestCount * 2;
+ QTRY_COMPARE_WITH_TIMEOUT(testIteration, desiredTestCount, tryTimeout);
+}
+
+void tst_QChronoTimer::remainingTimeInitial_data()
+{
+ using namespace std::chrono;
+
+ QTest::addColumn<nanoseconds>("startTimeNs");
+ QTest::addColumn<Qt::TimerType>("timerType");
+
+ QTest::addRow("precisetiemr-0ns") << 0ns << Qt::PreciseTimer;
+ QTest::addRow("precisetimer-1ms") << nanoseconds{1ms} << Qt::PreciseTimer;
+ QTest::addRow("precisetimer-10ms") <<nanoseconds{10ms} << Qt::PreciseTimer;
+
+ QTest::addRow("coarsetimer-0ns") << 0ns << Qt::CoarseTimer;
+ QTest::addRow("coarsetimer-1ms") << nanoseconds{1ms} << Qt::CoarseTimer;
+ QTest::addRow("coarsetimer-10ms") << nanoseconds{10ms} << Qt::CoarseTimer;
+}
+
+void tst_QChronoTimer::remainingTimeInitial()
+{
+ QFETCH(std::chrono::nanoseconds, startTimeNs);
+ QFETCH(Qt::TimerType, timerType);
+
+ QChronoTimer timer;
+ QCOMPARE(timer.timerType(), Qt::CoarseTimer);
+ timer.setTimerType(timerType);
+ QCOMPARE(timer.timerType(), timerType);
+ timer.setInterval(startTimeNs);
+ timer.start();
+
+ const std::chrono::nanoseconds rt = timer.remainingTime();
+ QCOMPARE_GE(rt, 0ns);
+ QCOMPARE_LE(rt, startTimeNs);
+}
+
+void tst_QChronoTimer::remainingTimeDuringActivation_data()
+{
+ QTest::addColumn<bool>("singleShot");
+ QTest::newRow("repeating") << false;
+ QTest::newRow("single-shot") << true;
+}
+
+void tst_QChronoTimer::remainingTimeDuringActivation()
+{
+ QFETCH(bool, singleShot);
+
+ QChronoTimer timer;
+ timer.setSingleShot(singleShot);
+
+ auto remainingTime = 0ns; // not the expected value in either case
+ connect(&timer, &QChronoTimer::timeout, this, [&]() { remainingTime = timer.remainingTime(); });
+ QSignalSpy timeoutSpy(&timer, &QChronoTimer::timeout);
+ // 20 ms is short enough and should not round down to 0 in any timer mode
+ constexpr auto timeout = 20ms;
+ timer.setInterval(timeout);
+ timer.start();
+
+ QVERIFY(timeoutSpy.wait());
+ if (singleShot)
+ QCOMPARE_LT(remainingTime, 0ns); // timer not running
+ else {
+ QCOMPARE_LE(remainingTime, timeout);
+ QCOMPARE_GT(remainingTime, 0ns);
+ }
+
+ if (!singleShot) {
+ // do it again - see QTBUG-46940
+ remainingTime = std::chrono::milliseconds::min();
+ QVERIFY(timeoutSpy.wait());
+ QCOMPARE_LE(remainingTime, timeout);
+ QCOMPARE_GT(remainingTime, 0ns);
+ }
+}
+
+namespace {
+ template <typename T>
+ auto to_ms(T t)
+ {
+ using namespace std::chrono;
+ return duration_cast<milliseconds>(t);
+ }
+} // unnamed namespace
+
+void tst_QChronoTimer::basic_chrono()
+{
+ // duplicates zeroTimer, singleShotTimeout, interval and remainingTime
+ using namespace std::chrono;
+ QChronoTimer timer;
+ QSignalSpy timeoutSpy(&timer, &QChronoTimer::timeout);
+ timer.start();
+ QCOMPARE(timer.interval(), 0ns);
+ QCOMPARE(timer.remainingTime(), 0ns);
+
+ QCoreApplication::processEvents();
+
+ QCOMPARE(timeoutSpy.size(), 1);
+
+ timeoutSpy.clear();
+ timer.setInterval(100ms);
+ timer.start();
+ QCOMPARE(timeoutSpy.size(), 0);
+
+ QVERIFY(timeoutSpy.wait(Timeout_Interval));
+ QVERIFY(timeoutSpy.size() > 0);
+ const qsizetype oldCount = timeoutSpy.size();
+
+ QVERIFY(timeoutSpy.wait(Timeout_Interval));
+ QVERIFY(timeoutSpy.size() > oldCount);
+
+ timeoutSpy.clear();
+ timer.setInterval(200ms);
+ timer.start();
+ QCOMPARE(timer.interval(), 200ms);
+ QTest::qWait(50ms);
+ QCOMPARE(timeoutSpy.size(), 0);
+
+ nanoseconds rt = timer.remainingTime();
+ QCOMPARE_GE(rt, 50ms);
+ QCOMPARE_LE(rt, 200ms);
+
+ timeoutSpy.clear();
+ timer.setSingleShot(true);
+ timer.setInterval(100ms);
+ timer.start();
+ QVERIFY(timeoutSpy.wait(Timeout_Interval));
+ QCOMPARE(timeoutSpy.size(), 1);
+ QTest::qWait(500ms);
+ QCOMPARE(timeoutSpy.size(), 1);
+}
+
+void tst_QChronoTimer::livelock_data()
+{
+ QTest::addColumn<std::chrono::nanoseconds>("interval");
+ QTest::newRow("zero-timer") << 0ns;
+ QTest::newRow("non-zero-timer") << std::chrono::nanoseconds{1ms};
+ QTest::newRow("longer-than-sleep") << std::chrono::nanoseconds{20ms};
+}
+
+/*!
+ *
+ * DO NOT "FIX" THIS TEST! it is written like this for a reason, do
+ * not *change it without first dicussing it with its maintainers.
+ *
+*/
+class LiveLockTester : public QObject
+{
+ static constexpr QEvent::Type PostEventType = static_cast<QEvent::Type>(4002);
+public:
+ LiveLockTester(std::chrono::nanoseconds i)
+ : interval(i)
+ {
+ firstTimerId = startTimer(interval);
+ extraTimerId = startTimer(interval + 80ms);
+ secondTimerId = -1; // started later
+ }
+
+ bool event(QEvent *e) override
+ {
+ if (e->type() == PostEventType) {
+ // got the posted event
+ if (timeoutsForFirst == 1 && timeoutsForSecond == 0)
+ postEventAtRightTime = true;
+ return true;
+ }
+ return QObject::event(e);
+ }
+
+ void timerEvent(QTimerEvent *te) override
+ {
+ if (te->timerId() == firstTimerId) {
+ if (++timeoutsForFirst == 1) {
+ killTimer(extraTimerId);
+ extraTimerId = -1;
+ QCoreApplication::postEvent(this, new QEvent(PostEventType));
+ secondTimerId = startTimer(interval);
+ }
+ } else if (te->timerId() == secondTimerId) {
+ ++timeoutsForSecond;
+ } else if (te->timerId() == extraTimerId) {
+ ++timeoutsForExtra;
+ }
+
+ // sleep for 2ms
+ QTest::qSleep(2);
+ killTimer(te->timerId());
+ }
+
+ const std::chrono::nanoseconds interval;
+ int firstTimerId = -1;
+ int secondTimerId = -1;
+ int extraTimerId = -1;
+ int timeoutsForFirst = 0;
+ int timeoutsForExtra = 0;
+ int timeoutsForSecond = 0;
+ bool postEventAtRightTime = false;
+};
+
+void tst_QChronoTimer::livelock()
+{
+ /*
+ New timers created in timer event handlers should not be sent
+ until the next iteration of the eventloop. Note: this test
+ depends on the fact that we send posted events before timer
+ events (since new posted events are not sent until the next
+ iteration of the eventloop either).
+ */
+ QFETCH(std::chrono::nanoseconds, interval);
+ LiveLockTester tester(interval);
+ QTest::qWait(180ms); // we have to use wait here, since we're testing timers with a non-zero timeout
+ QTRY_COMPARE(tester.timeoutsForFirst, 1);
+ QCOMPARE(tester.timeoutsForExtra, 0);
+ QTRY_COMPARE(tester.timeoutsForSecond, 1);
+ QVERIFY(tester.postEventAtRightTime);
+}
+
+class TimerInfiniteRecursionObject : public QObject
+{
+public:
+ bool inTimerEvent = false;
+ bool timerEventRecursed = false;
+ std::chrono::nanoseconds interval;
+
+ TimerInfiniteRecursionObject(std::chrono::nanoseconds interval)
+ : interval(interval)
+ { }
+
+ void timerEvent(QTimerEvent *timerEvent) override
+ {
+ timerEventRecursed = inTimerEvent;
+ if (timerEventRecursed) {
+ // bug detected!
+ return;
+ }
+
+ inTimerEvent = true;
+
+ QEventLoop eventLoop;
+ QChronoTimer::singleShot(std::max<std::chrono::nanoseconds>(100ms, interval * 2),
+ &eventLoop, &QEventLoop::quit);
+ eventLoop.exec();
+
+ inTimerEvent = false;
+
+ killTimer(timerEvent->timerId());
+ }
+};
+
+void tst_QChronoTimer::timerInfiniteRecursion_data()
+{
+ QTest::addColumn<std::chrono::nanoseconds>("interval");
+ QTest::newRow("zero timer") << 0ns;
+ QTest::newRow("non-zero timer") << std::chrono::nanoseconds{1ms};
+ QTest::newRow("10ms timer") << std::chrono::nanoseconds{10ms};
+ QTest::newRow("11ms timer") << std::chrono::nanoseconds{11ms};
+ QTest::newRow("100ms timer") << std::chrono::nanoseconds{100ms};
+ QTest::newRow("1s timer") << std::chrono::nanoseconds{1000ms};
+}
+
+
+void tst_QChronoTimer::timerInfiniteRecursion()
+{
+ QFETCH(std::chrono::nanoseconds, interval);
+ TimerInfiniteRecursionObject object(interval);
+ (void) object.startTimer(interval);
+
+ QEventLoop eventLoop;
+ QChronoTimer::singleShot(std::max<std::chrono::nanoseconds>(100ms, interval * 2), &eventLoop,
+ &QEventLoop::quit);
+ eventLoop.exec();
+
+ QVERIFY(!object.timerEventRecursed);
+}
+
+class RecurringTimerObject : public QObject
+{
+Q_OBJECT
+public:
+ int times;
+ int target;
+ bool recurse;
+
+ RecurringTimerObject(int target)
+ : times(0), target(target), recurse(false)
+ { }
+
+ void timerEvent(QTimerEvent *timerEvent) override
+ {
+ if (++times == target) {
+ killTimer(timerEvent->timerId());
+ Q_EMIT done();
+ } if (recurse) {
+ QEventLoop eventLoop;
+ QChronoTimer::singleShot(100ms, &eventLoop, &QEventLoop::quit);
+ eventLoop.exec();
+ }
+ }
+
+signals:
+ void done();
+};
+
+void tst_QChronoTimer::recurringTimer_data()
+{
+ QTest::addColumn<std::chrono::nanoseconds>("interval");
+ QTest::addColumn<bool>("recurse");
+ // make sure that eventloop recursion doesn't affect timer recurrence
+ QTest::newRow("zero timer, don't recurse") << 0ns << false;
+ QTest::newRow("zero timer, recurse") << 0ns << true;
+ QTest::newRow("non-zero timer, don't recurse") << std::chrono::nanoseconds{1ms} << false;
+ QTest::newRow("non-zero timer, recurse") << std::chrono::nanoseconds{1ms} << true;
+}
+
+void tst_QChronoTimer::recurringTimer()
+{
+ const int target = 5;
+ QFETCH(std::chrono::nanoseconds, interval);
+ QFETCH(bool, recurse);
+
+ RecurringTimerObject object(target);
+ object.recurse = recurse;
+ QSignalSpy doneSpy(&object, &RecurringTimerObject::done);
+
+ (void) object.startTimer(interval);
+ QVERIFY(doneSpy.wait());
+
+ QCOMPARE(object.times, target);
+}
+
+void tst_QChronoTimer::deleteLaterOnQChronoTimer()
+{
+ QChronoTimer *timer = new QChronoTimer;
+ connect(timer, &QChronoTimer::timeout, timer, &QObject::deleteLater);
+ QSignalSpy destroyedSpy(timer, &QObject::destroyed);
+ timer->setInterval(1ms);
+ timer->setSingleShot(true);
+ timer->start();
+ QPointer<QChronoTimer> pointer = timer;
+ QVERIFY(destroyedSpy.wait());
+ QVERIFY(pointer.isNull());
+}
+
+namespace {
+int operator&(Qt::TimerId id, int i) { return qToUnderlying(id) & i; }
+}
+
+static constexpr auto MoveToThread_Timeout = 200ms;
+static constexpr auto MoveToThread_Wait = 300ms;
+
+void tst_QChronoTimer::moveToThread()
+{
+#if defined(Q_OS_WIN32)
+ QSKIP("Does not work reliably on Windows :(");
+#elif defined(Q_OS_MACOS)
+ QSKIP("Does not work reliably on macOS 10.12+ (QTBUG-59679)");
+#endif
+ QChronoTimer timer1{MoveToThread_Timeout};
+ QChronoTimer timer2{MoveToThread_Timeout};
+ timer1.setSingleShot(true);
+ timer1.start();
+ timer2.start();
+ QVERIFY((timer1.id() & 0xffffff) != (timer2.id() & 0xffffff));
+ QThread tr;
+ timer1.moveToThread(&tr);
+ connect(&timer1, &QChronoTimer::timeout, &tr, &QThread::quit);
+ tr.start();
+ QChronoTimer ti3{MoveToThread_Timeout};
+ ti3.start();
+ QVERIFY((ti3.id() & 0xffffff) != (timer2.id() & 0xffffff));
+ QVERIFY((ti3.id() & 0xffffff) != (timer1.id() & 0xffffff));
+ QTest::qWait(MoveToThread_Wait);
+ QVERIFY(tr.wait());
+ timer2.stop();
+ QChronoTimer ti4{MoveToThread_Timeout};
+ ti4.start();
+ ti3.stop();
+ timer2.setInterval(MoveToThread_Timeout);
+ timer2.start();
+ ti3.setInterval(MoveToThread_Timeout);
+ ti3.start();
+ QVERIFY((ti4.id() & 0xffffff) != (timer2.id() & 0xffffff));
+ QVERIFY((ti3.id() & 0xffffff) != (timer2.id() & 0xffffff));
+ QVERIFY((ti3.id() & 0xffffff) != (timer1.id() & 0xffffff));
+}
+
+class RestartedTimerFiresTooSoonObject : public QObject
+{
+ Q_OBJECT
+
+public:
+ QBasicTimer m_timer;
+
+ std::chrono::milliseconds m_interval = 0ms;
+ QElapsedTimer m_elapsedTimer;
+ QEventLoop eventLoop;
+
+ RestartedTimerFiresTooSoonObject() = default;
+
+ void timerFired()
+ {
+ static std::chrono::milliseconds interval = 1s;
+
+ m_interval = interval;
+ m_elapsedTimer.start();
+ m_timer.start(interval, this);
+
+ // alternate between single-shot and 1 sec
+ interval = interval > 0ms ? 0ms : 1s;
+ }
+
+ void timerEvent(QTimerEvent* ev) override
+ {
+ if (ev->timerId() != m_timer.timerId())
+ return;
+
+ m_timer.stop();
+
+ std::chrono::nanoseconds elapsed = m_elapsedTimer.durationElapsed();
+
+ if (elapsed < m_interval / 2) {
+ // severely too early!
+ m_timer.stop();
+ eventLoop.exit(-1);
+ return;
+ }
+
+ timerFired();
+
+ // don't do this forever
+ static int count = 0;
+ if (count++ > 20) {
+ m_timer.stop();
+ eventLoop.quit();
+ return;
+ }
+ }
+};
+
+void tst_QChronoTimer::restartedTimerFiresTooSoon()
+{
+ RestartedTimerFiresTooSoonObject object;
+ object.timerFired();
+ QCOMPARE(object.eventLoop.exec(), 0);
+}
+
+class LongLastingSlotClass : public QObject
+{
+ Q_OBJECT
+
+public:
+ LongLastingSlotClass(QChronoTimer *timer) : timer(timer) { }
+
+public slots:
+ void longLastingSlot()
+ {
+ // Don't use QChronoTimer for this, because we are testing it.
+ QElapsedTimer control;
+ control.start();
+ while (control.durationElapsed() < 200ms) {
+ for (int c = 0; c < 100'000; c++) {} // Mindless looping.
+ }
+ if (++count >= 2) {
+ timer->stop();
+ }
+ }
+
+public:
+ int count = 0;
+ QChronoTimer *timer;
+};
+
+void tst_QChronoTimer::timerFiresOnlyOncePerProcessEvents_data()
+{
+ QTest::addColumn<std::chrono::nanoseconds>("interval");
+ QTest::newRow("zero-timer") << 0ns;
+ QTest::newRow("non-zero-timer") << std::chrono::nanoseconds{10ms};
+}
+
+void tst_QChronoTimer::timerFiresOnlyOncePerProcessEvents()
+{
+ QFETCH(std::chrono::nanoseconds, interval);
+
+ QChronoTimer t{interval};
+ LongLastingSlotClass longSlot(&t);
+ t.start();
+ connect(&t, &QChronoTimer::timeout, &longSlot, &LongLastingSlotClass::longLastingSlot);
+ // Loop because there may be other events pending.
+ while (longSlot.count == 0)
+ QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents);
+
+ QCOMPARE(longSlot.count, 1);
+}
+
+class TimerIdPersistsAfterThreadExitThread : public QThread
+{
+public:
+ std::unique_ptr<QChronoTimer> timer;
+ Qt::TimerId timerId = Qt::TimerId::Invalid;
+ int returnValue = -1;
+
+ void run() override
+ {
+ QEventLoop eventLoop;
+ timer = std::make_unique<QChronoTimer>();
+ connect(timer.get(), &QChronoTimer::timeout, &eventLoop, &QEventLoop::quit);
+ timer->setInterval(100ms);
+ timer->start();
+ timerId = timer->id();
+ returnValue = eventLoop.exec();
+ }
+};
+
+void tst_QChronoTimer::timerIdPersistsAfterThreadExit()
+{
+ TimerIdPersistsAfterThreadExitThread thread;
+ thread.start();
+ QVERIFY(thread.wait(30s));
+ QCOMPARE(thread.returnValue, 0);
+
+ // even though the thread has exited, and the event dispatcher destroyed, the timer is still
+ // "active", meaning the timer id should NOT be reused (i.e. the event dispatcher should not
+ // have unregistered it)
+ int timerId = thread.startTimer(100ms);
+ QVERIFY((timerId & 0xffffff) != (thread.timerId & 0xffffff));
+}
+
+void tst_QChronoTimer::cancelLongTimer()
+{
+ QChronoTimer timer{1h};
+ timer.setSingleShot(true);
+ timer.start();
+ QCoreApplication::processEvents();
+ // If the timer completes immediately with an error, then this will fail
+ QVERIFY(timer.isActive());
+ timer.stop();
+ QVERIFY(!timer.isActive());
+}
+
+class TimeoutCounter : public QObject
+{
+ Q_OBJECT
+public slots:
+ void timeout() { ++count; };
+public:
+ int count = 0;
+};
+
+class RecursOnTimeoutAndStopTimerTimer : public QObject
+{
+ Q_OBJECT
+
+public:
+ QChronoTimer *one;
+ QChronoTimer *two;
+
+public slots:
+ void onetrigger()
+ {
+ QCoreApplication::processEvents();
+ }
+
+ void twotrigger()
+ {
+ one->stop();
+ }
+};
+
+void tst_QChronoTimer::recurseOnTimeoutAndStopTimer()
+{
+ QEventLoop eventLoop;
+ QChronoTimer::singleShot(1s, &eventLoop, &QEventLoop::quit);
+
+ RecursOnTimeoutAndStopTimerTimer t;
+ t.one = new QChronoTimer(&t);
+ t.two = new QChronoTimer(&t);
+
+ QObject::connect(t.one, SIGNAL(timeout()), &t, SLOT(onetrigger()));
+ QObject::connect(t.two, SIGNAL(timeout()), &t, SLOT(twotrigger()));
+
+ t.two->setSingleShot(true);
+
+ t.one->start();
+ t.two->start();
+
+ (void) eventLoop.exec();
+
+ QVERIFY(!t.one->isActive());
+ QVERIFY(!t.two->isActive());
+}
+
+struct CountedStruct
+{
+ CountedStruct(int *count, QThread *t = nullptr) : count(count), thread(t) { }
+ ~CountedStruct() { }
+ void operator()() const { ++(*count); if (thread) QCOMPARE(QThread::currentThread(), thread); }
+
+ int *count;
+ QThread *thread;
+};
+
+static QScopedPointer<QEventLoop> _e;
+static QThread *_t = nullptr;
+
+class StaticEventLoop
+{
+public:
+ static void quitEventLoop()
+ {
+ quitEventLoop_noexcept();
+ }
+
+ static void quitEventLoop_noexcept() noexcept
+ {
+ QVERIFY(!_e.isNull());
+ _e->quit();
+ if (_t)
+ QCOMPARE(QThread::currentThread(), _t);
+ }
+};
+
+class DontBlockEvents : public QObject
+{
+ Q_OBJECT
+public:
+ DontBlockEvents();
+ void timerEvent(QTimerEvent*) override;
+
+ int count;
+ int total;
+ QBasicTimer m_timer;
+
+public slots:
+ void paintEvent();
+
+};
+
+DontBlockEvents::DontBlockEvents()
+{
+ count = 0;
+ total = 0;
+
+ const std::chrono::milliseconds intervals[] = {2s, 2500ms, 3s, 5s, 1s, 2s};
+ // need a few unrelated timers running to reproduce the bug.
+ for (auto dur : intervals) {
+ auto *t = new QChronoTimer(dur, this);
+ t->start();
+ }
+
+ m_timer.start(1ms, this);
+}
+
+void DontBlockEvents::timerEvent(QTimerEvent* event)
+{
+ if (event->timerId() == m_timer.timerId()) {
+ QMetaObject::invokeMethod(this, &DontBlockEvents::paintEvent, Qt::QueuedConnection);
+ m_timer.start(0ms, this);
+ count++;
+ QCOMPARE(count, 1);
+ total++;
+ }
+}
+
+void DontBlockEvents::paintEvent()
+{
+ count--;
+ QCOMPARE(count, 0);
+}
+
+// This is a regression test for QTBUG-13633, where a timer with a zero
+// timeout that was restarted by the event handler could starve other timers.
+void tst_QChronoTimer::dontBlockEvents()
+{
+ DontBlockEvents t;
+ QTest::qWait(60ms);
+ QTRY_VERIFY(t.total > 2);
+}
+
+class SlotRepeater : public QObject {
+ Q_OBJECT
+public:
+ SlotRepeater() {}
+
+public slots:
+ void repeatThisSlot()
+ {
+ QMetaObject::invokeMethod(this, &SlotRepeater::repeatThisSlot, Qt::QueuedConnection);
+ }
+};
+
+void tst_QChronoTimer::postedEventsShouldNotStarveTimers()
+{
+ QChronoTimer timer;
+ timer.setInterval(0ns);
+ timer.setSingleShot(false);
+ QSignalSpy timeoutSpy(&timer, &QChronoTimer::timeout);
+ timer.start();
+ SlotRepeater slotRepeater;
+ slotRepeater.repeatThisSlot();
+ QTRY_VERIFY_WITH_TIMEOUT(timeoutSpy.size() > 5, 100);
+}
+
+struct DummyFunctor {
+ static QThread *callThread;
+ void operator()() {
+ callThread = QThread::currentThread();
+ callThread->quit();
+ }
+};
+QThread *DummyFunctor::callThread = nullptr;
+
+void tst_QChronoTimer::callOnTimeout()
+{
+ QChronoTimer timer;
+ QSignalSpy timeoutSpy(&timer, &QChronoTimer::timeout);
+ timer.start();
+
+ auto context = std::make_unique<QObject>();
+
+ int count = 0;
+ timer.callOnTimeout([&count] { count++; });
+ QMetaObject::Connection connection = timer.callOnTimeout(context.get(), [&count] { count++; });
+ timer.callOnTimeout(&timer, &QChronoTimer::stop);
+
+
+ QTest::qWait(100ms);
+ QCOMPARE(count, 2);
+ QCOMPARE(timeoutSpy.size(), 1);
+
+ // Test that connection is bound to context lifetime
+ QVERIFY(connection);
+ context.reset();
+ QVERIFY(!connection);
+}
+
+void tst_QChronoTimer::bindToTimer()
+{
+ QChronoTimer timer;
+
+ // singleShot property
+ QProperty<bool> singleShot;
+ singleShot.setBinding(timer.bindableSingleShot().makeBinding());
+ QCOMPARE(timer.isSingleShot(), singleShot);
+
+ timer.setSingleShot(true);
+ QVERIFY(singleShot);
+ timer.setSingleShot(false);
+ QVERIFY(!singleShot);
+
+ // interval property
+ QProperty<std::chrono::nanoseconds> interval;
+ interval.setBinding([&](){ return timer.interval(); });
+ QCOMPARE(timer.interval(), interval.value());
+
+ timer.setInterval(10ms);
+ QCOMPARE(interval.value(), 10ms);
+ timer.setInterval(100ms);
+ QCOMPARE(interval.value(), 100ms);
+
+ // timerType property
+ QProperty<Qt::TimerType> timerType;
+ timerType.setBinding(timer.bindableTimerType().makeBinding());
+ QCOMPARE(timer.timerType(), timerType);
+
+ timer.setTimerType(Qt::PreciseTimer);
+ QCOMPARE(timerType, Qt::PreciseTimer);
+
+ timer.setTimerType(Qt::VeryCoarseTimer);
+ QCOMPARE(timerType, Qt::VeryCoarseTimer);
+
+ // active property
+ QProperty<bool> active;
+ active.setBinding([&](){ return timer.isActive(); });
+ QCOMPARE(active, timer.isActive());
+
+ timer.setInterval(1s);
+ timer.start();
+ QVERIFY(active);
+
+ timer.stop();
+ QVERIFY(!active);
+
+ // Also test that using negative interval updates the binding correctly
+ timer.setInterval(100ms);
+ timer.start();
+ QVERIFY(active);
+
+ auto ignoreMsg = [] {
+ QTest::ignoreMessage(QtWarningMsg,
+ "QObject::startTimer: Timers cannot have negative intervals");
+ };
+
+ ignoreMsg();
+ timer.setInterval(-100ms);
+ ignoreMsg();
+ timer.start();
+ QVERIFY(!active);
+
+ timer.setInterval(100ms);
+ timer.start();
+ QVERIFY(active);
+
+ ignoreMsg();
+ timer.setInterval(-100ms);
+ ignoreMsg();
+ timer.start();
+ QVERIFY(!active);
+}
+
+void tst_QChronoTimer::bindTimer()
+{
+ QChronoTimer timer;
+
+ // singleShot property
+ QVERIFY(!timer.isSingleShot());
+
+ QProperty<bool> singleShot;
+ timer.bindableSingleShot().setBinding(Qt::makePropertyBinding(singleShot));
+
+ singleShot = true;
+ QVERIFY(timer.isSingleShot());
+ singleShot = false;
+ QVERIFY(!timer.isSingleShot());
+
+ // interval property
+ QCOMPARE(timer.interval(), 0ns);
+
+ QProperty<std::chrono::nanoseconds> interval;
+ timer.bindableInterval().setBinding(Qt::makePropertyBinding(interval));
+
+ interval = 10ms;
+ QCOMPARE(timer.interval(), 10ms);
+ interval = 100ms;
+ QCOMPARE(timer.interval(), 100ms);
+ timer.setInterval(50ms);
+ QCOMPARE(timer.interval(), 50ms);
+ interval = 30ms;
+ QCOMPARE(timer.interval(), 50ms);
+
+ // timerType property
+ QCOMPARE(timer.timerType(), Qt::CoarseTimer);
+
+ QProperty<Qt::TimerType> timerType;
+ timer.bindableTimerType().setBinding(Qt::makePropertyBinding(timerType));
+
+ timerType = Qt::PreciseTimer;
+ QCOMPARE(timer.timerType(), Qt::PreciseTimer);
+ timerType = Qt::VeryCoarseTimer;
+ QCOMPARE(timer.timerType(), Qt::VeryCoarseTimer);
+}
+
+void tst_QChronoTimer::automatedBindingTests()
+{
+ QChronoTimer timer;
+
+ QVERIFY(!timer.isSingleShot());
+ QTestPrivate::testReadWritePropertyBasics(timer, true, false, "singleShot");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QChronoTimer::singleShot");
+ return;
+ }
+
+ QCOMPARE_NE(timer.interval(), 10ms);
+ using NSec = std::chrono::nanoseconds;
+ QTestPrivate::testReadWritePropertyBasics(timer, NSec{10ms}, NSec{20ms}, "interval");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QChronoTimer::interval");
+ return;
+ }
+
+ QCOMPARE_NE(timer.timerType(), Qt::PreciseTimer);
+ QTestPrivate::testReadWritePropertyBasics(timer, Qt::PreciseTimer, Qt::CoarseTimer,
+ "timerType");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QChronoTimer::timerType");
+ return;
+ }
+
+ timer.setInterval(1s);
+ timer.start();
+ QVERIFY(timer.isActive());
+ QTestPrivate::testReadOnlyPropertyBasics(timer, true, false, "active",
+ [&timer]() { timer.stop(); });
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QChronoTimer::active");
+ return;
+ }
+}
+
+void tst_QChronoTimer::negativeInterval()
+{
+ QChronoTimer timer;
+
+ auto ignoreMsg = [] {
+ QTest::ignoreMessage(QtWarningMsg,
+ "QObject::startTimer: Timers cannot have negative intervals");
+ };
+
+ ignoreMsg();
+ // Setting a negative interval does not change the active state.
+ timer.setInterval(-100ms);
+ ignoreMsg();
+ timer.start();
+ QVERIFY(!timer.isActive());
+
+ // Starting a timer that has a positive interval, the active state is changed
+ timer.setInterval(100ms);
+ timer.start();
+ QVERIFY(timer.isActive());
+
+ ignoreMsg();
+ // Setting a negative interval on an already running timer...
+ timer.setInterval(-100ms);
+ // ... the timer is stopped and the active state is changed
+ QVERIFY(!timer.isActive());
+
+ // Calling start on a timer that has a negative interval, does not change the active state
+ timer.start();
+ QVERIFY(!timer.isActive());
+}
+
+class OrderHelper : public QObject
+{
+ Q_OBJECT
+public:
+ enum CallType
+ {
+ String,
+ PMF,
+ Functor,
+ FunctorNoCtx
+ };
+ Q_ENUM(CallType)
+ QList<CallType> calls;
+
+ void triggerCall(CallType callType)
+ {
+ switch (callType)
+ {
+ case String:
+ QChronoTimer::singleShot(0ns, this, SLOT(stringSlot()));
+ break;
+ case PMF:
+ QChronoTimer::singleShot(0ns, this, &OrderHelper::pmfSlot);
+ break;
+ case Functor:
+ QChronoTimer::singleShot(0ns, this, [this]() { functorSlot(); });
+ break;
+ case FunctorNoCtx:
+ QChronoTimer::singleShot(0ns, [this]() { functorNoCtxSlot(); });
+ break;
+ }
+ }
+
+public slots:
+ void stringSlot() { calls << String; }
+ void pmfSlot() { calls << PMF; }
+ void functorSlot() { calls << Functor; }
+ void functorNoCtxSlot() { calls << FunctorNoCtx; }
+};
+
+Q_DECLARE_METATYPE(OrderHelper::CallType)
+
+void tst_QChronoTimer::timerOrder()
+{
+ QFETCH(QList<OrderHelper::CallType>, calls);
+
+ OrderHelper helper;
+
+ for (const auto call : calls)
+ helper.triggerCall(call);
+
+ QTRY_COMPARE(helper.calls, calls);
+}
+
+void tst_QChronoTimer::timerOrder_data()
+{
+ QTest::addColumn<QList<OrderHelper::CallType>>("calls");
+
+ QList<OrderHelper::CallType> calls = {
+ OrderHelper::String, OrderHelper::PMF,
+ OrderHelper::Functor, OrderHelper::FunctorNoCtx
+ };
+ std::sort(calls.begin(), calls.end());
+
+ int permutation = 0;
+ do {
+ QTest::addRow("permutation=%d", permutation) << calls;
+ ++permutation;
+ } while (std::next_permutation(calls.begin(), calls.end()));
+}
+
+void tst_QChronoTimer::timerOrderBackgroundThread()
+{
+ auto *thread = QThread::create([this]() { timerOrder(); });
+ thread->start();
+ QVERIFY(thread->wait());
+ delete thread;
+}
+
+void tst_QChronoTimer::timerPrecision()
+{
+ using namespace std::chrono;
+ steady_clock::time_point t1{};
+ steady_clock::time_point t2{};
+
+ QEventLoop loop;
+
+ QChronoTimer zeroTimer{0ns};
+ zeroTimer.setTimerType(Qt::PreciseTimer);
+ zeroTimer.setSingleShot(true);
+ connect(&zeroTimer, &QChronoTimer::timeout, this, [&t1] { t1 = steady_clock::now(); });
+
+ QChronoTimer oneNSecTimer{1ns};
+ oneNSecTimer.setTimerType(Qt::PreciseTimer);
+ oneNSecTimer.setSingleShot(true);
+ connect(&oneNSecTimer, &QChronoTimer::timeout, this, [&t2, &loop] {
+ t2 = steady_clock::now();
+ loop.quit();
+ });
+
+ zeroTimer.start();
+ oneNSecTimer.start();
+ loop.exec();
+ QCOMPARE_GT(t2, t1);
+ // qDebug() << "t2 - t1" << duration<double, std::chrono::milliseconds::period>{t2 - t1};
+}
+
+QTEST_MAIN(tst_QChronoTimer)
+
+#include "tst_qchronotimer.moc"
diff --git a/tests/auto/corelib/kernel/qcoreapplication/.prev_CMakeLists.txt b/tests/auto/corelib/kernel/qcoreapplication/.prev_CMakeLists.txt
deleted file mode 100644
index 08d1338d02..0000000000
--- a/tests/auto/corelib/kernel/qcoreapplication/.prev_CMakeLists.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-# Generated from qcoreapplication.pro.
-
-if(NOT QT_FEATURE_private_tests)
- return()
-endif()
-
-#####################################################################
-## tst_qcoreapplication Test:
-#####################################################################
-
-qt_add_test(tst_qcoreapplication
- SOURCES
- tst_qcoreapplication.cpp tst_qcoreapplication.h
- PUBLIC_LIBRARIES
- Qt::CorePrivate
-)
-
-#### Keys ignored in scope 1:.:.:qcoreapplication.pro:<TRUE>:
-# QMAKE_INFO_PLIST = "$$PWD/Info.plist"
-# _REQUIREMENTS = "qtConfig(private_tests)"
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 2:.:.:qcoreapplication.pro:WIN32:
-# VERSION = "1.2.3.4"
-
-#### Keys ignored in scope 3:.:.:qcoreapplication.pro:else:
-# VERSION = "1.2.3"
diff --git a/tests/auto/corelib/kernel/qcoreapplication/CMakeLists.txt b/tests/auto/corelib/kernel/qcoreapplication/CMakeLists.txt
index e552860688..8f9783088c 100644
--- a/tests/auto/corelib/kernel/qcoreapplication/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qcoreapplication/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qcoreapplication.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qcoreapplication LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -8,38 +15,25 @@ endif()
## tst_qcoreapplication Test:
#####################################################################
-# special case begin
if (WIN32)
set(target_version "1.2.3.4")
else()
set(target_version "1.2.3")
endif()
-# special case end
-qt_add_test(tst_qcoreapplication
- VERSION ${target_version} # special case
+qt_internal_add_test(tst_qcoreapplication
+ VERSION ${target_version}
SOURCES
tst_qcoreapplication.cpp tst_qcoreapplication.h
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
)
-# special case begin
if (APPLE)
set_property(TARGET tst_qcoreapplication PROPERTY MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/Info.plist")
set_property(TARGET tst_qcoreapplication PROPERTY PROPERTY MACOSX_BUNDLE TRUE)
endif()
-# special case end
-#### Keys ignored in scope 1:.:.:qcoreapplication.pro:<TRUE>:
-# QMAKE_INFO_PLIST = "$$PWD/Info.plist"
-# _REQUIREMENTS = "qtConfig(private_tests)"
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 2:.:.:qcoreapplication.pro:WIN32:
-# VERSION = "1.2.3.4"
-
-#### Keys ignored in scope 3:.:.:qcoreapplication.pro:else:
-# VERSION = "1.2.3"
+if (ANDROID)
+ set_property(TARGET tst_qcoreapplication PROPERTY QT_ANDROID_VERSION_NAME ${target_version})
+endif()
diff --git a/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro b/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro
deleted file mode 100644
index 1a76085c1b..0000000000
--- a/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro
+++ /dev/null
@@ -1,9 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qcoreapplication
-QT = core testlib core-private
-SOURCES = tst_qcoreapplication.cpp
-HEADERS = tst_qcoreapplication.h
-win32: VERSION = 1.2.3.4
-else: VERSION = 1.2.3
-QMAKE_INFO_PLIST = $$PWD/Info.plist
-requires(qtConfig(private_tests))
diff --git a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp
index 8b3d0503df..8f8ab33e64 100644
--- a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp
+++ b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp
@@ -1,38 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include "tst_qcoreapplication.h"
#include <QtCore/QtCore>
-#include <QtTest/QtTest>
+#include <QTest>
+#include <private/qabstracteventdispatcher_p.h> // for qGlobalPostedEventsCount()
#include <private/qcoreapplication_p.h>
+#include <private/qcoreevent_p.h>
#include <private/qeventloop_p.h>
#include <private/qthread_p.h>
@@ -48,9 +25,12 @@ class EventSpy : public QObject
public:
QList<int> recordedEvents;
- bool eventFilter(QObject *, QEvent *event) override
+ std::function<void(QObject *, QEvent *)> eventCallback;
+ bool eventFilter(QObject *target, QEvent *event) override
{
recordedEvents.append(event->type());
+ if (eventCallback)
+ eventCallback(target, event);
return false;
}
};
@@ -123,7 +103,7 @@ void tst_QCoreApplication::getSetCheck()
void tst_QCoreApplication::qAppName()
{
-#ifdef QT_GUI_LIB
+#ifdef QT_QGUIAPPLICATIONTEST
const char* appName = "tst_qguiapplication";
#else
const char* appName = "tst_qcoreapplication";
@@ -199,7 +179,7 @@ void tst_QCoreApplication::argc()
char *argv[] = { const_cast<char*>(QTest::currentAppName()) };
TestApplication app(argc, argv);
QCOMPARE(argc, 1);
- QCOMPARE(app.arguments().count(), 1);
+ QCOMPARE(app.arguments().size(), 1);
}
{
@@ -210,7 +190,7 @@ void tst_QCoreApplication::argc()
const_cast<char*>("arg3") };
TestApplication app(argc, argv);
QCOMPARE(argc, 4);
- QCOMPARE(app.arguments().count(), 4);
+ QCOMPARE(app.arguments().size(), 4);
}
{
@@ -218,7 +198,7 @@ void tst_QCoreApplication::argc()
char **argv = 0;
TestApplication app(argc, argv);
QCOMPARE(argc, 0);
- QCOMPARE(app.arguments().count(), 0);
+ QCOMPARE(app.arguments().size(), 0);
}
{
@@ -227,7 +207,7 @@ void tst_QCoreApplication::argc()
const_cast<char*>("-qmljsdebugger=port:3768,block") };
TestApplication app(argc, argv);
QCOMPARE(argc, 1);
- QCOMPARE(app.arguments().count(), 1);
+ QCOMPARE(app.arguments().size(), 1);
}
}
@@ -538,16 +518,13 @@ void tst_QCoreApplication::applicationPid()
QVERIFY(QCoreApplication::applicationPid() > 0);
}
-QT_BEGIN_NAMESPACE
-Q_CORE_EXPORT uint qGlobalPostedEventsCount();
-QT_END_NAMESPACE
-
+#ifdef QT_BUILD_INTERNAL
class GlobalPostedEventsCountObject : public QObject
{
Q_OBJECT
public:
- QList<int> globalPostedEventsCount;
+ QList<qsizetype> globalPostedEventsCount;
bool event(QEvent *event) override
{
@@ -564,7 +541,7 @@ void tst_QCoreApplication::globalPostedEventsCount()
TestApplication app(argc, argv);
QCoreApplication::sendPostedEvents();
- QCOMPARE(qGlobalPostedEventsCount(), 0u);
+ QCOMPARE(qGlobalPostedEventsCount(), qsizetype(0));
GlobalPostedEventsCountObject x;
QCoreApplication::postEvent(&x, new QEvent(QEvent::User));
@@ -572,19 +549,15 @@ void tst_QCoreApplication::globalPostedEventsCount()
QCoreApplication::postEvent(&x, new QEvent(QEvent::User));
QCoreApplication::postEvent(&x, new QEvent(QEvent::User));
QCoreApplication::postEvent(&x, new QEvent(QEvent::User));
- QCOMPARE(qGlobalPostedEventsCount(), 5u);
+ QCOMPARE(qGlobalPostedEventsCount(), qsizetype(5));
QCoreApplication::sendPostedEvents();
- QCOMPARE(qGlobalPostedEventsCount(), 0u);
-
- QList<int> expected = QList<int>()
- << 4
- << 3
- << 2
- << 1
- << 0;
+ QCOMPARE(qGlobalPostedEventsCount(), qsizetype(0));
+
+ const QList<qsizetype> expected = {4, 3, 2, 1, 0};
QCOMPARE(x.globalPostedEventsCount, expected);
}
+#endif // QT_BUILD_INTERNAL
class ProcessEventsAlwaysSendsPostedEventsObject : public QObject
{
@@ -824,13 +797,13 @@ class JobObject : public QObject
Q_OBJECT
public:
- explicit JobObject(QEventLoop *loop, QObject *parent = 0)
+ explicit JobObject(QEventLoop *loop, QObject *parent = nullptr)
: QObject(parent), locker(loop)
{
QTimer::singleShot(1000, this, SLOT(timeout()));
}
- explicit JobObject(QObject *parent = 0)
+ explicit JobObject(QObject *parent = nullptr)
: QObject(parent)
{
QTimer::singleShot(1000, this, SLOT(timeout()));
@@ -860,7 +833,7 @@ class QuitTester : public QObject
{
Q_OBJECT
public:
- QuitTester(QObject *parent = 0)
+ QuitTester(QObject *parent = nullptr)
: QObject(parent)
{
QTimer::singleShot(0, this, SLOT(doTest()));
@@ -1052,7 +1025,7 @@ void tst_QCoreApplication::addRemoveLibPaths()
TestApplication app(argc, argv);
// If libraryPaths only contains currentDir, neither will be in libraryPaths now.
- if (paths.length() != 1 && currentDir != paths[0]) {
+ if (paths.size() != 1 && currentDir != paths[0]) {
// Check that modifications stay alive across the creation of an application.
QVERIFY(QCoreApplication::libraryPaths().contains(currentDir));
QVERIFY(!QCoreApplication::libraryPaths().contains(paths[0]));
@@ -1065,20 +1038,128 @@ void tst_QCoreApplication::addRemoveLibPaths()
}
#endif
+static bool theMainThreadIsSet()
+{
+ // QCoreApplicationPrivate::mainThread() has a Q_ASSERT we'd trigger
+ return QCoreApplicationPrivate::theMainThreadId.loadRelaxed() != nullptr;
+}
+
+static bool theMainThreadWasUnset = !theMainThreadIsSet(); // global static
+void tst_QCoreApplication::theMainThread()
+{
+ QVERIFY2(theMainThreadWasUnset, "Something set the theMainThread before main()");
+ QVERIFY(theMainThreadIsSet()); // we have at LEAST one QObject alive: tst_QCoreApplication
+
+ int argc = 1;
+ char *argv[] = { const_cast<char*>(QTest::currentAppName()) };
+ TestApplication app(argc, argv);
+ QVERIFY(QCoreApplicationPrivate::theMainThreadId.loadRelaxed());
+ QVERIFY(QThread::isMainThread());
+ QCOMPARE(app.thread(), thread());
+ QCOMPARE(app.thread(), QThread::currentThread());
+}
+
static void createQObjectOnDestruction()
{
- // Make sure that we can create a QObject after the last QObject has been
- // destroyed (especially after QCoreApplication has).
- //
+ // Make sure that we can create a QObject (and thus have an associated
+ // QThread) after the last QObject has been destroyed (especially after
+ // QCoreApplication has).
+
+#if !defined(QT_QGUIAPPLICATIONTEST) && !defined(Q_OS_WIN)
+ // QCoreApplicationData's global static destructor has run and cleaned up
+ // the QAdoptedThread.
+ if (theMainThreadIsSet())
+ qFatal("theMainThreadIsSet() returned true; some QObject must have leaked");
+#endif
+
// Before the fixes, this would cause a dangling pointer dereference. If
// the problem comes back, it's possible that the following causes no
// effect.
QObject obj;
obj.thread()->setProperty("testing", 1);
+ if (!theMainThreadIsSet())
+ qFatal("theMainThreadIsSet() returned false");
+
+ // because we created a QObject after QCoreApplicationData was destroyed,
+ // the QAdoptedThread won't get cleaned up
}
Q_DESTRUCTOR_FUNCTION(createQObjectOnDestruction)
-#ifndef QT_GUI_LIB
+void tst_QCoreApplication::testDeleteLaterFromBeforeOutermostEventLoop()
+{
+ int argc = 0;
+ QCoreApplication app(argc, nullptr);
+
+ EventSpy *spy = new EventSpy();
+ QPointer<QObject> spyPointer = spy;
+
+ app.installEventFilter(spy);
+ spy->eventCallback = [spy](QObject *, QEvent *event) {
+ if (event->type() == QEvent::User + 1)
+ spy->deleteLater();
+ };
+
+ QCoreApplication::postEvent(&app, new QEvent(QEvent::Type(QEvent::User + 1)));
+ QCoreApplication::processEvents();
+
+ QEventLoop loop;
+ QTimer::singleShot(0, &loop, &QEventLoop::quit);
+ loop.exec();
+ QVERIFY(!spyPointer);
+}
+
+void tst_QCoreApplication::setIndividualAttributes_data()
+{
+ QTest::addColumn<Qt::ApplicationAttribute>("attribute");
+
+ const QMetaEnum &metaEnum = Qt::staticMetaObject.enumerator(Qt::staticMetaObject.indexOfEnumerator("ApplicationAttribute"));
+ // - 1 to avoid AA_AttributeCount.
+ for (int i = 0; i < metaEnum.keyCount(); ++i) {
+ const auto attribute = static_cast<Qt::ApplicationAttribute>(metaEnum.value(i));
+ if (attribute == Qt::AA_AttributeCount)
+ continue;
+
+ QTest::addRow("%s", metaEnum.key(i)) << attribute;
+ }
+}
+
+void tst_QCoreApplication::setIndividualAttributes()
+{
+ QFETCH(Qt::ApplicationAttribute, attribute);
+
+ const auto originalValue = QCoreApplication::testAttribute(attribute);
+ auto cleanup = qScopeGuard([=]() {
+ QCoreApplication::setAttribute(attribute, originalValue);
+ });
+
+ QCoreApplication::setAttribute(attribute, true);
+ QVERIFY(QCoreApplication::testAttribute(attribute));
+
+ QCoreApplication::setAttribute(attribute, false);
+ QVERIFY(!QCoreApplication::testAttribute(attribute));
+}
+
+void tst_QCoreApplication::setMultipleAttributes()
+{
+ const auto originalDontUseNativeMenuWindowsValue = QCoreApplication::testAttribute(Qt::AA_DontUseNativeMenuWindows);
+ const auto originalDisableSessionManagerValue = QCoreApplication::testAttribute(Qt::AA_DisableSessionManager);
+ auto cleanup = qScopeGuard([=]() {
+ QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuWindows, originalDontUseNativeMenuWindowsValue);
+ QCoreApplication::setAttribute(Qt::AA_DisableSessionManager, originalDisableSessionManagerValue);
+ });
+
+ QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuWindows, true);
+ QCoreApplication::setAttribute(Qt::AA_DisableSessionManager, true);
+ QVERIFY(QCoreApplication::testAttribute(Qt::AA_DontUseNativeMenuWindows));
+ QVERIFY(QCoreApplication::testAttribute(Qt::AA_DisableSessionManager));
+
+ QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuWindows, false);
+ QCoreApplication::setAttribute(Qt::AA_DisableSessionManager, false);
+ QVERIFY(!QCoreApplication::testAttribute(Qt::AA_DontUseNativeMenuWindows));
+ QVERIFY(!QCoreApplication::testAttribute(Qt::AA_DisableSessionManager));
+}
+
+#ifndef QT_QGUIAPPLICATIONTEST
QTEST_APPLESS_MAIN(tst_QCoreApplication)
#endif
diff --git a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h
index 655a879afa..1c25f63534 100644
--- a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h
+++ b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h
@@ -1,31 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#ifndef TST_QCOREAPPLICATION_H
#define TST_QCOREAPPLICATION_H
@@ -47,7 +22,9 @@ private slots:
void deliverInDefinedOrder();
#endif
void applicationPid();
+#ifdef QT_BUILD_INTERNAL
void globalPostedEventsCount();
+#endif
void processEventsAlwaysSendsPostedEvents();
#ifdef Q_OS_WIN
void sendPostedEventsInNativeLoop();
@@ -67,6 +44,11 @@ private slots:
#if QT_CONFIG(library)
void addRemoveLibPaths();
#endif
+ void theMainThread();
+ void testDeleteLaterFromBeforeOutermostEventLoop();
+ void setIndividualAttributes_data();
+ void setIndividualAttributes();
+ void setMultipleAttributes();
};
#endif // TST_QCOREAPPLICATION_H
diff --git a/tests/auto/corelib/kernel/qdeadlinetimer/BLACKLIST b/tests/auto/corelib/kernel/qdeadlinetimer/BLACKLIST
new file mode 100644
index 0000000000..8c6c88c444
--- /dev/null
+++ b/tests/auto/corelib/kernel/qdeadlinetimer/BLACKLIST
@@ -0,0 +1,2 @@
+[stdchrono]
+windows clang ci
diff --git a/tests/auto/corelib/kernel/qdeadlinetimer/CMakeLists.txt b/tests/auto/corelib/kernel/qdeadlinetimer/CMakeLists.txt
index 933f8e937e..2031cd9d48 100644
--- a/tests/auto/corelib/kernel/qdeadlinetimer/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qdeadlinetimer/CMakeLists.txt
@@ -1,10 +1,19 @@
-# Generated from qdeadlinetimer.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qdeadlinetimer Test:
#####################################################################
-qt_add_test(tst_qdeadlinetimer
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qdeadlinetimer LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qdeadlinetimer
SOURCES
tst_qdeadlinetimer.cpp
+ LIBRARIES
+ Qt::TestPrivate
)
diff --git a/tests/auto/corelib/kernel/qdeadlinetimer/qdeadlinetimer.pro b/tests/auto/corelib/kernel/qdeadlinetimer/qdeadlinetimer.pro
deleted file mode 100644
index 12ad7dabc2..0000000000
--- a/tests/auto/corelib/kernel/qdeadlinetimer/qdeadlinetimer.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qdeadlinetimer
-QT = core testlib
-SOURCES = tst_qdeadlinetimer.cpp
-
diff --git a/tests/auto/corelib/kernel/qdeadlinetimer/tst_qdeadlinetimer.cpp b/tests/auto/corelib/kernel/qdeadlinetimer/tst_qdeadlinetimer.cpp
index db53c3f20c..79416faaf9 100644
--- a/tests/auto/corelib/kernel/qdeadlinetimer/tst_qdeadlinetimer.cpp
+++ b/tests/auto/corelib/kernel/qdeadlinetimer/tst_qdeadlinetimer.cpp
@@ -1,51 +1,42 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtCore/QString>
#include <QtCore/QTime>
#include <QtCore/QDeadlineTimer>
#include <QtCore/QElapsedTimer>
-#include <QtTest/QtTest>
+#include <QTest>
+#include <QtTest/private/qcomparisontesthelper_p.h>
+#include <QTimer>
-#if __has_include(<chrono>)
-# include <chrono>
-#endif
+#include <chrono>
+#include <inttypes.h>
static const int minResolution = 400; // the minimum resolution for the tests
-Q_DECLARE_METATYPE(Qt::TimerType)
+QT_BEGIN_NAMESPACE
+namespace QTest {
+template<> char *toString(const QDeadlineTimer &dt)
+{
+ if (dt.isForever())
+ return qstrdup("QDeadlineTimer::Forever");
+
+ qint64 deadline = dt.deadlineNSecs();
+ char *buf = new char[256];
+ qsnprintf(buf, 256, "%lld.%09d%s",
+ deadline / 1000 / 1000 / 1000, qAbs(deadline) % (1000 * 1000 * 1000),
+ dt.hasExpired() ? " (expired)" : "");
+ return buf;
+}
+}
+QT_END_NAMESPACE
class tst_QDeadlineTimer : public QObject
{
Q_OBJECT
private Q_SLOTS:
- void initTestCase_data();
+ void compareCompiles();
void basics();
void foreverness();
void current();
@@ -56,12 +47,11 @@ private Q_SLOTS:
void stdchrono();
};
-void tst_QDeadlineTimer::initTestCase_data()
+static constexpr auto timerType = Qt::PreciseTimer;
+
+void tst_QDeadlineTimer::compareCompiles()
{
- qRegisterMetaType<Qt::TimerType>();
- QTest::addColumn<Qt::TimerType>("timerType");
- QTest::newRow("precise") << Qt::PreciseTimer;
- QTest::newRow("coarse") << Qt::CoarseTimer;
+ QTestPrivate::testAllComparisonOperatorsCompile<QDeadlineTimer>();
}
void tst_QDeadlineTimer::basics()
@@ -69,20 +59,22 @@ void tst_QDeadlineTimer::basics()
QDeadlineTimer deadline;
QCOMPARE(deadline.timerType(), Qt::CoarseTimer);
- QFETCH_GLOBAL(Qt::TimerType, timerType);
deadline = QDeadlineTimer(timerType);
QCOMPARE(deadline.timerType(), timerType);
QVERIFY(!deadline.isForever());
QCOMPARE(deadline, QDeadlineTimer(timerType));
QVERIFY(!(deadline != QDeadlineTimer(timerType)));
QVERIFY(!(deadline < QDeadlineTimer()));
- QVERIFY(deadline <= QDeadlineTimer());
- QVERIFY(deadline >= QDeadlineTimer());
+ QCOMPARE_LE(deadline, QDeadlineTimer());
+ QCOMPARE_GE(deadline, QDeadlineTimer());
QVERIFY(!(deadline > QDeadlineTimer()));
QVERIFY(!(deadline < deadline));
- QVERIFY(deadline <= deadline);
- QVERIFY(deadline >= deadline);
+ QCOMPARE_LE(deadline, deadline);
+ QCOMPARE_GE(deadline, deadline);
QVERIFY(!(deadline > deadline));
+ QT_TEST_ALL_COMPARISON_OPS(deadline, QDeadlineTimer(timerType), Qt::strong_ordering::equal);
+ QT_TEST_ALL_COMPARISON_OPS(deadline, QDeadlineTimer(), Qt::strong_ordering::equal);
+ QT_TEST_ALL_COMPARISON_OPS(QDeadlineTimer(), QDeadlineTimer(), Qt::strong_ordering::equal);
// should have expired, but we may be running too early after boot
QTRY_VERIFY_WITH_TIMEOUT(deadline.hasExpired(), 100);
@@ -95,18 +87,18 @@ void tst_QDeadlineTimer::basics()
deadline.setRemainingTime(0, timerType);
QCOMPARE(deadline.remainingTime(), qint64(0));
QCOMPARE(deadline.remainingTimeNSecs(), qint64(0));
- QVERIFY(deadline.deadline() != 0);
- QVERIFY(deadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(deadline.deadlineNSecs() != 0);
- QVERIFY(deadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadline(), 0);
+ QCOMPARE_NE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
deadline.setPreciseRemainingTime(0, 0, timerType);
QCOMPARE(deadline.remainingTime(), qint64(0));
QCOMPARE(deadline.remainingTimeNSecs(), qint64(0));
- QVERIFY(deadline.deadline() != 0);
- QVERIFY(deadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(deadline.deadlineNSecs() != 0);
- QVERIFY(deadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadline(), 0);
+ QCOMPARE_NE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
deadline.setDeadline(0, timerType);
QCOMPARE(deadline.remainingTime(), qint64(0));
@@ -123,9 +115,6 @@ void tst_QDeadlineTimer::basics()
void tst_QDeadlineTimer::foreverness()
{
- QFETCH_GLOBAL(Qt::TimerType, timerType);
- // we don't check whether timerType() is our type since it's possible it detects it's forever
-
QDeadlineTimer deadline = QDeadlineTimer::Forever;
QCOMPARE(deadline.timerType(), Qt::CoarseTimer);
QVERIFY(deadline.isForever());
@@ -185,9 +174,10 @@ void tst_QDeadlineTimer::foreverness()
QCOMPARE(deadline, deadline);
QVERIFY(!(deadline < deadline));
- QVERIFY(deadline <= deadline);
- QVERIFY(deadline >= deadline);
+ QCOMPARE_LE(deadline, deadline);
+ QCOMPARE_GE(deadline, deadline);
QVERIFY(!(deadline > deadline));
+ QT_TEST_ALL_COMPARISON_OPS(deadline, deadline, Qt::strong_ordering::equal);
// adding to forever must still be forever
QDeadlineTimer deadline2 = deadline + 1;
@@ -202,9 +192,10 @@ void tst_QDeadlineTimer::foreverness()
QCOMPARE(deadline2 - deadline, qint64(0));
QCOMPARE(deadline2, deadline);
QVERIFY(!(deadline2 < deadline));
- QVERIFY(deadline2 <= deadline);
- QVERIFY(deadline2 >= deadline);
+ QCOMPARE_LE(deadline2, deadline);
+ QCOMPARE_GE(deadline2, deadline);
QVERIFY(!(deadline2 > deadline));
+ QT_TEST_ALL_COMPARISON_OPS(deadline2, deadline, Qt::strong_ordering::equal);
// subtracting from forever is *also* forever
deadline2 = deadline - 1;
@@ -219,33 +210,34 @@ void tst_QDeadlineTimer::foreverness()
QCOMPARE(deadline2 - deadline, qint64(0));
QCOMPARE(deadline2, deadline);
QVERIFY(!(deadline2 < deadline));
- QVERIFY(deadline2 <= deadline);
- QVERIFY(deadline2 >= deadline);
+ QCOMPARE_LE(deadline2, deadline);
+ QCOMPARE_GE(deadline2, deadline);
QVERIFY(!(deadline2 > deadline));
+ QT_TEST_ALL_COMPARISON_OPS(deadline2, deadline, Qt::strong_ordering::equal);
// compare and order against a default-constructed object
QDeadlineTimer expired;
QVERIFY(!(deadline == expired));
- QVERIFY(deadline != expired);
+ QCOMPARE_NE(deadline, expired);
QVERIFY(!(deadline < expired));
QVERIFY(!(deadline <= expired));
- QVERIFY(deadline >= expired);
- QVERIFY(deadline > expired);
+ QCOMPARE_GE(deadline, expired);
+ QCOMPARE_GT(deadline, expired);
+ QT_TEST_EQUALITY_OPS(deadline, expired, false);
}
void tst_QDeadlineTimer::current()
{
- QFETCH_GLOBAL(Qt::TimerType, timerType);
auto deadline = QDeadlineTimer::current(timerType);
QVERIFY(deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
QCOMPARE(deadline.remainingTime(), qint64(0));
QCOMPARE(deadline.remainingTimeNSecs(), qint64(0));
- QVERIFY(deadline.deadline() != 0);
- QVERIFY(deadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(deadline.deadlineNSecs() != 0);
- QVERIFY(deadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadline(), 0);
+ QCOMPARE_NE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
// subtracting from current should be "more expired"
QDeadlineTimer earlierDeadline = deadline - 1;
@@ -254,122 +246,123 @@ void tst_QDeadlineTimer::current()
QCOMPARE(earlierDeadline.timerType(), timerType);
QCOMPARE(earlierDeadline.remainingTime(), qint64(0));
QCOMPARE(earlierDeadline.remainingTimeNSecs(), qint64(0));
- QVERIFY(earlierDeadline.deadline() != 0);
- QVERIFY(earlierDeadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(earlierDeadline.deadlineNSecs() != 0);
- QVERIFY(earlierDeadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(earlierDeadline.deadline(), 0);
+ QCOMPARE_NE(earlierDeadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(earlierDeadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(earlierDeadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
QCOMPARE(earlierDeadline.deadline(), deadline.deadline() - 1);
QCOMPARE(earlierDeadline.deadlineNSecs(), deadline.deadlineNSecs() - 1000*1000);
QCOMPARE(earlierDeadline - deadline, qint64(-1));
- QVERIFY(earlierDeadline != deadline);
- QVERIFY(earlierDeadline < deadline);
- QVERIFY(earlierDeadline <= deadline);
+ QCOMPARE_NE(earlierDeadline, deadline);
+ QCOMPARE_LT(earlierDeadline, deadline);
+ QCOMPARE_LE(earlierDeadline, deadline);
QVERIFY(!(earlierDeadline >= deadline));
QVERIFY(!(earlierDeadline > deadline));
+ QT_TEST_ALL_COMPARISON_OPS(earlierDeadline, deadline, Qt::strong_ordering::less);
}
void tst_QDeadlineTimer::deadlines()
{
- QFETCH_GLOBAL(Qt::TimerType, timerType);
-
QDeadlineTimer deadline(4 * minResolution, timerType);
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTime() > (3 * minResolution));
- QVERIFY(deadline.remainingTime() <= (4 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() > (3000000 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() <= (4000000 * minResolution));
- QVERIFY(deadline.deadline() != 0);
- QVERIFY(deadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(deadline.deadlineNSecs() != 0);
- QVERIFY(deadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_GT(deadline.remainingTime(), (3 * minResolution));
+ QCOMPARE_LE(deadline.remainingTime(), (4 * minResolution));
+ QCOMPARE_GT(deadline.remainingTimeNSecs(), (3000000 * minResolution));
+ QCOMPARE_LE(deadline.remainingTimeNSecs(), (4000000 * minResolution));
+ QCOMPARE_NE(deadline.deadline(), 0);
+ QCOMPARE_NE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
deadline.setRemainingTime(4 * minResolution, timerType);
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTime() > (3 * minResolution));
- QVERIFY(deadline.remainingTime() <= (4 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() > (3000000 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() <= (4000000 * minResolution));
- QVERIFY(deadline.deadline() != 0);
- QVERIFY(deadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(deadline.deadlineNSecs() != 0);
- QVERIFY(deadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_GT(deadline.remainingTime(), (3 * minResolution));
+ QCOMPARE_LE(deadline.remainingTime(), (4 * minResolution));
+ QCOMPARE_GT(deadline.remainingTimeNSecs(), (3000000 * minResolution));
+ QCOMPARE_LE(deadline.remainingTimeNSecs(), (4000000 * minResolution));
+ QCOMPARE_NE(deadline.deadline(), 0);
+ QCOMPARE_NE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
deadline.setPreciseRemainingTime(0, 4000000 * minResolution, timerType);
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTime() > (3 * minResolution));
- QVERIFY(deadline.remainingTime() <= (4 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() > (3000000 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() <= (4000000 * minResolution));
- QVERIFY(deadline.deadline() != 0);
- QVERIFY(deadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(deadline.deadlineNSecs() != 0);
- QVERIFY(deadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_GT(deadline.remainingTime(), (3 * minResolution));
+ QCOMPARE_LE(deadline.remainingTime(), (4 * minResolution));
+ QCOMPARE_GT(deadline.remainingTimeNSecs(), (3000000 * minResolution));
+ QCOMPARE_LE(deadline.remainingTimeNSecs(), (4000000 * minResolution));
+ QCOMPARE_NE(deadline.deadline(), 0);
+ QCOMPARE_NE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
deadline.setPreciseRemainingTime(1, 0, timerType); // 1 sec
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTime() > (1000 - minResolution));
- QVERIFY(deadline.remainingTime() <= 1000);
- QVERIFY(deadline.remainingTimeNSecs() > (1000 - minResolution)*1000*1000);
- QVERIFY(deadline.remainingTimeNSecs() <= (1000*1000*1000));
- QVERIFY(deadline.deadline() != 0);
- QVERIFY(deadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(deadline.deadlineNSecs() != 0);
- QVERIFY(deadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_GT(deadline.remainingTime(), (1000 - minResolution));
+ QCOMPARE_LE(deadline.remainingTime(), 1000);
+ QCOMPARE_GT(deadline.remainingTimeNSecs(), (1000 - minResolution)*1000*1000);
+ QCOMPARE_LE(deadline.remainingTimeNSecs(), (1000*1000*1000));
+ QCOMPARE_NE(deadline.deadline(), 0);
+ QCOMPARE_NE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
// adding to a future deadline must still be further in the future
QDeadlineTimer laterDeadline = deadline + 1;
QVERIFY(!laterDeadline.hasExpired());
QVERIFY(!laterDeadline.isForever());
QCOMPARE(laterDeadline.timerType(), timerType);
- QVERIFY(laterDeadline.remainingTime() > (1000 - minResolution));
- QVERIFY(laterDeadline.remainingTime() <= 1001);
- QVERIFY(laterDeadline.remainingTimeNSecs() > (1001 - minResolution)*1000*1000);
- QVERIFY(laterDeadline.remainingTimeNSecs() <= (1001*1000*1000));
- QVERIFY(laterDeadline.deadline() != 0);
- QVERIFY(laterDeadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(laterDeadline.deadlineNSecs() != 0);
- QVERIFY(laterDeadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_GT(laterDeadline.remainingTime(), (1000 - minResolution));
+ QCOMPARE_LE(laterDeadline.remainingTime(), 1001);
+ QCOMPARE_GT(laterDeadline.remainingTimeNSecs(), (1001 - minResolution)*1000*1000);
+ QCOMPARE_LE(laterDeadline.remainingTimeNSecs(), (1001*1000*1000));
+ QCOMPARE_NE(laterDeadline.deadline(), 0);
+ QCOMPARE_NE(laterDeadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(laterDeadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(laterDeadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
QCOMPARE(laterDeadline.deadline(), deadline.deadline() + 1);
QCOMPARE(laterDeadline.deadlineNSecs(), deadline.deadlineNSecs() + 1000*1000);
QCOMPARE(laterDeadline - deadline, qint64(1));
- QVERIFY(laterDeadline != deadline);
+ QCOMPARE_NE(laterDeadline, deadline);
QVERIFY(!(laterDeadline < deadline));
QVERIFY(!(laterDeadline <= deadline));
- QVERIFY(laterDeadline >= deadline);
- QVERIFY(laterDeadline > deadline);
+ QCOMPARE_GE(laterDeadline, deadline);
+ QCOMPARE_GT(laterDeadline, deadline);
+ QT_TEST_ALL_COMPARISON_OPS(laterDeadline, deadline, Qt::strong_ordering::greater);
// compare and order against a default-constructed object
QDeadlineTimer expired;
QVERIFY(!(deadline == expired));
- QVERIFY(deadline != expired);
+ QCOMPARE_NE(deadline, expired);
QVERIFY(!(deadline < expired));
QVERIFY(!(deadline <= expired));
- QVERIFY(deadline >= expired);
- QVERIFY(deadline > expired);
+ QCOMPARE_GE(deadline, expired);
+ QCOMPARE_GT(deadline, expired);
+ QT_TEST_EQUALITY_OPS(deadline, expired, false);
// compare and order against a forever deadline
QDeadlineTimer forever_(QDeadlineTimer::Forever);
+ QT_TEST_EQUALITY_OPS(deadline, forever_, false);
QVERIFY(!(deadline == forever_));
- QVERIFY(deadline != forever_);
- QVERIFY(deadline < forever_);
- QVERIFY(deadline <= forever_);
+ QCOMPARE_NE(deadline, forever_);
+ QCOMPARE_LT(deadline, forever_);
+ QCOMPARE_LE(deadline, forever_);
QVERIFY(!(deadline >= forever_));
QVERIFY(!(deadline > forever_));
}
void tst_QDeadlineTimer::setDeadline()
{
- QFETCH_GLOBAL(Qt::TimerType, timerType);
auto now = QDeadlineTimer::current(timerType);
QDeadlineTimer deadline;
@@ -397,10 +390,10 @@ void tst_QDeadlineTimer::setDeadline()
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTime() > (3 * minResolution));
- QVERIFY(deadline.remainingTime() <= (4 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() > (3000000 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() <= (4000000 * minResolution));
+ QCOMPARE_GT(deadline.remainingTime(), (3 * minResolution));
+ QCOMPARE_LE(deadline.remainingTime(), (4 * minResolution));
+ QCOMPARE_GT(deadline.remainingTimeNSecs(), (3000000 * minResolution));
+ QCOMPARE_LE(deadline.remainingTimeNSecs(), (4000000 * minResolution));
QCOMPARE(deadline.deadline(), now.deadline() + 4 * minResolution); // yes, it's exact
// don't check deadlineNSecs!
@@ -411,17 +404,16 @@ void tst_QDeadlineTimer::setDeadline()
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTime() > (3 * minResolution));
- QVERIFY(deadline.remainingTime() <= (4 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() > (3000000 * minResolution));
- QVERIFY(deadline.remainingTimeNSecs() <= (4000000 * minResolution));
+ QCOMPARE_GT(deadline.remainingTime(), (3 * minResolution));
+ QCOMPARE_LE(deadline.remainingTime(), (4 * minResolution));
+ QCOMPARE_GT(deadline.remainingTimeNSecs(), (3000000 * minResolution));
+ QCOMPARE_LE(deadline.remainingTimeNSecs(), (4000000 * minResolution));
QCOMPARE(deadline.deadline(), nsec / (1000 * 1000));
QCOMPARE(deadline.deadlineNSecs(), nsec);
}
void tst_QDeadlineTimer::overflow()
{
- QFETCH_GLOBAL(Qt::TimerType, timerType);
// Check the constructor for overflows (should also cover saturating the result of the deadline() method if overflowing)
QDeadlineTimer now = QDeadlineTimer::current(timerType), deadline(std::numeric_limits<qint64>::max() - 1, timerType);
QVERIFY(deadline.isForever() || deadline.deadline() >= now.deadline());
@@ -479,27 +471,48 @@ void tst_QDeadlineTimer::overflow()
// However we are tracking the elapsed time, so it shouldn't be a problem.
deadline.setPreciseRemainingTime(1, -1000, timerType);
qint64 difference = (deadline.deadlineNSecs() - nsDeadline) - nsExpected;
- QVERIFY(difference >= 0); // Should always be true, but just in case
- QVERIFY(difference <= callTimer.nsecsElapsed()); // Ideally difference should be 0 exactly
+ QCOMPARE_GE(difference, 0); // Should always be true, but just in case
+ QCOMPARE_LE(difference, callTimer.nsecsElapsed()); // Ideally difference should be 0 exactly
// Make sure setRemainingTime underflows gracefully
deadline.setPreciseRemainingTime(std::numeric_limits<qint64>::min() / 10, 0, timerType);
- QVERIFY(!deadline.isForever()); // On Win/macOS the above underflows, make sure we don't saturate to Forever
- QVERIFY(deadline.remainingTime() == 0);
+ QVERIFY(deadline.isForever()); // The above could underflow, so make sure we did set to Forever
+ QCOMPARE(deadline.remainingTimeNSecs(), -1);
+ QCOMPARE(deadline.remainingTime(), -1);
// If the timer is saturated we don't want to get a valid number of milliseconds
- QVERIFY(deadline.deadline() == std::numeric_limits<qint64>::min());
+ QCOMPARE(deadline.deadline(), std::numeric_limits<qint64>::max());
// Check that the conversion to milliseconds and nanoseconds underflows gracefully
deadline.setPreciseDeadline(std::numeric_limits<qint64>::min() / 10, 0, timerType);
- QVERIFY(!deadline.isForever()); // On Win/macOS the above underflows, make sure we don't saturate to Forever
+ QVERIFY(!deadline.isForever()); // The above underflows, make sure we don't saturate to Forever
QVERIFY(deadline.deadline() == std::numeric_limits<qint64>::min());
QVERIFY(deadline.deadlineNSecs() == std::numeric_limits<qint64>::min());
+
+ // Check that subtracting max() twice doesn't make it become positive
+ deadline.setPreciseDeadline(0);
+ deadline -= std::numeric_limits<qint64>::max();
+ deadline -= std::numeric_limits<qint64>::max();
+ QVERIFY(!deadline.isForever());
+ QCOMPARE(deadline.deadline(), std::numeric_limits<qint64>::min());
+ QCOMPARE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::min());
+
+ // Ditto for adding max()
+ deadline.setPreciseDeadline(0);
+ deadline += std::numeric_limits<qint64>::max();
+ deadline += std::numeric_limits<qint64>::max();
+ QVERIFY(deadline.isForever()); // it's so far in the future it's effectively forever
+ QCOMPARE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
+
+ // But we don't un-become forever after saturation
+ deadline -= std::numeric_limits<qint64>::max();
+ QVERIFY(deadline.isForever());
+ QCOMPARE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
}
void tst_QDeadlineTimer::expire()
{
- QFETCH_GLOBAL(Qt::TimerType, timerType);
-
QDeadlineTimer deadline(minResolution, timerType);
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
@@ -510,20 +523,17 @@ void tst_QDeadlineTimer::expire()
QCOMPARE(deadline.remainingTime(), qint64(0));
QCOMPARE(deadline.remainingTimeNSecs(), qint64(0));
- QVERIFY(deadline.deadline() != 0);
- QVERIFY(deadline.deadline() != std::numeric_limits<qint64>::max());
- QVERIFY(deadline.deadlineNSecs() != 0);
- QVERIFY(deadline.deadlineNSecs() != std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadline(), 0);
+ QCOMPARE_NE(deadline.deadline(), std::numeric_limits<qint64>::max());
+ QCOMPARE_NE(deadline.deadlineNSecs(), 0);
+ QCOMPARE_NE(deadline.deadlineNSecs(), std::numeric_limits<qint64>::max());
QCOMPARE(deadline.deadlineNSecs(), previousDeadline);
}
void tst_QDeadlineTimer::stdchrono()
{
-#if !__has_include(<chrono>)
- QSKIP("std::chrono not found on this system");
-#else
using namespace std::chrono;
- QFETCH_GLOBAL(Qt::TimerType, timerType);
+ using namespace std::chrono_literals;
// create some forevers
QDeadlineTimer deadline = milliseconds::max();
@@ -573,163 +583,157 @@ void tst_QDeadlineTimer::stdchrono()
QCOMPARE(deadline.remainingTimeAsDuration(), nanoseconds::zero());
- /*
- Call QTest::qSleep, and return true if the time actually slept is
- within \a deviationPercent percent of the requested sleep time.
- Otherwise, return false, in which case the test should to abort.
- */
- auto sleepHelper = [](int ms, int deviationPercent = 10) -> bool {
- auto before = steady_clock::now();
- QTest::qSleep(ms);
- auto after = steady_clock::now();
- auto diff = duration_cast<milliseconds>(after - before).count();
- bool inRange = qAbs(diff - ms) < ms * deviationPercent/100.0;
- if (!inRange)
- qWarning() << "sleeping" << diff << "instead of" << ms << inRange;
- return inRange;
- };
+ QDeadlineTimer now;
+ bool timersExecuted = false;
auto steady_before = steady_clock::now();
auto system_before = system_clock::now();
- if (!sleepHelper(minResolution))
- QSKIP("Slept too long");
- auto now = QDeadlineTimer::current(timerType);
- auto steady_reference = steady_clock::now();
- auto system_reference = system_clock::now();
- if (!sleepHelper(minResolution))
- QSKIP("Slept too long");
-
- auto sampling_start = steady_clock::now();
- auto steady_deadline = now.deadline<steady_clock>();
- auto system_deadline = now.deadline<system_clock>();
- auto steady_after = steady_clock::now();
- auto system_after = system_clock::now();
- auto sampling_end = steady_clock::now();
-
- auto sampling_diff = duration_cast<milliseconds>(sampling_end - sampling_start).count();
- if (sampling_diff > minResolution/2) {
- qWarning() << "Sampling clock took" << sampling_diff << "ms";
- QSKIP("Sampling clock took too long, aborting test", Abort);
- }
- auto total_diff = duration_cast<milliseconds>(steady_after - steady_before).count();
- if (total_diff >= 3*minResolution) {
- qWarning() << "Measurement took" << total_diff << "ms";
- QSKIP("Measurement took too long, aborting test", Abort);
+ decltype(steady_before) steady_after, steady_deadline;
+ decltype(system_before) system_after, system_deadline;
+
+ QTimer::singleShot(minResolution, Qt::PreciseTimer, [&]() {
+ now = QDeadlineTimer::current(timerType);
+ QTimer::singleShot(minResolution, Qt::PreciseTimer, [&]() {
+ steady_deadline = now.deadline<steady_clock>();
+ system_deadline = now.deadline<system_clock>();
+ steady_after = steady_clock::now();
+ system_after = system_clock::now();
+ timersExecuted = true;
+ });
+ });
+
+ QTRY_VERIFY2_WITH_TIMEOUT(timersExecuted,
+ "Looks like timers didn't fire on time.", 4 * minResolution);
+
+ {
+ qint64 before = duration_cast<nanoseconds>(steady_before.time_since_epoch()).count();
+ qint64 after = duration_cast<nanoseconds>(steady_after.time_since_epoch()).count();
+ QCOMPARE_GT(now.deadlineNSecs(), before);
+ QCOMPARE_LT(now.deadlineNSecs(), after);
}
{
- auto reference = duration_cast<milliseconds>(steady_after - steady_reference).count();
- auto diff = duration_cast<milliseconds>(steady_after - steady_deadline).count();
- QVERIFY2(diff > reference * 0.9 && diff < reference*1.1, QByteArray::number(qint64(diff)));
+ auto diff = duration_cast<milliseconds>(steady_after - steady_deadline);
+ QCOMPARE_GT(diff.count(), minResolution / 2);
+ QCOMPARE_LT(diff.count(), 3 * minResolution / 2);
QDeadlineTimer dt_after(steady_after, timerType);
- QVERIFY2(now < dt_after,
- ("now = " + QLocale().toString(now.deadlineNSecs()) +
- "; after = " + QLocale().toString(dt_after.deadlineNSecs())).toLatin1());
+ QCOMPARE_LT(now, dt_after);
+ QT_TEST_ALL_COMPARISON_OPS(now, dt_after, Qt::strong_ordering::less);
- reference = duration_cast<milliseconds>(steady_reference - steady_before).count();
- diff = duration_cast<milliseconds>(steady_deadline - steady_before).count();
- QVERIFY2(diff > reference * 0.9 && diff < reference*1.1, QByteArray::number(qint64(diff)));
+ diff = duration_cast<milliseconds>(steady_deadline - steady_before);
+ QCOMPARE_GT(diff.count(), minResolution / 2);
+ QCOMPARE_LT(diff.count(), 3 * minResolution / 2);
QDeadlineTimer dt_before(steady_before, timerType);
- QVERIFY2(now > dt_before,
- ("now = " + QLocale().toString(now.deadlineNSecs()) +
- "; before = " + QLocale().toString(dt_before.deadlineNSecs())).toLatin1());
+ QCOMPARE_GT(now, dt_before);
+ QT_TEST_ALL_COMPARISON_OPS(now, dt_before, Qt::strong_ordering::greater);
}
{
- auto reference = duration_cast<milliseconds>(system_after - system_reference).count();
- auto diff = duration_cast<milliseconds>(system_after - system_deadline).count();
- QVERIFY2(diff > reference * 0.9 && diff < reference*1.1, QByteArray::number(qint64(diff))); QDeadlineTimer dt_after(system_after, timerType);
- QVERIFY2(now < dt_after,
- ("now = " + QLocale().toString(now.deadlineNSecs()) +
- "; after = " + QLocale().toString(dt_after.deadlineNSecs())).toLatin1());
-
- reference = duration_cast<milliseconds>(system_reference - system_before).count();
- diff = duration_cast<milliseconds>(steady_deadline - steady_before).count();
- QVERIFY2(diff > reference * 0.9 && diff < reference*1.1, QByteArray::number(qint64(diff))); QDeadlineTimer dt_before(system_before, timerType);
- QVERIFY2(now > dt_before,
- ("now = " + QLocale().toString(now.deadlineNSecs()) +
- "; before = " + QLocale().toString(dt_before.deadlineNSecs())).toLatin1());
+ auto diff = duration_cast<milliseconds>(system_after - system_deadline);
+ QCOMPARE_GT(diff.count(), minResolution / 2);
+ QCOMPARE_LT(diff.count(), 3 * minResolution / 2);
+ QDeadlineTimer dt_after(system_after, timerType);
+ QCOMPARE_LT(now, dt_after);
+ QT_TEST_ALL_COMPARISON_OPS(now, dt_after, Qt::strong_ordering::less);
+
+ diff = duration_cast<milliseconds>(system_deadline - system_before);
+ QCOMPARE_GT(diff.count(), minResolution / 2);
+ QCOMPARE_LT(diff.count(), 3 * minResolution / 2);
+ QDeadlineTimer dt_before(system_before, timerType);
+ QCOMPARE_GT(now, dt_before);
+ QT_TEST_ALL_COMPARISON_OPS(now, dt_before, Qt::strong_ordering::greater);
}
// make it regular
now = QDeadlineTimer::current(timerType);
- deadline.setRemainingTime(milliseconds(4 * minResolution), timerType);
+ deadline.setRemainingTime(4ms * minResolution, timerType);
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTimeAsDuration() > milliseconds(3 * minResolution));
- QVERIFY(deadline.remainingTimeAsDuration() < milliseconds(5 * minResolution));
- QVERIFY(deadline.remainingTimeAsDuration() > nanoseconds(3000000 * minResolution));
- QVERIFY(deadline.remainingTimeAsDuration() < nanoseconds(5000000 * minResolution));
- QVERIFY(deadline.deadline<steady_clock>() > (steady_clock::now() + milliseconds(3 * minResolution)));
- QVERIFY(deadline.deadline<steady_clock>() < (steady_clock::now() + milliseconds(5 * minResolution)));
- QVERIFY(deadline.deadline<system_clock>() > (system_clock::now() + milliseconds(3 * minResolution)));
- QVERIFY(deadline.deadline<system_clock>() < (system_clock::now() + milliseconds(5 * minResolution)));
- if (timerType == Qt::CoarseTimer) {
- QVERIFY(deadline > (now + milliseconds(3 * minResolution)));
- QVERIFY(deadline < (now + milliseconds(5 * minResolution)));
- QVERIFY(deadline > (now + nanoseconds(3000000 * minResolution)));
- QVERIFY(deadline < (now + nanoseconds(5000000 * minResolution)));
- QVERIFY(deadline > milliseconds(3 * minResolution));
- QVERIFY(deadline < milliseconds(5 * minResolution));
- QVERIFY(deadline > nanoseconds(3000000 * minResolution));
- QVERIFY(deadline < nanoseconds(5000000 * minResolution));
- QVERIFY(deadline >= steady_clock::now());
- QVERIFY(deadline >= system_clock::now());
- }
+ QCOMPARE_GT(deadline.remainingTimeAsDuration(), 3ms * minResolution);
+ QCOMPARE_LT(deadline.remainingTimeAsDuration(), 5ms * minResolution);
+ QCOMPARE_GT(deadline.remainingTimeAsDuration(), 3'000'000ns * minResolution);
+ QCOMPARE_LT(deadline.remainingTimeAsDuration(), 5'000'000ns * minResolution);
+ QCOMPARE_GT(deadline.deadline<steady_clock>(), (steady_clock::now() + 3ms * minResolution));
+ QCOMPARE_LT(deadline.deadline<steady_clock>(), (steady_clock::now() + 5ms * minResolution));
+ QCOMPARE_GT(deadline.deadline<system_clock>(), (system_clock::now() + 3ms * minResolution));
+ QCOMPARE_LT(deadline.deadline<system_clock>(), (system_clock::now() + 5ms * minResolution));
+ QCOMPARE_GT((deadline.deadline<steady_clock, milliseconds>()),
+ steady_clock::now() + 3ms * minResolution);
+ QCOMPARE_LT((deadline.deadline<steady_clock, milliseconds>()),
+ steady_clock::now() + 5ms * minResolution);
+ QCOMPARE_GT((deadline.deadline<system_clock, milliseconds>()),
+ system_clock::now() + 3ms * minResolution);
+ QCOMPARE_LT((deadline.deadline<system_clock, milliseconds>()),
+ system_clock::now() + 5ms * minResolution);
+ QCOMPARE_GT(deadline, now + 3ms * minResolution);
+ QCOMPARE_LT(deadline, now + 5ms * minResolution);
+ QCOMPARE_GT(deadline, now + 3000000ns * minResolution);
+ QCOMPARE_LT(deadline, now + 5000000ns * minResolution);
+ QCOMPARE_GT(deadline, 3ms * minResolution);
+ QCOMPARE_LT(deadline, 5ms * minResolution);
+ QCOMPARE_GT(deadline, 3000000ns * minResolution);
+ QCOMPARE_LT(deadline, 5000000ns * minResolution);
+ QCOMPARE_GE(deadline, steady_clock::now());
+ QCOMPARE_GE(deadline, system_clock::now());
+ QT_TEST_ALL_COMPARISON_OPS(deadline, now + 3ms * minResolution, Qt::strong_ordering::greater);
+ QT_TEST_ALL_COMPARISON_OPS(deadline, now + 5ms * minResolution, Qt::strong_ordering::less);
+ QT_TEST_ALL_COMPARISON_OPS(deadline, now + 3000000ns * minResolution, Qt::strong_ordering::greater);
+ QT_TEST_ALL_COMPARISON_OPS(deadline, now + 5000000ns * minResolution, Qt::strong_ordering::less);
+ QT_TEST_ALL_COMPARISON_OPS(deadline, 3ms * minResolution, Qt::strong_ordering::greater);
+ QT_TEST_ALL_COMPARISON_OPS(deadline, 5ms * minResolution, Qt::strong_ordering::less);
+ QT_TEST_ALL_COMPARISON_OPS(deadline, steady_clock::now(), Qt::strong_ordering::greater);
+ QT_TEST_ALL_COMPARISON_OPS(deadline, system_clock::now(), Qt::strong_ordering::greater);
now = QDeadlineTimer::current(timerType);
- deadline = QDeadlineTimer(seconds(1), timerType);
+ deadline = QDeadlineTimer(1s, timerType);
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTimeAsDuration() > (seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline.remainingTimeAsDuration() <= seconds(1));
- QVERIFY(deadline.deadline<steady_clock>() > (steady_clock::now() + seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline.deadline<steady_clock>() <= (steady_clock::now() + seconds(1) + milliseconds(minResolution)));
- QVERIFY(deadline.deadline<system_clock>() > (system_clock::now() + seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline.deadline<system_clock>() <= (system_clock::now() + seconds(1) + milliseconds(minResolution)));
- if (timerType == Qt::CoarseTimer) {
- QVERIFY(deadline > (seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline <= seconds(1));
- }
+ QCOMPARE_GT(deadline.remainingTimeAsDuration(), 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline.remainingTimeAsDuration(), 1s);
+ QCOMPARE_GT(deadline.deadline<steady_clock>(), steady_clock::now() + 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline.deadline<steady_clock>(), steady_clock::now() + 1s + 1ms * minResolution);
+ QCOMPARE_GT(deadline.deadline<system_clock>(), system_clock::now() + 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline.deadline<system_clock>(), system_clock::now() + 1s + 1ms * minResolution);
+ QCOMPARE_GT(deadline, 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline, 1s);
now = QDeadlineTimer::current(timerType);
- deadline.setRemainingTime(hours(1), timerType);
+ deadline.setRemainingTime(1h, timerType);
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTimeAsDuration() > (hours(1) - milliseconds(minResolution)));
- QVERIFY(deadline.remainingTimeAsDuration() <= hours(1));
- QVERIFY(deadline.deadline<steady_clock>() > (steady_clock::now() + hours(1) - milliseconds(minResolution)));
- QVERIFY(deadline.deadline<steady_clock>() <= (steady_clock::now() + hours(1) + milliseconds(minResolution)));
- QVERIFY(deadline.deadline<system_clock>() > (system_clock::now() + hours(1) - milliseconds(minResolution)));
- QVERIFY(deadline.deadline<system_clock>() <= (system_clock::now() + hours(1) + milliseconds(minResolution)));
+ QCOMPARE_GT(deadline.remainingTimeAsDuration(), 1h - 1ms * minResolution);
+ QCOMPARE_LE(deadline.remainingTimeAsDuration(), 1h);
+ QCOMPARE_GT(deadline.deadline<steady_clock>(), steady_clock::now() + 1h - 1ms * minResolution);
+ QCOMPARE_LE(deadline.deadline<steady_clock>(), steady_clock::now() + 1h + 1ms * minResolution);
+ QCOMPARE_GT(deadline.deadline<system_clock>(), system_clock::now() + 1h - 1ms * minResolution);
+ QCOMPARE_LE(deadline.deadline<system_clock>(), system_clock::now() + 1h + 1ms * minResolution);
now = QDeadlineTimer::current(timerType);
- deadline.setDeadline(system_clock::now() + seconds(1), timerType);
+ deadline.setDeadline(system_clock::now() + 1s, timerType);
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTimeAsDuration() > (seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline.remainingTimeAsDuration() <= seconds(1));
- QVERIFY(deadline.deadline<steady_clock>() > (steady_clock::now() + seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline.deadline<steady_clock>() <= (steady_clock::now() + seconds(1) + milliseconds(minResolution)));
- QVERIFY(deadline.deadline<system_clock>() > (system_clock::now() + seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline.deadline<system_clock>() <= (system_clock::now() + seconds(1) + milliseconds(minResolution)));
+ QCOMPARE_GT(deadline.remainingTimeAsDuration(), 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline.remainingTimeAsDuration(), 1s);
+ QCOMPARE_GT(deadline.deadline<steady_clock>(), steady_clock::now() + 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline.deadline<steady_clock>(), steady_clock::now() + 1s + 1ms * minResolution);
+ QCOMPARE_GT(deadline.deadline<system_clock>(), system_clock::now() + 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline.deadline<system_clock>(), system_clock::now() + 1s + 1ms * minResolution);
now = QDeadlineTimer::current(timerType);
- deadline.setDeadline(steady_clock::now() + seconds(1), timerType);
+ deadline.setDeadline(steady_clock::now() + 1s, timerType);
QVERIFY(!deadline.hasExpired());
QVERIFY(!deadline.isForever());
QCOMPARE(deadline.timerType(), timerType);
- QVERIFY(deadline.remainingTimeAsDuration() > (seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline.remainingTimeAsDuration() <= seconds(1));
- QVERIFY(deadline.deadline<steady_clock>() > (steady_clock::now() + seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline.deadline<steady_clock>() <= (steady_clock::now() + seconds(1) + milliseconds(minResolution)));
- QVERIFY(deadline.deadline<system_clock>() > (system_clock::now() + seconds(1) - milliseconds(minResolution)));
- QVERIFY(deadline.deadline<system_clock>() <= (system_clock::now() + seconds(1) + milliseconds(minResolution)));
-#endif
+ QCOMPARE_GT(deadline.remainingTimeAsDuration(), 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline.remainingTimeAsDuration(), 1s);
+ QCOMPARE_GT(deadline.deadline<steady_clock>(), steady_clock::now() + 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline.deadline<steady_clock>(), steady_clock::now() + 1s + 1ms * minResolution);
+ QCOMPARE_GT(deadline.deadline<system_clock>(), system_clock::now() + 1s - 1ms * minResolution);
+ QCOMPARE_LE(deadline.deadline<system_clock>(), system_clock::now() + 1s + 1ms * minResolution);
}
QTEST_MAIN(tst_QDeadlineTimer)
diff --git a/tests/auto/corelib/kernel/qelapsedtimer/CMakeLists.txt b/tests/auto/corelib/kernel/qelapsedtimer/CMakeLists.txt
index e88fb72bec..9a40a2f905 100644
--- a/tests/auto/corelib/kernel/qelapsedtimer/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qelapsedtimer/CMakeLists.txt
@@ -1,10 +1,17 @@
-# Generated from qelapsedtimer.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qelapsedtimer Test:
#####################################################################
-qt_add_test(tst_qelapsedtimer
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qelapsedtimer LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qelapsedtimer
SOURCES
tst_qelapsedtimer.cpp
)
diff --git a/tests/auto/corelib/kernel/qelapsedtimer/qelapsedtimer.pro b/tests/auto/corelib/kernel/qelapsedtimer/qelapsedtimer.pro
deleted file mode 100644
index 657a63a5d7..0000000000
--- a/tests/auto/corelib/kernel/qelapsedtimer/qelapsedtimer.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qelapsedtimer
-QT = core testlib
-SOURCES = tst_qelapsedtimer.cpp
-
diff --git a/tests/auto/corelib/kernel/qelapsedtimer/tst_qelapsedtimer.cpp b/tests/auto/corelib/kernel/qelapsedtimer/tst_qelapsedtimer.cpp
index d0b6992fce..7623fd2e43 100644
--- a/tests/auto/corelib/kernel/qelapsedtimer/tst_qelapsedtimer.cpp
+++ b/tests/auto/corelib/kernel/qelapsedtimer/tst_qelapsedtimer.cpp
@@ -1,43 +1,21 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+#include <QtCore/QDateTime>
#include <QtCore/QString>
-#include <QtCore/QTime>
#include <QtCore/QElapsedTimer>
-#include <QtTest/QtTest>
+#include <QTest>
+#include <QTimer>
static const int minResolution = 100; // the minimum resolution for the tests
+QT_BEGIN_NAMESPACE
QDebug operator<<(QDebug s, const QElapsedTimer &t)
{
s.nospace() << "(" << t.msecsSinceReference() << ")";
return s.space();
}
+QT_END_NAMESPACE
class tst_QElapsedTimer : public QObject
{
@@ -53,11 +31,25 @@ private Q_SLOTS:
void tst_QElapsedTimer::statics()
{
- qDebug() << "Clock type is" << QElapsedTimer::clockType();
- qDebug() << "Said clock is" << (QElapsedTimer::isMonotonic() ? "monotonic" : "not monotonic");
+ // these have been required since Qt 6.6
+ QCOMPARE(QElapsedTimer::clockType(), QElapsedTimer::MonotonicClock);
+ QVERIFY(QElapsedTimer::isMonotonic());
+
QElapsedTimer t;
t.start();
- qDebug() << "Current time is" << t.msecsSinceReference();
+ qint64 system_now = QDateTime::currentMSecsSinceEpoch();
+
+ auto setprecision = +[](QTextStream &s) -> QTextStream & {
+ s.setRealNumberNotation(QTextStream::FixedNotation);
+ s.setRealNumberPrecision(3);
+ return s;
+ };
+ qDebug() << setprecision
+ << "Current monotonic time is" << (t.msecsSinceReference() / 1000.)
+ << "s and current system time is" << (system_now / 1000.) << 's';
+ if (qAbs(system_now - t.msecsSinceReference()) < 5 * minResolution)
+ qWarning() << "The monotonic clock is awfully close to the system clock"
+ " (it may not be monotonic at all!)";
}
void tst_QElapsedTimer::validity()
@@ -126,7 +118,8 @@ void tst_QElapsedTimer::elapsed()
timerExecuted = true;
});
- QTRY_VERIFY_WITH_TIMEOUT(timerExecuted, 4 * minResolution);
+ QTRY_VERIFY2_WITH_TIMEOUT(timerExecuted,
+ "Looks like timer didn't fire on time.", 4 * minResolution);
QVERIFY(nsecs > 0);
QVERIFY(msecs > 0);
diff --git a/tests/auto/corelib/kernel/qeventdispatcher/CMakeLists.txt b/tests/auto/corelib/kernel/qeventdispatcher/CMakeLists.txt
index 1893dedc30..1f9cfb9449 100644
--- a/tests/auto/corelib/kernel/qeventdispatcher/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qeventdispatcher/CMakeLists.txt
@@ -1,10 +1,33 @@
-# Generated from qeventdispatcher.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qeventdispatcher Test:
#####################################################################
-qt_add_test(tst_qeventdispatcher
- SOURCES
- tst_qeventdispatcher.cpp
-)
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qeventdispatcher LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+set(test_names "tst_qeventdispatcher")
+if(QT_FEATURE_glib AND UNIX)
+ list(APPEND test_names "tst_qeventdispatcher_no_glib")
+endif()
+
+foreach(test ${test_names})
+ qt_internal_add_test(${test}
+ NO_BATCH
+ SOURCES
+ tst_qeventdispatcher.cpp
+ )
+endforeach()
+
+if (TARGET tst_qeventdispatcher_no_glib)
+ qt_internal_extend_target(tst_qeventdispatcher_no_glib
+ DEFINES
+ DISABLE_GLIB
+ tst_QEventDispatcher=tst_QEventDispatcher_no_glib
+ )
+endif()
diff --git a/tests/auto/corelib/kernel/qeventdispatcher/qeventdispatcher.pro b/tests/auto/corelib/kernel/qeventdispatcher/qeventdispatcher.pro
deleted file mode 100644
index ff048d0429..0000000000
--- a/tests/auto/corelib/kernel/qeventdispatcher/qeventdispatcher.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qeventdispatcher
-QT = core testlib
-SOURCES += tst_qeventdispatcher.cpp
diff --git a/tests/auto/corelib/kernel/qeventdispatcher/tst_qeventdispatcher.cpp b/tests/auto/corelib/kernel/qeventdispatcher/tst_qeventdispatcher.cpp
index fa5c78bceb..285d080960 100644
--- a/tests/auto/corelib/kernel/qeventdispatcher/tst_qeventdispatcher.cpp
+++ b/tests/auto/corelib/kernel/qeventdispatcher/tst_qeventdispatcher.cpp
@@ -1,44 +1,49 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#ifdef QT_GUI_LIB
# include <QtGui/QGuiApplication>
-# define tst_QEventDispatcher tst_QGuiEventDispatcher
#else
# include <QtCore/QCoreApplication>
#endif
-#include <QtTest/QtTest>
+#include <QTest>
+#include <QAbstractEventDispatcher>
+#include <QTimer>
+#include <QThreadPool>
+
+#ifdef DISABLE_GLIB
+static bool glibDisabled = []() {
+ qputenv("QT_NO_GLIB", "1");
+ return true;
+}();
+#endif
-enum {
- PreciseTimerInterval = 10,
- CoarseTimerInterval = 200,
- VeryCoarseTimerInterval = 1000
-};
+#include <chrono>
+
+using namespace std::chrono_literals;
+
+static constexpr auto PreciseTimerInterval = 10ms;
+static constexpr auto CoarseTimerInterval = 200ms;
+static constexpr auto VeryCoarseTimerInterval = 1s;
+
+static constexpr
+std::chrono::nanoseconds fudgeInterval(std::chrono::nanoseconds interval, Qt::TimerType timerType)
+{
+ // Make the intervals have have fractions of milliseconds so we can check
+ // that they have been rounded & stored properly (where applicable).
+ switch (timerType) {
+ case Qt::VeryCoarseTimer:
+ // rounds down (floor) to seconds
+ return interval + 1010us;
+ case Qt::CoarseTimer:
+ // rounds up (ceil) to milliseconds
+ return interval - 10us;
+ case Qt::PreciseTimer:
+ // not rounded using QAbstractEventDispatcherV2; rounded up (ceil) on V1
+ return interval - 10us;
+ }
+ Q_UNREACHABLE_RETURN(std::chrono::nanoseconds::min());
+}
class tst_QEventDispatcher : public QObject
{
@@ -56,19 +61,31 @@ protected:
public:
inline tst_QEventDispatcher()
: QObject(),
- eventDispatcher(QAbstractEventDispatcher::instance(thread()))
+ eventDispatcher(QAbstractEventDispatcher::instance(thread())),
+ isGuiEventDispatcher(QCoreApplication::instance()->inherits("QGuiApplication"))
{ }
private slots:
void initTestCase();
+ void cleanup();
+
void registerTimer();
+
/* void registerSocketNotifier(); */ // Not implemented here, see tst_QSocketNotifier instead
/* void registerEventNotifiier(); */ // Not implemented here, see tst_QWinEventNotifier instead
void sendPostedEvents_data();
void sendPostedEvents();
void processEventsOnlySendsQueuedEvents();
+ // these two tests need to run before postedEventsPingPong
+ void postEventFromThread();
+ void postEventFromEventHandler();
+ // these tests don't leave the event dispatcher in a reliable state
void postedEventsPingPong();
void eventLoopExit();
+ void interruptTrampling();
+
+private:
+ const bool isGuiEventDispatcher;
};
bool tst_QEventDispatcher::event(QEvent *e)
@@ -91,11 +108,15 @@ bool tst_QEventDispatcher::event(QEvent *e)
// drain the system event queue after the test starts to avoid destabilizing the test functions
void tst_QEventDispatcher::initTestCase()
{
- QElapsedTimer elapsedTimer;
- elapsedTimer.start();
- while (!elapsedTimer.hasExpired(CoarseTimerInterval) && eventDispatcher->processEvents(QEventLoop::AllEvents)) {
- ;
- }
+ QDeadlineTimer deadline(CoarseTimerInterval);
+ while (!deadline.hasExpired() && eventDispatcher->processEvents(QEventLoop::AllEvents))
+ ;
+}
+
+// consume pending posted events to avoid impact on the next test function
+void tst_QEventDispatcher::cleanup()
+{
+ eventDispatcher->processEvents(QEventLoop::AllEvents);
}
class TimerManager {
@@ -116,35 +137,36 @@ public:
TimerManager(TimerManager &&) = delete;
TimerManager &operator=(TimerManager &&) = delete;
- int preciseTimerId() const { return m_preciseTimerId; }
- int coarseTimerId() const { return m_coarseTimerId; }
- int veryCoarseTimerId() const { return m_veryCoarseTimerId; }
+ int preciseTimerId() const { return int(m_preciseTimerId); }
+ int coarseTimerId() const { return int(m_coarseTimerId); }
+ int veryCoarseTimerId() const { return int(m_veryCoarseTimerId); }
- bool foundPrecise() const { return m_preciseTimerId > 0; }
- bool foundCoarse() const { return m_coarseTimerId > 0; }
- bool foundVeryCoarse() const { return m_veryCoarseTimerId > 0; }
+ bool foundPrecise() const { return preciseTimerId() > 0; }
+ bool foundCoarse() const { return coarseTimerId() > 0; }
+ bool foundVeryCoarse() const { return veryCoarseTimerId() > 0; }
- QList<QAbstractEventDispatcher::TimerInfo> registeredTimers() const
+ QList<QAbstractEventDispatcher::TimerInfoV2> registeredTimers() const
{
- return m_eventDispatcher->registeredTimers(m_parent);
+ return m_eventDispatcher->timersForObject(m_parent);
}
void registerAll()
{
// start 3 timers, each with the different timer types and different intervals
- m_preciseTimerId = m_eventDispatcher->registerTimer(
- PreciseTimerInterval, Qt::PreciseTimer, m_parent);
- m_coarseTimerId = m_eventDispatcher->registerTimer(
- CoarseTimerInterval, Qt::CoarseTimer, m_parent);
- m_veryCoarseTimerId = m_eventDispatcher->registerTimer(
- VeryCoarseTimerInterval, Qt::VeryCoarseTimer, m_parent);
- QVERIFY(m_preciseTimerId > 0);
- QVERIFY(m_coarseTimerId > 0);
- QVERIFY(m_veryCoarseTimerId > 0);
+ auto registerTimer = [&](std::chrono::milliseconds interval, Qt::TimerType timerType) {
+ return m_eventDispatcher->registerTimer(fudgeInterval(interval, timerType), timerType,
+ m_parent);
+ };
+ m_preciseTimerId = registerTimer(PreciseTimerInterval, Qt::PreciseTimer);
+ m_coarseTimerId = registerTimer(CoarseTimerInterval, Qt::CoarseTimer);
+ m_veryCoarseTimerId = registerTimer(VeryCoarseTimerInterval, Qt::VeryCoarseTimer);
+ QVERIFY(foundPrecise());
+ QVERIFY(foundCoarse());
+ QVERIFY(foundVeryCoarse());
findTimers();
}
- void unregister(int timerId)
+ void unregister(Qt::TimerId timerId)
{
m_eventDispatcher->unregisterTimer(timerId);
findTimers();
@@ -162,36 +184,43 @@ private:
bool foundPrecise = false;
bool foundCoarse = false;
bool foundVeryCoarse = false;
- const QList<QAbstractEventDispatcher::TimerInfo> timers = registeredTimers();
- for (int i = 0; i < timers.count(); ++i) {
- const QAbstractEventDispatcher::TimerInfo &timerInfo = timers.at(i);
+ const QList<QAbstractEventDispatcher::TimerInfoV2> timers = registeredTimers();
+ for (const QAbstractEventDispatcher::TimerInfoV2 &timerInfo : timers) {
if (timerInfo.timerId == m_preciseTimerId) {
- QCOMPARE(timerInfo.interval, int(PreciseTimerInterval));
+ // For precise timers, we expect the fudge factor to be present
+ QAbstractEventDispatcher::Duration interval =
+ fudgeInterval(PreciseTimerInterval, Qt::PreciseTimer);
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
+ if (!qobject_cast<QAbstractEventDispatcherV2 *>(m_eventDispatcher))
+ interval = PreciseTimerInterval;
+#endif
+ QCOMPARE(timerInfo.interval, interval);
QCOMPARE(timerInfo.timerType, Qt::PreciseTimer);
foundPrecise = true;
} else if (timerInfo.timerId == m_coarseTimerId) {
- QCOMPARE(timerInfo.interval, int(CoarseTimerInterval));
+ // For other timers, the fudge factors ought to have been rounded away
+ QCOMPARE(timerInfo.interval, CoarseTimerInterval);
QCOMPARE(timerInfo.timerType, Qt::CoarseTimer);
foundCoarse = true;
} else if (timerInfo.timerId == m_veryCoarseTimerId) {
- QCOMPARE(timerInfo.interval, int(VeryCoarseTimerInterval));
+ QCOMPARE(timerInfo.interval, VeryCoarseTimerInterval);
QCOMPARE(timerInfo.timerType, Qt::VeryCoarseTimer);
foundVeryCoarse = true;
}
}
if (!foundPrecise)
- m_preciseTimerId = -1;
+ m_preciseTimerId = Qt::TimerId::Invalid;
if (!foundCoarse)
- m_coarseTimerId = -1;
+ m_coarseTimerId = Qt::TimerId::Invalid;
if (!foundVeryCoarse)
- m_veryCoarseTimerId = -1;
+ m_veryCoarseTimerId = Qt::TimerId::Invalid;
}
QAbstractEventDispatcher *m_eventDispatcher = nullptr;
- int m_preciseTimerId = -1;
- int m_coarseTimerId = -1;
- int m_veryCoarseTimerId = -1;
+ Qt::TimerId m_preciseTimerId = Qt::TimerId::Invalid;
+ Qt::TimerId m_coarseTimerId = Qt::TimerId::Invalid;
+ Qt::TimerId m_veryCoarseTimerId = Qt::TimerId::Invalid;
QObject *m_parent = nullptr;
};
@@ -205,7 +234,7 @@ void tst_QEventDispatcher::registerTimer()
return;
// check that all 3 are present in the eventDispatcher's registeredTimer() list
- QCOMPARE(timers.registeredTimers().count(), 3);
+ QCOMPARE(timers.registeredTimers().size(), 3);
QVERIFY(timers.foundPrecise());
QVERIFY(timers.foundCoarse());
QVERIFY(timers.foundVeryCoarse());
@@ -231,16 +260,16 @@ void tst_QEventDispatcher::registerTimer()
if (doubleTimer)
QSKIP("Double timer during a single timeout - aborting test as flaky on macOS");
if (timerIdFromEvent != timers.preciseTimerId()
- && elapsedTimer.elapsed() > PreciseTimerInterval * 3)
+ && elapsedTimer.durationElapsed() > PreciseTimerInterval * 3)
QSKIP("Ignore flaky test behavior due to VM scheduling on macOS");
#endif
QCOMPARE(timerIdFromEvent, timers.preciseTimerId());
// now unregister it and make sure it's gone
- timers.unregister(timers.preciseTimerId());
+ timers.unregister(Qt::TimerId(timers.preciseTimerId()));
if (QTest::currentTestFailed())
return;
- QCOMPARE(timers.registeredTimers().count(), 2);
+ QCOMPARE(timers.registeredTimers().size(), 2);
QVERIFY(!timers.foundPrecise());
QVERIFY(timers.foundCoarse());
QVERIFY(timers.foundVeryCoarse());
@@ -255,16 +284,16 @@ void tst_QEventDispatcher::registerTimer()
if (doubleTimer)
QSKIP("Double timer during a single timeout - aborting test as flaky on macOS");
if (timerIdFromEvent != timers.coarseTimerId()
- && elapsedTimer.elapsed() > CoarseTimerInterval * 3)
+ && elapsedTimer.durationElapsed() > CoarseTimerInterval * 3)
QSKIP("Ignore flaky test behavior due to VM scheduling on macOS");
#endif
QCOMPARE(timerIdFromEvent, timers.coarseTimerId());
// now unregister it and make sure it's gone
- timers.unregister(timers.coarseTimerId());
+ timers.unregister(Qt::TimerId(timers.coarseTimerId()));
if (QTest::currentTestFailed())
return;
- QCOMPARE(timers.registeredTimers().count(), 1);
+ QCOMPARE(timers.registeredTimers().size(), 1);
QVERIFY(!timers.foundPrecise());
QVERIFY(!timers.foundCoarse());
QVERIFY(timers.foundVeryCoarse());
@@ -290,9 +319,8 @@ void tst_QEventDispatcher::sendPostedEvents()
QFETCH(int, processEventsFlagsInt);
QEventLoop::ProcessEventsFlags processEventsFlags = QEventLoop::ProcessEventsFlags(processEventsFlagsInt);
- QElapsedTimer elapsedTimer;
- elapsedTimer.start();
- while (!elapsedTimer.hasExpired(200)) {
+ QDeadlineTimer deadline(200ms);
+ while (!deadline.hasExpired()) {
receivedEventType = -1;
QCoreApplication::postEvent(this, new QEvent(QEvent::User));
@@ -350,6 +378,96 @@ void tst_QEventDispatcher::processEventsOnlySendsQueuedEvents()
QCOMPARE(object.eventsReceived, 4);
}
+void tst_QEventDispatcher::postEventFromThread()
+{
+ QThreadPool *threadPool = QThreadPool::globalInstance();
+ QAtomicInt hadToQuit = false;
+ QAtomicInt done = false;
+
+ threadPool->start([&]{
+ int loop = 1000 / 10; // give it a second
+ while (!done && --loop)
+ QThread::sleep(std::chrono::milliseconds{10});
+ if (done)
+ return;
+ hadToQuit = true;
+ QCoreApplication::eventDispatcher()->wakeUp();
+ });
+
+ struct EventReceiver : public QObject {
+ bool event(QEvent* event) override {
+ if (event->type() == QEvent::User)
+ return true;
+ return QObject::event(event);
+ }
+ } receiver;
+
+ int count = 500;
+ while (!hadToQuit && --count) {
+ threadPool->start([&receiver]{
+ QCoreApplication::postEvent(&receiver, new QEvent(QEvent::User));
+ });
+
+ QAbstractEventDispatcher::instance()->processEvents(QEventLoop::WaitForMoreEvents);
+ }
+ done = true;
+
+ QVERIFY(!hadToQuit);
+ QVERIFY(threadPool->waitForDone());
+}
+
+void tst_QEventDispatcher::postEventFromEventHandler()
+{
+ QThreadPool *threadPool = QThreadPool::globalInstance();
+ QAtomicInt hadToQuit = false;
+ QAtomicInt done = false;
+
+ threadPool->start([&]{
+ int loop = 250 / 10; // give it 250ms
+ while (!done && --loop)
+ QThread::sleep(std::chrono::milliseconds{10});
+ if (done)
+ return;
+ hadToQuit = true;
+ QCoreApplication::eventDispatcher()->wakeUp();
+ });
+
+ struct EventReceiver : public QObject {
+ int i = 0;
+ bool event(QEvent* event) override
+ {
+ if (event->type() == QEvent::User) {
+ ++i;
+ if (i < 2)
+ QCoreApplication::postEvent(this, new QEvent(QEvent::User));
+ return true;
+ }
+ return QObject::event(event);
+ }
+ } receiver;
+ QCoreApplication::postEvent(&receiver, new QEvent(QEvent::User));
+ while (receiver.i < 2)
+ QAbstractEventDispatcher::instance()->processEvents(QEventLoop::WaitForMoreEvents);
+ done = true;
+
+ const QByteArrayView eventDispatcherName(QAbstractEventDispatcher::instance()->metaObject()->className());
+ qDebug() << eventDispatcherName;
+ // QXcbUnixEventDispatcher and QEventDispatcherUNIX do not do this correctly on any platform;
+ // both Windows event dispatchers fail as well.
+ const bool knownToFail = eventDispatcherName.contains("UNIX")
+ || eventDispatcherName.contains("Unix")
+ || eventDispatcherName.contains("Win32")
+ || eventDispatcherName.contains("WindowsGui")
+ || eventDispatcherName.contains("Android");
+
+ if (knownToFail)
+ QEXPECT_FAIL("", eventDispatcherName.constData(), Continue);
+
+ QVERIFY(!hadToQuit);
+ QVERIFY(threadPool->waitForDone());
+}
+
+
void tst_QEventDispatcher::postedEventsPingPong()
{
QEventLoop mainLoop;
@@ -368,7 +486,7 @@ void tst_QEventDispatcher::postedEventsPingPong()
// We should use Qt::CoarseTimer on Windows, to prevent event
// dispatcher from sending a posted event.
- QTimer::singleShot(500, Qt::CoarseTimer, [&mainLoop]() {
+ QTimer::singleShot(500, Qt::CoarseTimer, &mainLoop, [&mainLoop]() {
mainLoop.exit(1);
});
@@ -385,12 +503,12 @@ void tst_QEventDispatcher::eventLoopExit()
// Imitates QApplication::exec():
QEventLoop mainLoop;
// The test itself is a lambda:
- QTimer::singleShot(0, [&mainLoop]() {
+ QTimer::singleShot(0, &mainLoop, [&mainLoop]() {
// Two more single shots, both will be posted as events
// (zero timeout) and supposed to be processes by the
// mainLoop:
- QTimer::singleShot(0, [&mainLoop]() {
+ QTimer::singleShot(0, &mainLoop, [&mainLoop]() {
// wakeUp triggers QCocoaEventDispatcher into incrementing
// its 'serialNumber':
mainLoop.wakeUp();
@@ -399,7 +517,7 @@ void tst_QEventDispatcher::eventLoopExit()
QCoreApplication::processEvents();
});
- QTimer::singleShot(0, [&mainLoop]() {
+ QTimer::singleShot(0, &mainLoop, [&mainLoop]() {
// With QCocoaEventDispatcher this is executed while in the
// processEvents (see above) and would fail to actually
// interrupt the loop.
@@ -408,7 +526,7 @@ void tst_QEventDispatcher::eventLoopExit()
});
bool timeoutObserved = false;
- QTimer::singleShot(500, [&timeoutObserved, &mainLoop]() {
+ QTimer::singleShot(500, &mainLoop, [&timeoutObserved, &mainLoop]() {
// In case the QEventLoop::exit above failed, we have to bail out
// early, not wasting time:
mainLoop.exit();
@@ -419,5 +537,31 @@ void tst_QEventDispatcher::eventLoopExit()
QVERIFY(!timeoutObserved);
}
+// Based on QTBUG-91539: In the event dispatcher on Windows we overwrite the
+// interrupt once we start processing events (this pattern is also in the 'unix' dispatcher)
+// which would lead the dispatcher to accidentally ignore certain interrupts and,
+// as in the bug report, would not quit, leaving the thread alive and running.
+void tst_QEventDispatcher::interruptTrampling()
+{
+ class WorkerThread : public QThread
+ {
+ void run() override {
+ auto dispatcher = eventDispatcher();
+ QVERIFY(dispatcher);
+ dispatcher->processEvents(QEventLoop::AllEvents);
+ QTimer::singleShot(0, dispatcher, [dispatcher]() {
+ dispatcher->wakeUp();
+ });
+ dispatcher->processEvents(QEventLoop::WaitForMoreEvents);
+ dispatcher->interrupt();
+ dispatcher->processEvents(QEventLoop::WaitForMoreEvents);
+ }
+ };
+ WorkerThread thread;
+ thread.start();
+ QVERIFY(thread.wait(1000));
+ QVERIFY(thread.isFinished());
+}
+
QTEST_MAIN(tst_QEventDispatcher)
#include "tst_qeventdispatcher.moc"
diff --git a/tests/auto/corelib/kernel/qeventloop/BLACKLIST b/tests/auto/corelib/kernel/qeventloop/BLACKLIST
new file mode 100644
index 0000000000..772ec3312c
--- /dev/null
+++ b/tests/auto/corelib/kernel/qeventloop/BLACKLIST
@@ -0,0 +1,2 @@
+[processEvents]
+qnx # QTBUG-119359
diff --git a/tests/auto/corelib/kernel/qeventloop/CMakeLists.txt b/tests/auto/corelib/kernel/qeventloop/CMakeLists.txt
index b09f6715e1..5d90f97b21 100644
--- a/tests/auto/corelib/kernel/qeventloop/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qeventloop/CMakeLists.txt
@@ -1,13 +1,20 @@
-# Generated from qeventloop.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qeventloop Test:
#####################################################################
-qt_add_test(tst_qeventloop
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qeventloop LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qeventloop
SOURCES
tst_qeventloop.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::Network
)
@@ -15,12 +22,12 @@ qt_add_test(tst_qeventloop
## Scopes:
#####################################################################
-qt_extend_target(tst_qeventloop CONDITION WIN32
- PUBLIC_LIBRARIES
+qt_internal_extend_target(tst_qeventloop CONDITION WIN32
+ LIBRARIES
user32
)
-qt_extend_target(tst_qeventloop CONDITION QT_FEATURE_glib
+qt_internal_extend_target(tst_qeventloop CONDITION QT_FEATURE_glib
DEFINES
HAVE_GLIB
)
diff --git a/tests/auto/corelib/kernel/qeventloop/qeventloop.pro b/tests/auto/corelib/kernel/qeventloop/qeventloop.pro
deleted file mode 100644
index 827ecec883..0000000000
--- a/tests/auto/corelib/kernel/qeventloop/qeventloop.pro
+++ /dev/null
@@ -1,8 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qeventloop
-QT = core network testlib core-private
-SOURCES = $$PWD/tst_qeventloop.cpp
-
-win32: QMAKE_USE += user32
-
-qtConfig(glib): DEFINES += HAVE_GLIB
diff --git a/tests/auto/corelib/kernel/qeventloop/tst_qeventloop.cpp b/tests/auto/corelib/kernel/qeventloop/tst_qeventloop.cpp
index 3765b6fbf8..06175e6f2f 100644
--- a/tests/auto/corelib/kernel/qeventloop/tst_qeventloop.cpp
+++ b/tests/auto/corelib/kernel/qeventloop/tst_qeventloop.cpp
@@ -1,32 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
#include <qabstracteventdispatcher.h>
#include <qcoreapplication.h>
@@ -34,7 +9,9 @@
#include <qeventloop.h>
#include <private/qeventloop_p.h>
#if defined(Q_OS_UNIX)
- #include <private/qeventdispatcher_unix_p.h>
+ #if !defined(Q_OS_WASM)
+ #include <private/qeventdispatcher_unix_p.h>
+ #endif
#include <QtCore/private/qcore_unix_p.h>
#if defined(HAVE_GLIB)
#include <private/qeventdispatcher_glib_p.h>
@@ -46,6 +23,7 @@
#include <qwaitcondition.h>
#include <QTcpServer>
#include <QTcpSocket>
+#include <QSignalSpy>
class EventLoopExiter : public QObject
{
@@ -86,7 +64,7 @@ void EventLoopThread::run()
emit checkPoint();
(void) eventLoop->exec();
delete eventLoop;
- eventLoop = 0;
+ eventLoop = nullptr;
}
class MultipleExecThread : public QThread
@@ -126,7 +104,7 @@ public:
class StartStopEvent: public QEvent
{
public:
- explicit StartStopEvent(int type, QEventLoop *loop = 0)
+ explicit StartStopEvent(int type, QEventLoop *loop = nullptr)
: QEvent(Type(type)), el(loop)
{ }
@@ -162,6 +140,7 @@ class tst_QEventLoop : public QObject
Q_OBJECT
private slots:
// This test *must* run first. See the definition for why.
+ void processEvents_data();
void processEvents();
void exec();
void reexec();
@@ -183,8 +162,21 @@ protected:
void customEvent(QEvent *e) override;
};
+void tst_QEventLoop::processEvents_data()
+{
+ QTest::addColumn<QString>("mode");
+
+#ifdef QT_GUI_LIB
+ QTest::addRow("gui") << "gui";
+#else
+ QTest::addRow("core") << "core";
+#endif
+}
+
void tst_QEventLoop::processEvents()
{
+ QFETCH(QString, mode);
+
QSignalSpy aboutToBlockSpy(QAbstractEventDispatcher::instance(), &QAbstractEventDispatcher::aboutToBlock);
QSignalSpy awakeSpy(QAbstractEventDispatcher::instance(), &QAbstractEventDispatcher::awake);
@@ -198,8 +190,8 @@ void tst_QEventLoop::processEvents()
// process posted events, QEventLoop::processEvents() should return
// true
QVERIFY(eventLoop.processEvents());
- QCOMPARE(aboutToBlockSpy.count(), 0);
- QCOMPARE(awakeSpy.count(), 1);
+ QCOMPARE(aboutToBlockSpy.size(), 0);
+ QCOMPARE(awakeSpy.size(), 1);
// allow any session manager to complete its handshake, so that
// there are no pending events left. This tests that we are able
@@ -220,8 +212,8 @@ void tst_QEventLoop::processEvents()
// processEvents is entered. There is no guarantee that that the
// processEvents call actually blocked, since the OS may introduce
// native events at any time.
- QVERIFY(awakeSpy.count() > 0);
- QVERIFY(awakeSpy.count() >= aboutToBlockSpy.count());
+ QVERIFY(awakeSpy.size() > 0);
+ QVERIFY(awakeSpy.size() >= aboutToBlockSpy.size());
killTimer(timerId);
}
@@ -264,7 +256,7 @@ void tst_QEventLoop::exec()
QVERIFY(spy.isValid());
thread.cond.wakeOne();
thread.cond.wait(&thread.mutex);
- QVERIFY(spy.count() > 0);
+ QVERIFY(spy.size() > 0);
int v = thread.result1;
QCOMPARE(v, 0);
@@ -273,7 +265,7 @@ void tst_QEventLoop::exec()
thread.cond.wakeOne();
thread.mutex.unlock();
thread.wait();
- QCOMPARE(spy.count(), 0);
+ QCOMPARE(spy.size(), 0);
v = thread.result2;
QCOMPARE(v, -1);
}
@@ -331,7 +323,7 @@ void tst_QEventLoop::wakeUp()
QTimer::singleShot(1000, &eventLoop, SLOT(quit()));
(void) eventLoop.exec();
- QVERIFY(spy.count() > 0);
+ QVERIFY(spy.size() > 0);
thread.quit();
(void) eventLoop.exec();
@@ -424,8 +416,8 @@ public slots:
dataSent = serverSocket->waitForBytesWritten(-1);
if (dataSent) {
- pollfd pfd = qt_make_pollfd(socket->socketDescriptor(), POLLIN);
- dataReadable = (1 == qt_safe_poll(&pfd, 1, nullptr));
+ pollfd pfd = qt_make_pollfd(int(socket->socketDescriptor()), POLLIN);
+ dataReadable = (1 == qt_safe_poll(&pfd, 1, QDeadlineTimer::Forever));
}
if (!dataReadable) {
@@ -510,7 +502,7 @@ void tst_QEventLoop::processEventsExcludeTimers()
// but not if we exclude timers
eventLoop.processEvents(QEventLoop::X11ExcludeTimers);
-#if defined(Q_OS_UNIX)
+#if defined(Q_OS_UNIX) && !defined(Q_OS_WASM)
QAbstractEventDispatcher *eventDispatcher = QCoreApplication::eventDispatcher();
if (!qobject_cast<QEventDispatcherUNIX *>(eventDispatcher)
#if defined(HAVE_GLIB)
@@ -569,7 +561,8 @@ void tst_QEventLoop::deliverInDefinedOrder()
using namespace DeliverInDefinedOrder;
qMetaTypeId<QThread*>();
QThread threads[NbThread];
- Object objects[NbObject];
+ // GHS compiler needs the namespace prefix, despite using above.
+ DeliverInDefinedOrder::Object objects[NbObject];
for (int t = 0; t < NbThread; t++) {
threads[t].start();
}
@@ -602,12 +595,12 @@ class JobObject : public QObject
Q_OBJECT
public:
- explicit JobObject(QEventLoop *loop, QObject *parent = 0)
+ explicit JobObject(QEventLoop *loop, QObject *parent = nullptr)
: QObject(parent), locker(loop)
{
}
- explicit JobObject(QObject *parent = 0)
+ explicit JobObject(QObject *parent = nullptr)
: QObject(parent)
{
}
diff --git a/tests/auto/corelib/kernel/qjniarray/CMakeLists.txt b/tests/auto/corelib/kernel/qjniarray/CMakeLists.txt
new file mode 100644
index 0000000000..308b2c6427
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjniarray/CMakeLists.txt
@@ -0,0 +1,13 @@
+# Copyright (C) 2023 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qjnitypes LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qjniarray
+ SOURCES
+ tst_qjniarray.cpp
+)
diff --git a/tests/auto/corelib/kernel/qjniarray/tst_qjniarray.cpp b/tests/auto/corelib/kernel/qjniarray/tst_qjniarray.cpp
new file mode 100644
index 0000000000..b7b1f95b39
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjniarray/tst_qjniarray.cpp
@@ -0,0 +1,165 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QtTest>
+
+#include <QtCore/qjnitypes.h>
+#include <QtCore/qjniarray.h>
+
+using namespace Qt::StringLiterals;
+
+class tst_QJniArray : public QObject
+{
+ Q_OBJECT
+
+public:
+ tst_QJniArray() = default;
+
+private slots:
+ void construct();
+ void size();
+ void operators();
+};
+
+using namespace QtJniTypes;
+
+// fake type so that we can compile-time test and assert correct type mappings
+Q_DECLARE_JNI_CLASS(List, "qt/test/List");
+
+// verify that we get the return type we expect for the specified return type
+#define VERIFY_RETURN_FOR_TYPE(In, Out) \
+static_assert(std::is_same_v<decltype(List::callStaticMethod<In>("toByteArray")), Out>)
+
+VERIFY_RETURN_FOR_TYPE(jobjectArray, QJniObject);
+VERIFY_RETURN_FOR_TYPE(jobject[], QJniArray<jobject>);
+//VERIFY_RETURN_FOR_TYPE(QList<QJniObject>, QList<QJniObject>);
+VERIFY_RETURN_FOR_TYPE(QList<jobject>, QList<jobject>);
+
+VERIFY_RETURN_FOR_TYPE(jbyteArray, QJniObject);
+VERIFY_RETURN_FOR_TYPE(jbyte[], QJniArray<jbyte>);
+VERIFY_RETURN_FOR_TYPE(QByteArray, QByteArray);
+
+VERIFY_RETURN_FOR_TYPE(jbooleanArray, QJniObject);
+VERIFY_RETURN_FOR_TYPE(jboolean[], QJniArray<jboolean>);
+VERIFY_RETURN_FOR_TYPE(QList<jboolean>, QList<jboolean>);
+VERIFY_RETURN_FOR_TYPE(QList<bool>, QList<jboolean>);
+
+VERIFY_RETURN_FOR_TYPE(jcharArray, QJniObject);
+VERIFY_RETURN_FOR_TYPE(jchar[], QJniArray<jchar>);
+VERIFY_RETURN_FOR_TYPE(QList<jchar>, QList<jchar>);
+
+VERIFY_RETURN_FOR_TYPE(jshortArray, QJniObject);
+VERIFY_RETURN_FOR_TYPE(jshort[], QJniArray<jshort>);
+VERIFY_RETURN_FOR_TYPE(QList<jshort>, QList<jshort>);
+VERIFY_RETURN_FOR_TYPE(QList<short>, QList<short>);
+
+VERIFY_RETURN_FOR_TYPE(jintArray, QJniObject);
+VERIFY_RETURN_FOR_TYPE(jint[], QJniArray<jint>);
+VERIFY_RETURN_FOR_TYPE(QList<jint>, QList<jint>);
+VERIFY_RETURN_FOR_TYPE(QList<int>, QList<int>);
+
+VERIFY_RETURN_FOR_TYPE(jlongArray, QJniObject);
+VERIFY_RETURN_FOR_TYPE(jlong[], QJniArray<jlong>);
+VERIFY_RETURN_FOR_TYPE(QList<jlong>, QList<jlong>);
+// VERIFY_RETURN_FOR_TYPE(QList<long>, QList<long>); // assumes long is 64bit
+
+VERIFY_RETURN_FOR_TYPE(jfloatArray, QJniObject);
+VERIFY_RETURN_FOR_TYPE(jfloat[], QJniArray<jfloat>);
+VERIFY_RETURN_FOR_TYPE(QList<jfloat>, QList<jfloat>);
+VERIFY_RETURN_FOR_TYPE(QList<float>, QList<float>);
+
+VERIFY_RETURN_FOR_TYPE(jdoubleArray, QJniObject);
+VERIFY_RETURN_FOR_TYPE(jdouble[], QJniArray<jdouble>);
+VERIFY_RETURN_FOR_TYPE(QList<jdouble>, QList<jdouble>);
+VERIFY_RETURN_FOR_TYPE(QList<double>, QList<double>);
+
+VERIFY_RETURN_FOR_TYPE(QString, QString);
+
+VERIFY_RETURN_FOR_TYPE(List, List);
+VERIFY_RETURN_FOR_TYPE(List[], QJniArray<List>);
+VERIFY_RETURN_FOR_TYPE(QJniArray<List>, QJniArray<List>);
+
+void tst_QJniArray::construct()
+{
+ {
+ QStringList strings;
+ for (int i = 0; i < 10000; ++i)
+ strings << QString::number(i);
+ QJniArray<QString> list(strings);
+ QCOMPARE(list.size(), 10000);
+ }
+ {
+ QJniArray<jint> list{1, 2, 3};
+ QCOMPARE(list.size(), 3);
+ }
+ {
+ QJniArray<jint> list(QList<int>{1, 2, 3});
+ QCOMPARE(list.size(), 3);
+ }
+ {
+ QJniArray<jint> list{QList<int>{1, 2, 3}};
+ QCOMPARE(list.size(), 3);
+ }
+}
+
+void tst_QJniArray::size()
+{
+ QJniArray<jint> array;
+ QVERIFY(!array.isValid());
+ QCOMPARE(array.size(), 0);
+
+ QList<int> intList;
+ intList.resize(10);
+ auto intArray = QJniArrayBase::fromContainer(intList);
+ QCOMPARE(intArray.size(), 10);
+}
+
+void tst_QJniArray::operators()
+{
+ QByteArray bytes("abcde");
+ QJniArray<jbyte> array(bytes);
+ QVERIFY(array.isValid());
+
+ {
+ auto it = array.begin();
+ QCOMPARE(*it, 'a');
+ QCOMPARE(*++it, 'b');
+ QCOMPARE(*it++, 'b');
+ QCOMPARE(*it, 'c');
+ ++it;
+ it++;
+ QCOMPARE(*it, 'e');
+ QCOMPARE(++it, array.end());
+ }
+ {
+ auto it = array.rbegin();
+ QCOMPARE(*it, 'e');
+ QCOMPARE(*++it, 'd');
+ QCOMPARE(*it++, 'd');
+ QCOMPARE(*it, 'c');
+ ++it;
+ it++;
+ QCOMPARE(*it, 'a');
+ QCOMPARE(++it, array.rend());
+ }
+ {
+ QJniArray<jbyte>::const_iterator it = {};
+ QCOMPARE(it, QJniArray<jbyte>::const_iterator{});
+ QCOMPARE_NE(array.begin(), array.end());
+
+ it = array.begin();
+ QCOMPARE(it, array.begin());
+ }
+
+ QCOMPARE(std::distance(array.begin(), array.end()), array.size());
+
+ qsizetype index = 0;
+ for (const auto &value : array) {
+ QCOMPARE(value, bytes.at(index));
+ ++index;
+ }
+}
+
+QTEST_MAIN(tst_QJniArray)
+
+#include "tst_qjniarray.moc"
diff --git a/tests/auto/corelib/kernel/qjnienvironment/CMakeLists.txt b/tests/auto/corelib/kernel/qjnienvironment/CMakeLists.txt
new file mode 100644
index 0000000000..f405438314
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjnienvironment/CMakeLists.txt
@@ -0,0 +1,23 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+#####################################################################
+## tst_qjnienvironment Test:
+#####################################################################
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qjnienvironment LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qjnienvironment
+ SOURCES
+ tst_qjnienvironment.cpp
+)
+
+if(ANDROID)
+ set_property(TARGET tst_qjnienvironment APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
+ ${CMAKE_CURRENT_SOURCE_DIR}/testdata
+ )
+endif()
diff --git a/tests/auto/corelib/kernel/qjnienvironment/testdata/src/org/qtproject/qt/android/testdata/QtJniEnvironmentTestClass.java b/tests/auto/corelib/kernel/qjnienvironment/testdata/src/org/qtproject/qt/android/testdata/QtJniEnvironmentTestClass.java
new file mode 100644
index 0000000000..4f307b3bc7
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjnienvironment/testdata/src/org/qtproject/qt/android/testdata/QtJniEnvironmentTestClass.java
@@ -0,0 +1,60 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+package org.qtproject.qt.android.testdatapackage;
+
+public class QtJniEnvironmentTestClass
+{
+ private static native void callbackFromJava(String message);
+ private static native void namedCallbackFromJava(String message);
+ private static native void memberCallbackFromJava(String message);
+ private static native void namedMemberCallbackFromJava(String message);
+ private static native void namespaceCallbackFromJava(String message);
+ private static native void intCallbackFromJava(int value);
+
+ public final int INT_FIELD = 123;
+ public static final int S_INT_FIELD = 321;
+
+ QtJniEnvironmentTestClass() {}
+
+ public static void appendJavaToString(String message)
+ {
+ callbackFromJava("From Java: " + message);
+ }
+
+ public static void namedAppendJavaToString(String message)
+ {
+ namedCallbackFromJava("From Java (named): " + message);
+ }
+
+ public static void memberAppendJavaToString(String message)
+ {
+ memberCallbackFromJava("From Java (member): " + message);
+ }
+
+ public static void namedMemberAppendJavaToString(String message)
+ {
+ namedMemberCallbackFromJava("From Java (named member): " + message);
+ }
+
+ public static void namespaceAppendJavaToString(String message)
+ {
+ namespaceCallbackFromJava("From Java (namespace): " + message);
+ }
+
+ public static void convertToInt(String message)
+ {
+ intCallbackFromJava(Integer.parseInt(message));
+ }
+}
+
+class QtJniEnvironmentTestClassNoCtor
+{
+ private static native void callbackFromJavaNoCtor(String message);
+
+ public static void appendJavaToString(String message)
+ {
+ callbackFromJavaNoCtor("From Java (no ctor): " + message);
+ }
+}
+
diff --git a/tests/auto/corelib/kernel/qjnienvironment/tst_qjnienvironment.cpp b/tests/auto/corelib/kernel/qjnienvironment/tst_qjnienvironment.cpp
new file mode 100644
index 0000000000..95748f46f7
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjnienvironment/tst_qjnienvironment.cpp
@@ -0,0 +1,379 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <jni.h>
+
+#include <QtCore/QJniEnvironment>
+#include <QtCore/QJniObject>
+#include <QtTest/QtTest>
+
+static const char javaTestClass[] =
+ "org/qtproject/qt/android/testdatapackage/QtJniEnvironmentTestClass";
+static const char javaTestClassNoCtor[] =
+ "org/qtproject/qt/android/testdatapackage/QtJniEnvironmentTestClassNoCtor";
+
+static QString registerNativesString = QStringLiteral("Qt");
+static int registerNativeInteger = 0;
+
+class tst_QJniEnvironment : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void init();
+ void jniEnv();
+ void javaVM();
+ void registerNativeMethods();
+ void registerNativeMethodsByJclass();
+ void findMethod();
+ void findStaticMethod();
+ void findField();
+ void findStaticField();
+};
+
+void tst_QJniEnvironment::init()
+{
+ // Unless explicitly ignored to test error handling, warning messages
+ // in this test about a failure to look up a field, method, or class
+ // make the test fail.
+ QTest::failOnWarning(QRegularExpression("java.lang.NoSuch.*Error"));
+}
+
+void tst_QJniEnvironment::jniEnv()
+{
+ QJniEnvironment env;
+ JavaVM *javaVM = env.javaVM();
+ QVERIFY(javaVM);
+
+ {
+ // JNI environment should now be attached to the current thread
+ JNIEnv *jni = 0;
+ QCOMPARE(javaVM->GetEnv((void**)&jni, JNI_VERSION_1_6), JNI_OK);
+
+ JNIEnv *e = env.jniEnv();
+ QVERIFY(e);
+
+ QCOMPARE(env->GetVersion(), JNI_VERSION_1_6);
+
+ // try to find an existing class
+ QVERIFY(env->FindClass("java/lang/Object"));
+ QVERIFY(!env->ExceptionCheck());
+
+ // try to find a nonexistent class
+ QVERIFY(!env->FindClass("this/doesnt/Exist"));
+ QVERIFY(env->ExceptionCheck());
+ env->ExceptionClear();
+
+ QVERIFY(env->FindClass("java/lang/Object"));
+ QVERIFY(!QJniEnvironment::checkAndClearExceptions(env.jniEnv()));
+
+ // try to find a nonexistent class
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.ClassNotFoundException: .*"));
+ QVERIFY(!env->FindClass("this/doesnt/Exist"));
+ QVERIFY(QJniEnvironment::checkAndClearExceptions(env.jniEnv()));
+
+ // try to find an existing class with QJniEnvironment
+ QJniEnvironment env;
+ QVERIFY(env.findClass("java/lang/Object"));
+ QVERIFY(env.findClass<jstring>());
+
+ // try to find a nonexistent class
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.ClassNotFoundException: .*"));
+ QVERIFY(!env.findClass("this/doesnt/Exist"));
+
+ // clear exception with member function
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.ClassNotFoundException: .*"));
+ QVERIFY(!env->FindClass("this/doesnt/Exist"));
+ QVERIFY(env.checkAndClearExceptions());
+ }
+
+ // The env does not detach automatically, even if it goes out of scope. The only way it can
+ // be detached is if it's done explicitly, or if the thread we attached to gets killed (TLS clean-up).
+ JNIEnv *jni = nullptr;
+ QCOMPARE(javaVM->GetEnv((void**)&jni, JNI_VERSION_1_6), JNI_OK);
+}
+
+void tst_QJniEnvironment::javaVM()
+{
+ QJniEnvironment env;
+ JavaVM *javaVM = env.javaVM();
+ QVERIFY(javaVM);
+
+ QCOMPARE(env.javaVM(), javaVM);
+
+ JavaVM *vm = 0;
+ QCOMPARE(env->GetJavaVM(&vm), JNI_OK);
+ QCOMPARE(env.javaVM(), vm);
+}
+
+static void callbackFromJava(JNIEnv *env, jobject /*thiz*/, jstring value)
+{
+ Q_UNUSED(env)
+ registerNativesString = QJniObject(value).toString();
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackFromJava);
+
+static void tediouslyLongNamed_callbackFromJava(JNIEnv *env, jobject /*thiz*/, jstring value)
+{
+ Q_UNUSED(env)
+ registerNativesString = QJniObject(value).toString();
+}
+Q_DECLARE_JNI_NATIVE_METHOD(tediouslyLongNamed_callbackFromJava, namedCallbackFromJava)
+
+static void callbackFromJavaNoCtor(JNIEnv *env, jobject /*thiz*/, jstring value)
+{
+ Q_UNUSED(env)
+ registerNativesString = QJniObject(value).toString();
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackFromJavaNoCtor);
+
+class CallbackClass {
+public:
+ static void memberCallbackFromJava(JNIEnv *env, jobject /*thiz*/, jstring value)
+ {
+ Q_UNUSED(env)
+ registerNativesString = QJniObject(value).toString();
+ }
+ Q_DECLARE_JNI_NATIVE_METHOD_IN_CURRENT_SCOPE(memberCallbackFromJava)
+
+ static void tediouslyLongNamed_memberCallbackFromJava(JNIEnv *env, jobject /*thiz*/,
+ jstring value)
+ {
+ Q_UNUSED(env)
+ registerNativesString = QJniObject(value).toString();
+ }
+ Q_DECLARE_JNI_NATIVE_METHOD_IN_CURRENT_SCOPE(tediouslyLongNamed_memberCallbackFromJava,
+ namedMemberCallbackFromJava)
+};
+
+namespace CallbackNamespace {
+ static void namespaceCallbackFromJava(JNIEnv *env, jobject /*thiz*/, jstring value)
+ {
+ Q_UNUSED(env)
+ registerNativesString = QJniObject(value).toString();
+ }
+ Q_DECLARE_JNI_NATIVE_METHOD_IN_CURRENT_SCOPE(namespaceCallbackFromJava)
+}
+
+void tst_QJniEnvironment::registerNativeMethods()
+{
+ QJniObject QtString = QJniObject::fromString(registerNativesString);
+ QJniEnvironment env;
+
+ {
+ QVERIFY(env.registerNativeMethods(javaTestClass, {
+ Q_JNI_NATIVE_METHOD(callbackFromJava)
+ }));
+
+ QJniObject::callStaticMethod<void>(javaTestClass,
+ "appendJavaToString",
+ "(Ljava/lang/String;)V",
+ QtString.object<jstring>());
+ QTest::qWait(200);
+ QVERIFY(registerNativesString == QStringLiteral("From Java: Qt"));
+ }
+
+ // Named native function
+ {
+ QVERIFY(env.registerNativeMethods(javaTestClass, {
+ Q_JNI_NATIVE_METHOD(tediouslyLongNamed_callbackFromJava)
+ }));
+
+ QJniObject::callStaticMethod<void>(javaTestClass,
+ "namedAppendJavaToString",
+ "(Ljava/lang/String;)V",
+ QtString.object<jstring>());
+ QTest::qWait(200);
+ QVERIFY(registerNativesString == QStringLiteral("From Java (named): Qt"));
+ }
+
+ // Static class member as callback
+ {
+ QVERIFY(env.registerNativeMethods(javaTestClass, {
+ Q_JNI_NATIVE_SCOPED_METHOD(memberCallbackFromJava, CallbackClass)
+ }));
+
+ QJniObject::callStaticMethod<void>(javaTestClass,
+ "memberAppendJavaToString",
+ "(Ljava/lang/String;)V",
+ QtString.object<jstring>());
+ QTest::qWait(200);
+ QVERIFY(registerNativesString == QStringLiteral("From Java (member): Qt"));
+ }
+
+ // Static named class member as callback
+ {
+ QVERIFY(env.registerNativeMethods(javaTestClass, {
+ Q_JNI_NATIVE_SCOPED_METHOD(tediouslyLongNamed_memberCallbackFromJava,
+ CallbackClass)
+ }));
+
+ QJniObject::callStaticMethod<void>(javaTestClass,
+ "namedMemberAppendJavaToString",
+ "(Ljava/lang/String;)V",
+ QtString.object<jstring>());
+ QTest::qWait(200);
+ QVERIFY(registerNativesString == QStringLiteral("From Java (named member): Qt"));
+ }
+
+ // Function generally just in namespace as callback
+ {
+ QVERIFY(env.registerNativeMethods(javaTestClass, {
+ Q_JNI_NATIVE_SCOPED_METHOD(namespaceCallbackFromJava, CallbackNamespace)
+ }));
+
+ QJniObject::callStaticMethod<void>(javaTestClass,
+ "namespaceAppendJavaToString",
+ "(Ljava/lang/String;)V",
+ QtString.object<jstring>());
+ QTest::qWait(200);
+ QVERIFY(registerNativesString == QStringLiteral("From Java (namespace): Qt"));
+ }
+
+ // No default constructor in class
+ {
+ QVERIFY(env.registerNativeMethods(javaTestClassNoCtor, {
+ Q_JNI_NATIVE_METHOD(callbackFromJavaNoCtor)
+ }));
+
+ QJniObject::callStaticMethod<void>(javaTestClassNoCtor,
+ "appendJavaToString",
+ "(Ljava/lang/String;)V",
+ QtString.object<jstring>());
+ QTest::qWait(200);
+ QVERIFY(registerNativesString == QStringLiteral("From Java (no ctor): Qt"));
+ }
+}
+
+static void intCallbackFromJava(JNIEnv *env, jobject /*thiz*/, jint value)
+{
+ Q_UNUSED(env)
+ registerNativeInteger = static_cast<int>(value);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(intCallbackFromJava);
+
+void tst_QJniEnvironment::registerNativeMethodsByJclass()
+{
+ QJniEnvironment env;
+ jclass clazz = env.findClass(javaTestClass);
+ QVERIFY(clazz != 0);
+ QVERIFY(env.registerNativeMethods(clazz, {
+ Q_JNI_NATIVE_METHOD(intCallbackFromJava)
+ }));
+
+ QCOMPARE(registerNativeInteger, 0);
+
+ QJniObject parameter = QJniObject::fromString(QString("123"));
+ QJniObject::callStaticMethod<void>(clazz, "convertToInt", "(Ljava/lang/String;)V",
+ parameter.object<jstring>());
+ QTest::qWait(200);
+ QCOMPARE(registerNativeInteger, 123);
+}
+
+void tst_QJniEnvironment::findMethod()
+{
+ QJniEnvironment env;
+ jclass clazz = env.findClass("java/lang/Integer");
+ QVERIFY(clazz != nullptr);
+
+ // existing method
+ jmethodID methodId = env.findMethod(clazz, "toString", "()Ljava/lang/String;");
+ QVERIFY(methodId != nullptr);
+
+ // existing method
+ methodId = env.findMethod<jstring>(clazz, "toString");
+ QVERIFY(methodId != nullptr);
+
+ // invalid signature
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.NoSuchMethodError: .*"));
+ jmethodID invalid = env.findMethod(clazz, "unknown", "()I");
+ QVERIFY(invalid == nullptr);
+ // check that all exceptions are already cleared
+ QVERIFY(!env.checkAndClearExceptions());
+}
+
+void tst_QJniEnvironment::findStaticMethod()
+{
+ QJniEnvironment env;
+ jclass clazz = env.findClass("java/lang/Integer");
+ QVERIFY(clazz != nullptr);
+
+ // existing method
+ jmethodID staticMethodId = env.findStaticMethod(clazz, "parseInt", "(Ljava/lang/String;)I");
+ QVERIFY(staticMethodId != nullptr);
+
+ // existing method
+ staticMethodId = env.findStaticMethod<jint, jstring>(clazz, "parseInt");
+ QVERIFY(staticMethodId != nullptr);
+
+ QJniObject parameter = QJniObject::fromString("123");
+ jint result = QJniObject::callStaticMethod<jint>(clazz, staticMethodId,
+ parameter.object<jstring>());
+ QCOMPARE(result, 123);
+
+ // invalid method
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.NoSuchMethodError: .*"));
+ jmethodID invalid = env.findStaticMethod(clazz, "unknown", "()I");
+ QVERIFY(invalid == nullptr);
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.NoSuchMethodError: .*"));
+ invalid = env.findStaticMethod<jint>(clazz, "unknown");
+ QVERIFY(invalid == nullptr);
+ // check that all exceptions are already cleared
+ QVERIFY(!env.checkAndClearExceptions());
+}
+
+void tst_QJniEnvironment::findField()
+{
+ QJniEnvironment env;
+ jclass clazz = env.findClass(javaTestClass);
+ QVERIFY(clazz != nullptr);
+
+ // valid field
+ jfieldID validId = env.findField(clazz, "INT_FIELD", "I");
+ QVERIFY(validId != nullptr);
+ validId = env.findField<jint>(clazz, "INT_FIELD");
+ QVERIFY(validId != nullptr);
+
+ jmethodID constructorId = env.findMethod(clazz, "<init>", "()V");
+ QVERIFY(constructorId != nullptr);
+ jobject obj = env->NewObject(clazz, constructorId);
+ QVERIFY(!env.checkAndClearExceptions());
+ int value = env->GetIntField(obj, validId);
+ QVERIFY(!env.checkAndClearExceptions());
+ QVERIFY(value == 123);
+
+ // invalid signature
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.NoSuchFieldError: .*"));
+ jfieldID invalidId = env.findField(clazz, "unknown", "I");
+ QVERIFY(invalidId == nullptr);
+ // check that all exceptions are already cleared
+ QVERIFY(!env.checkAndClearExceptions());
+}
+
+void tst_QJniEnvironment::findStaticField()
+{
+ QJniEnvironment env;
+ jclass clazz = env.findClass(javaTestClass);
+ QVERIFY(clazz != nullptr);
+
+ // valid field
+ jfieldID validId = env.findStaticField(clazz, "S_INT_FIELD", "I");
+ QVERIFY(validId != nullptr);
+ validId = env.findStaticField<jint>(clazz, "S_INT_FIELD");
+ QVERIFY(validId != nullptr);
+
+ int size = env->GetStaticIntField(clazz, validId);
+ QVERIFY(!env.checkAndClearExceptions());
+ QVERIFY(size == 321);
+
+ // invalid signature
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.NoSuchFieldError: .*"));
+ jfieldID invalidId = env.findStaticField(clazz, "unknown", "I");
+ QVERIFY(invalidId == nullptr);
+ // check that all exceptions are already cleared
+ QVERIFY(!env.checkAndClearExceptions());
+}
+
+QTEST_MAIN(tst_QJniEnvironment)
+
+#include "tst_qjnienvironment.moc"
diff --git a/tests/auto/corelib/kernel/qjniobject/CMakeLists.txt b/tests/auto/corelib/kernel/qjniobject/CMakeLists.txt
new file mode 100644
index 0000000000..98509dc0e5
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjniobject/CMakeLists.txt
@@ -0,0 +1,23 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+#####################################################################
+## tst_qjniobject Test:
+#####################################################################
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qjniobject LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qjniobject
+ SOURCES
+ tst_qjniobject.cpp
+)
+
+if(ANDROID)
+ set_property(TARGET tst_qjniobject APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
+ ${CMAKE_CURRENT_SOURCE_DIR}/testdata
+ )
+endif()
diff --git a/tests/auto/corelib/kernel/qjniobject/testdata/src/org/qtproject/qt/android/testdata/QtJniObjectTestClass.java b/tests/auto/corelib/kernel/qjniobject/testdata/src/org/qtproject/qt/android/testdata/QtJniObjectTestClass.java
new file mode 100644
index 0000000000..07a94d1cac
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjniobject/testdata/src/org/qtproject/qt/android/testdata/QtJniObjectTestClass.java
@@ -0,0 +1,345 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+package org.qtproject.qt.android.testdatapackage;
+
+public class QtJniObjectTestClass
+{
+ static final byte A_BYTE_VALUE = 127;
+ static final short A_SHORT_VALUE = 32767;
+ static final int A_INT_VALUE = 060701;
+ static final long A_LONG_VALUE = 060701;
+ static final float A_FLOAT_VALUE = 1.0f;
+ static final double A_DOUBLE_VALUE = 1.0;
+ static final boolean A_BOOLEAN_VALUE = true;
+ static final char A_CHAR_VALUE = 'Q';
+ static final String A_STRING_OBJECT = "TEST_DATA_STRING";
+ static final Class A_CLASS_OBJECT = QtJniObjectTestClass.class;
+ static final Object A_OBJECT_OBJECT = new QtJniObjectTestClass();
+ static final Throwable A_THROWABLE_OBJECT = new Throwable(A_STRING_OBJECT);
+
+ // --------------------------------------------------------------------------------------------
+
+ final int INT_FIELD = 123;
+ final boolean BOOL_FIELD = true;
+
+ byte BYTE_VAR;
+ short SHORT_VAR;
+ int INT_VAR;
+ long LONG_VAR;
+ float FLOAT_VAR;
+ double DOUBLE_VAR;
+ boolean BOOLEAN_VAR;
+ char CHAR_VAR;
+ String STRING_OBJECT_VAR;
+
+ static byte S_BYTE_VAR;
+ static short S_SHORT_VAR;
+ static int S_INT_VAR;
+ static long S_LONG_VAR;
+ static float S_FLOAT_VAR;
+ static double S_DOUBLE_VAR;
+ static boolean S_BOOLEAN_VAR;
+ static char S_CHAR_VAR;
+ static String S_STRING_OBJECT_VAR;
+
+ // --------------------------------------------------------------------------------------------
+ public static void staticVoidMethod() { return; }
+ public static void staticVoidMethodWithArgs(int a, boolean b, char c) { return; }
+
+ public void voidMethod() { return; }
+ public void voidMethodWithArgs(int a, boolean b, char c) { return; }
+
+ // --------------------------------------------------------------------------------------------
+ public static boolean staticBooleanMethod() { return A_BOOLEAN_VALUE; }
+ public static boolean staticBooleanMethodWithArgs(boolean a, boolean b, boolean c)
+ { return staticBooleanMethod(); }
+
+ public boolean booleanMethod() { return staticBooleanMethod(); }
+ public boolean booleanMethodWithArgs(boolean a, boolean b, boolean c)
+ { return staticBooleanMethodWithArgs(a, b, c); }
+
+ // --------------------------------------------------------------------------------------------
+ public static byte staticByteMethod() { return A_BYTE_VALUE; }
+ public static byte staticByteMethodWithArgs(byte a, byte b, byte c) { return staticByteMethod(); }
+
+ public byte byteMethod() { return staticByteMethod(); }
+ public byte byteMethodWithArgs(byte a, byte b, byte c)
+ { return staticByteMethodWithArgs(a, b, c); }
+
+ // --------------------------------------------------------------------------------------------
+ public static char staticCharMethod() { return A_CHAR_VALUE; }
+ public static char staticCharMethodWithArgs(char a, char b, char c) { return staticCharMethod(); }
+
+ public char charMethod() { return staticCharMethod(); }
+ public char charMethodWithArgs(char a, char b, char c)
+ { return staticCharMethodWithArgs(a, b, c); }
+
+ // --------------------------------------------------------------------------------------------
+ public static short staticShortMethod() { return A_SHORT_VALUE; }
+ public static short staticShortMethodWithArgs(short a, short b, short c) { return staticShortMethod(); }
+
+ public short shortMethod() { return staticShortMethod(); }
+ public short shortMethodWithArgs(short a, short b, short c)
+ { return staticShortMethodWithArgs(a, b, c); }
+
+ // --------------------------------------------------------------------------------------------
+ public static int staticIntMethod() { return A_INT_VALUE; }
+ public static int staticIntMethodWithArgs(int a, int b, int c) { return staticIntMethod(); }
+
+ public int intMethod() { return staticIntMethod(); }
+ public int intMethodWithArgs(int a, int b, int c) { return staticIntMethodWithArgs(a, b, c); }
+
+ // --------------------------------------------------------------------------------------------
+ public static long staticLongMethod() { return A_LONG_VALUE; }
+ public static long staticLongMethodWithArgs(long a, long b, long c) { return staticLongMethod(); }
+
+ public long longMethod() { return staticLongMethod(); }
+ public long longMethodWithArgs(long a, long b, long c)
+ { return staticLongMethodWithArgs(a, b, c); }
+
+ // --------------------------------------------------------------------------------------------
+ public static float staticFloatMethod() { return A_FLOAT_VALUE; }
+ public static float staticFloatMethodWithArgs(float a, float b, float c) { return staticFloatMethod(); }
+
+ public float floatMethod() { return staticFloatMethod(); }
+ public float floatMethodWithArgs(float a, float b, float c)
+ { return staticFloatMethodWithArgs(a, b, c); }
+
+ // --------------------------------------------------------------------------------------------
+ public static double staticDoubleMethod() { return A_DOUBLE_VALUE; }
+ public static double staticDoubleMethodWithArgs(double a, double b, double c)
+ { return staticDoubleMethod(); }
+
+ public double doubleMethod() { return staticDoubleMethod(); }
+ public double doubleMethodWithArgs(double a, double b, double c)
+ { return staticDoubleMethodWithArgs(a, b, c); }
+
+ // --------------------------------------------------------------------------------------------
+ public static Object staticObjectMethod() { return A_OBJECT_OBJECT; }
+ public Object objectMethod() { return staticObjectMethod(); }
+
+ // --------------------------------------------------------------------------------------------
+ public static Class staticClassMethod() { return A_CLASS_OBJECT; }
+ public Class classMethod() { return staticClassMethod(); }
+
+ // --------------------------------------------------------------------------------------------
+ public static String staticStringMethod() { return A_STRING_OBJECT; }
+ public String stringMethod() { return staticStringMethod(); }
+
+ // --------------------------------------------------------------------------------------------
+ public static String staticEchoMethod(String value) { return value; }
+
+ // --------------------------------------------------------------------------------------------
+ public static Throwable staticThrowableMethod() { return A_THROWABLE_OBJECT; }
+ public Throwable throwableMethod() { return staticThrowableMethod(); }
+
+ // --------------------------------------------------------------------------------------------
+ public static Object[] staticObjectArrayMethod()
+ { Object[] array = { new Object(), new Object(), new Object() }; return array; }
+ public Object[] objectArrayMethod() { return staticObjectArrayMethod(); }
+ public static Object[] staticReverseObjectArray(Object[] array)
+ {
+ for (int i = 0; i < array.length / 2; ++i) {
+ Object old = array[array.length - i - 1];
+ array[array.length - i - 1] = array[i];
+ array[i] = old;
+ }
+ return array;
+ }
+ public Object[] reverseObjectArray(Object[] array)
+ { return staticReverseObjectArray(array); }
+
+ // --------------------------------------------------------------------------------------------
+ public static boolean[] staticBooleanArrayMethod()
+ { boolean[] array = { true, true, true }; return array; }
+ public boolean[] booleanArrayMethod() { return staticBooleanArrayMethod(); }
+ public static boolean[] staticReverseBooleanArray(boolean[] array)
+ {
+ for (int i = 0; i < array.length / 2; ++i) {
+ boolean old = array[array.length - i - 1];
+ array[array.length - i - 1] = array[i];
+ array[i] = old;
+ }
+ return array;
+ }
+ public boolean[] reverseBooleanArray(boolean[] array)
+ { return staticReverseBooleanArray(array); }
+
+ // --------------------------------------------------------------------------------------------
+ public static byte[] staticByteArrayMethod()
+ { byte[] array = { 'a', 'b', 'c' }; return array; }
+ public byte[] byteArrayMethod() { return staticByteArrayMethod(); }
+ public static byte[] staticReverseByteArray(byte[] array)
+ {
+ for (int i = 0; i < array.length / 2; ++i) {
+ byte old = array[array.length - i - 1];
+ array[array.length - i - 1] = array[i];
+ array[i] = old;
+ }
+ return array;
+ }
+ public byte[] reverseByteArray(byte[] array)
+ { return staticReverseByteArray(array); }
+
+ // --------------------------------------------------------------------------------------------
+ public static char[] staticCharArrayMethod()
+ { char[] array = { 'a', 'b', 'c' }; return array; }
+ public char[] charArrayMethod() { return staticCharArrayMethod(); }
+ public static char[] staticReverseCharArray(char[] array)
+ {
+ for (int i = 0; i < array.length / 2; ++i) {
+ char old = array[array.length - i - 1];
+ array[array.length - i - 1] = array[i];
+ array[i] = old;
+ }
+ return array;
+ }
+ public char[] reverseCharArray(char[] array)
+ { return staticReverseCharArray(array); }
+
+ // --------------------------------------------------------------------------------------------
+ public static short[] staticShortArrayMethod() { short[] array = { 3, 2, 1 }; return array; }
+ public short[] shortArrayMethod() { return staticShortArrayMethod(); }
+ public static short[] staticReverseShortArray(short[] array)
+ {
+ for (int i = 0; i < array.length / 2; ++i) {
+ short old = array[array.length - i - 1];
+ array[array.length - i - 1] = array[i];
+ array[i] = old;
+ }
+ return array;
+ }
+ public short[] reverseShortArray(short[] array)
+ { return staticReverseShortArray(array); }
+
+ // --------------------------------------------------------------------------------------------
+ public static int[] staticIntArrayMethod() { int[] array = { 3, 2, 1 }; return array; }
+ public int[] intArrayMethod() { return staticIntArrayMethod(); }
+ public static int[] staticReverseIntArray(int[] array)
+ {
+ for (int i = 0; i < array.length / 2; ++i) {
+ int old = array[array.length - i - 1];
+ array[array.length - i - 1] = array[i];
+ array[i] = old;
+ }
+ return array;
+ }
+ public int[] reverseIntArray(int[] array)
+ { return staticReverseIntArray(array); }
+
+ // --------------------------------------------------------------------------------------------
+ public static long[] staticLongArrayMethod()
+ { long[] array = { 3, 2, 1 }; return array; }
+ public long[] longArrayMethod() { return staticLongArrayMethod(); }
+ public static long[] staticReverseLongArray(long[] array)
+ {
+ for (int i = 0; i < array.length / 2; ++i) {
+ long old = array[array.length - i - 1];
+ array[array.length - i - 1] = array[i];
+ array[i] = old;
+ }
+ return array;
+ }
+ public long[] reverseLongArray(long[] array)
+ { return staticReverseLongArray(array); }
+
+ // --------------------------------------------------------------------------------------------
+ public static float[] staticFloatArrayMethod()
+ { float[] array = { 1.0f, 2.0f, 3.0f }; return array; }
+ public float[] floatArrayMethod() { return staticFloatArrayMethod(); }
+ public static float[] staticReverseFloatArray(float[] array)
+ {
+ for (int i = 0; i < array.length / 2; ++i) {
+ float old = array[array.length - i - 1];
+ array[array.length - i - 1] = array[i];
+ array[i] = old;
+ }
+ return array;
+ }
+ public float[] reverseFloatArray(float[] array)
+ { return staticReverseFloatArray(array); }
+
+ // --------------------------------------------------------------------------------------------
+ public static double[] staticDoubleArrayMethod()
+ { double[] array = { 3.0, 2.0, 1.0 }; return array; }
+ public double[] doubleArrayMethod() { return staticDoubleArrayMethod(); }
+ public static double[] staticReverseDoubleArray(double[] array)
+ {
+ for (int i = 0; i < array.length / 2; ++i) {
+ double old = array[array.length - i - 1];
+ array[array.length - i - 1] = array[i];
+ array[i] = old;
+ }
+ return array;
+ }
+ public double[] reverseDoubleArray(double[] array)
+ { return staticReverseDoubleArray(array); }
+
+ // --------------------------------------------------------------------------------------------
+ native public int callbackWithObject(QtJniObjectTestClass that);
+ native public int callbackWithObjectRef(QtJniObjectTestClass that);
+ native public int callbackWithString(String string);
+ native public int callbackWithByte(byte value);
+ native public int callbackWithBoolean(boolean value);
+ native public int callbackWithInt(int value);
+ native public int callbackWithDouble(double value);
+ native public int callbackWithJniArray(double[] value);
+ native public int callbackWithQList(double[] value);
+ native public int callbackWithStringList(String[] value);
+
+ public int callMeBackWithObject(QtJniObjectTestClass that)
+ {
+ return callbackWithObject(that);
+ }
+
+ public int callMeBackWithObjectRef(QtJniObjectTestClass that)
+ {
+ return callbackWithObjectRef(that);
+ }
+
+ public int callMeBackWithString(String string)
+ {
+ return callbackWithString(string);
+ }
+
+ public int callMeBackWithByte(byte value)
+ {
+ return callbackWithByte(value);
+ }
+
+ public int callMeBackWithBoolean(boolean value)
+ {
+ return callbackWithBoolean(value);
+ }
+
+ public int callMeBackWithInt(int value)
+ {
+ return callbackWithInt(value);
+ }
+
+ public int callMeBackWithDouble(double value)
+ {
+ return callbackWithDouble(value);
+ }
+ public int callMeBackWithJniArray(double[] value)
+ {
+ return callbackWithJniArray(value);
+ }
+ public int callMeBackWithQList(double[] value)
+ {
+ return callbackWithQList(value);
+ }
+ public int callMeBackWithStringList(String[] value)
+ {
+ return callbackWithStringList(value);
+ }
+
+ public Object callMethodThrowsException() throws Exception {
+ throw new Exception();
+ }
+
+ public static Object callStaticMethodThrowsException() throws Exception {
+ throw new Exception();
+ }
+}
diff --git a/tests/auto/corelib/kernel/qjniobject/tst_qjniobject.cpp b/tests/auto/corelib/kernel/qjniobject/tst_qjniobject.cpp
new file mode 100644
index 0000000000..64b464e002
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjniobject/tst_qjniobject.cpp
@@ -0,0 +1,2108 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <jni.h>
+
+#include <QString>
+#include <QtCore/QJniEnvironment>
+#include <QtCore/QJniObject>
+#include <QtTest>
+
+using namespace Qt::StringLiterals;
+
+static constexpr const char testClassName[] = "org/qtproject/qt/android/testdatapackage/QtJniObjectTestClass";
+Q_DECLARE_JNI_CLASS(QtJniObjectTestClass, testClassName)
+using TestClass = QtJniTypes::QtJniObjectTestClass;
+
+static const jbyte A_BYTE_VALUE = 127;
+static const jshort A_SHORT_VALUE = 32767;
+static const jint A_INT_VALUE = 060701;
+static const jlong A_LONG_VALUE = 060701;
+static const jfloat A_FLOAT_VALUE = 1.0;
+static const jdouble A_DOUBLE_VALUE = 1.0;
+static const jchar A_CHAR_VALUE = 'Q';
+
+static QString A_STRING_OBJECT()
+{
+ return QStringLiteral("TEST_DATA_STRING");
+}
+
+class tst_QJniObject : public QObject
+{
+ Q_OBJECT
+
+public:
+ tst_QJniObject();
+
+private slots:
+ void initTestCase();
+ void init();
+
+ void ctor();
+ void callMethodTest();
+ void callMethodThrowsException();
+ void callObjectMethodTest();
+ void stringConvertionTest();
+ void compareOperatorTests();
+ void className();
+ void callStaticMethodThrowsException();
+ void callStaticObjectMethodClassName();
+ void callStaticObjectMethod();
+ void callStaticObjectMethodById();
+ void callStaticBooleanMethodClassName();
+ void callStaticBooleanMethod();
+ void callStaticBooleanMethodById();
+ void callStaticCharMethodClassName();
+ void callStaticCharMethod();
+ void callStaticCharMethodById();
+ void callStaticIntMethodClassName();
+ void callStaticIntMethod();
+ void callStaticIntMethodById();
+ void callStaticByteMethodClassName();
+ void callStaticByteMethod();
+ void callStaticByteMethodById();
+ void callStaticDoubleMethodClassName();
+ void callStaticDoubleMethod();
+ void callStaticDoubleMethodById();
+ void callStaticFloatMethodClassName();
+ void callStaticFloatMethod();
+ void callStaticFloatMethodById();
+ void callStaticLongMethodClassName();
+ void callStaticLongMethod();
+ void callStaticLongMethodById();
+ void callStaticShortMethodClassName();
+ void callStaticShortMethod();
+ void callStaticShortMethodById();
+ void getStaticObjectFieldClassName();
+ void getStaticObjectField();
+ void getStaticIntFieldClassName();
+ void getStaticIntField();
+ void getStaticByteFieldClassName();
+ void getStaticByteField();
+ void getStaticBooleanField();
+ void getStaticLongFieldClassName();
+ void getStaticLongField();
+ void getStaticDoubleFieldClassName();
+ void getStaticDoubleField();
+ void getStaticFloatFieldClassName();
+ void getStaticFloatField();
+ void getStaticShortFieldClassName();
+ void getStaticShortField();
+ void getStaticCharFieldClassName();
+ void getStaticCharField();
+ void getBooleanField();
+ void getIntField();
+
+ void setIntField();
+ void setByteField();
+ void setLongField();
+ void setDoubleField();
+ void setFloatField();
+ void setShortField();
+ void setCharField();
+ void setBooleanField();
+ void setObjectField();
+ void setStaticIntField();
+ void setStaticByteField();
+ void setStaticLongField();
+ void setStaticDoubleField();
+ void setStaticFloatField();
+ void setStaticShortField();
+ void setStaticCharField();
+ void setStaticBooleanField();
+ void setStaticObjectField();
+
+ void templateApiCheck();
+ void isClassAvailable();
+ void fromLocalRef();
+ void largeObjectArray();
+
+ void callback_data();
+ void callback();
+ void callStaticOverloadResolution();
+
+ void cleanupTestCase();
+};
+
+tst_QJniObject::tst_QJniObject()
+{
+}
+
+void tst_QJniObject::initTestCase()
+{
+}
+
+void tst_QJniObject::init()
+{
+ // Unless explicitly ignored to test error handling, warning messages
+ // in this test about a failure to look up a field, method, or class
+ // make the test fail.
+ QTest::failOnWarning(QRegularExpression("java.lang.NoSuch.*Error"));
+}
+
+void tst_QJniObject::cleanupTestCase()
+{
+}
+
+void tst_QJniObject::ctor()
+{
+ {
+ QJniObject object;
+ QVERIFY(!object.isValid());
+ }
+
+ {
+ QJniObject object("java/lang/String");
+ QVERIFY(object.isValid());
+ }
+
+ {
+ QJniObject object = QJniObject::construct<jstring>();
+ QVERIFY(object.isValid());
+ }
+
+ {
+ // from Qt 6.7 on we can construct declared classes through the helper type
+ QJniObject object = TestClass::construct();
+ QVERIFY(object.isValid());
+
+ // or even directly
+ TestClass testObject;
+ QVERIFY(testObject.isValid());
+ }
+
+ {
+ QJniObject string = QJniObject::fromString(QLatin1String("Hello, Java"));
+ QJniObject object("java/lang/String", "(Ljava/lang/String;)V", string.object<jstring>());
+ QVERIFY(object.isValid());
+ QCOMPARE(string.toString(), object.toString());
+ }
+
+ {
+ QJniObject string = QJniObject::fromString(QLatin1String("Hello, Java"));
+ QJniObject object = QJniObject::construct<jstring>(string.object<jstring>());
+ QVERIFY(object.isValid());
+ QCOMPARE(string.toString(), object.toString());
+ }
+
+ {
+ QJniEnvironment env;
+ jclass javaStringClass = env->FindClass("java/lang/String");
+ QJniObject string(javaStringClass);
+ QVERIFY(string.isValid());
+ }
+
+ {
+ QJniEnvironment env;
+ const QString qString = QLatin1String("Hello, Java");
+ jclass javaStringClass = env->FindClass("java/lang/String");
+ QJniObject string = QJniObject::fromString(qString);
+ QJniObject stringCpy(javaStringClass, "(Ljava/lang/String;)V", string.object<jstring>());
+ QVERIFY(stringCpy.isValid());
+ QCOMPARE(qString, stringCpy.toString());
+ }
+
+ {
+ QJniEnvironment env;
+ const QString qString = QLatin1String("Hello, Java");
+ jclass javaStringClass = env->FindClass("java/lang/String");
+ QJniObject string = QJniObject::fromString(qString);
+ QJniObject stringCpy(javaStringClass, string.object<jstring>());
+ QVERIFY(stringCpy.isValid());
+ QCOMPARE(qString, stringCpy.toString());
+ }
+}
+
+void tst_QJniObject::callMethodTest()
+{
+ {
+ const QString qString1 = u"Hello, Java"_s;
+ const QString qString2 = u"hELLO, jAVA"_s;
+ QJniObject jString1 = QJniObject::fromString(qString1);
+ QJniObject jString2 = QJniObject::fromString(qString2);
+ QVERIFY(jString1 != jString2);
+
+ const jboolean isEmpty = jString1.callMethod<jboolean>("isEmpty");
+ QVERIFY(!isEmpty);
+
+ jint ret = jString1.callMethod<jint>("compareToIgnoreCase",
+ "(Ljava/lang/String;)I",
+ jString2.object<jstring>());
+ QVERIFY(0 == ret);
+
+ ret = jString1.callMethod<jint>("compareToIgnoreCase", jString2.object<jstring>());
+ QVERIFY(0 == ret);
+
+ // as of Qt 6.7, we can pass QString directly
+ ret = jString1.callMethod<jint>("compareToIgnoreCase", qString2);
+ QVERIFY(0 == ret);
+ }
+
+ {
+ jlong jLong = 100;
+ QJniObject longObject("java/lang/Long", "(J)V", jLong);
+ jlong ret = longObject.callMethod<jlong>("longValue");
+ QCOMPARE(ret, jLong);
+ }
+
+ // as of Qt 6.4, callMethod works with an object type as well!
+ {
+ const QString qString = QLatin1String("Hello, Java");
+ QJniObject jString = QJniObject::fromString(qString);
+ const QString qStringRet = jString.callMethod<jstring>("toUpperCase").toString();
+ QCOMPARE(qString.toUpper(), qStringRet);
+
+ QJniObject subString = jString.callMethod<jstring>("substring", 0, 4);
+ QCOMPARE(subString.toString(), qString.mid(0, 4));
+
+ // and as of Qt 6.7, we can return and take QString directly
+ QCOMPARE(jString.callMethod<QString>("substring", 0, 4), qString.mid(0, 4));
+
+ QCOMPARE(jString.callMethod<jstring>("substring", 0, 7)
+ .callMethod<jstring>("toUpperCase")
+ .callMethod<QString>("concat", u"C++"_s), u"HELLO, C++"_s);
+ }
+}
+
+void tst_QJniObject::callMethodThrowsException()
+{
+ QtJniTypes::QtJniObjectTestClass instance;
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.Exception"));
+ auto res = instance.callMethod<jobject>("callMethodThrowsException");
+ QVERIFY(!res.isValid());
+ QVERIFY(!QJniEnvironment().checkAndClearExceptions());
+}
+
+void tst_QJniObject::callObjectMethodTest()
+{
+ const QString qString = QLatin1String("Hello, Java");
+ QJniObject jString = QJniObject::fromString(qString);
+ const QString qStringRet = jString.callObjectMethod<jstring>("toUpperCase").toString();
+ QCOMPARE(qString.toUpper(), qStringRet);
+
+ QJniObject subString = jString.callObjectMethod("substring",
+ "(II)Ljava/lang/String;",
+ 0, 4);
+ QCOMPARE(subString.toString(), qString.mid(0, 4));
+
+ subString = jString.callObjectMethod<jstring>("substring", 0, 4);
+ QCOMPARE(subString.toString(), qString.mid(0, 4));
+
+}
+
+void tst_QJniObject::stringConvertionTest()
+{
+ const QString qString(QLatin1String("Hello, Java"));
+ QJniObject jString = QJniObject::fromString(qString);
+ QVERIFY(jString.isValid());
+ QString qStringRet = jString.toString();
+ QCOMPARE(qString, qStringRet);
+}
+
+void tst_QJniObject::compareOperatorTests()
+{
+ QString str("hello!");
+ QJniObject stringObject = QJniObject::fromString(str);
+
+ jobject obj = stringObject.object();
+ jobject jobj = stringObject.object<jobject>();
+ jstring jsobj = stringObject.object<jstring>();
+
+ QVERIFY(obj == stringObject);
+ QVERIFY(jobj == stringObject);
+ QVERIFY(stringObject == jobj);
+ QVERIFY(jsobj == stringObject);
+ QVERIFY(stringObject == jsobj);
+
+ QJniObject stringObject3 = stringObject.object<jstring>();
+ QVERIFY(stringObject3 == stringObject);
+
+ QJniObject stringObject2 = QJniObject::fromString(str);
+ QVERIFY(stringObject != stringObject2);
+
+ jstring jstrobj = nullptr;
+ QJniObject invalidStringObject;
+ QVERIFY(invalidStringObject == jstrobj);
+
+ QVERIFY(jstrobj != stringObject);
+ QVERIFY(stringObject != jstrobj);
+ QVERIFY(!invalidStringObject.isValid());
+}
+
+void tst_QJniObject::className()
+{
+ const QString str("Hello!");
+ QJniObject jString = QJniObject::fromString(str);
+ {
+ QCOMPARE(jString.className(), "java/lang/String");
+ QCOMPARE(jString.toString(), str);
+ }
+
+ {
+ QJniObject strObject = QJniObject("java/lang/String", str);
+ QCOMPARE(strObject.className(), "java/lang/String");
+ QCOMPARE(strObject.toString(), str);
+ }
+
+ {
+ TestClass test;
+ QCOMPARE(test.className(), testClassName);
+ }
+}
+
+void tst_QJniObject::callStaticMethodThrowsException()
+{
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.Exception"));
+ auto res = QtJniTypes::QtJniObjectTestClass::callStaticMethod<jobject>(
+ "callStaticMethodThrowsException");
+ QVERIFY(!res.isValid());
+ QVERIFY(!QJniEnvironment().checkAndClearExceptions());
+}
+
+void tst_QJniObject::callStaticObjectMethodClassName()
+{
+ QJniObject formatString = QJniObject::fromString(QLatin1String("test format"));
+ QVERIFY(formatString.isValid());
+
+ QVERIFY(QJniObject::isClassAvailable("java/lang/String"));
+ QJniObject returnValue = QJniObject::callStaticObjectMethod("java/lang/String",
+ "format",
+ "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;",
+ formatString.object<jstring>(),
+ jobjectArray(0));
+ QVERIFY(returnValue.isValid());
+
+ QString returnedString = returnValue.toString();
+
+ QCOMPARE(returnedString, QString::fromLatin1("test format"));
+
+ returnValue = QJniObject::callStaticObjectMethod<jstring>("java/lang/String",
+ "format",
+ formatString.object<jstring>(),
+ jobjectArray(0));
+ QVERIFY(returnValue.isValid());
+
+ returnedString = returnValue.toString();
+
+ QCOMPARE(returnedString, QString::fromLatin1("test format"));
+}
+
+void tst_QJniObject::callStaticObjectMethod()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/String");
+ QVERIFY(cls != 0);
+
+ const QString string = u"test format"_s;
+ QJniObject formatString = QJniObject::fromString(string);
+ QVERIFY(formatString.isValid());
+
+ QJniObject returnValue = QJniObject::callStaticObjectMethod(cls,
+ "format",
+ "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;",
+ formatString.object<jstring>(),
+ jobjectArray(0));
+ QVERIFY(returnValue.isValid());
+ QCOMPARE(returnValue.toString(), string);
+
+ returnValue = QJniObject::callStaticObjectMethod<jstring>(cls,
+ "format",
+ formatString.object<jstring>(),
+ jobjectArray(0));
+ QVERIFY(returnValue.isValid());
+ QCOMPARE(returnValue.toString(), string);
+
+ // from 6.4 on we can use callStaticMethod
+ returnValue = QJniObject::callStaticMethod<jstring>(cls,
+ "format",
+ formatString.object<jstring>(),
+ jobjectArray(0));
+ QVERIFY(returnValue.isValid());
+ QCOMPARE(returnValue.toString(), string);
+
+ // from 6.7 we can use callStaticMethod without specifying the class string
+ returnValue = QJniObject::callStaticMethod<jstring, jstring>("format",
+ formatString.object<jstring>(),
+ jobjectArray(0));
+ QVERIFY(returnValue.isValid());
+ QCOMPARE(returnValue.toString(), string);
+
+ // from 6.7 we can pass QString directly, both as parameters and return type
+ QString result = QJniObject::callStaticMethod<jstring, QString>("format",
+ string,
+ jobjectArray(0));
+ QCOMPARE(result, string);
+}
+
+void tst_QJniObject::callStaticObjectMethodById()
+{
+ QJniEnvironment env;
+ jclass cls = env.findClass("java/lang/String");
+ QVERIFY(cls != 0);
+
+ jmethodID id = env.findStaticMethod(
+ cls, "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;");
+ QVERIFY(id != 0);
+
+ QJniObject formatString = QJniObject::fromString(QLatin1String("test format"));
+ QVERIFY(formatString.isValid());
+
+ QJniObject returnValue = QJniObject::callStaticObjectMethod(
+ cls, id, formatString.object<jstring>(), jobjectArray(0));
+ QVERIFY(returnValue.isValid());
+
+ QString returnedString = returnValue.toString();
+
+ QCOMPARE(returnedString, QString::fromLatin1("test format"));
+
+ // from Qt 6.4 on we can use callStaticMethod as well
+ returnValue = QJniObject::callStaticMethod<jstring>(
+ cls, id, formatString.object<jstring>(), jobjectArray(0));
+ QVERIFY(returnValue.isValid());
+
+ returnedString = returnValue.toString();
+
+ QCOMPARE(returnedString, QString::fromLatin1("test format"));
+}
+
+void tst_QJniObject::callStaticBooleanMethod()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Boolean");
+ QVERIFY(cls != 0);
+
+ {
+ QJniObject parameter = QJniObject::fromString("true");
+ QVERIFY(parameter.isValid());
+
+ jboolean b = QJniObject::callStaticMethod<jboolean>(cls,
+ "parseBoolean",
+ "(Ljava/lang/String;)Z",
+ parameter.object<jstring>());
+ QVERIFY(b);
+
+ b = QJniObject::callStaticMethod<jboolean>(cls, "parseBoolean", parameter.object<jstring>());
+ QVERIFY(b);
+ }
+
+ {
+ QJniObject parameter = QJniObject::fromString("false");
+ QVERIFY(parameter.isValid());
+
+ jboolean b = QJniObject::callStaticMethod<jboolean>(cls,
+ "parseBoolean",
+ "(Ljava/lang/String;)Z",
+ parameter.object<jstring>());
+ QVERIFY(!b);
+
+ b = QJniObject::callStaticMethod<jboolean>(cls, "parseBoolean", parameter.object<jstring>());
+ QVERIFY(!b);
+ }
+}
+
+void tst_QJniObject::callStaticBooleanMethodById()
+{
+ QJniEnvironment env;
+ jclass cls = env.findClass("java/lang/Boolean");
+ QVERIFY(cls != 0);
+
+ jmethodID id = env.findStaticMethod(cls, "parseBoolean", "(Ljava/lang/String;)Z");
+ QVERIFY(id != 0);
+
+ {
+ QJniObject parameter = QJniObject::fromString("true");
+ QVERIFY(parameter.isValid());
+
+ jboolean b = QJniObject::callStaticMethod<jboolean>(cls, id, parameter.object<jstring>());
+ QVERIFY(b);
+ }
+
+ {
+ QJniObject parameter = QJniObject::fromString("false");
+ QVERIFY(parameter.isValid());
+
+ jboolean b = QJniObject::callStaticMethod<jboolean>(cls, id, parameter.object<jstring>());
+ QVERIFY(!b);
+ }
+}
+
+void tst_QJniObject::callStaticBooleanMethodClassName()
+{
+ {
+ QJniObject parameter = QJniObject::fromString("true");
+ QVERIFY(parameter.isValid());
+
+ jboolean b = QJniObject::callStaticMethod<jboolean>("java/lang/Boolean",
+ "parseBoolean",
+ "(Ljava/lang/String;)Z",
+ parameter.object<jstring>());
+ QVERIFY(b);
+ b = QJniObject::callStaticMethod<jboolean>("java/lang/Boolean",
+ "parseBoolean",
+ parameter.object<jstring>());
+ QVERIFY(b);
+ }
+
+ {
+ QJniObject parameter = QJniObject::fromString("false");
+ QVERIFY(parameter.isValid());
+
+ jboolean b = QJniObject::callStaticMethod<jboolean>("java/lang/Boolean",
+ "parseBoolean",
+ "(Ljava/lang/String;)Z",
+ parameter.object<jstring>());
+ QVERIFY(!b);
+ b = QJniObject::callStaticMethod<jboolean>("java/lang/Boolean",
+ "parseBoolean",
+ parameter.object<jstring>());
+ QVERIFY(!b);
+ }
+}
+
+void tst_QJniObject::callStaticByteMethodClassName()
+{
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jbyte returnValue = QJniObject::callStaticMethod<jbyte>("java/lang/Byte",
+ "parseByte",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, jbyte(number.toInt()));
+}
+
+void tst_QJniObject::callStaticByteMethod()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Byte");
+ QVERIFY(cls != 0);
+
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jbyte returnValue = QJniObject::callStaticMethod<jbyte>(cls,
+ "parseByte",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, jbyte(number.toInt()));
+}
+
+void tst_QJniObject::callStaticByteMethodById()
+{
+ QJniEnvironment env;
+ jclass cls = env.findClass("java/lang/Byte");
+ QVERIFY(cls != 0);
+
+ jmethodID id = env.findStaticMethod(cls, "parseByte", "(Ljava/lang/String;)B");
+ QVERIFY(id != 0);
+
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jbyte returnValue = QJniObject::callStaticMethod<jbyte>(cls, id, parameter.object<jstring>());
+ QCOMPARE(returnValue, jbyte(number.toInt()));
+}
+
+void tst_QJniObject::callStaticIntMethodClassName()
+{
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jint returnValue = QJniObject::callStaticMethod<jint>("java/lang/Integer",
+ "parseInt",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toInt());
+}
+
+
+void tst_QJniObject::callStaticIntMethod()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Integer");
+ QVERIFY(cls != 0);
+
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jint returnValue = QJniObject::callStaticMethod<jint>(cls,
+ "parseInt",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toInt());
+}
+
+void tst_QJniObject::callStaticIntMethodById()
+{
+ QJniEnvironment env;
+ jclass cls = env.findClass("java/lang/Integer");
+ QVERIFY(cls != 0);
+
+ jmethodID id = env.findStaticMethod(cls, "parseInt", "(Ljava/lang/String;)I");
+ QVERIFY(id != 0);
+
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jint returnValue = QJniObject::callStaticMethod<jint>(cls, id, parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toInt());
+}
+
+void tst_QJniObject::callStaticCharMethodClassName()
+{
+ jchar returnValue = QJniObject::callStaticMethod<jchar>("java/lang/Character",
+ "toUpperCase",
+ jchar('a'));
+ QCOMPARE(returnValue, jchar('A'));
+}
+
+
+void tst_QJniObject::callStaticCharMethod()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Character");
+ QVERIFY(cls != 0);
+
+ jchar returnValue = QJniObject::callStaticMethod<jchar>(cls,
+ "toUpperCase",
+ jchar('a'));
+ QCOMPARE(returnValue, jchar('A'));
+}
+
+void tst_QJniObject::callStaticCharMethodById()
+{
+ QJniEnvironment env;
+ jclass cls = env.findClass("java/lang/Character");
+ QVERIFY(cls != 0);
+
+ jmethodID id = env.findStaticMethod(cls, "toUpperCase", "(C)C");
+ QVERIFY(id != 0);
+
+ jchar returnValue = QJniObject::callStaticMethod<jchar>(cls, id, jchar('a'));
+ QCOMPARE(returnValue, jchar('A'));
+}
+
+void tst_QJniObject::callStaticDoubleMethodClassName ()
+{
+ QString number = QString::number(123.45);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jdouble returnValue = QJniObject::callStaticMethod<jdouble>("java/lang/Double",
+ "parseDouble",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toDouble());
+}
+
+
+void tst_QJniObject::callStaticDoubleMethod()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Double");
+ QVERIFY(cls != 0);
+
+ QString number = QString::number(123.45);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jdouble returnValue = QJniObject::callStaticMethod<jdouble>(cls,
+ "parseDouble",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toDouble());
+}
+
+void tst_QJniObject::callStaticDoubleMethodById()
+{
+ QJniEnvironment env;
+ jclass cls = env.findClass("java/lang/Double");
+ QVERIFY(cls != 0);
+
+ jmethodID id = env.findStaticMethod(cls, "parseDouble", "(Ljava/lang/String;)D");
+ QVERIFY(id != 0);
+
+ QString number = QString::number(123.45);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jdouble returnValue =
+ QJniObject::callStaticMethod<jdouble>(cls, id, parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toDouble());
+}
+
+void tst_QJniObject::callStaticFloatMethodClassName()
+{
+ QString number = QString::number(123.45);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jfloat returnValue = QJniObject::callStaticMethod<jfloat>("java/lang/Float",
+ "parseFloat",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toFloat());
+}
+
+
+void tst_QJniObject::callStaticFloatMethod()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Float");
+ QVERIFY(cls != 0);
+
+ QString number = QString::number(123.45);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jfloat returnValue = QJniObject::callStaticMethod<jfloat>(cls,
+ "parseFloat",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toFloat());
+}
+
+void tst_QJniObject::callStaticFloatMethodById()
+{
+ QJniEnvironment env;
+ jclass cls = env.findClass("java/lang/Float");
+ QVERIFY(cls != 0);
+
+ jmethodID id = env.findStaticMethod(cls, "parseFloat", "(Ljava/lang/String;)F");
+ QVERIFY(id != 0);
+
+ QString number = QString::number(123.45);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jfloat returnValue = QJniObject::callStaticMethod<jfloat>(cls, id, parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toFloat());
+}
+
+void tst_QJniObject::callStaticShortMethodClassName()
+{
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jshort returnValue = QJniObject::callStaticMethod<jshort>("java/lang/Short",
+ "parseShort",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toShort());
+}
+
+
+void tst_QJniObject::callStaticShortMethod()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Short");
+ QVERIFY(cls != 0);
+
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jshort returnValue = QJniObject::callStaticMethod<jshort>(cls,
+ "parseShort",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toShort());
+}
+
+void tst_QJniObject::callStaticShortMethodById()
+{
+ QJniEnvironment env;
+ jclass cls = env.findClass("java/lang/Short");
+ QVERIFY(cls != 0);
+
+ jmethodID id = env.findStaticMethod(cls, "parseShort", "(Ljava/lang/String;)S");
+ QVERIFY(id != 0);
+
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jshort returnValue = QJniObject::callStaticMethod<jshort>(cls, id, parameter.object<jstring>());
+ QCOMPARE(returnValue, number.toShort());
+}
+
+void tst_QJniObject::callStaticLongMethodClassName()
+{
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jlong returnValue = QJniObject::callStaticMethod<jlong>("java/lang/Long",
+ "parseLong",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, jlong(number.toLong()));
+}
+
+void tst_QJniObject::callStaticLongMethod()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Long");
+ QVERIFY(cls != 0);
+
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jlong returnValue = QJniObject::callStaticMethod<jlong>(cls,
+ "parseLong",
+ parameter.object<jstring>());
+ QCOMPARE(returnValue, jlong(number.toLong()));
+}
+
+void tst_QJniObject::callStaticLongMethodById()
+{
+ QJniEnvironment env;
+ jclass cls = env.findClass("java/lang/Long");
+ QVERIFY(cls != 0);
+
+ jmethodID id = env.findStaticMethod(cls, "parseLong", "(Ljava/lang/String;)J");
+ QVERIFY(id != 0);
+
+ QString number = QString::number(123);
+ QJniObject parameter = QJniObject::fromString(number);
+
+ jlong returnValue = QJniObject::callStaticMethod<jlong>(cls, id, parameter.object<jstring>());
+ QCOMPARE(returnValue, jlong(number.toLong()));
+}
+
+void tst_QJniObject::getStaticObjectFieldClassName()
+{
+ {
+ QJniObject boolObject = QJniObject::getStaticObjectField("java/lang/Boolean",
+ "FALSE",
+ "Ljava/lang/Boolean;");
+ QVERIFY(boolObject.isValid());
+
+ jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue");
+ QVERIFY(!booleanValue);
+ }
+
+ {
+ QJniObject boolObject = QJniObject::getStaticObjectField("java/lang/Boolean",
+ "TRUE",
+ "Ljava/lang/Boolean;");
+ QVERIFY(boolObject.isValid());
+
+ jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue");
+ QVERIFY(booleanValue);
+ }
+
+ {
+ QJniObject boolObject = QJniObject::getStaticObjectField("java/lang/Boolean",
+ "FALSE",
+ "Ljava/lang/Boolean;");
+ QVERIFY(boolObject.isValid());
+ jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue");
+ QVERIFY(!booleanValue);
+ }
+}
+
+void tst_QJniObject::getStaticObjectField()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Boolean");
+ QVERIFY(cls != 0);
+
+ {
+ QJniObject boolObject = QJniObject::getStaticObjectField(cls,
+ "FALSE",
+ "Ljava/lang/Boolean;");
+ QVERIFY(boolObject.isValid());
+
+ jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue");
+ QVERIFY(!booleanValue);
+ }
+
+ {
+ QJniObject boolObject = QJniObject::getStaticObjectField(cls,
+ "TRUE",
+ "Ljava/lang/Boolean;");
+ QVERIFY(boolObject.isValid());
+
+ jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue");
+ QVERIFY(booleanValue);
+ }
+
+ {
+ QJniObject boolObject = QJniObject::getStaticObjectField(cls,
+ "FALSE",
+ "Ljava/lang/Boolean;");
+ QVERIFY(boolObject.isValid());
+
+ jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue");
+ QVERIFY(!booleanValue);
+ }
+}
+
+void tst_QJniObject::getStaticIntFieldClassName()
+{
+ jint i = QJniObject::getStaticField<jint>("java/lang/Double", "SIZE");
+ QCOMPARE(i, 64);
+}
+
+void tst_QJniObject::getStaticIntField()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Double");
+ QVERIFY(cls != 0);
+
+ jint i = QJniObject::getStaticField<jint>(cls, "SIZE");
+ QCOMPARE(i, 64);
+
+ enum class Enum { SIZE = 64 };
+ Enum e = QJniObject::getStaticField<Enum>(cls, "SIZE");
+ QCOMPARE(e, Enum::SIZE);
+}
+
+void tst_QJniObject::getStaticByteFieldClassName()
+{
+ jbyte i = QJniObject::getStaticField<jbyte>("java/lang/Byte", "MAX_VALUE");
+ QCOMPARE(i, jbyte(127));
+}
+
+void tst_QJniObject::getStaticByteField()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Byte");
+ QVERIFY(cls != 0);
+
+ jbyte i = QJniObject::getStaticField<jbyte>(cls, "MAX_VALUE");
+ QCOMPARE(i, jbyte(127));
+
+ enum class Enum : jbyte { MAX_VALUE = 127 };
+ Enum e = QJniObject::getStaticField<Enum>(cls, "MAX_VALUE");
+ QCOMPARE(e, Enum::MAX_VALUE);
+}
+
+void tst_QJniObject::getStaticBooleanField()
+{
+ QCOMPARE(TestClass::getStaticField<jboolean>("S_BOOLEAN_VAR"),
+ TestClass::getStaticField<bool>("S_BOOLEAN_VAR"));
+}
+
+void tst_QJniObject::getStaticLongFieldClassName()
+{
+ jlong i = QJniObject::getStaticField<jlong>("java/lang/Long", "MAX_VALUE");
+ QCOMPARE(i, jlong(9223372036854775807L));
+}
+
+void tst_QJniObject::getStaticLongField()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Long");
+ QVERIFY(cls != 0);
+
+ jlong i = QJniObject::getStaticField<jlong>(cls, "MAX_VALUE");
+ QCOMPARE(i, jlong(9223372036854775807L));
+
+ enum class Enum : jlong { MAX_VALUE = 9223372036854775807L };
+ Enum e = QJniObject::getStaticField<Enum>(cls, "MAX_VALUE");
+ QCOMPARE(e, Enum::MAX_VALUE);
+}
+
+void tst_QJniObject::getStaticDoubleFieldClassName()
+{
+ jdouble i = QJniObject::getStaticField<jdouble>("java/lang/Double", "NaN");
+ jlong *k = reinterpret_cast<jlong*>(&i);
+ QCOMPARE(*k, jlong(0x7ff8000000000000L));
+}
+
+void tst_QJniObject::getStaticDoubleField()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Double");
+ QVERIFY(cls != 0);
+
+ jdouble i = QJniObject::getStaticField<jdouble>(cls, "NaN");
+ jlong *k = reinterpret_cast<jlong*>(&i);
+ QCOMPARE(*k, jlong(0x7ff8000000000000L));
+}
+
+void tst_QJniObject::getStaticFloatFieldClassName()
+{
+ jfloat i = QJniObject::getStaticField<jfloat>("java/lang/Float", "NaN");
+ unsigned *k = reinterpret_cast<unsigned*>(&i);
+ QCOMPARE(*k, unsigned(0x7fc00000));
+}
+
+void tst_QJniObject::getStaticFloatField()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Float");
+ QVERIFY(cls != 0);
+
+ jfloat i = QJniObject::getStaticField<jfloat>(cls, "NaN");
+ unsigned *k = reinterpret_cast<unsigned*>(&i);
+ QCOMPARE(*k, unsigned(0x7fc00000));
+}
+
+void tst_QJniObject::getStaticShortFieldClassName()
+{
+ jshort i = QJniObject::getStaticField<jshort>("java/lang/Short", "MAX_VALUE");
+ QCOMPARE(i, jshort(32767));
+}
+
+void tst_QJniObject::getStaticShortField()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Short");
+ QVERIFY(cls != 0);
+
+ jshort i = QJniObject::getStaticField<jshort>(cls, "MAX_VALUE");
+ QCOMPARE(i, jshort(32767));
+ enum class Enum : jshort { MAX_VALUE = 32767 };
+ Enum e = QJniObject::getStaticField<Enum>(cls, "MAX_VALUE");
+ QCOMPARE(e, Enum::MAX_VALUE);
+}
+
+void tst_QJniObject::getStaticCharFieldClassName()
+{
+ jchar i = QJniObject::getStaticField<jchar>("java/lang/Character", "MAX_VALUE");
+ QCOMPARE(i, jchar(0xffff));
+}
+
+void tst_QJniObject::getStaticCharField()
+{
+ QJniEnvironment env;
+ jclass cls = env->FindClass("java/lang/Character");
+ QVERIFY(cls != 0);
+
+ jchar i = QJniObject::getStaticField<jchar>(cls, "MAX_VALUE");
+ QCOMPARE(i, jchar(0xffff));
+
+ enum class Enum : jchar { MAX_VALUE = 0xffff };
+ Enum e = QJniObject::getStaticField<Enum>(cls, "MAX_VALUE");
+ QCOMPARE(e, Enum::MAX_VALUE);
+}
+
+
+void tst_QJniObject::getBooleanField()
+{
+ QJniObject obj(testClassName);
+
+ QVERIFY(obj.isValid());
+ QVERIFY(obj.getField<jboolean>("BOOL_FIELD"));
+ QVERIFY(obj.getField<bool>("BOOL_FIELD"));
+}
+
+void tst_QJniObject::getIntField()
+{
+ QJniObject obj(testClassName);
+
+ QVERIFY(obj.isValid());
+ jint res = obj.getField<jint>("INT_FIELD");
+ QCOMPARE(res, 123);
+}
+
+template <typename T>
+void setField(const char *fieldName, T testValue)
+{
+ QJniObject obj(testClassName);
+ QVERIFY(obj.isValid());
+
+ obj.setField(fieldName, testValue);
+
+ T res = obj.getField<T>(fieldName);
+ QCOMPARE(res, testValue);
+}
+
+void tst_QJniObject::setIntField()
+{
+ setField("INT_VAR", 555);
+ enum class Enum : jint { VALUE = 555 };
+ setField("INT_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setByteField()
+{
+ setField("BYTE_VAR", jbyte(123));
+ enum class Enum : jbyte { VALUE = 123 };
+ setField("BYTE_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setLongField()
+{
+ setField("LONG_VAR", jlong(9223372036847758232L));
+ enum class Enum : jlong { VALUE = 9223372036847758232L };
+ setField("LONG_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setDoubleField()
+{
+ setField("DOUBLE_VAR", jdouble(1.2));
+}
+
+void tst_QJniObject::setFloatField()
+{
+ setField("FLOAT_VAR", jfloat(1.2));
+}
+
+void tst_QJniObject::setShortField()
+{
+ setField("SHORT_VAR", jshort(555));
+ enum class Enum : jshort { VALUE = 555 };
+ setField("SHORT_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setCharField()
+{
+ setField("CHAR_VAR", jchar('A'));
+ enum class Enum : jchar { VALUE = 'A' };
+ setField("CHAR_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setBooleanField()
+{
+ setField("BOOLEAN_VAR", jboolean(true));
+ setField("BOOLEAN_VAR", true);
+}
+
+void tst_QJniObject::setObjectField()
+{
+ QJniObject obj(testClassName);
+ QVERIFY(obj.isValid());
+
+ const QString qString = u"Hello"_s;
+ QJniObject testValue = QJniObject::fromString(qString);
+ obj.setField("STRING_OBJECT_VAR", testValue.object<jstring>());
+
+ QJniObject res = obj.getObjectField<jstring>("STRING_OBJECT_VAR");
+ QCOMPARE(res.toString(), testValue.toString());
+
+ // as of Qt 6.7, we can set and get strings directly
+ obj.setField("STRING_OBJECT_VAR", qString);
+ QCOMPARE(obj.getField<QString>("STRING_OBJECT_VAR"), qString);
+}
+
+template <typename T>
+void setStaticField(const char *fieldName, T testValue)
+{
+ QJniObject::setStaticField(testClassName, fieldName, testValue);
+
+ T res = QJniObject::getStaticField<T>(testClassName, fieldName);
+ QCOMPARE(res, testValue);
+
+ // use template overload to reset to default
+ T defaultValue = {};
+ TestClass::setStaticField(fieldName, defaultValue);
+ res = TestClass::getStaticField<T>(fieldName);
+ QCOMPARE(res, defaultValue);
+}
+
+void tst_QJniObject::setStaticIntField()
+{
+ setStaticField("S_INT_VAR", 555);
+ enum class Enum : jint { VALUE = 555 };
+ setStaticField("S_INT_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setStaticByteField()
+{
+ setStaticField("S_BYTE_VAR", jbyte(123));
+ enum class Enum : jbyte { VALUE = 123 };
+ setStaticField("S_BYTE_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setStaticLongField()
+{
+ setStaticField("S_LONG_VAR", jlong(9223372036847758232L));
+ enum class Enum : jlong { VALUE = 9223372036847758232L };
+ setStaticField("S_LONG_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setStaticDoubleField()
+{
+ setStaticField("S_DOUBLE_VAR", jdouble(1.2));
+}
+
+void tst_QJniObject::setStaticFloatField()
+{
+ setStaticField("S_FLOAT_VAR", jfloat(1.2));
+}
+
+void tst_QJniObject::setStaticShortField()
+{
+ setStaticField("S_SHORT_VAR", jshort(555));
+ enum class Enum : jshort { VALUE = 555 };
+ setStaticField("S_SHORT_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setStaticCharField()
+{
+ setStaticField("S_CHAR_VAR", jchar('A'));
+ enum class Enum : jchar { VALUE = 'A' };
+ setStaticField("S_CHAR_VAR", Enum::VALUE);
+}
+
+void tst_QJniObject::setStaticBooleanField()
+{
+ setStaticField("S_BOOLEAN_VAR", jboolean(true));
+ setStaticField("S_BOOLEAN_VAR", true);
+}
+
+void tst_QJniObject::setStaticObjectField()
+{
+ const QString qString = u"Hello"_s;
+ QJniObject testValue = QJniObject::fromString(qString);
+ QJniObject::setStaticField(testClassName, "S_STRING_OBJECT_VAR", testValue.object<jstring>());
+
+ QJniObject res = QJniObject::getStaticObjectField<jstring>(testClassName, "S_STRING_OBJECT_VAR");
+ QCOMPARE(res.toString(), testValue.toString());
+
+ // as of Qt 6.7, we can set and get strings directly
+ using namespace QtJniTypes;
+ QtJniObjectTestClass::setStaticField("S_STRING_OBJECT_VAR", qString);
+ QCOMPARE(QtJniObjectTestClass::getStaticField<QString>("S_STRING_OBJECT_VAR"), qString);
+}
+
+void tst_QJniObject::templateApiCheck()
+{
+ QJniObject testClass(testClassName);
+ QVERIFY(testClass.isValid());
+
+ // void ---------------------------------------------------------------------------------------
+ QJniObject::callStaticMethod<void>(testClassName, "staticVoidMethod");
+ QJniObject::callStaticMethod<void>(testClassName,
+ "staticVoidMethodWithArgs",
+ "(IZC)V",
+ 1,
+ true,
+ 'c');
+ QJniObject::callStaticMethod<void>(testClassName,
+ "staticVoidMethodWithArgs",
+ 1,
+ true,
+ 'c');
+
+ testClass.callMethod<void>("voidMethod");
+ testClass.callMethod<void>("voidMethodWithArgs", "(IZC)V", 1, true, 'c');
+ testClass.callMethod<void>("voidMethodWithArgs", 1, true, 'c');
+
+ // jboolean -----------------------------------------------------------------------------------
+ QVERIFY(QJniObject::callStaticMethod<jboolean>(testClassName, "staticBooleanMethod"));
+ QVERIFY(QJniObject::callStaticMethod<jboolean>(testClassName,
+ "staticBooleanMethodWithArgs",
+ "(ZZZ)Z",
+ true,
+ true,
+ true));
+ QVERIFY(QJniObject::callStaticMethod<jboolean>(testClassName,
+ "staticBooleanMethodWithArgs",
+ true,
+ true,
+ true));
+
+ QVERIFY(testClass.callMethod<jboolean>("booleanMethod"));
+ QVERIFY(testClass.callMethod<jboolean>("booleanMethodWithArgs",
+ "(ZZZ)Z",
+ true,
+ true,
+ true));
+ QVERIFY(testClass.callMethod<jboolean>("booleanMethodWithArgs",
+ true,
+ true,
+ true));
+
+ // jbyte --------------------------------------------------------------------------------------
+ QVERIFY(QJniObject::callStaticMethod<jbyte>(testClassName,
+ "staticByteMethod") == A_BYTE_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jbyte>(testClassName,
+ "staticByteMethodWithArgs",
+ "(BBB)B",
+ 1,
+ 1,
+ 1) == A_BYTE_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jbyte>(testClassName,
+ "staticByteMethodWithArgs",
+ jbyte(1),
+ jbyte(1),
+ jbyte(1)) == A_BYTE_VALUE);
+
+ QVERIFY(testClass.callMethod<jbyte>("byteMethod") == A_BYTE_VALUE);
+ QVERIFY(testClass.callMethod<jbyte>("byteMethodWithArgs", "(BBB)B", 1, 1, 1) == A_BYTE_VALUE);
+ QVERIFY(testClass.callMethod<jbyte>("byteMethodWithArgs", jbyte(1), jbyte(1), jbyte(1)) == A_BYTE_VALUE);
+
+ // jchar --------------------------------------------------------------------------------------
+ QVERIFY(QJniObject::callStaticMethod<jchar>(testClassName,
+ "staticCharMethod") == A_CHAR_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jchar>(testClassName,
+ "staticCharMethodWithArgs",
+ "(CCC)C",
+ jchar(1),
+ jchar(1),
+ jchar(1)) == A_CHAR_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jchar>(testClassName,
+ "staticCharMethodWithArgs",
+ jchar(1),
+ jchar(1),
+ jchar(1)) == A_CHAR_VALUE);
+
+ QVERIFY(testClass.callMethod<jchar>("charMethod") == A_CHAR_VALUE);
+ QVERIFY(testClass.callMethod<jchar>("charMethodWithArgs",
+ "(CCC)C",
+ jchar(1),
+ jchar(1),
+ jchar(1)) == A_CHAR_VALUE);
+ QVERIFY(testClass.callMethod<jchar>("charMethodWithArgs",
+ jchar(1),
+ jchar(1),
+ jchar(1)) == A_CHAR_VALUE);
+
+ // jshort -------------------------------------------------------------------------------------
+ QVERIFY(QJniObject::callStaticMethod<jshort>(testClassName,
+ "staticShortMethod") == A_SHORT_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jshort>(testClassName,
+ "staticShortMethodWithArgs",
+ "(SSS)S",
+ jshort(1),
+ jshort(1),
+ jshort(1)) == A_SHORT_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jshort>(testClassName,
+ "staticShortMethodWithArgs",
+ jshort(1),
+ jshort(1),
+ jshort(1)) == A_SHORT_VALUE);
+
+ QVERIFY(testClass.callMethod<jshort>("shortMethod") == A_SHORT_VALUE);
+ QVERIFY(testClass.callMethod<jshort>("shortMethodWithArgs",
+ "(SSS)S",
+ jshort(1),
+ jshort(1),
+ jshort(1)) == A_SHORT_VALUE);
+ QVERIFY(testClass.callMethod<jshort>("shortMethodWithArgs",
+ jshort(1),
+ jshort(1),
+ jshort(1)) == A_SHORT_VALUE);
+
+ // jint ---------------------------------------------------------------------------------------
+ QVERIFY(QJniObject::callStaticMethod<jint>(testClassName,
+ "staticIntMethod") == A_INT_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jint>(testClassName,
+ "staticIntMethodWithArgs",
+ "(III)I",
+ jint(1),
+ jint(1),
+ jint(1)) == A_INT_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jint>(testClassName,
+ "staticIntMethodWithArgs",
+ jint(1),
+ jint(1),
+ jint(1)) == A_INT_VALUE);
+
+ QVERIFY(testClass.callMethod<jint>("intMethod") == A_INT_VALUE);
+ QVERIFY(testClass.callMethod<jint>("intMethodWithArgs",
+ "(III)I",
+ jint(1),
+ jint(1),
+ jint(1)) == A_INT_VALUE);
+ QVERIFY(testClass.callMethod<jint>("intMethodWithArgs",
+ jint(1),
+ jint(1),
+ jint(1)) == A_INT_VALUE);
+
+ // jlong --------------------------------------------------------------------------------------
+ QVERIFY(QJniObject::callStaticMethod<jlong>(testClassName,
+ "staticLongMethod") == A_LONG_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jlong>(testClassName,
+ "staticLongMethodWithArgs",
+ "(JJJ)J",
+ jlong(1),
+ jlong(1),
+ jlong(1)) == A_LONG_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jlong>(testClassName,
+ "staticLongMethodWithArgs",
+ jlong(1),
+ jlong(1),
+ jlong(1)) == A_LONG_VALUE);
+
+ QVERIFY(testClass.callMethod<jlong>("longMethod") == A_LONG_VALUE);
+ QVERIFY(testClass.callMethod<jlong>("longMethodWithArgs",
+ "(JJJ)J",
+ jlong(1),
+ jlong(1),
+ jlong(1)) == A_LONG_VALUE);
+ QVERIFY(testClass.callMethod<jlong>("longMethodWithArgs",
+ jlong(1),
+ jlong(1),
+ jlong(1)) == A_LONG_VALUE);
+
+ // jfloat -------------------------------------------------------------------------------------
+ QVERIFY(QJniObject::callStaticMethod<jfloat>(testClassName,
+ "staticFloatMethod") == A_FLOAT_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jfloat>(testClassName,
+ "staticFloatMethodWithArgs",
+ "(FFF)F",
+ jfloat(1.1),
+ jfloat(1.1),
+ jfloat(1.1)) == A_FLOAT_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jfloat>(testClassName,
+ "staticFloatMethodWithArgs",
+ jfloat(1.1),
+ jfloat(1.1),
+ jfloat(1.1)) == A_FLOAT_VALUE);
+
+ QVERIFY(testClass.callMethod<jfloat>("floatMethod") == A_FLOAT_VALUE);
+ QVERIFY(testClass.callMethod<jfloat>("floatMethodWithArgs",
+ "(FFF)F",
+ jfloat(1.1),
+ jfloat(1.1),
+ jfloat(1.1)) == A_FLOAT_VALUE);
+ QVERIFY(testClass.callMethod<jfloat>("floatMethodWithArgs",
+ jfloat(1.1),
+ jfloat(1.1),
+ jfloat(1.1)) == A_FLOAT_VALUE);
+
+ // jdouble ------------------------------------------------------------------------------------
+ QVERIFY(QJniObject::callStaticMethod<jdouble>(testClassName,
+ "staticDoubleMethod") == A_DOUBLE_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jdouble>(testClassName,
+ "staticDoubleMethodWithArgs",
+ "(DDD)D",
+ jdouble(1.1),
+ jdouble(1.1),
+ jdouble(1.1)) == A_DOUBLE_VALUE);
+ QVERIFY(QJniObject::callStaticMethod<jdouble>(testClassName,
+ "staticDoubleMethodWithArgs",
+ jdouble(1.1),
+ jdouble(1.1),
+ jdouble(1.1)) == A_DOUBLE_VALUE);
+
+ QVERIFY(testClass.callMethod<jdouble>("doubleMethod") == A_DOUBLE_VALUE);
+ QVERIFY(testClass.callMethod<jdouble>("doubleMethodWithArgs",
+ "(DDD)D",
+ jdouble(1.1),
+ jdouble(1.1),
+ jdouble(1.1)) == A_DOUBLE_VALUE);
+ QVERIFY(testClass.callMethod<jdouble>("doubleMethodWithArgs",
+ jdouble(1.1),
+ jdouble(1.1),
+ jdouble(1.1)) == A_DOUBLE_VALUE);
+
+ // jobject ------------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jobject>(testClassName,
+ "staticObjectMethod");
+ QVERIFY(res.isValid());
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jobject>("objectMethod");
+ QVERIFY(res.isValid());
+ }
+
+ // jclass -------------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jclass>(testClassName,
+ "staticClassMethod");
+ QVERIFY(res.isValid());
+ QJniEnvironment env;
+ QVERIFY(env->IsInstanceOf(testClass.object(), res.object<jclass>()));
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jclass>("classMethod");
+ QVERIFY(res.isValid());
+ QJniEnvironment env;
+ QVERIFY(env->IsInstanceOf(testClass.object(), res.object<jclass>()));
+ }
+ // jstring ------------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jstring>(testClassName,
+ "staticStringMethod");
+ QVERIFY(res.isValid());
+ QVERIFY(res.toString() == A_STRING_OBJECT());
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jstring>("stringMethod");
+ QVERIFY(res.isValid());
+ QVERIFY(res.toString() == A_STRING_OBJECT());
+
+ }
+ // jthrowable ---------------------------------------------------------------------------------
+ {
+ // The Throwable object the same message (see: "getMessage()") as A_STRING_OBJECT
+ QJniObject res = QJniObject::callStaticObjectMethod<jthrowable>(testClassName,
+ "staticThrowableMethod");
+ QVERIFY(res.isValid());
+ QVERIFY(res.callObjectMethod<jstring>("getMessage").toString() == A_STRING_OBJECT());
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jthrowable>("throwableMethod");
+ QVERIFY(res.isValid());
+ QVERIFY(res.callObjectMethod<jstring>("getMessage").toString() == A_STRING_OBJECT());
+ }
+
+ // jobjectArray -------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jobjectArray>(testClassName,
+ "staticObjectArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = TestClass::callStaticMethod<jobject[]>("staticObjectArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+
+ QJniArray<jobject> newArray(QList<QJniObject>{QJniObject::fromString(u"one"_s),
+ QJniObject::fromString(u"two"_s),
+ QJniObject::fromString(u"three"_s)});
+ QVERIFY(newArray.isValid());
+ const auto reverse = TestClass::callStaticMethod<jobject[]>("staticReverseObjectArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.size(), 3);
+ QCOMPARE(QJniObject(reverse.at(0)).toString(), u"three"_s);
+ QCOMPARE(QJniObject(reverse.at(1)).toString(), u"two"_s);
+ QCOMPARE(QJniObject(reverse.at(2)).toString(), u"one"_s);
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jobjectArray>("objectArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = testClass.callMethod<jobject[]>("objectArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+
+ QJniArray<jobject> newArray(QList<QJniObject>{QJniObject::fromString(u"one"_s),
+ QJniObject::fromString(u"two"_s),
+ QJniObject::fromString(u"three"_s)});
+ QVERIFY(newArray.isValid());
+ const auto reverse = testClass.callMethod<jobject[]>("reverseObjectArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.size(), 3);
+ // QJniArray::at returns a jobject that's a local reference; make sure we don't free it twice
+ QCOMPARE(QJniObject::fromLocalRef(reverse.at(0)).toString(), u"three"_s);
+ QCOMPARE(QJniObject::fromLocalRef(reverse.at(1)).toString(), u"two"_s);
+ QCOMPARE(QJniObject::fromLocalRef(reverse.at(2)).toString(), u"one"_s);
+ }
+
+ // jbooleanArray ------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jbooleanArray>(testClassName,
+ "staticBooleanArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = TestClass::callStaticMethod<jboolean[]>("staticBooleanArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jboolean>{true, true, true}));
+
+ QJniArray<jboolean> newArray(QList<jboolean>{true, false, false});
+ QVERIFY(newArray.isValid());
+ const auto reverse = TestClass::callStaticMethod<jboolean[]>("staticReverseBooleanArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jboolean>{false, false, true}));
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jbooleanArray>("booleanArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = testClass.callMethod<jboolean[]>("booleanArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jboolean>{true, true, true}));
+
+ QJniArray<jboolean> newArray(QList<jboolean>{true, false, false});
+ QVERIFY(newArray.isValid());
+ const auto reverse = testClass.callMethod<jboolean[]>("reverseBooleanArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jboolean>{false, false, true}));
+ }
+
+ // jbyteArray ---------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jbyteArray>(testClassName,
+ "staticByteArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = TestClass::callStaticMethod<jbyte[]>("staticByteArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), "abc");
+
+ QJniArray<jbyte> newArray(QByteArray{"cba"});
+ QVERIFY(newArray.isValid());
+ const auto reverse = TestClass::callStaticMethod<jbyte[]>("staticReverseByteArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), "abc");
+
+ const QByteArray reverse2 = TestClass::callStaticMethod<QByteArray>("staticReverseByteArray",
+ QByteArray("abc"));
+ QCOMPARE(reverse2, "cba");
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jbyteArray>("byteArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = testClass.callMethod<jbyte[]>("byteArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), "abc");
+
+ QJniArray<jbyte> newArray = QJniArrayBase::fromContainer(QByteArray{"cba"});
+ QVERIFY(newArray.isValid());
+ const auto reverse = testClass.callMethod<jbyte[]>("reverseByteArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), "abc");
+ }
+
+ // jcharArray ---------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jcharArray>(testClassName,
+ "staticCharArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = TestClass::callStaticMethod<jchar[]>("staticCharArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jchar>{u'a', u'b', u'c'}));
+
+ QJniArray<jchar> newArray = {u'c', u'b', u'a'};
+ QVERIFY(newArray.isValid());
+ const auto reverse = TestClass::callStaticMethod<jchar[]>("staticReverseCharArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jchar>{u'a', u'b', u'c'}));
+
+ const QList<jchar> reverse2 = TestClass::callStaticMethod<QList<jchar>>("staticReverseCharArray",
+ (QList<jchar>{u'c', u'b', u'a'}));
+ QCOMPARE(reverse2, (QList<jchar>{u'a', u'b', u'c'}));
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jcharArray>("charArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = testClass.callMethod<jchar[]>("charArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jchar>{u'a', u'b', u'c'}));
+
+ QJniArray<jchar> newArray = {u'c', u'b', u'a'};
+ QVERIFY(newArray.isValid());
+ const auto reverse = testClass.callMethod<jchar[]>("reverseCharArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jchar>{u'a', u'b', u'c'}));
+ }
+
+ // jshortArray --------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jshortArray>(testClassName,
+ "staticShortArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = TestClass::callStaticMethod<jshort[]>("staticShortArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jshort>{3, 2, 1}));
+
+ QJniArray<jshort> newArray = {3, 2, 1};
+ QVERIFY(newArray.isValid());
+ const auto reverse = TestClass::callStaticMethod<jshort[]>("staticReverseShortArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jshort>{1, 2, 3}));
+
+ const QList<jshort> reverse2 = TestClass::callStaticMethod<QList<jshort>>("staticReverseShortArray",
+ (QList<jshort>{1, 2, 3}));
+ QCOMPARE(reverse2, (QList<jshort>{3, 2, 1}));
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jshortArray>("shortArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = testClass.callMethod<jshort[]>("shortArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jshort>{3, 2, 1}));
+
+ QJniArray<jshort> newArray = {3, 2, 1};
+ static_assert(std::is_same_v<decltype(newArray)::Type, jshort>);
+ QVERIFY(newArray.isValid());
+ const auto reverse = testClass.callMethod<jshort[]>("reverseShortArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jshort>{1, 2, 3}));
+ }
+
+ // jintArray ----------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jintArray>(testClassName,
+ "staticIntArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = TestClass::callStaticMethod<jint[]>("staticIntArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jint>{3, 2, 1}));
+
+ QJniArray<jint> newArray = {3, 2, 1};
+ QVERIFY(newArray.isValid());
+ const auto reverse = TestClass::callStaticMethod<jint[]>("staticReverseIntArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jint>{1, 2, 3}));
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jintArray>("intArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = testClass.callMethod<jint[]>("intArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jint>{3, 2, 1}));
+
+ QJniArray<jint> newArray = {3, 2, 1};
+ QVERIFY(newArray.isValid());
+ const auto reverse = testClass.callMethod<jint[]>("reverseIntArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jint>{1, 2, 3}));
+ }
+
+ // jlongArray ---------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jlongArray>(testClassName,
+ "staticLongArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = TestClass::callStaticMethod<jlong[]>("staticLongArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jlong>{3, 2, 1}));
+
+ QJniArray<jlong> newArray = {3, 2, 1};
+ QVERIFY(newArray.isValid());
+ const auto reverse = TestClass::callStaticMethod<jlong[]>("staticReverseLongArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jlong>{1, 2, 3}));
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jlongArray>("longArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = testClass.callMethod<jlong[]>("longArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jlong>{3, 2, 1}));
+
+ QJniArray<jlong> newArray = {3, 2, 1};
+ QVERIFY(newArray.isValid());
+ const auto reverse = testClass.callMethod<jlong[]>("reverseLongArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jlong>{1, 2, 3}));
+ }
+
+ // jfloatArray --------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jfloatArray>(testClassName,
+ "staticFloatArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = TestClass::callStaticMethod<jfloat[]>("staticFloatArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jfloat>{1.0f, 2.0f, 3.0f}));
+
+ QJniArray<jfloat> newArray = {3.0f, 2.0f, 1.0f};
+ QVERIFY(newArray.isValid());
+ const auto reverse = TestClass::callStaticMethod<jfloat[]>("staticReverseFloatArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jfloat>{1.0f, 2.0f, 3.0f}));
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jfloatArray>("floatArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = testClass.callMethod<jfloat[]>("floatArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jfloat>{1.0f, 2.0f, 3.0f}));
+
+ QJniArray<jfloat> newArray = {3.0f, 2.0f, 1.0f};
+ QVERIFY(newArray.isValid());
+ const auto reverse = testClass.callMethod<jfloat[]>("reverseFloatArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jfloat>{1.0f, 2.0f, 3.0f}));
+ }
+
+ // jdoubleArray -------------------------------------------------------------------------------
+ {
+ QJniObject res = QJniObject::callStaticObjectMethod<jdoubleArray>(testClassName,
+ "staticDoubleArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = TestClass::callStaticMethod<jdouble[]>("staticDoubleArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jdouble>{3.0, 2.0, 1.0}));
+
+ QJniArray<jdouble> newArray = {3.0, 2.0, 1.0};
+ QVERIFY(newArray.isValid());
+ const auto reverse = TestClass::callStaticMethod<jdouble[]>("staticReverseDoubleArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jdouble>{1.0, 2.0, 3.0}));
+ }
+
+ {
+ QJniObject res = testClass.callObjectMethod<jdoubleArray>("doubleArrayMethod");
+ QVERIFY(res.isValid());
+
+ const auto array = testClass.callMethod<jdouble[]>("doubleArrayMethod");
+ QVERIFY(array.isValid());
+ QCOMPARE(array.size(), 3);
+ QCOMPARE(array.toContainer(), (QList<jdouble>{3.0, 2.0, 1.0}));
+
+ QJniArray<jdouble> newArray = {3.0, 2.0, 1.0};
+ QVERIFY(newArray.isValid());
+ const auto reverse = testClass.callMethod<jdouble[]>("reverseDoubleArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.toContainer(), (QList<jdouble>{1.0, 2.0, 3.0}));
+ }
+
+}
+
+void tst_QJniObject::isClassAvailable()
+{
+ QVERIFY(QJniObject::isClassAvailable("java/lang/String"));
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("java.lang.ClassNotFoundException"));
+ QVERIFY(!QJniObject::isClassAvailable("class/not/Available"));
+ QVERIFY(QJniObject::isClassAvailable("org/qtproject/qt/android/QtActivityDelegate"));
+}
+
+void tst_QJniObject::fromLocalRef()
+{
+ const int limit = 512 + 1;
+ QJniEnvironment env;
+ for (int i = 0; i != limit; ++i)
+ QJniObject o = QJniObject::fromLocalRef(env->FindClass("java/lang/String"));
+}
+
+void tst_QJniObject::largeObjectArray()
+{
+ QJniArray<jobject> newArray(QList<QJniObject>{QJniObject::fromString(u"one"_s),
+ QJniObject::fromString(u"two"_s),
+ QJniObject::fromString(u"three"_s)});
+ QVERIFY(newArray.isValid());
+ const QJniArray<QJniObject> reverse = TestClass::callStaticMethod<jobject[]>(
+ "staticReverseObjectArray", newArray);
+ QVERIFY(reverse.isValid());
+ QCOMPARE(reverse.size(), 3);
+
+ // make sure we don't leak local references
+ for (int i = 0; i < 10000; ++i) {
+ QVERIFY(reverse.at(0).isValid());
+ QVERIFY(reverse.at(1).isValid());
+ QVERIFY(reverse.at(2).isValid());
+ }
+}
+
+enum class CallbackParameterType
+{
+ Object,
+ ObjectRef,
+ String,
+ Byte,
+ Boolean,
+ Int,
+ Double,
+ JniArray,
+ QList,
+ QStringList,
+};
+
+static std::optional<TestClass> calledWithObject;
+static int callbackWithObject(JNIEnv *, jobject, TestClass that)
+{
+ calledWithObject.emplace(that);
+ return int(CallbackParameterType::Object);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithObject)
+static int callbackWithObjectRef(JNIEnv *, jobject, const TestClass &that)
+{
+ calledWithObject.emplace(that);
+ return int(CallbackParameterType::ObjectRef);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithObjectRef)
+
+static std::optional<QString> calledWithString;
+static int callbackWithString(JNIEnv *, jobject, const QString &string)
+{
+ calledWithString.emplace(string);
+ return int(CallbackParameterType::String);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithString)
+
+static std::optional<jbyte> calledWithByte;
+static int callbackWithByte(JNIEnv *, jobject, jbyte value)
+{
+ calledWithByte.emplace(value);
+ return int(CallbackParameterType::Byte);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithByte)
+
+static std::optional<jbyte> calledWithBoolean;
+static int callbackWithBoolean(JNIEnv *, jobject, bool value)
+{
+ calledWithBoolean.emplace(value);
+ return int(CallbackParameterType::Boolean);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithBoolean)
+
+static std::optional<int> calledWithInt;
+static int callbackWithInt(JNIEnv *, jobject, int value)
+{
+ calledWithInt.emplace(value);
+ return int(CallbackParameterType::Int);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithInt)
+
+static std::optional<double> calledWithDouble;
+static int callbackWithDouble(JNIEnv *, jobject, double value)
+{
+ calledWithDouble.emplace(value);
+ return int(CallbackParameterType::Double);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithDouble)
+
+static std::optional<QJniArray<jdouble>> calledWithJniArray;
+static int callbackWithJniArray(JNIEnv *, jobject, const QJniArray<jdouble> &value)
+{
+ calledWithJniArray.emplace(value);
+ return int(CallbackParameterType::JniArray);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithJniArray)
+
+static std::optional<QList<double>> calledWithQList;
+static int callbackWithQList(JNIEnv *, jobject, const QList<double> &value)
+{
+ calledWithQList.emplace(value);
+ return int(CallbackParameterType::QList);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithQList)
+
+static std::optional<QStringList> calledWithStringList;
+static int callbackWithStringList(JNIEnv *, jobject, const QStringList &value)
+{
+ calledWithStringList.emplace(value);
+ return int(CallbackParameterType::QStringList);
+}
+Q_DECLARE_JNI_NATIVE_METHOD(callbackWithStringList)
+
+void tst_QJniObject::callback_data()
+{
+ QTest::addColumn<CallbackParameterType>("parameterType");
+
+ QTest::addRow("Object") << CallbackParameterType::Object;
+ QTest::addRow("ObjectRef") << CallbackParameterType::ObjectRef;
+ QTest::addRow("String") << CallbackParameterType::String;
+ QTest::addRow("Byte") << CallbackParameterType::Byte;
+ QTest::addRow("Boolean") << CallbackParameterType::Boolean;
+ QTest::addRow("Int") << CallbackParameterType::Int;
+ QTest::addRow("Double") << CallbackParameterType::Double;
+ QTest::addRow("JniArray") << CallbackParameterType::JniArray;
+ QTest::addRow("QList") << CallbackParameterType::QList;
+ QTest::addRow("QStringList") << CallbackParameterType::QStringList;
+}
+
+void tst_QJniObject::callback()
+{
+ QFETCH(const CallbackParameterType, parameterType);
+
+ TestClass testObject;
+ int result = -1;
+
+ switch (parameterType) {
+ case CallbackParameterType::Object:
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithObject)
+ }));
+ result = testObject.callMethod<int>("callMeBackWithObject", testObject);
+ QVERIFY(calledWithObject);
+ QCOMPARE(calledWithObject.value(), testObject);
+ break;
+ case CallbackParameterType::ObjectRef:
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithObjectRef)
+ }));
+ result = testObject.callMethod<int>("callMeBackWithObjectRef", testObject);
+ QVERIFY(calledWithObject);
+ QCOMPARE(calledWithObject.value(), testObject);
+ break;
+ case CallbackParameterType::String:
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithString)
+ }));
+ result = testObject.callMethod<int>("callMeBackWithString", QString::number(123));
+ QVERIFY(calledWithString);
+ QCOMPARE(calledWithString.value(), "123");
+ break;
+ case CallbackParameterType::Byte:
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithByte)
+ }));
+ result = testObject.callMethod<int>("callMeBackWithByte", jbyte(123));
+ QVERIFY(calledWithByte);
+ QCOMPARE(calledWithByte.value(), 123);
+ break;
+ case CallbackParameterType::Boolean:
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithBoolean)
+ }));
+ result = testObject.callMethod<int>("callMeBackWithBoolean", true);
+ QVERIFY(calledWithBoolean);
+ QCOMPARE(calledWithBoolean.value(), true);
+ break;
+ case CallbackParameterType::Int:
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithInt)
+ }));
+ result = testObject.callMethod<int>("callMeBackWithInt", 12345);
+ QVERIFY(calledWithInt);
+ QCOMPARE(calledWithInt.value(), 12345);
+ break;
+ case CallbackParameterType::Double:
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithDouble)
+ }));
+ result = testObject.callMethod<int>("callMeBackWithDouble", 1.2345);
+ QVERIFY(calledWithDouble);
+ QCOMPARE(calledWithDouble.value(), 1.2345);
+ break;
+ case CallbackParameterType::JniArray: {
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithJniArray)
+ }));
+ const QJniArray<double> doubles = { 1.2, 3.4, 5.6 };
+ result = testObject.callMethod<int>("callMeBackWithJniArray", doubles);
+ QVERIFY(calledWithJniArray);
+ QCOMPARE(calledWithJniArray, doubles);
+ break;
+ }
+ case CallbackParameterType::QList: {
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithQList)
+ }));
+ const QList<double> doubles = { 1.2, 3.4, 5.6 };
+ result = testObject.callMethod<int>("callMeBackWithQList", doubles);
+ QVERIFY(calledWithQList);
+ QCOMPARE(calledWithQList.value(), doubles);
+ break;
+ }
+ case CallbackParameterType::QStringList: {
+ QVERIFY(TestClass::registerNativeMethods({
+ Q_JNI_NATIVE_METHOD(callbackWithStringList)
+ }));
+ const QStringList strings = { "one", "two" };
+ result = testObject.callMethod<int>("callMeBackWithStringList", strings);
+ QVERIFY(calledWithStringList);
+ QCOMPARE(calledWithStringList.value(), strings);
+ break;
+ }
+ }
+ QCOMPARE(result, int(parameterType));
+}
+
+// Make sure the new callStaticMethod overload taking a class, return type,
+// and argument as template parameters, doesn't break overload resolution
+// and that the class name doesn't get interpreted as the function name.
+void tst_QJniObject::callStaticOverloadResolution()
+{
+ const QString value = u"Hello World"_s;
+ QJniObject str = QJniObject::fromString(value);
+ const auto result = QJniObject::callStaticMethod<jstring, jstring>(
+ QtJniTypes::Traits<TestClass>::className(),
+ "staticEchoMethod", str.object<jstring>()).toString();
+ QCOMPARE(result, value);
+}
+
+QTEST_MAIN(tst_QJniObject)
+
+#include "tst_qjniobject.moc"
diff --git a/tests/auto/corelib/kernel/qjnitypes/CMakeLists.txt b/tests/auto/corelib/kernel/qjnitypes/CMakeLists.txt
new file mode 100644
index 0000000000..104b039d4d
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjnitypes/CMakeLists.txt
@@ -0,0 +1,13 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qjnitypes LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qjnitypes
+ SOURCES
+ tst_qjnitypes.cpp
+)
diff --git a/tests/auto/corelib/kernel/qjnitypes/tst_qjnitypes.cpp b/tests/auto/corelib/kernel/qjnitypes/tst_qjnitypes.cpp
new file mode 100644
index 0000000000..bf582041f3
--- /dev/null
+++ b/tests/auto/corelib/kernel/qjnitypes/tst_qjnitypes.cpp
@@ -0,0 +1,284 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QtTest>
+
+#include <QtCore/qjnitypes.h>
+#include <QtCore/qjniarray.h>
+
+using namespace Qt::StringLiterals;
+
+class tst_QJniTypes : public QObject
+{
+ Q_OBJECT
+
+public:
+ tst_QJniTypes() = default;
+
+ static void nativeClassMethod(JNIEnv *, jclass, int);
+ Q_DECLARE_JNI_NATIVE_METHOD_IN_CURRENT_SCOPE(nativeClassMethod);
+
+private slots:
+ void initTestCase();
+ void nativeMethod();
+ void construct();
+ void stringTypeCantBeArgument();
+};
+
+struct QtJavaWrapper {};
+template<>
+struct QtJniTypes::Traits<QtJavaWrapper>
+{
+ static constexpr auto signature()
+ {
+ return QtJniTypes::CTString("Lorg/qtproject/qt/android/QtJavaWrapper;");
+ }
+};
+
+template<>
+struct QtJniTypes::Traits<QJniObject>
+{
+ static constexpr auto signature()
+ {
+ return QtJniTypes::CTString("Ljava/lang/Object;");
+ }
+};
+
+struct QtCustomJniObject : QJniObject {};
+
+template<>
+struct QtJniTypes::Traits<QtCustomJniObject>
+{
+ static constexpr auto signature()
+ {
+ return QtJniTypes::CTString("Lorg/qtproject/qt/android/QtCustomJniObject;");
+ }
+};
+
+static_assert(QtJniTypes::Traits<QtJavaWrapper>::signature() == "Lorg/qtproject/qt/android/QtJavaWrapper;");
+static_assert(QtJniTypes::Traits<QtJavaWrapper>::signature() != "Ljava/lang/Object;");
+static_assert(!(QtJniTypes::Traits<QtJavaWrapper>::signature() == "X"));
+
+Q_DECLARE_JNI_CLASS(JavaType, "org/qtproject/qt/JavaType");
+static_assert(QtJniTypes::Traits<QtJniTypes::JavaType>::signature() == "Lorg/qtproject/qt/JavaType;");
+static_assert(QtJniTypes::Traits<QtJniTypes::JavaType[]>::signature() == "[Lorg/qtproject/qt/JavaType;");
+
+Q_DECLARE_JNI_CLASS(String, "java/lang/String");
+static_assert(QtJniTypes::Traits<jstring>::className() == "java/lang/String");
+static_assert(QtJniTypes::Traits<QtJniTypes::String>::className() == "java/lang/String");
+static_assert(QtJniTypes::Traits<QtJniTypes::String>::signature() == "Ljava/lang/String;");
+static_assert(QtJniTypes::Traits<QtJniTypes::String[]>::signature() == "[Ljava/lang/String;");
+
+Q_DECLARE_JNI_CLASS(QtTextToSpeech, "org/qtproject/qt/android/speech/QtTextToSpeech")
+static_assert(QtJniTypes::Traits<QtJniTypes::QtTextToSpeech>::className() == "org/qtproject/qt/android/speech/QtTextToSpeech");
+
+static_assert(QtJniTypes::fieldSignature<jint>() == "I");
+static_assert(QtJniTypes::fieldSignature<jint[]>() == "[I");
+static_assert(QtJniTypes::fieldSignature<jint>() != "X");
+static_assert(QtJniTypes::fieldSignature<jint>() != "Ljava/lang/Object;");
+static_assert(QtJniTypes::fieldSignature<jlong>() == "J");
+static_assert(QtJniTypes::fieldSignature<jstring>() == "Ljava/lang/String;");
+static_assert(QtJniTypes::fieldSignature<jobject>() == "Ljava/lang/Object;");
+static_assert(QtJniTypes::fieldSignature<jobject[]>() == "[Ljava/lang/Object;");
+static_assert(QtJniTypes::fieldSignature<jobjectArray>() == "[Ljava/lang/Object;");
+static_assert(QtJniTypes::fieldSignature<QJniObject>() == "Ljava/lang/Object;");
+static_assert(QtJniTypes::fieldSignature<QtJavaWrapper>() == "Lorg/qtproject/qt/android/QtJavaWrapper;");
+static_assert(QtJniTypes::fieldSignature<QtJavaWrapper[]>() == "[Lorg/qtproject/qt/android/QtJavaWrapper;");
+static_assert(QtJniTypes::fieldSignature<QtCustomJniObject>() == "Lorg/qtproject/qt/android/QtCustomJniObject;");
+
+static_assert(QtJniTypes::methodSignature<void>() == "()V");
+static_assert(QtJniTypes::methodSignature<void>() != "()X");
+static_assert(QtJniTypes::methodSignature<void, jint>() == "(I)V");
+static_assert(QtJniTypes::methodSignature<void, jint, jstring>() == "(ILjava/lang/String;)V");
+static_assert(QtJniTypes::methodSignature<jlong, jint, jclass>() == "(ILjava/lang/Class;)J");
+static_assert(QtJniTypes::methodSignature<jobject, jint, jstring>() == "(ILjava/lang/String;)Ljava/lang/Object;");
+static_assert(QtJniTypes::methodSignature<QtJniTypes::JavaType, jint, jstring>()
+ == "(ILjava/lang/String;)Lorg/qtproject/qt/JavaType;");
+
+static_assert(QtJniTypes::isPrimitiveType<jint>());
+static_assert(QtJniTypes::isPrimitiveType<void>());
+static_assert(!QtJniTypes::isPrimitiveType<jobject>());
+static_assert(!QtJniTypes::isPrimitiveType<QtCustomJniObject>());
+
+static_assert(!QtJniTypes::isObjectType<jint>());
+static_assert(!QtJniTypes::isObjectType<void>());
+static_assert(QtJniTypes::isObjectType<jobject>());
+static_assert(QtJniTypes::isObjectType<jobjectArray>());
+static_assert(QtJniTypes::isObjectType<QtCustomJniObject>());
+
+static_assert(!QtJniTypes::isArrayType<jint>());
+static_assert(QtJniTypes::isArrayType<jint[]>());
+static_assert(QtJniTypes::isArrayType<jobject[]>());
+static_assert(QtJniTypes::isArrayType<jobjectArray>());
+static_assert(QtJniTypes::isArrayType<QtJavaWrapper[]>());
+
+static_assert(QtJniTypes::CTString("ABCDE").startsWith("ABC"));
+static_assert(QtJniTypes::CTString("ABCDE").startsWith("A"));
+static_assert(QtJniTypes::CTString("ABCDE").startsWith("ABCDE"));
+static_assert(!QtJniTypes::CTString("ABCDE").startsWith("ABCDEF"));
+static_assert(!QtJniTypes::CTString("ABCDE").startsWith("9AB"));
+static_assert(QtJniTypes::CTString("ABCDE").startsWith('A'));
+static_assert(!QtJniTypes::CTString("ABCDE").startsWith('B'));
+
+static_assert(QtJniTypes::Traits<QJniArray<jobject>>::signature() == "[Ljava/lang/Object;");
+static_assert(QtJniTypes::Traits<QJniArray<jbyte>>::signature() == "[B");
+static_assert(QtJniTypes::isObjectType<QJniArray<jbyte>>());
+
+static_assert(QtJniTypes::CTString("ABCDE").endsWith("CDE"));
+static_assert(QtJniTypes::CTString("ABCDE").endsWith("E"));
+static_assert(QtJniTypes::CTString("ABCDE").endsWith("ABCDE"));
+static_assert(!QtJniTypes::CTString("ABCDE").endsWith("DEF"));
+static_assert(!QtJniTypes::CTString("ABCDE").endsWith("ABCDEF"));
+static_assert(QtJniTypes::CTString("ABCDE").endsWith('E'));
+static_assert(!QtJniTypes::CTString("ABCDE").endsWith('F'));
+
+enum UnscopedEnum {};
+enum class ScopedEnum {};
+enum class IntEnum : int {};
+enum class UnsignedEnum : unsigned {};
+enum class Int8Enum : int8_t {};
+enum class ShortEnum : short {};
+enum class LongEnum : quint64 {};
+enum class JIntEnum : jint {};
+
+static_assert(QtJniTypes::Traits<UnscopedEnum>::signature() == "I");
+static_assert(QtJniTypes::Traits<ScopedEnum>::signature() == "I");
+static_assert(QtJniTypes::Traits<IntEnum>::signature() == "I");
+static_assert(QtJniTypes::Traits<UnsignedEnum>::signature() == "I");
+static_assert(QtJniTypes::Traits<Int8Enum>::signature() == "B");
+static_assert(QtJniTypes::Traits<LongEnum>::signature() == "J");
+static_assert(QtJniTypes::Traits<JIntEnum>::signature() == "I");
+
+void tst_QJniTypes::initTestCase()
+{
+
+}
+
+static bool nativeFunction(JNIEnv *, jclass, int, jstring, quint64)
+{
+ return true;
+}
+Q_DECLARE_JNI_NATIVE_METHOD(nativeFunction)
+
+static_assert(QtJniTypes::nativeMethodSignature(nativeFunction) == "(ILjava/lang/String;J)Z");
+
+static QString nativeFunctionStrings(JNIEnv *, jclass, const QString &, const QtJniTypes::String &)
+{
+ return QString();
+}
+Q_DECLARE_JNI_NATIVE_METHOD(nativeFunctionStrings)
+
+static_assert(QtJniTypes::nativeMethodSignature(nativeFunctionStrings)
+ == "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
+
+static int forwardDeclaredNativeFunction(JNIEnv *, jobject, bool);
+Q_DECLARE_JNI_NATIVE_METHOD(forwardDeclaredNativeFunction)
+static int forwardDeclaredNativeFunction(JNIEnv *, jobject, bool) { return 0; }
+static_assert(QtJniTypes::nativeMethodSignature(forwardDeclaredNativeFunction) == "(Z)I");
+
+static_assert(QtJniTypes::nativeMethodSignature(tst_QJniTypes::nativeClassMethod) == "(I)V");
+void tst_QJniTypes::nativeClassMethod(JNIEnv *, jclass, int) {}
+
+void tst_QJniTypes::nativeMethod()
+{
+ {
+ const auto method = Q_JNI_NATIVE_METHOD(nativeFunction);
+ QVERIFY(method.fnPtr == QtJniMethods::va_nativeFunction);
+ QCOMPARE(method.name, "nativeFunction");
+ QCOMPARE(method.signature, "(ILjava/lang/String;J)Z");
+ }
+
+ {
+ const auto method = Q_JNI_NATIVE_METHOD(forwardDeclaredNativeFunction);
+ QVERIFY(method.fnPtr == QtJniMethods::va_forwardDeclaredNativeFunction);
+ }
+
+ {
+ const auto method = Q_JNI_NATIVE_SCOPED_METHOD(nativeClassMethod, tst_QJniTypes);
+ QVERIFY(method.fnPtr == va_nativeClassMethod);
+ }
+}
+
+void tst_QJniTypes::construct()
+{
+ using namespace QtJniTypes;
+
+ const QString text = u"Java String"_s;
+ String str(text);
+ QVERIFY(str.isValid());
+ QCOMPARE(str.toString(), text);
+
+ jobject jref = nullptr; // must be jobject, not jstring
+ {
+ // if jref would be a jstring, then this would call the
+ // Java String copy constructor!
+ String jstr(jref);
+ QVERIFY(!jstr.isValid());
+ }
+ jref = str.object<jstring>();
+ {
+ String jstr(jref);
+ QVERIFY(jstr.isValid());
+ QCOMPARE(jstr.toString(), text);
+ }
+
+ String str2 = str;
+ QCOMPARE(str.toString(), text);
+ String str3 = std::move(str2);
+ QCOMPARE(str3.toString(), text);
+}
+
+template <typename ...Arg>
+static constexpr bool isValidArgument(Arg &&...) noexcept
+{
+ return QtJniTypes::ValidSignatureTypesDetail<q20::remove_cvref_t<Arg>...>;
+}
+
+enum class Overload
+{
+ ClassNameAndMethod,
+ OnlyMethod,
+};
+
+template <typename Ret, typename ...Args
+#ifndef Q_QDOC
+ , QtJniTypes::IfValidSignatureTypes<Ret, Args...> = true
+#endif
+>
+static constexpr auto callStaticMethod(const char *className, const char *methodName, Args &&...)
+{
+ Q_UNUSED(className);
+ Q_UNUSED(methodName);
+ return Overload::ClassNameAndMethod;
+}
+
+template <typename Klass, typename Ret, typename ...Args
+#ifndef Q_QDOC
+ , QtJniTypes::IfValidSignatureTypes<Ret, Args...> = true
+#endif
+>
+static constexpr auto callStaticMethod(const char *methodName, Args &&...)
+{
+ Q_UNUSED(methodName);
+ return Overload::OnlyMethod;
+}
+
+void tst_QJniTypes::stringTypeCantBeArgument()
+{
+ const char *methodName = "staticEchoMethod";
+
+ static_assert(!isValidArgument(QtJniTypes::Traits<QtJniTypes::JavaType>::className()));
+ static_assert(!isValidArgument("someFunctionName"));
+ static_assert(!isValidArgument(methodName));
+ static_assert(!isValidArgument(QtJniTypes::Traits<QtJniTypes::JavaType>::className(),
+ "someFunctionName", methodName, 42));
+
+ static_assert(callStaticMethod<jstring, jint>("class name", "method name", 42)
+ == Overload::ClassNameAndMethod);
+ static_assert(callStaticMethod<QtJniTypes::JavaType, jint>("method name", 42)
+ == Overload::OnlyMethod);
+}
+
+QTEST_MAIN(tst_QJniTypes)
+
+#include "tst_qjnitypes.moc"
diff --git a/tests/auto/corelib/kernel/qmath/CMakeLists.txt b/tests/auto/corelib/kernel/qmath/CMakeLists.txt
index 4174144141..39a5a8b6df 100644
--- a/tests/auto/corelib/kernel/qmath/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qmath/CMakeLists.txt
@@ -1,10 +1,17 @@
-# Generated from qmath.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qmath Test:
#####################################################################
-qt_add_test(tst_qmath
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qmath LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qmath
SOURCES
tst_qmath.cpp
)
diff --git a/tests/auto/corelib/kernel/qmath/qmath.pro b/tests/auto/corelib/kernel/qmath/qmath.pro
deleted file mode 100644
index 703c530e35..0000000000
--- a/tests/auto/corelib/kernel/qmath/qmath.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qmath
-QT = core testlib
-SOURCES = tst_qmath.cpp
diff --git a/tests/auto/corelib/kernel/qmath/tst_qmath.cpp b/tests/auto/corelib/kernel/qmath/tst_qmath.cpp
index feb704e0aa..1961b71d83 100644
--- a/tests/auto/corelib/kernel/qmath/tst_qmath.cpp
+++ b/tests/auto/corelib/kernel/qmath/tst_qmath.cpp
@@ -1,34 +1,10 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2013 Laszlo Papp <lpapp@kde.org>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2021 The Qt Company Ltd.
+// Copyright (C) 2013 Laszlo Papp <lpapp@kde.org>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
#include <qmath.h>
+#include <qfloat16.h>
class tst_QMath : public QObject
{
@@ -39,6 +15,11 @@ private slots:
void degreesToRadians();
void radiansToDegrees_data();
void radiansToDegrees();
+ void trigonometry_data();
+ void trigonometry();
+ void hypotenuse();
+ void funcs_data();
+ void funcs();
void qNextPowerOfTwo32S_data();
void qNextPowerOfTwo32S();
void qNextPowerOfTwo64S_data();
@@ -131,6 +112,143 @@ void tst_QMath::radiansToDegrees()
QCOMPARE(qRadiansToDegrees(radiansDouble), degreesDouble);
}
+void tst_QMath::trigonometry_data()
+{
+ QTest::addColumn<double>("x");
+ QTest::addColumn<double>("y");
+ QTest::addColumn<double>("angle");
+
+ QTest::newRow("zero") << 1.0 << 0.0 << 0.0;
+ QTest::newRow("turn/4") << 0.0 << 1.0 << M_PI_2;
+ QTest::newRow("turn/2") << -1.0 << 0.0 << M_PI;
+ QTest::newRow("3*turn/4") << 0.0 << -1.0 << -M_PI_2;
+}
+
+void tst_QMath::trigonometry()
+{
+ QFETCH(const double, x);
+ QFETCH(const double, y);
+ QFETCH(const double, angle);
+ const double hypot = qHypot(x, y);
+ QVERIFY(hypot > 0);
+ QCOMPARE(qAtan2(y, x), angle);
+ QCOMPARE(qSin(angle), y / hypot);
+ if (x >= 0 && (y || x)) // aSin() always in right half-plane
+ QCOMPARE(qAsin(y / hypot), angle);
+ QCOMPARE(qCos(angle), x / hypot);
+ if (y >= 0 && (y || x)) // aCos() always in upper half-plane
+ QCOMPARE(qAcos(x / hypot), angle);
+ if (x > 0) {
+ QCOMPARE(qTan(angle), y / x);
+ QCOMPARE(qAtan(y / x), angle);
+ }
+}
+
+void tst_QMath::hypotenuse()
+{
+ // Correct return-types, particularly when qfloat16 is involved:
+ static_assert(std::is_same<decltype(qHypot(qfloat16(1), qfloat16(1), qfloat16(1),
+ qfloat16(1), qfloat16(1), qfloat16(1),
+ qfloat16(1), qfloat16(1), qfloat16(1))),
+ qfloat16>::value);
+ static_assert(std::is_same<decltype(qHypot(qfloat16(3), qfloat16(4), qfloat16(12))),
+ qfloat16>::value);
+ static_assert(std::is_same<decltype(qHypot(qfloat16(3), qfloat16(4), 12.0f)), float>::value);
+ static_assert(std::is_same<decltype(qHypot(qfloat16(3), 4.0f, qfloat16(12))), float>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0f, qfloat16(4), qfloat16(12))), float>::value);
+ static_assert(std::is_same<decltype(qHypot(qfloat16(3), 4.0f, 12.0f)), float>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0f, qfloat16(4), 12.0f)), float>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0f, 4.0f, qfloat16(12))), float>::value);
+ static_assert(std::is_same<decltype(qHypot(qfloat16(3), qfloat16(4))), qfloat16>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0f, qfloat16(4))), float>::value);
+ static_assert(std::is_same<decltype(qHypot(qfloat16(3), 4.0f)), float>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0, qfloat16(4))), double>::value);
+ static_assert(std::is_same<decltype(qHypot(qfloat16(3), 4.0)), double>::value);
+ static_assert(std::is_same<decltype(qHypot(qfloat16(3), 4)), double>::value);
+ static_assert(std::is_same<decltype(qHypot(3, qfloat16(4))), double>::value);
+ static_assert(std::is_same<decltype(qHypot(qfloat16(3), 4.0L)), long double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0L, qfloat16(4))), long double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0f, 4.0f)), float>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0f, 4.0)), double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0f, 4)), double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0f, 4.0L)), long double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0, 4.0f)), double>::value);
+ static_assert(std::is_same<decltype(qHypot(3, 4.0f)), double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0L, 4.0f)), long double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0, 4.0L)), long double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0L, 4.0)), long double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0, 4.0)), double>::value);
+ static_assert(std::is_same<decltype(qHypot(3, 4.0)), double>::value);
+ static_assert(std::is_same<decltype(qHypot(3.0, 4)), double>::value);
+ static_assert(std::is_same<decltype(qHypot(3, 4)), double>::value);
+
+ // Works for all numeric types:
+ QCOMPARE(qHypot(3, 4), 5);
+ QCOMPARE(qHypot(qfloat16(5), qfloat16(12)), qfloat16(13));
+ QCOMPARE(qHypot(3.0f, 4.0f, 12.0f), 13.0f);
+ QCOMPARE(qHypot(3.0, 4.0, 12.0, 84.0), 85.0);
+ QCOMPARE(qHypot(3.0f, 4.0f, 12.0f, 84.0f, 720.0f), 725.0f);
+ QCOMPARE(qHypot(3.0, 4.0, 12.0, 84.0, 3612.0), 3613.0);
+ // Integral gets promoted to double:
+ QCOMPARE(qHypot(1, 1), M_SQRT2);
+ // Caller can mix types freely:
+ QCOMPARE(qHypot(3.0f, 4, 12.0, 84.0f, qfloat16(720), 10500), 10525);
+ // NaN wins over any finite:
+ QCOMPARE(qHypot(3, 4.0, 12.0f, qQNaN()), qQNaN());
+ QCOMPARE(qHypot(3, 4.0, qQNaN(), 12.0f), qQNaN());
+ QCOMPARE(qHypot(3, qQNaN(), 4.0, 12.0f), qQNaN());
+ QCOMPARE(qHypot(qQNaN(), 3, 4.0, 12.0f), qQNaN());
+ // but Infinity beats NaN:
+ QCOMPARE(qHypot(3, 4.0f, -qInf(), qQNaN()), qInf());
+ QCOMPARE(qHypot(3, -qInf(), 4.0f, qQNaN()), qInf());
+ QCOMPARE(qHypot(-qInf(), 3, 4.0f, qQNaN()), qInf());
+ QCOMPARE(qHypot(qQNaN(), 3, -qInf(), 4.0f), qInf());
+ QCOMPARE(qHypot(3, qQNaN(), 4.0f, -qInf()), qInf());
+ QCOMPARE(qHypot(3, 4.0f, qQNaN(), -qInf()), qInf());
+ // Components whose squares sum to zero don't change the end result:
+ const double minD = std::numeric_limits<double>::min();
+ QVERIFY(minD * minD + minD * minD == 0); // *NOT* QCOMPARE
+ QCOMPARE(qHypot(minD, minD, 12.0), 12.0);
+ const float minF = std::numeric_limits<float>::min();
+ QVERIFY(minF * minF + minF * minF == 0.0f); // *NOT* QCOMPARE
+ QCOMPARE(qHypot(minF, minF, 12.0f), 12.0f);
+ const qfloat16 minF16 = std::numeric_limits<qfloat16>::min();
+ QVERIFY(minF16 * minF16 + minF16 * minF16 == qfloat16(0)); // *NOT* QCOMPARE
+ QCOMPARE(qHypot(minF16, minF16, qfloat16(12)), qfloat16(12));
+}
+
+void tst_QMath::funcs_data()
+{
+ QTest::addColumn<double>("value");
+ QTest::addColumn<int>("floor");
+ QTest::addColumn<int>("ceil");
+ QTest::addColumn<double>("abs");
+ QTest::addColumn<double>("sqrt");
+ QTest::addColumn<double>("log");
+ QTest::addColumn<double>("exp");
+ QTest::addColumn<double>("cube");
+ const double nan = qQNaN();
+
+ QTest::newRow("0") << 0.0 << 0 << 0 << 0.0 << 0.0 << nan << 1.0 << 0.0;
+ QTest::newRow("1.44")
+ << 1.44 << 1 << 2 << 1.44 << 1.2 << 0.36464311358790924 << 4.220695816996552 << 2.985984;
+ QTest::newRow("-1.44")
+ << -1.44 << -2 << -1 << 1.44 << nan << nan << 0.23692775868212176 << -2.985984;
+}
+
+void tst_QMath::funcs()
+{
+ QFETCH(double, value);
+ QTEST(qFloor(value), "floor");
+ QTEST(qCeil(value), "ceil");
+ QTEST(qFabs(value), "abs");
+ if (value >= 0)
+ QTEST(qSqrt(value), "sqrt");
+ if (value > 0)
+ QTEST(qLn(value), "log");
+ QTEST(qExp(value), "exp");
+ QTEST(qPow(value, 3), "cube");
+}
void tst_QMath::qNextPowerOfTwo32S_data()
{
@@ -147,9 +265,6 @@ void tst_QMath::qNextPowerOfTwo32S_data()
QTest::newRow("2^30") << (1 << 30) << (1U << 31);
QTest::newRow("2^30 + 1") << (1 << 30) + 1 << (1U << 31);
QTest::newRow("2^31 - 1") << 0x7FFFFFFF << (1U<<31);
- QTest::newRow("-1") << -1 << 0U;
- QTest::newRow("-128") << -128 << 0U;
- QTest::newRow("-(2^31)") << int(0x80000000) << 0U;
}
void tst_QMath::qNextPowerOfTwo32S()
@@ -175,8 +290,6 @@ void tst_QMath::qNextPowerOfTwo32U_data()
QTest::newRow("2^30") << (1U << 30) << (1U << 31);
QTest::newRow("2^30 + 1") << (1U << 30) + 1 << (1U << 31);
QTest::newRow("2^31 - 1") << 2147483647U << 2147483648U;
- QTest::newRow("2^31") << 2147483648U << 0U;
- QTest::newRow("2^31 + 1") << 2147483649U << 0U;
}
void tst_QMath::qNextPowerOfTwo32U()
@@ -203,10 +316,6 @@ void tst_QMath::qNextPowerOfTwo64S_data()
QTest::newRow("2^31") << Q_INT64_C(2147483648) << Q_UINT64_C(0x100000000);
QTest::newRow("2^31 + 1") << Q_INT64_C(2147483649) << Q_UINT64_C(0x100000000);
QTest::newRow("2^63 - 1") << Q_INT64_C(0x7FFFFFFFFFFFFFFF) << Q_UINT64_C(0x8000000000000000);
- QTest::newRow("-1") << Q_INT64_C(-1) << Q_UINT64_C(0);
- QTest::newRow("-128") << Q_INT64_C(-128) << Q_UINT64_C(0);
- QTest::newRow("-(2^31)") << -Q_INT64_C(0x80000000) << Q_UINT64_C(0);
- QTest::newRow("-(2^63)") << (qint64)Q_INT64_C(0x8000000000000000) << Q_UINT64_C(0);
}
void tst_QMath::qNextPowerOfTwo64S()
@@ -230,8 +339,6 @@ void tst_QMath::qNextPowerOfTwo64U_data()
QTest::newRow("65535") << Q_UINT64_C(65535) << Q_UINT64_C(65536);
QTest::newRow("65536") << Q_UINT64_C(65536) << Q_UINT64_C(131072);
QTest::newRow("2^63 - 1") << Q_UINT64_C(0x7FFFFFFFFFFFFFFF) << Q_UINT64_C(0x8000000000000000);
- QTest::newRow("2^63") << Q_UINT64_C(0x8000000000000000) << Q_UINT64_C(0);
- QTest::newRow("2^63 + 1") << Q_UINT64_C(0x8000000000000001) << Q_UINT64_C(0);
}
void tst_QMath::qNextPowerOfTwo64U()
diff --git a/tests/auto/corelib/kernel/qmetacontainer/CMakeLists.txt b/tests/auto/corelib/kernel/qmetacontainer/CMakeLists.txt
index 6f0192155d..fb58aebe73 100644
--- a/tests/auto/corelib/kernel/qmetacontainer/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qmetacontainer/CMakeLists.txt
@@ -1,16 +1,20 @@
-# Generated from qmetacontainer.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qmetacontainer Test:
#####################################################################
-# Collect test data
-list(APPEND test_data "./typeFlags.bin")
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qmetacontainer LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
-qt_add_test(tst_qmetacontainer
+qt_internal_add_test(tst_qmetacontainer
SOURCES
tst_qmetacontainer.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
- TESTDATA ${test_data}
+ Qt::TestPrivate
)
diff --git a/tests/auto/corelib/kernel/qmetacontainer/qmetacontainer.pro b/tests/auto/corelib/kernel/qmetacontainer/qmetacontainer.pro
deleted file mode 100644
index 65f3eaa10b..0000000000
--- a/tests/auto/corelib/kernel/qmetacontainer/qmetacontainer.pro
+++ /dev/null
@@ -1,7 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qmetacontainer
-QT = core-private testlib
-SOURCES = tst_qmetacontainer.cpp
-TESTDATA=./typeFlags.bin
-
-
diff --git a/tests/auto/corelib/kernel/qmetacontainer/tst_qmetacontainer.cpp b/tests/auto/corelib/kernel/qmetacontainer/tst_qmetacontainer.cpp
index 4bfef31b00..cc1d8baa8e 100644
--- a/tests/auto/corelib/kernel/qmetacontainer/tst_qmetacontainer.cpp
+++ b/tests/auto/corelib/kernel/qmetacontainer/tst_qmetacontainer.cpp
@@ -1,34 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtTest/qtest.h>
+#include <QtTest/private/qcomparisontesthelper_p.h>
#include <QtCore/qcontainerinfo.h>
#include <QtCore/qmetacontainer.h>
+#include <QtCore/QMap>
+#include <QtCore/QHash>
#include <QtCore/qvector.h>
#include <QtCore/qset.h>
@@ -44,121 +22,121 @@ namespace CheckContainerTraits
{
struct NotAContainer {};
-static_assert(QContainerTraits::has_size_v<QVector<int>>);
-static_assert(QContainerTraits::has_size_v<QSet<int>>);
-static_assert(!QContainerTraits::has_size_v<NotAContainer>);
-static_assert(QContainerTraits::has_size_v<std::vector<int>>);
-static_assert(QContainerTraits::has_size_v<std::set<int>>);
-static_assert(!QContainerTraits::has_size_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::has_clear_v<QVector<int>>);
-static_assert(QContainerTraits::has_clear_v<QSet<int>>);
-static_assert(!QContainerTraits::has_clear_v<NotAContainer>);
-static_assert(QContainerTraits::has_clear_v<std::vector<int>>);
-static_assert(QContainerTraits::has_clear_v<std::set<int>>);
-static_assert(QContainerTraits::has_clear_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::has_at_index_v<QVector<int>>);
-static_assert(!QContainerTraits::has_at_index_v<QSet<int>>);
-static_assert(!QContainerTraits::has_at_index_v<NotAContainer>);
-static_assert(QContainerTraits::has_at_index_v<std::vector<int>>);
-static_assert(!QContainerTraits::has_at_index_v<std::set<int>>);
-static_assert(!QContainerTraits::has_at_index_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::can_get_at_index_v<QVector<int>>);
-static_assert(!QContainerTraits::can_get_at_index_v<QSet<int>>);
-static_assert(!QContainerTraits::can_get_at_index_v<NotAContainer>);
-static_assert(QContainerTraits::can_get_at_index_v<std::vector<int>>);
-static_assert(!QContainerTraits::can_get_at_index_v<std::set<int>>);
-static_assert(!QContainerTraits::can_get_at_index_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::can_set_at_index_v<QVector<int>>);
-static_assert(!QContainerTraits::can_set_at_index_v<QSet<int>>);
-static_assert(!QContainerTraits::can_set_at_index_v<NotAContainer>);
-static_assert(QContainerTraits::can_set_at_index_v<std::vector<int>>);
-static_assert(!QContainerTraits::can_set_at_index_v<std::set<int>>);
-static_assert(!QContainerTraits::can_set_at_index_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::has_push_back_v<QVector<int>>);
-static_assert(!QContainerTraits::has_push_back_v<QSet<int>>);
-static_assert(!QContainerTraits::has_push_back_v<NotAContainer>);
-static_assert(QContainerTraits::has_push_back_v<std::vector<int>>);
-static_assert(!QContainerTraits::has_push_back_v<std::set<int>>);
-static_assert(!QContainerTraits::has_push_back_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::has_push_front_v<QVector<int>>);
-static_assert(!QContainerTraits::has_push_front_v<QSet<int>>);
-static_assert(!QContainerTraits::has_push_front_v<NotAContainer>);
-static_assert(!QContainerTraits::has_push_front_v<std::vector<int>>);
-static_assert(!QContainerTraits::has_push_front_v<std::set<int>>);
-static_assert(QContainerTraits::has_push_front_v<std::forward_list<int>>);
-
-static_assert(!QContainerTraits::has_insert_v<QVector<int>>);
-static_assert(QContainerTraits::has_insert_v<QSet<int>>);
-static_assert(!QContainerTraits::has_insert_v<NotAContainer>);
-static_assert(!QContainerTraits::has_insert_v<std::vector<int>>);
-static_assert(QContainerTraits::has_insert_v<std::set<int>>);
-static_assert(!QContainerTraits::has_insert_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::has_pop_back_v<QVector<int>>);
-static_assert(!QContainerTraits::has_pop_back_v<QSet<int>>);
-static_assert(!QContainerTraits::has_pop_back_v<NotAContainer>);
-static_assert(QContainerTraits::has_pop_back_v<std::vector<int>>);
-static_assert(!QContainerTraits::has_pop_back_v<std::set<int>>);
-static_assert(!QContainerTraits::has_pop_back_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::has_pop_front_v<QVector<int>>);
-static_assert(!QContainerTraits::has_pop_front_v<QSet<int>>);
-static_assert(!QContainerTraits::has_pop_front_v<NotAContainer>);
-static_assert(!QContainerTraits::has_pop_front_v<std::vector<int>>);
-static_assert(!QContainerTraits::has_pop_front_v<std::set<int>>);
-static_assert(QContainerTraits::has_pop_front_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::has_iterator_v<QVector<int>>);
-static_assert(QContainerTraits::has_iterator_v<QSet<int>>);
-static_assert(!QContainerTraits::has_iterator_v<NotAContainer>);
-static_assert(QContainerTraits::has_iterator_v<std::vector<int>>);
-static_assert(QContainerTraits::has_iterator_v<std::set<int>>);
-static_assert(QContainerTraits::has_iterator_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::has_const_iterator_v<QVector<int>>);
-static_assert(QContainerTraits::has_const_iterator_v<QSet<int>>);
-static_assert(!QContainerTraits::has_const_iterator_v<NotAContainer>);
-static_assert(QContainerTraits::has_const_iterator_v<std::vector<int>>);
-static_assert(QContainerTraits::has_const_iterator_v<std::set<int>>);
-static_assert(QContainerTraits::has_const_iterator_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::iterator_dereferences_to_value_v<QVector<int>>);
-static_assert(QContainerTraits::iterator_dereferences_to_value_v<QSet<int>>);
-static_assert(!QContainerTraits::iterator_dereferences_to_value_v<NotAContainer>);
-static_assert(QContainerTraits::iterator_dereferences_to_value_v<std::vector<int>>);
-static_assert(QContainerTraits::iterator_dereferences_to_value_v<std::set<int>>);
-static_assert(QContainerTraits::iterator_dereferences_to_value_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::can_set_value_at_iterator_v<QVector<int>>);
-static_assert(!QContainerTraits::can_set_value_at_iterator_v<QSet<int>>);
-static_assert(!QContainerTraits::can_set_value_at_iterator_v<NotAContainer>);
-static_assert(QContainerTraits::can_set_value_at_iterator_v<std::vector<int>>);
-static_assert(!QContainerTraits::can_set_value_at_iterator_v<std::set<int>>);
-static_assert(QContainerTraits::can_set_value_at_iterator_v<std::forward_list<int>>);
-
-static_assert(QContainerTraits::can_insert_value_at_iterator_v<QVector<int>>);
-static_assert(!QContainerTraits::can_insert_value_at_iterator_v<QSet<int>>);
-static_assert(!QContainerTraits::can_insert_value_at_iterator_v<NotAContainer>);
-static_assert(QContainerTraits::can_insert_value_at_iterator_v<std::vector<int>>);
-static_assert(!QContainerTraits::can_insert_value_at_iterator_v<std::forward_list<int>>);
+static_assert(QContainerInfo::has_size_v<QVector<int>>);
+static_assert(QContainerInfo::has_size_v<QSet<int>>);
+static_assert(!QContainerInfo::has_size_v<NotAContainer>);
+static_assert(QContainerInfo::has_size_v<std::vector<int>>);
+static_assert(QContainerInfo::has_size_v<std::set<int>>);
+static_assert(!QContainerInfo::has_size_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::has_clear_v<QVector<int>>);
+static_assert(QContainerInfo::has_clear_v<QSet<int>>);
+static_assert(!QContainerInfo::has_clear_v<NotAContainer>);
+static_assert(QContainerInfo::has_clear_v<std::vector<int>>);
+static_assert(QContainerInfo::has_clear_v<std::set<int>>);
+static_assert(QContainerInfo::has_clear_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::has_at_index_v<QVector<int>>);
+static_assert(!QContainerInfo::has_at_index_v<QSet<int>>);
+static_assert(!QContainerInfo::has_at_index_v<NotAContainer>);
+static_assert(QContainerInfo::has_at_index_v<std::vector<int>>);
+static_assert(!QContainerInfo::has_at_index_v<std::set<int>>);
+static_assert(!QContainerInfo::has_at_index_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::can_get_at_index_v<QVector<int>>);
+static_assert(!QContainerInfo::can_get_at_index_v<QSet<int>>);
+static_assert(!QContainerInfo::can_get_at_index_v<NotAContainer>);
+static_assert(QContainerInfo::can_get_at_index_v<std::vector<int>>);
+static_assert(!QContainerInfo::can_get_at_index_v<std::set<int>>);
+static_assert(!QContainerInfo::can_get_at_index_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::can_set_at_index_v<QVector<int>>);
+static_assert(!QContainerInfo::can_set_at_index_v<QSet<int>>);
+static_assert(!QContainerInfo::can_set_at_index_v<NotAContainer>);
+static_assert(QContainerInfo::can_set_at_index_v<std::vector<int>>);
+static_assert(!QContainerInfo::can_set_at_index_v<std::set<int>>);
+static_assert(!QContainerInfo::can_set_at_index_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::has_push_back_v<QVector<int>>);
+static_assert(!QContainerInfo::has_push_back_v<QSet<int>>);
+static_assert(!QContainerInfo::has_push_back_v<NotAContainer>);
+static_assert(QContainerInfo::has_push_back_v<std::vector<int>>);
+static_assert(!QContainerInfo::has_push_back_v<std::set<int>>);
+static_assert(!QContainerInfo::has_push_back_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::has_push_front_v<QVector<int>>);
+static_assert(!QContainerInfo::has_push_front_v<QSet<int>>);
+static_assert(!QContainerInfo::has_push_front_v<NotAContainer>);
+static_assert(!QContainerInfo::has_push_front_v<std::vector<int>>);
+static_assert(!QContainerInfo::has_push_front_v<std::set<int>>);
+static_assert(QContainerInfo::has_push_front_v<std::forward_list<int>>);
+
+static_assert(!QContainerInfo::has_insert_v<QVector<int>>);
+static_assert(QContainerInfo::has_insert_v<QSet<int>>);
+static_assert(!QContainerInfo::has_insert_v<NotAContainer>);
+static_assert(!QContainerInfo::has_insert_v<std::vector<int>>);
+static_assert(QContainerInfo::has_insert_v<std::set<int>>);
+static_assert(!QContainerInfo::has_insert_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::has_pop_back_v<QVector<int>>);
+static_assert(!QContainerInfo::has_pop_back_v<QSet<int>>);
+static_assert(!QContainerInfo::has_pop_back_v<NotAContainer>);
+static_assert(QContainerInfo::has_pop_back_v<std::vector<int>>);
+static_assert(!QContainerInfo::has_pop_back_v<std::set<int>>);
+static_assert(!QContainerInfo::has_pop_back_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::has_pop_front_v<QVector<int>>);
+static_assert(!QContainerInfo::has_pop_front_v<QSet<int>>);
+static_assert(!QContainerInfo::has_pop_front_v<NotAContainer>);
+static_assert(!QContainerInfo::has_pop_front_v<std::vector<int>>);
+static_assert(!QContainerInfo::has_pop_front_v<std::set<int>>);
+static_assert(QContainerInfo::has_pop_front_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::has_iterator_v<QVector<int>>);
+static_assert(QContainerInfo::has_iterator_v<QSet<int>>);
+static_assert(!QContainerInfo::has_iterator_v<NotAContainer>);
+static_assert(QContainerInfo::has_iterator_v<std::vector<int>>);
+static_assert(QContainerInfo::has_iterator_v<std::set<int>>);
+static_assert(QContainerInfo::has_iterator_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::has_const_iterator_v<QVector<int>>);
+static_assert(QContainerInfo::has_const_iterator_v<QSet<int>>);
+static_assert(!QContainerInfo::has_const_iterator_v<NotAContainer>);
+static_assert(QContainerInfo::has_const_iterator_v<std::vector<int>>);
+static_assert(QContainerInfo::has_const_iterator_v<std::set<int>>);
+static_assert(QContainerInfo::has_const_iterator_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::iterator_dereferences_to_value_v<QVector<int>>);
+static_assert(QContainerInfo::iterator_dereferences_to_value_v<QSet<int>>);
+static_assert(!QContainerInfo::iterator_dereferences_to_value_v<NotAContainer>);
+static_assert(QContainerInfo::iterator_dereferences_to_value_v<std::vector<int>>);
+static_assert(QContainerInfo::iterator_dereferences_to_value_v<std::set<int>>);
+static_assert(QContainerInfo::iterator_dereferences_to_value_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::can_set_value_at_iterator_v<QVector<int>>);
+static_assert(!QContainerInfo::can_set_value_at_iterator_v<QSet<int>>);
+static_assert(!QContainerInfo::can_set_value_at_iterator_v<NotAContainer>);
+static_assert(QContainerInfo::can_set_value_at_iterator_v<std::vector<int>>);
+static_assert(!QContainerInfo::can_set_value_at_iterator_v<std::set<int>>);
+static_assert(QContainerInfo::can_set_value_at_iterator_v<std::forward_list<int>>);
+
+static_assert(QContainerInfo::can_insert_value_at_iterator_v<QVector<int>>);
+static_assert(QContainerInfo::can_insert_value_at_iterator_v<QSet<int>>);
+static_assert(!QContainerInfo::can_insert_value_at_iterator_v<NotAContainer>);
+static_assert(QContainerInfo::can_insert_value_at_iterator_v<std::vector<int>>);
+static_assert(!QContainerInfo::can_insert_value_at_iterator_v<std::forward_list<int>>);
// The iterator is only a hint, but syntactically indistinguishable from others.
// It's explicitly there to be signature compatible with std::vector::insert, though.
// Also, inserting into a set is not guaranteed to actually do anything.
-static_assert(QContainerTraits::can_insert_value_at_iterator_v<std::set<int>>);
+static_assert(QContainerInfo::can_insert_value_at_iterator_v<std::set<int>>);
-static_assert(QContainerTraits::can_erase_at_iterator_v<QVector<int>>);
-static_assert(QContainerTraits::can_erase_at_iterator_v<QSet<int>>);
-static_assert(!QContainerTraits::can_erase_at_iterator_v<NotAContainer>);
-static_assert(QContainerTraits::can_erase_at_iterator_v<std::vector<int>>);
-static_assert(QContainerTraits::can_erase_at_iterator_v<std::set<int>>);
-static_assert(!QContainerTraits::can_erase_at_iterator_v<std::forward_list<int>>);
+static_assert(QContainerInfo::can_erase_at_iterator_v<QVector<int>>);
+static_assert(QContainerInfo::can_erase_at_iterator_v<QSet<int>>);
+static_assert(!QContainerInfo::can_erase_at_iterator_v<NotAContainer>);
+static_assert(QContainerInfo::can_erase_at_iterator_v<std::vector<int>>);
+static_assert(QContainerInfo::can_erase_at_iterator_v<std::set<int>>);
+static_assert(!QContainerInfo::can_erase_at_iterator_v<std::forward_list<int>>);
}
@@ -180,6 +158,7 @@ private:
private slots:
void init();
+ void compareCompiles();
void testSequence_data();
void testSequence();
@@ -226,6 +205,12 @@ void tst_QMetaContainer::init()
};
}
+void tst_QMetaContainer::compareCompiles()
+{
+ QTestPrivate::testEqualityOperatorsCompile<QMetaSequence>();
+ QTestPrivate::testEqualityOperatorsCompile<QMetaAssociation>();
+}
+
void tst_QMetaContainer::cleanup()
{
qvector.clear();
@@ -267,7 +252,7 @@ void tst_QMetaContainer::testSequence_data()
<< static_cast<void *>(&qset)
<< QMetaSequence::fromContainer<QSet<QByteArray>>()
<< QMetaType::fromType<QByteArray>()
- << true << false << false << false << false << false << true << false;
+ << true << false << false << false << false << true << true << false;
QTest::addRow("std::set")
<< static_cast<void *>(&stdset)
<< QMetaSequence::fromContainer<std::set<int>>()
@@ -520,6 +505,13 @@ void tst_QMetaContainer::testSequence()
QVERIFY(metaSequence.compareConstIterator(constIt, constEnd));
metaSequence.destroyConstIterator(constIt);
metaSequence.destroyConstIterator(constEnd);
+
+ QVERIFY(metaSequence.iface() != nullptr);
+ QMetaSequence defaultConstructed;
+ QVERIFY(defaultConstructed.iface() == nullptr);
+ QT_TEST_EQUALITY_OPS(QMetaSequence(), defaultConstructed, true);
+ QT_TEST_EQUALITY_OPS(QMetaSequence(), QMetaSequence(), true);
+ QT_TEST_EQUALITY_OPS(defaultConstructed, metaSequence, false);
}
void tst_QMetaContainer::testAssociation_data()
@@ -745,6 +737,12 @@ void tst_QMetaContainer::testAssociation()
QVERIFY(metaAssociation.compareConstIterator(constIt, constEnd));
metaAssociation.destroyConstIterator(constIt);
metaAssociation.destroyConstIterator(constEnd);
+
+ QVERIFY(metaAssociation.iface() != nullptr);
+ QMetaAssociation defaultConstructed;
+ QVERIFY(defaultConstructed.iface() == nullptr);
+ QT_TEST_EQUALITY_OPS(QMetaAssociation(), QMetaAssociation(), true);
+ QT_TEST_EQUALITY_OPS(QMetaAssociation(), metaAssociation, false);
}
QTEST_MAIN(tst_QMetaContainer)
diff --git a/tests/auto/corelib/kernel/qmetaenum/CMakeLists.txt b/tests/auto/corelib/kernel/qmetaenum/CMakeLists.txt
index eba96be7db..46f3ece069 100644
--- a/tests/auto/corelib/kernel/qmetaenum/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qmetaenum/CMakeLists.txt
@@ -1,10 +1,17 @@
-# Generated from qmetaenum.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qmetaenum Test:
#####################################################################
-qt_add_test(tst_qmetaenum
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qmetaenum LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qmetaenum
SOURCES
tst_qmetaenum.cpp
)
diff --git a/tests/auto/corelib/kernel/qmetaenum/qmetaenum.pro b/tests/auto/corelib/kernel/qmetaenum/qmetaenum.pro
deleted file mode 100644
index 718f2b51de..0000000000
--- a/tests/auto/corelib/kernel/qmetaenum/qmetaenum.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qmetaenum
-QT = core testlib
-SOURCES = tst_qmetaenum.cpp
diff --git a/tests/auto/corelib/kernel/qmetaenum/tst_qmetaenum.cpp b/tests/auto/corelib/kernel/qmetaenum/tst_qmetaenum.cpp
index 6452800bf0..3d958a78fe 100644
--- a/tests/auto/corelib/kernel/qmetaenum/tst_qmetaenum.cpp
+++ b/tests/auto/corelib/kernel/qmetaenum/tst_qmetaenum.cpp
@@ -1,33 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QtTest/QtTest>
+// Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+
+#include <QTest>
#include <QtCore/qobject.h>
#include <QtCore/qmetaobject.h>
@@ -98,6 +73,9 @@ void tst_QMetaEnum::valuesToKeys()
QMetaEnum me = QMetaEnum::fromType<Qt::WindowFlags>();
QCOMPARE(me.valueToKeys(windowFlags), expected);
+ bool ok = false;
+ QCOMPARE(uint(me.keysToValue(expected, &ok)), windowFlags.toInt());
+ QVERIFY(ok);
}
void tst_QMetaEnum::defaultConstructed()
diff --git a/tests/auto/corelib/kernel/qmetamethod/CMakeLists.txt b/tests/auto/corelib/kernel/qmetamethod/CMakeLists.txt
index 5062dc7a3f..0d46aef8bd 100644
--- a/tests/auto/corelib/kernel/qmetamethod/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qmetamethod/CMakeLists.txt
@@ -1,10 +1,19 @@
-# Generated from qmetamethod.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qmetamethod Test:
#####################################################################
-qt_add_test(tst_qmetamethod
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qmetamethod LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qmetamethod
SOURCES
tst_qmetamethod.cpp
+ LIBRARIES
+ Qt::TestPrivate
)
diff --git a/tests/auto/corelib/kernel/qmetamethod/qmetamethod.pro b/tests/auto/corelib/kernel/qmetamethod/qmetamethod.pro
deleted file mode 100644
index 9dfa29b0fc..0000000000
--- a/tests/auto/corelib/kernel/qmetamethod/qmetamethod.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qmetamethod
-QT = core testlib
-SOURCES = tst_qmetamethod.cpp
diff --git a/tests/auto/corelib/kernel/qmetamethod/tst_qmetamethod.cpp b/tests/auto/corelib/kernel/qmetamethod/tst_qmetamethod.cpp
index 942f075723..59fb747524 100644
--- a/tests/auto/corelib/kernel/qmetamethod/tst_qmetamethod.cpp
+++ b/tests/auto/corelib/kernel/qmetamethod/tst_qmetamethod.cpp
@@ -1,34 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2014 Olivier Goffart <ogoffart@woboq.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QtTest/QtTest>
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2014 Olivier Goffart <ogoffart@woboq.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+
+#include <QTest>
+#include <QtTest/private/qcomparisontesthelper_p.h>
+#include <QTypeRevision>
#include <qobject.h>
#include <qmetaobject.h>
@@ -38,6 +15,7 @@ class tst_QMetaMethod : public QObject
Q_OBJECT
private slots:
+ void compareCompiles();
void method_data();
void method();
@@ -46,6 +24,7 @@ private slots:
void comparisonOperators();
void fromSignal();
+ void fromSignalOfNullSignalIsInvalid();
void gadget();
void revision();
@@ -54,6 +33,11 @@ private slots:
void parameterMetaType();
void parameterTypeName();
+
+ void isConst();
+
+ void methodIndexes_data();
+ void methodIndexes();
};
struct CustomType { };
@@ -81,7 +65,7 @@ public:
uchar ucharArg, float floatArg);
Q_INVOKABLE MethodTestObject(bool, int);
- Q_INVOKABLE void voidInvokable();
+ Q_INVOKABLE void voidInvokable() const;
Q_INVOKABLE void voidInvokableInt(int voidInvokableIntArg);
Q_INVOKABLE void voidInvokableQReal(qreal voidInvokableQRealArg);
Q_INVOKABLE void voidInvokableQString(const QString &voidInvokableQStringArg);
@@ -142,7 +126,7 @@ MethodTestObject::MethodTestObject(bool, int, uint, qlonglong, qulonglong,
uchar, float) {}
MethodTestObject::MethodTestObject(bool, int) {}
-void MethodTestObject::voidInvokable() {}
+void MethodTestObject::voidInvokable() const {}
void MethodTestObject::voidInvokableInt(int) {}
void MethodTestObject::voidInvokableQReal(qreal) {}
void MethodTestObject::voidInvokableQString(const QString &) {}
@@ -184,6 +168,11 @@ QVariant MethodTestObject::qvariantSlotBoolIntUIntLonglongULonglongDoubleLongSho
}
void MethodTestObject::voidSlotNoParameterNames(bool, int) {}
+void tst_QMetaMethod::compareCompiles()
+{
+ QTestPrivate::testEqualityOperatorsCompile<QMetaMethod>();
+}
+
void tst_QMetaMethod::method_data()
{
QTest::addColumn<QByteArray>("signature");
@@ -665,6 +654,8 @@ void tst_QMetaMethod::method()
// Bogus indexes
QCOMPARE(method.parameterType(-1), 0);
QCOMPARE(method.parameterType(parameterTypes.size()), 0);
+ QT_TEST_EQUALITY_OPS(method, QMetaMethod(), false);
+ QT_TEST_EQUALITY_OPS(QMetaMethod(), QMetaMethod(), true);
}
void tst_QMetaMethod::invalidMethod()
@@ -677,6 +668,9 @@ void tst_QMetaMethod::invalidMethod()
QMetaMethod method3 = staticMetaObject.method(-1);
QVERIFY(!method3.isValid());
+ QT_TEST_EQUALITY_OPS(method, method2, true);
+ QT_TEST_EQUALITY_OPS(method2, method3, true);
+ QT_TEST_EQUALITY_OPS(method, method3, true);
}
void tst_QMetaMethod::comparisonOperators()
@@ -691,16 +685,9 @@ void tst_QMetaMethod::comparisonOperators()
QMetaMethod other = x ? mo->constructor(j) : mo->method(j);
bool expectedEqual = ((methodMo == other.enclosingMetaObject())
&& (i == j));
- QCOMPARE(method == other, expectedEqual);
- QCOMPARE(method != other, !expectedEqual);
- QCOMPARE(other == method, expectedEqual);
- QCOMPARE(other != method, !expectedEqual);
+ QT_TEST_EQUALITY_OPS(method, other, expectedEqual);
}
-
- QVERIFY(method != QMetaMethod());
- QVERIFY(QMetaMethod() != method);
- QVERIFY(!(method == QMetaMethod()));
- QVERIFY(!(QMetaMethod() == method));
+ QT_TEST_EQUALITY_OPS(method, QMetaMethod(), false);
}
}
@@ -709,8 +696,7 @@ void tst_QMetaMethod::comparisonOperators()
for (int i = 0; i < qMin(mo->methodCount(), mo->constructorCount()); ++i) {
QMetaMethod method = mo->method(i);
QMetaMethod constructor = mo->constructor(i);
- QVERIFY(method != constructor);
- QVERIFY(!(method == constructor));
+ QT_TEST_EQUALITY_OPS(method, constructor, false);
}
}
@@ -738,6 +724,12 @@ void tst_QMetaMethod::fromSignal()
#undef FROMSIGNAL_HELPER
}
+void tst_QMetaMethod::fromSignalOfNullSignalIsInvalid()
+{
+ constexpr decltype(&QObject::destroyed) ptr = nullptr;
+ QVERIFY(!QMetaMethod::fromSignal(ptr).isValid());
+}
+
class MyGadget {
Q_GADGET
public:
@@ -760,6 +752,7 @@ void tst_QMetaMethod::gadget()
QMetaMethod getValueMethod = MyGadget::staticMetaObject.method(idx);
QVERIFY(getValueMethod.isValid());
+ QT_TEST_EQUALITY_OPS(setValueMethod, getValueMethod, false);
{
MyGadget gadget;
QString string;
@@ -865,6 +858,61 @@ void tst_QMetaMethod::parameterTypeName()
}
}
+void tst_QMetaMethod::isConst()
+{
+ auto mo = MethodTestObject::staticMetaObject;
+ {
+ const auto normalized = QMetaObject::normalizedSignature("qrealInvokable()");
+ const int idx = mo.indexOfSlot(normalized);
+ QMetaMethod mm = mo.method(idx);
+ QVERIFY(mm.isValid());
+ QCOMPARE(mm.isConst(), false);
+ }
+ {
+ const auto normalized = QMetaObject::normalizedSignature("voidInvokable()");
+ const int idx = mo.indexOfSlot(normalized);
+ QMetaMethod mm = mo.method(idx);
+ QVERIFY(mm.isValid());
+ QCOMPARE(mm.isConst(), true);
+ }
+}
+
+void tst_QMetaMethod::methodIndexes_data()
+{
+ QTest::addColumn<QByteArray>("signature");
+ QTest::addColumn<QMetaMethod::MethodType>("methodType");
+
+ QTest::newRow("constructor1") << QByteArray("MethodTestObject()") << QMetaMethod::Constructor;
+ QTest::newRow("constructor5") << QByteArray("MethodTestObject(CustomUnregisteredType)")
+ << QMetaMethod::Constructor;
+ QTest::newRow("method0") << QByteArray("voidInvokable()") << QMetaMethod::Method;
+ QTest::newRow("method6") << QByteArray("boolInvokable()") << QMetaMethod::Method;
+}
+
+void tst_QMetaMethod::methodIndexes()
+{
+ QFETCH(QByteArray, signature);
+ QFETCH(QMetaMethod::MethodType, methodType);
+
+ const bool isConstructor = methodType == QMetaMethod::Constructor;
+
+ // roundtrip: index = QMetaObject::indexOfConstructor/Method()
+ // <-> method = QMetaObject::constructor/method()
+ // <-> indexThatShouldBeEqualToAboveIndex = QMetaMethod::methodIndex()
+
+ const QMetaObject *mo = &MethodTestObject::staticMetaObject;
+ const int index =
+ isConstructor ? mo->indexOfConstructor(signature) : mo->indexOfMethod(signature);
+ QVERIFY(index != -1);
+
+ QMetaMethod methodFromMetaObject =
+ mo->method(index); // should work on all methods (constructors, signals, ...)
+ const int absoluteMethodIndex =
+ methodFromMetaObject
+ .methodIndex(); // should work on all methods (constructors, signals, ...)
+
+ QCOMPARE(absoluteMethodIndex, index);
+}
QTEST_MAIN(tst_QMetaMethod)
#include "tst_qmetamethod.moc"
diff --git a/tests/auto/corelib/kernel/qmetaobject/CMakeLists.txt b/tests/auto/corelib/kernel/qmetaobject/CMakeLists.txt
index 0a9a839505..d17773ada6 100644
--- a/tests/auto/corelib/kernel/qmetaobject/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qmetaobject/CMakeLists.txt
@@ -1,15 +1,36 @@
-# Generated from qmetaobject.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qmetaobject LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+set(tst_qmetaobject_SOURCES
+ tst_qmetaobject.cpp
+ forwarddeclared.h
+ forwarddeclared.cpp
+)
+
#####################################################################
## tst_qmetaobject Test:
#####################################################################
-qt_add_test(tst_qmetaobject
+qt_internal_add_test(tst_qmetaobject
SOURCES
- tst_qmetaobject.cpp
- PUBLIC_LIBRARIES
+ ${tst_qmetaobject_SOURCES}
+ LIBRARIES
Qt::CorePrivate
)
-## Scopes:
-#####################################################################
+qt_internal_add_test(tst_qmetaobject_compat
+ SOURCES
+ ${tst_qmetaobject_SOURCES}
+ DEFINES
+ USE_COMPAT_Q_ARG=1
+ LIBRARIES
+ Qt::CorePrivate
+ NO_BATCH
+)
diff --git a/tests/auto/corelib/kernel/qmetaobject/forwarddeclared.cpp b/tests/auto/corelib/kernel/qmetaobject/forwarddeclared.cpp
new file mode 100644
index 0000000000..c736a63227
--- /dev/null
+++ b/tests/auto/corelib/kernel/qmetaobject/forwarddeclared.cpp
@@ -0,0 +1,17 @@
+// Copyright (C) 2022 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include "forwarddeclared.h"
+
+struct MyForwardDeclaredType { };
+static MyForwardDeclaredType t;
+
+const MyForwardDeclaredType &getForwardDeclaredType() noexcept
+{
+ return t;
+}
+
+MyForwardDeclaredType *getForwardDeclaredPointer() noexcept
+{
+ return &t;
+}
diff --git a/tests/auto/corelib/kernel/qmetaobject/forwarddeclared.h b/tests/auto/corelib/kernel/qmetaobject/forwarddeclared.h
new file mode 100644
index 0000000000..a0158f19cd
--- /dev/null
+++ b/tests/auto/corelib/kernel/qmetaobject/forwarddeclared.h
@@ -0,0 +1,12 @@
+// Copyright (C) 2022 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#ifndef FORWARDDECLARED_H
+#define FORWARDDECLARED_H
+
+struct MyForwardDeclaredType; // and ONLY forward-declared
+
+const MyForwardDeclaredType &getForwardDeclaredType() noexcept;
+MyForwardDeclaredType *getForwardDeclaredPointer() noexcept;
+
+#endif // FORWARDDECLARED_H
diff --git a/tests/auto/corelib/kernel/qmetaobject/qmetaobject.pro b/tests/auto/corelib/kernel/qmetaobject/qmetaobject.pro
deleted file mode 100644
index 980c247ab5..0000000000
--- a/tests/auto/corelib/kernel/qmetaobject/qmetaobject.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-CONFIG += testcase
-qtConfig(c++14): CONFIG += c++14
-TARGET = tst_qmetaobject
-QT = core-private testlib
-SOURCES = tst_qmetaobject.cpp
diff --git a/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp b/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp
index fde1255443..ee13c32353 100644
--- a/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp
+++ b/tests/auto/corelib/kernel/qmetaobject/tst_qmetaobject.cpp
@@ -1,32 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
+#include <QSignalSpy>
+#include <QSortFilterProxyModel>
#include <qobject.h>
#include <qmetaobject.h>
@@ -35,6 +12,27 @@
Q_DECLARE_METATYPE(const QMetaObject *)
+#include "forwarddeclared.h"
+
+#ifdef USE_COMPAT_Q_ARG
+# define tst_QMetaObject tst_QMetaObject_CompatQArg
+# if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0)
+# error "This is a Qt 6 compatibility check test"
+# endif
+
+# undef Q_ARG
+# undef Q_RETURN_ARG
+# define Q_ARG(type, data) QArgument<type >(#type, data)
+# define Q_RETURN_ARG(type, data) QReturnArgument<type >(#type, data)
+# define Q_NO_ARG , QGenericArgument()
+#else
+// This macro is used to force the overload selection to the compat
+// (non-variadic) code above
+# define Q_NO_ARG
+#endif
+
+using namespace Qt::StringLiterals;
+
struct MyStruct
{
int i;
@@ -90,7 +88,7 @@ namespace MyNamespace {
MyFlags myFlags() const { return m_flags; }
void setMyFlags(MyFlags val) { m_flags = val; }
- MyClass(QObject *parent = 0)
+ MyClass(QObject *parent = nullptr)
: QObject(parent),
m_enum(MyEnum1),
m_flags(MyFlag1|MyFlag2)
@@ -139,7 +137,7 @@ namespace MyNamespace {
MyFlags myFlags() const { return m_flags; }
void setMyFlags(MyFlags val) { m_flags = val; }
- MyClass2(QObject *parent = 0)
+ MyClass2(QObject *parent = nullptr)
: QObject(parent),
m_enum(MyEnum1),
m_flags(MyFlag1|MyFlag2)
@@ -238,8 +236,7 @@ namespace MyNamespace {
int m_value2 = 0;
int m_value3 = 0;
};
-}
-
+} // namespace MyNamespace
class tst_QMetaObject : public QObject
{
@@ -288,39 +285,53 @@ public:
QList<QVariant> value4;
QVariantList value5;
+ tst_QMetaObject();
+
private slots:
void connectSlotsByName();
void invokeMetaMember();
+ void invokeMetaMemberNoMacros();
void invokePointer();
void invokeQueuedMetaMember();
+ void invokeQueuedMetaMemberNoMacro();
void invokeQueuedPointer();
void invokeBlockingQueuedMetaMember();
+ void invokeBlockingQueuedMetaMemberNoMacros();
void invokeBlockingQueuedPointer();
void invokeCustomTypes();
void invokeMetaConstructor();
+ void invokeMetaConstructorNoMacro();
void invokeTypedefTypes();
void invokeException();
void invokeQueuedAutoRegister();
+ void invokeFreeFunction();
+ void invokeBind();
void qtMetaObjectInheritance();
void normalizedSignature_data();
void normalizedSignature();
void normalizedType_data();
void normalizedType();
void customPropertyType();
- void checkScope_data();
- void checkScope();
+ void keysToValue_data();
+ void keysToValue(); // Also keyToValue()
void propertyNotify();
void propertyConstant();
void propertyFinal();
+ void metaType();
+
void stdSet();
void classInfo();
void metaMethod();
+ void metaMethodNoMacro();
void indexOfMethod_data();
void indexOfMethod();
+ void firstMethod_data();
+ void firstMethod();
+
void indexOfMethodPMF();
void signalOffset_data();
@@ -419,6 +430,11 @@ private slots:
#define FUNCTION(x) "QMetaObject::" x ": "
+tst_QMetaObject::tst_QMetaObject()
+{
+ qRegisterMetaType<qlonglong *>();
+}
+
void tst_QMetaObject::connectSlotsByName()
{
CTestObject obj;
@@ -453,8 +469,6 @@ void tst_QMetaObject::connectSlotsByName()
QCOMPARE(obj2.invokeCount2, 1);
}
-struct MyUnregisteredType { };
-
static int countedStructObjectsCount = 0;
struct CountedStruct
{
@@ -477,6 +491,8 @@ public:
QtTestObject();
QtTestObject(const QString &s) : slotResult(s) {}
Q_INVOKABLE QtTestObject(QObject *parent);
+ Q_INVOKABLE QtTestObject(QObject *parent, int, int);
+ Q_INVOKABLE QtTestObject(QObject *parent, int);
public slots:
void sl0();
@@ -497,17 +513,24 @@ public slots:
const char *sl12();
QList<QString> sl13(QList<QString> l1);
qint64 sl14();
- void testSender();
+ qlonglong *sl15(qlonglong *);
+ MyForwardDeclaredType *sl16(MyForwardDeclaredType *);
- void testReference(QString &str);
+ void sl17(int *i) { *i = 242; }
+
+ void overloadedSlot();
+ void overloadedSlot(int, int);
+ void overloadedSlot(int);
+ void testSender();
+ void testReference(QString &str);
void testLongLong(qint64 ll1, quint64 ll2);
void moveToThread(QThread *t)
{ QObject::moveToThread(t); }
- void slotWithUnregisteredParameterType(MyUnregisteredType);
- void slotWithOneUnregisteredParameterType(QString a1, MyUnregisteredType a2);
+ void slotWithUnregisteredParameterType(const MyForwardDeclaredType &);
+ void slotWithOneUnregisteredParameterType(QString a1, const MyForwardDeclaredType &a2);
CountedStruct throwingSlot(const CountedStruct &, CountedStruct s2) {
#ifndef QT_NO_EXCEPTIONS
@@ -558,6 +581,14 @@ QtTestObject::QtTestObject(QObject *parent)
{
}
+QtTestObject::QtTestObject(QObject *parent, int, int)
+ : QObject(parent)
+{ slotResult = "ii"; }
+
+QtTestObject::QtTestObject(QObject *parent, int)
+ : QObject(parent)
+{ slotResult = "i"; }
+
void QtTestObject::sl0() { slotResult = "sl0"; };
QString QtTestObject::sl1(QString s1) { slotResult = "sl1:" + s1; return "yessir"; }
void QtTestObject::sl2(QString s1, QString s2) { slotResult = "sl2:" + s1 + s2; }
@@ -590,6 +621,27 @@ QList<QString> QtTestObject::sl13(QList<QString> l1)
{ slotResult = "sl13"; return l1; }
qint64 QtTestObject::sl14()
{ slotResult = "sl14"; return Q_INT64_C(123456789)*123456789; }
+qlonglong *QtTestObject::sl15(qlonglong *ptr)
+{ slotResult = "sl15"; return ptr; }
+MyForwardDeclaredType *QtTestObject::sl16(MyForwardDeclaredType *ptr)
+{
+ slotResult = "sl16:";
+ if (ptr) {
+ slotResult += "notnull";
+ return nullptr;
+ }
+ slotResult += "null";
+ return getForwardDeclaredPointer();
+}
+
+void QtTestObject::overloadedSlot()
+{ slotResult = "overloadedSlot"; }
+
+void QtTestObject::overloadedSlot(int x, int y)
+{ slotResult = "overloadedSlot:" + QString::number(x) + ',' + QString::number(y); }
+
+void QtTestObject::overloadedSlot(int x)
+{ slotResult = "overloadedSlot:" + QString::number(x); }
void QtTestObject::testReference(QString &str)
{ slotResult = "testReference:" + str; str = "gotcha"; }
@@ -602,10 +654,10 @@ void QtTestObject::testSender()
slotResult = QString::asprintf("%p", sender());
}
-void QtTestObject::slotWithUnregisteredParameterType(MyUnregisteredType)
+void QtTestObject::slotWithUnregisteredParameterType(const MyForwardDeclaredType &)
{ slotResult = "slotWithUnregisteredReturnType"; }
-void QtTestObject::slotWithOneUnregisteredParameterType(QString a1, MyUnregisteredType)
+void QtTestObject::slotWithOneUnregisteredParameterType(QString a1, const MyForwardDeclaredType &)
{ slotResult = "slotWithUnregisteredReturnType-" + a1; }
void QtTestObject::staticFunction0()
@@ -616,6 +668,7 @@ void QtTestObject::staticFunction0()
qint64 QtTestObject::staticFunction1()
{ staticResult = "staticFunction1"; return Q_INT64_C(123456789)*123456789; }
+// this test is duplicated below
void tst_QMetaObject::invokeMetaMember()
{
QtTestObject obj;
@@ -626,17 +679,17 @@ void tst_QMetaObject::invokeMetaMember()
// Test nullptr
char *nullCharArray = nullptr;
const char *nullConstCharArray = nullptr;
- QVERIFY(!QMetaObject::invokeMethod(nullptr, nullCharArray));
- QVERIFY(!QMetaObject::invokeMethod(nullptr, nullConstCharArray));
- QVERIFY(!QMetaObject::invokeMethod(nullptr, "sl0"));
- QVERIFY(!QMetaObject::invokeMethod(&obj, nullCharArray));
- QVERIFY(!QMetaObject::invokeMethod(&obj, nullConstCharArray));
- QVERIFY(!QMetaObject::invokeMethod(&obj, nullCharArray, Qt::AutoConnection));
- QVERIFY(!QMetaObject::invokeMethod(&obj, nullConstCharArray, Qt::AutoConnection));
+ QVERIFY(!QMetaObject::invokeMethod(nullptr, nullCharArray Q_NO_ARG));
+ QVERIFY(!QMetaObject::invokeMethod(nullptr, nullConstCharArray Q_NO_ARG));
+ QVERIFY(!QMetaObject::invokeMethod(nullptr, "sl0" Q_NO_ARG));
+ QVERIFY(!QMetaObject::invokeMethod(&obj, nullCharArray Q_NO_ARG));
+ QVERIFY(!QMetaObject::invokeMethod(&obj, nullConstCharArray Q_NO_ARG));
+ QVERIFY(!QMetaObject::invokeMethod(&obj, nullCharArray, Qt::AutoConnection Q_NO_ARG));
+ QVERIFY(!QMetaObject::invokeMethod(&obj, nullConstCharArray, Qt::AutoConnection Q_NO_ARG));
QVERIFY(!QMetaObject::invokeMethod(&obj, nullCharArray, Qt::AutoConnection, QGenericReturnArgument()));
QVERIFY(!QMetaObject::invokeMethod(&obj, nullConstCharArray, Qt::AutoConnection, QGenericReturnArgument()));
- QVERIFY(QMetaObject::invokeMethod(&obj, "sl0"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl0" Q_NO_ARG));
QCOMPARE(obj.slotResult, QString("sl0"));
QVERIFY(QMetaObject::invokeMethod(&obj, "sl1", Q_ARG(QString, t1)));
@@ -675,16 +728,23 @@ void tst_QMetaObject::invokeMetaMember()
Q_ARG(QString, t7), Q_ARG(QString, t8), Q_ARG(QString, t9)));
QCOMPARE(obj.slotResult, QString("sl9:123456789"));
- QVERIFY(QMetaObject::invokeMethod(&obj, "sl11"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl11" Q_NO_ARG));
QCOMPARE(obj.slotResult, QString("sl11"));
- QVERIFY(QMetaObject::invokeMethod(&obj, "testSender"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "testSender" Q_NO_ARG));
QCOMPARE(obj.slotResult, QString("0x0"));
QString refStr("whatever");
+#ifdef USE_COMPAT_Q_ARG
QVERIFY(QMetaObject::invokeMethod(&obj, "testReference", QGenericArgument("QString&", &refStr)));
QCOMPARE(obj.slotResult, QString("testReference:whatever"));
QCOMPARE(refStr, QString("gotcha"));
+ obj.slotResult.clear();
+#endif
+ refStr = "whatever";
+ QVERIFY(QMetaObject::invokeMethod(&obj, "testReference", Q_ARG(QString&, refStr)));
+ QCOMPARE(obj.slotResult, QString("testReference:whatever"));
+ QCOMPARE(refStr, QString("gotcha"));
qint64 ll1 = -1;
quint64 ll2 = 0;
@@ -699,24 +759,24 @@ void tst_QMetaObject::invokeMetaMember()
QCOMPARE(exp, QString("yessir"));
QCOMPARE(obj.slotResult, QString("sl1:bubu"));
- QObject *ptr = 0;
+ QObject *ptr = nullptr;
QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", Q_RETURN_ARG(QObject*,ptr)));
QCOMPARE(ptr, (QObject *)&obj);
QCOMPARE(obj.slotResult, QString("sl11"));
// try again with a space:
- ptr = 0;
+ ptr = nullptr;
QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", Q_RETURN_ARG(QObject * , ptr)));
QCOMPARE(ptr, (QObject *)&obj);
QCOMPARE(obj.slotResult, QString("sl11"));
- const char *ptr2 = 0;
+ const char *ptr2 = nullptr;
QVERIFY(QMetaObject::invokeMethod(&obj, "sl12", Q_RETURN_ARG(const char*, ptr2)));
- QVERIFY(ptr2 != 0);
+ QVERIFY(ptr2 != nullptr);
QCOMPARE(obj.slotResult, QString("sl12"));
// try again with a space:
- ptr2 = 0;
+ ptr2 = nullptr;
QVERIFY(QMetaObject::invokeMethod(&obj, "sl12", Q_RETURN_ARG(char const * , ptr2)));
- QVERIFY(ptr2 != 0);
+ QVERIFY(ptr2 != nullptr);
QCOMPARE(obj.slotResult, QString("sl12"));
// test w/ template args
@@ -735,8 +795,37 @@ void tst_QMetaObject::invokeMetaMember()
QCOMPARE(return64, Q_INT64_C(123456789)*123456789);
QCOMPARE(obj.slotResult, QString("sl14"));
+ // pointers
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", Q_ARG(qlonglong*, &return64)));
+ QCOMPARE(obj.slotResult, QString("sl15"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", Q_ARG(MyForwardDeclaredType*, getForwardDeclaredPointer())));
+ QCOMPARE(obj.slotResult, QString("sl16:notnull"));
+
+ obj.slotResult.clear();
+ qint64 *return64Ptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", Q_RETURN_ARG(qlonglong*, return64Ptr), Q_ARG(qlonglong*, &return64)));
+ QCOMPARE(return64Ptr, &return64);
+ QCOMPARE(obj.slotResult, QString("sl15"));
+
+ obj.slotResult.clear();
+ MyForwardDeclaredType *forwardPtr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", Q_RETURN_ARG(MyForwardDeclaredType*, forwardPtr),
+ Q_ARG(MyForwardDeclaredType*, nullptr)));
+ QCOMPARE(forwardPtr, getForwardDeclaredPointer());
+ QCOMPARE(obj.slotResult, QString("sl16:null"));
+
+#ifndef QT_NO_DATA_RELOCATION // this doesn't work with the new API on Windows
+#endif
+ // test overloads
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot" Q_NO_ARG));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Q_ARG(int, 1)));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Q_ARG(int, 1), Q_ARG(int, 42)));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1,42"));
+
//test signals
- QVERIFY(QMetaObject::invokeMethod(&obj, "sig0"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig0" Q_NO_ARG));
QCOMPARE(obj.slotResult, QString("sl0"));
QVERIFY(QMetaObject::invokeMethod(&obj, "sig1", Q_ARG(QString, "baba")));
@@ -757,6 +846,175 @@ void tst_QMetaObject::invokeMetaMember()
QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl1(QString,QString,QString)\n"
"Candidates are:\n sl1(QString)");
QVERIFY(!QMetaObject::invokeMethod(&obj, "sl1", Q_ARG(QString, "arg"), Q_ARG(QString, "arg"), Q_ARG(QString, "arg")));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::testReference(QString)\n"
+ "Candidates are:\n testReference(QString&)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "testReference", Q_ARG(QString, exp)));
+
+ //should not have changed since last test.
+ QCOMPARE(exp, QString("yessir"));
+ QCOMPARE(obj.slotResult, QString("sl1:hehe"));
+}
+
+// this is a copy-paste-adapt of the above
+void tst_QMetaObject::invokeMetaMemberNoMacros()
+{
+ QtTestObject obj;
+
+ QString t1("1"); QString t2("2"); QString t3("3"); QString t4("4"); QString t5("5");
+ QString t6("6"); QString t7("7"); QString t8("8"); QString t9("9"); QString t10("X");
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl0"));
+ QCOMPARE(obj.slotResult, QString("sl0"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl1", t1));
+ QCOMPARE(obj.slotResult, QString("sl1:1"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl2", std::as_const(t1), t2));
+ QCOMPARE(obj.slotResult, QString("sl2:12"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl3", t1, t2, t3));
+ QCOMPARE(obj.slotResult, QString("sl3:123"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl4", t1, t2, t3,
+ t4));
+ QCOMPARE(obj.slotResult, QString("sl4:1234"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl5", t1, t2, t3,
+ t4, QStringLiteral("5")));
+ QCOMPARE(obj.slotResult, QString("sl5:12345"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl6", t1, t2, t3,
+ t4, t5, t6));
+ QCOMPARE(obj.slotResult, QString("sl6:123456"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl7", t1, t2, t3,
+ t4, t5, t6,
+ t7));
+ QCOMPARE(obj.slotResult, QString("sl7:1234567"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl8", t1, t2, t3,
+ t4, t5, t6,
+ t7, t8));
+ QCOMPARE(obj.slotResult, QString("sl8:12345678"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl9", t1, t2, t3,
+ t4, t5, t6,
+ t7, t8, t9));
+ QCOMPARE(obj.slotResult, QString("sl9:123456789"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl11"));
+ QCOMPARE(obj.slotResult, QString("sl11"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "testSender"));
+ QCOMPARE(obj.slotResult, QString("0x0"));
+
+ // this is not working for now
+// QString refStr("whatever");
+// QVERIFY(QMetaObject::invokeMethod(&obj, "testReference", refStr));
+// QCOMPARE(obj.slotResult, QString("testReference:whatever"));
+// QCOMPARE(refStr, QString("gotcha"));
+
+ qint64 ll1 = -1;
+ quint64 ll2 = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj,
+ "testLongLong",
+ ll1,
+ ll2));
+ QCOMPARE(obj.slotResult, QString("testLongLong:-1,0"));
+
+ QString exp;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl1", qReturnArg(exp), QStringLiteral("bubu")));
+ QCOMPARE(exp, QString("yessir"));
+ QCOMPARE(obj.slotResult, QString("sl1:bubu"));
+
+ QObject *ptr = nullptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", qReturnArg(ptr)));
+ QCOMPARE(ptr, (QObject *)&obj);
+ QCOMPARE(obj.slotResult, QString("sl11"));
+ // try again with a space:
+ ptr = nullptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", qReturnArg(ptr)));
+ QCOMPARE(ptr, (QObject *)&obj);
+ QCOMPARE(obj.slotResult, QString("sl11"));
+
+ const char *ptr2 = nullptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl12", qReturnArg(ptr2)));
+ QVERIFY(ptr2 != nullptr);
+ QCOMPARE(obj.slotResult, QString("sl12"));
+ // try again with a space:
+ ptr2 = nullptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl12", qReturnArg(ptr2)));
+ QVERIFY(ptr2 != nullptr);
+ QCOMPARE(obj.slotResult, QString("sl12"));
+
+ // test w/ template args
+ QList<QString> returnValue, argument;
+ argument << QString("one") << QString("two") << QString("three");
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl13",
+ qReturnArg(returnValue),
+ argument));
+ QCOMPARE(returnValue, argument);
+ QCOMPARE(obj.slotResult, QString("sl13"));
+
+ // return qint64
+ qint64 return64;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl14",
+ qReturnArg(return64)));
+ QCOMPARE(return64, Q_INT64_C(123456789)*123456789);
+ QCOMPARE(obj.slotResult, QString("sl14"));
+
+ // pointers
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", &return64));
+ QCOMPARE(obj.slotResult, QString("sl15"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", getForwardDeclaredPointer()));
+ QCOMPARE(obj.slotResult, QString("sl16:notnull"));
+
+ obj.slotResult.clear();
+ qint64 *return64Ptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", qReturnArg(return64Ptr), &return64));
+ QCOMPARE(return64Ptr, &return64);
+ QCOMPARE(obj.slotResult, QString("sl15"));
+
+ obj.slotResult.clear();
+ MyForwardDeclaredType *forwardPtr = nullptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", qReturnArg(forwardPtr),
+ forwardPtr));
+ QCOMPARE(forwardPtr, getForwardDeclaredPointer());
+ QCOMPARE(obj.slotResult, QString("sl16:null"));
+
+ // test overloads
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot"));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", 1));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", 1, 42));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1,42"));
+
+ //test signals
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig0"));
+ QCOMPARE(obj.slotResult, QString("sl0"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig1", QStringLiteral("baba")));
+ QCOMPARE(obj.slotResult, QString("sl1:baba"));
+
+ exp.clear();
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig1", qReturnArg(exp), QStringLiteral("hehe")));
+ QCOMPARE(exp, QString("yessir"));
+ QCOMPARE(obj.slotResult, QString("sl1:hehe"));
+
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::doesNotExist()");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "doesNotExist"));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl1(QString)(QString)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "sl1(QString)", QStringLiteral("arg")));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl3(QString)\n"
+ "Candidates are:\n sl3(QString,QString,QString)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "sl3", QStringLiteral("arg")));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl1(QString,QString,QString)\n"
+ "Candidates are:\n sl1(QString)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "sl1", QStringLiteral("arg"), QStringLiteral("arg"), QStringLiteral("arg")));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::testReference(QString)\n"
+ "Candidates are:\n testReference(QString&)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "testReference", exp));
//should not have changed since last test.
QCOMPARE(exp, QString("yessir"));
@@ -820,7 +1078,6 @@ void tst_QMetaObject::invokePointer()
QCOMPARE(obj.slotResult, QString("sl1:bubu"));
}
QCOMPARE(countedStructObjectsCount, 0);
-#ifdef __cpp_init_captures
{
CountedStruct str;
std::unique_ptr<int> ptr( new int );
@@ -828,14 +1085,123 @@ void tst_QMetaObject::invokePointer()
QCOMPARE(obj.slotResult, QString("sl1:1"));
}
QCOMPARE(countedStructObjectsCount, 0);
-#endif
+
+ // Invoking with parameters
+ QString result;
+ QVERIFY(QMetaObject::invokeMethod(&obj, &QtTestObject::sl1, qReturnArg(result), u"bubu"_s));
+ QCOMPARE(obj.slotResult, u"sl1:bubu");
+ QCOMPARE(result, u"yessir");
+
+ // without taking return value
+ QVERIFY(QMetaObject::invokeMethod(&obj, &QtTestObject::sl1, u"bubu"_s));
+ QCOMPARE(obj.slotResult, u"sl1:bubu");
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, &QtTestObject::sl1, Qt::DirectConnection, qReturnArg(result),
+ u"byebye"_s));
+ QCOMPARE(obj.slotResult, u"sl1:byebye");
+ QCOMPARE(result, u"yessir");
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, qOverload<int, int>(&QtTestObject::overloadedSlot), 1, 2));
+ QCOMPARE(obj.slotResult, u"overloadedSlot:1,2");
+
+ // non-const ref parameter
+ QString original = u"bubu"_s;
+ QString &ref = original;
+ QVERIFY(QMetaObject::invokeMethod(&obj, &QtTestObject::sl1, qReturnArg(result), ref));
+ QCOMPARE(obj.slotResult, u"sl1:bubu");
+ QCOMPARE(result, u"yessir");
+
+ struct R {
+ bool operator()(int) { return true; }
+ int operator()(char) { return 15; }
+ int operator()(QString = {}, int = {}, int = {}) { return 242; }
+ } r;
+
+ // Test figuring out which operator() to call:
+ {
+ bool res = false;
+ QVERIFY(QMetaObject::invokeMethod(&obj, r, qReturnArg(res), 1));
+ QCOMPARE(res, true);
+ }
+ {
+ int res;
+ QVERIFY(QMetaObject::invokeMethod(&obj, r, qReturnArg(res), 'c'));
+ QCOMPARE(res, 15);
+ }
+ {
+ int res;
+ QVERIFY(QMetaObject::invokeMethod(&obj, r, qReturnArg(res)));
+ QCOMPARE(res, 242);
+ res = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj, r, qReturnArg(res), u"bu"_s));
+ QCOMPARE(res, 242);
+ res = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj, r, qReturnArg(res), u"bu"_s, 1));
+ QCOMPARE(res, 242);
+ res = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj, r, qReturnArg(res), u"bu"_s, 1, 2));
+ QCOMPARE(res, 242);
+ }
+
+ {
+ auto lambda = [](const QString &s) { return s + s; };
+ QVERIFY(QMetaObject::invokeMethod(&obj, lambda, qReturnArg(result), u"bu"_s));
+ QCOMPARE(result, u"bubu");
+ }
+
+ {
+ auto lambda = [](const QString &s = u"bu"_s) { return s + s; };
+ QVERIFY(QMetaObject::invokeMethod(&obj, lambda, qReturnArg(result)));
+ QCOMPARE(result, u"bubu");
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, lambda, qReturnArg(result), u"bye"_s));
+ QCOMPARE(result, u"byebye");
+ }
+
+ {
+ auto lambda = [](const QString &s, qint64 a, qint16 b, qint8 c) {
+ return s + QString::number(a) + QString::number(b) + QString::number(c);
+ };
+ // Testing mismatching argument (int for qint64). The other arguments
+ // would static_assert for potential truncation if they were ints.
+ QVERIFY(QMetaObject::invokeMethod(&obj, lambda, qReturnArg(result), u"bu"_s, 1, qint16(2), qint8(3)));
+ QCOMPARE(result, u"bu123");
+ }
+ {
+ // Testing deduction
+ auto lambda = [](const QString &s, auto a) { return s + a; };
+ QVERIFY(QMetaObject::invokeMethod(&obj, lambda, qReturnArg(result), u"bu"_s, "bu"_L1));
+ QCOMPARE(result, u"bubu");
+
+ auto variadic = [](const QString &s, auto... a) { return s + (QString::number(a) + ...); };
+ QVERIFY(QMetaObject::invokeMethod(&obj, variadic, qReturnArg(result), u"bu"_s, 1, 2, 3, 4, 5, 6));
+ QCOMPARE(result, u"bu123456");
+ }
+ {
+ // Testing a functor returning void and accepting a pointer,
+ // this may trigger the pointer to be interpreted as the old void*
+ // return parameter.
+ bool invoked = false;
+ auto lambda = [&invoked](void *ptr) -> void {
+ Q_UNUSED(ptr);
+ invoked = true;
+ };
+ int i = 242;
+ QVERIFY(QMetaObject::invokeMethod(&obj, lambda, &i));
+ QVERIFY(invoked);
+
+ // member fn
+ i = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj, &QtTestObject::sl17, &i));
+ QCOMPARE(i, 242);
+ }
}
void tst_QMetaObject::invokeQueuedMetaMember()
{
QtTestObject obj;
- QVERIFY(QMetaObject::invokeMethod(&obj, "sl0", Qt::QueuedConnection));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl0", Qt::QueuedConnection Q_NO_ARG));
QVERIFY(obj.slotResult.isEmpty());
qApp->processEvents(QEventLoop::AllEvents);
QCOMPARE(obj.slotResult, QString("sl0"));
@@ -855,10 +1221,36 @@ void tst_QMetaObject::invokeQueuedMetaMember()
qApp->processEvents(QEventLoop::AllEvents);
QCOMPARE(obj.slotResult, QString("sl9:123456789"));
+ // pointers
+ qint64 return64;
+ obj.slotResult.clear();
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", Qt::QueuedConnection, Q_ARG(qlonglong*, &return64)));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("sl15"));
+
+ // since Qt 6.5, this works even for pointers to forward-declared types
+ obj.slotResult.clear();
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", Qt::QueuedConnection, Q_ARG(MyForwardDeclaredType*, getForwardDeclaredPointer())));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("sl16:notnull"));
+
+#ifndef QT_NO_DATA_RELOCATION // this doesn't work with the new API on Windows
+#endif
+ // test overloads
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::QueuedConnection Q_NO_ARG));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("overloadedSlot"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::QueuedConnection, Q_ARG(int, 1)));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::QueuedConnection, Q_ARG(int, 1), Q_ARG(int, 42)));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1,42"));
+
// signals
obj.slotResult.clear();
- QVERIFY(QMetaObject::invokeMethod(&obj, "sig0", Qt::QueuedConnection));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig0", Qt::QueuedConnection Q_NO_ARG));
QVERIFY(obj.slotResult.isEmpty());
qApp->processEvents(QEventLoop::AllEvents);
QCOMPARE(obj.slotResult, QString("sl0"));
@@ -882,23 +1274,142 @@ void tst_QMetaObject::invokeQueuedMetaMember()
qApp->processEvents(QEventLoop::AllEvents);
QCOMPARE(obj.slotResult, QString("testLongLong:-1,0"));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::testReference(QString)\n"
+ "Candidates are:\n testReference(QString&)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "testReference", Qt::QueuedConnection, Q_ARG(QString, exp)));
+
+ QString refStr = "whatever";
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: Unable to handle unregistered datatype 'QString&'");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "testReference", Qt::QueuedConnection, Q_ARG(QString&, refStr)));
+ QCOMPARE(refStr, "whatever");
+
+#ifdef USE_COMPAT_Q_ARG // this doesn't compile with the new API
+ obj.slotResult.clear();
+ {
+ const MyForwardDeclaredType &t = getForwardDeclaredType();
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: Unable to handle unregistered datatype 'MyForwardDeclaredType'");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "slotWithUnregisteredParameterType", Qt::QueuedConnection, Q_ARG(MyForwardDeclaredType, t)));
+ QVERIFY(obj.slotResult.isEmpty());
+ }
+
+ obj.slotResult.clear();
+ {
+ QString a1("Cannot happen");
+ const MyForwardDeclaredType &t = getForwardDeclaredType();
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: Unable to handle unregistered datatype 'MyForwardDeclaredType'");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "slotWithOneUnregisteredParameterType", Qt::QueuedConnection,
+ Q_ARG(QString, a1), Q_ARG(MyForwardDeclaredType, t)));
+ QVERIFY(obj.slotResult.isEmpty());
+ }
+#endif
+}
+
+// this is a copy-paste-adapt of the above
+void tst_QMetaObject::invokeQueuedMetaMemberNoMacro()
+{
+ QtTestObject obj;
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl0", Qt::QueuedConnection));
+ QVERIFY(obj.slotResult.isEmpty());
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("sl0"));
+ obj.slotResult = QString();
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl1", Qt::QueuedConnection, QString("hallo")));
+ QVERIFY(obj.slotResult.isEmpty());
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("sl1:hallo"));
+ obj.slotResult = QString();
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl9", Qt::QueuedConnection, QStringLiteral("1"), QStringLiteral("2"),
+ QStringLiteral("3"), QStringLiteral("4"), QStringLiteral("5"),
+ QStringLiteral("6"), QStringLiteral("7"), QStringLiteral("8"),
+ QStringLiteral("9")));
+ QVERIFY(obj.slotResult.isEmpty());
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("sl9:123456789"));
+
+ // pointers
+ qint64 return64;
+ obj.slotResult.clear();
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", Qt::QueuedConnection, &return64));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("sl15"));
+
+ obj.slotResult.clear();
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", Qt::QueuedConnection, getForwardDeclaredPointer()));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("sl16:notnull"));
+
+ // test overloads
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::QueuedConnection));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("overloadedSlot"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::QueuedConnection, 1));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::QueuedConnection, 1, 42));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1,42"));
+
+ // signals
+
+ obj.slotResult.clear();
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig0", Qt::QueuedConnection));
+ QVERIFY(obj.slotResult.isEmpty());
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("sl0"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig1", Qt::QueuedConnection, QStringLiteral("gogo")));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("sl1:gogo"));
+
+ QString exp;
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: Unable to invoke methods with return values in queued connections");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "sig1", Qt::QueuedConnection, qReturnArg(exp),
+ QStringLiteral("nono")));
+
+ qint64 ll1 = -1;
+ quint64 ll2 = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj,
+ "testLongLong",
+ Qt::QueuedConnection,
+ ll1,
+ ll2));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, QString("testLongLong:-1,0"));
+
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::testReference(QString)\n"
+ "Candidates are:\n testReference(QString&)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "testReference", exp));
+ QCOMPARE(obj.slotResult, QString("testLongLong:-1,0"));
+ QVERIFY(exp.isEmpty());
+
+ // this doesn't work yet
+// QString refStr = "whatever";
+// QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: Unable to handle unregistered datatype 'QString&'");
+// QVERIFY(!QMetaObject::invokeMethod(&obj, "testReference", Qt::QueuedConnection, Q_ARG(QString&, refStr)));
+// QCOMPARE(refStr, "whatever");
+
+#if 0 // this won't even compile any more
obj.slotResult.clear();
{
- MyUnregisteredType t;
- QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: Unable to handle unregistered datatype 'MyUnregisteredType'");
- QVERIFY(!QMetaObject::invokeMethod(&obj, "slotWithUnregisteredParameterType", Qt::QueuedConnection, Q_ARG(MyUnregisteredType, t)));
+ const MyForwardDeclaredType &t = getForwardDeclaredType();
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: Unable to handle unregistered datatype 'MyForwardDeclaredType'");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "slotWithUnregisteredParameterType", Qt::QueuedConnection, t));
QVERIFY(obj.slotResult.isEmpty());
}
obj.slotResult.clear();
{
QString a1("Cannot happen");
- MyUnregisteredType t;
- QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: Unable to handle unregistered datatype 'MyUnregisteredType'");
+ const MyForwardDeclaredType &t = getForwardDeclaredType();
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: Unable to handle unregistered datatype 'MyForwardDeclaredType'");
QVERIFY(!QMetaObject::invokeMethod(&obj, "slotWithOneUnregisteredParameterType", Qt::QueuedConnection,
- Q_ARG(QString, a1), Q_ARG(MyUnregisteredType, t)));
+ a1, t));
QVERIFY(obj.slotResult.isEmpty());
}
+#endif
}
void tst_QMetaObject::invokeQueuedPointer()
@@ -948,9 +1459,15 @@ void tst_QMetaObject::invokeQueuedPointer()
QCOMPARE(var, 0);
}
QCOMPARE(countedStructObjectsCount, 0);
-}
+ // Invoking with parameters
+ using namespace Qt::StringLiterals;
+ QVERIFY(QMetaObject::invokeMethod(&obj, &QtTestObject::sl1, Qt::QueuedConnection, u"bubu"_s));
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult, u"sl1:bubu");
+}
+// this test is duplicated below
void tst_QMetaObject::invokeBlockingQueuedMetaMember()
{
QThread t;
@@ -997,16 +1514,23 @@ void tst_QMetaObject::invokeBlockingQueuedMetaMember()
Q_ARG(QString, t7), Q_ARG(QString, t8), Q_ARG(QString, t9)));
QCOMPARE(obj.slotResult, QString("sl9:123456789"));
- QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", Qt::BlockingQueuedConnection));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", Qt::BlockingQueuedConnection Q_NO_ARG));
QCOMPARE(obj.slotResult, QString("sl11"));
- QVERIFY(QMetaObject::invokeMethod(&obj, "testSender", Qt::BlockingQueuedConnection));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "testSender", Qt::BlockingQueuedConnection Q_NO_ARG));
QCOMPARE(obj.slotResult, QString("0x0"));
QString refStr("whatever");
+#ifdef USE_COMPAT_Q_ARG
QVERIFY(QMetaObject::invokeMethod(&obj, "testReference", Qt::BlockingQueuedConnection, QGenericArgument("QString&", &refStr)));
QCOMPARE(obj.slotResult, QString("testReference:whatever"));
QCOMPARE(refStr, QString("gotcha"));
+ obj.slotResult.clear();
+#endif
+ refStr = "whatever";
+ QVERIFY(QMetaObject::invokeMethod(&obj, "testReference", Qt::BlockingQueuedConnection, Q_ARG(QString&, refStr)));
+ QCOMPARE(obj.slotResult, QString("testReference:whatever"));
+ QCOMPARE(refStr, QString("gotcha"));
qint64 ll1 = -1;
quint64 ll2 = 0;
@@ -1022,12 +1546,12 @@ void tst_QMetaObject::invokeBlockingQueuedMetaMember()
QCOMPARE(exp, QString("yessir"));
QCOMPARE(obj.slotResult, QString("sl1:bubu"));
- QObject *ptr = 0;
+ QObject *ptr = nullptr;
QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QObject*,ptr)));
QCOMPARE(ptr, (QObject *)&obj);
QCOMPARE(obj.slotResult, QString("sl11"));
// try again with a space:
- ptr = 0;
+ ptr = nullptr;
QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QObject * , ptr)));
QCOMPARE(ptr, (QObject *)&obj);
QCOMPARE(obj.slotResult, QString("sl11"));
@@ -1051,8 +1575,44 @@ void tst_QMetaObject::invokeBlockingQueuedMetaMember()
QCOMPARE(returnValue, argument);
QCOMPARE(obj.slotResult, QString("sl13"));
+ // return qint64
+ qint64 return64;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl14", Qt::BlockingQueuedConnection,
+ Q_RETURN_ARG(qint64, return64)));
+ QCOMPARE(return64, Q_INT64_C(123456789)*123456789);
+ QCOMPARE(obj.slotResult, QString("sl14"));
+
+ // pointers
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", Qt::BlockingQueuedConnection, Q_ARG(qlonglong*, &return64)));
+ QCOMPARE(obj.slotResult, QString("sl15"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", Qt::BlockingQueuedConnection, Q_ARG(MyForwardDeclaredType*, getForwardDeclaredPointer())));
+ QCOMPARE(obj.slotResult, QString("sl16:notnull"));
+
+ obj.slotResult.clear();
+ qint64 *return64Ptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", Qt::BlockingQueuedConnection, Q_RETURN_ARG(qlonglong*, return64Ptr), Q_ARG(qlonglong*, &return64)));
+ QCOMPARE(return64Ptr, &return64);
+ QCOMPARE(obj.slotResult, QString("sl15"));
+
+ obj.slotResult.clear();
+ MyForwardDeclaredType *forwardPtr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", Qt::BlockingQueuedConnection, Q_RETURN_ARG(MyForwardDeclaredType*, forwardPtr),
+ Q_ARG(MyForwardDeclaredType*, nullptr)));
+ QCOMPARE(forwardPtr, getForwardDeclaredPointer());
+ QCOMPARE(obj.slotResult, QString("sl16:null"));
+
+#ifndef QT_NO_DATA_RELOCATION // this doesn't work with the new API on Windows
+#endif
+ // test overloads
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::BlockingQueuedConnection Q_NO_ARG));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::BlockingQueuedConnection, Q_ARG(int, 1)));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::BlockingQueuedConnection, Q_ARG(int, 1), Q_ARG(int, 42)));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1,42"));
+
//test signals
- QVERIFY(QMetaObject::invokeMethod(&obj, "sig0", Qt::BlockingQueuedConnection));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig0", Qt::BlockingQueuedConnection Q_NO_ARG));
QCOMPARE(obj.slotResult, QString("sl0"));
QVERIFY(QMetaObject::invokeMethod(&obj, "sig1", Qt::BlockingQueuedConnection, Q_ARG(QString, "baba")));
@@ -1064,7 +1624,7 @@ void tst_QMetaObject::invokeBlockingQueuedMetaMember()
QCOMPARE(obj.slotResult, QString("sl1:hehe"));
QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::doesNotExist()");
- QVERIFY(!QMetaObject::invokeMethod(&obj, "doesNotExist", Qt::BlockingQueuedConnection));
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "doesNotExist", Qt::BlockingQueuedConnection Q_NO_ARG));
QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl1(QString)(QString)");
QVERIFY(!QMetaObject::invokeMethod(&obj, "sl1(QString)", Qt::BlockingQueuedConnection, Q_ARG(QString, "arg")));
QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl3(QString)\n"
@@ -1073,6 +1633,9 @@ void tst_QMetaObject::invokeBlockingQueuedMetaMember()
QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl1(QString,QString,QString)\n"
"Candidates are:\n sl1(QString)");
QVERIFY(!QMetaObject::invokeMethod(&obj, "sl1", Qt::BlockingQueuedConnection, Q_ARG(QString, "arg"), Q_ARG(QString, "arg"), Q_ARG(QString, "arg")));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::testReference(QString)\n"
+ "Candidates are:\n testReference(QString&)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "testReference", Qt::BlockingQueuedConnection, Q_ARG(QString, exp)));
//should not have changed since last test.
QCOMPARE(exp, QString("yessir"));
@@ -1081,7 +1644,177 @@ void tst_QMetaObject::invokeBlockingQueuedMetaMember()
QVERIFY(QMetaObject::invokeMethod(&obj, "moveToThread", Qt::BlockingQueuedConnection, Q_ARG(QThread*, QThread::currentThread())));
t.quit();
QVERIFY(t.wait());
+}
+
+// this is a copy-paste-adapt of the above
+void tst_QMetaObject::invokeBlockingQueuedMetaMemberNoMacros()
+{
+ QThread t;
+ t.start();
+ QtTestObject obj;
+ obj.moveToThread(&t);
+
+ QString t1("1"); QString t2("2"); QString t3("3"); QString t4("4"); QString t5("5");
+ QString t6("6"); QString t7("7"); QString t8("8"); QString t9("9"); QString t10("X");
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl1", Qt::BlockingQueuedConnection, t1));
+ QCOMPARE(obj.slotResult, QString("sl1:1"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl2", Qt::BlockingQueuedConnection, t1, t2));
+ QCOMPARE(obj.slotResult, QString("sl2:12"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl3", Qt::BlockingQueuedConnection, t1, t2, t3));
+ QCOMPARE(obj.slotResult, QString("sl3:123"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl4", Qt::BlockingQueuedConnection, t1, t2,
+ t3, t4));
+ QCOMPARE(obj.slotResult, QString("sl4:1234"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl5", Qt::BlockingQueuedConnection, t1, t2,
+ t3, t4, QStringLiteral("5")));
+ QCOMPARE(obj.slotResult, QString("sl5:12345"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl6", Qt::BlockingQueuedConnection, t1, t2,
+ t3, t4, t5, t6));
+ QCOMPARE(obj.slotResult, QString("sl6:123456"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl7", Qt::BlockingQueuedConnection, t1, t2,
+ t3, t4, t5, t6,
+ t7));
+ QCOMPARE(obj.slotResult, QString("sl7:1234567"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl8", Qt::BlockingQueuedConnection, t1, t2,
+ t3, t4, t5, t6,
+ t7, t8));
+ QCOMPARE(obj.slotResult, QString("sl8:12345678"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl9", Qt::BlockingQueuedConnection, t1, t2,
+ t3, t4, t5, t6,
+ t7, t8, t9));
+ QCOMPARE(obj.slotResult, QString("sl9:123456789"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", Qt::BlockingQueuedConnection));
+ QCOMPARE(obj.slotResult, QString("sl11"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "testSender", Qt::BlockingQueuedConnection));
+ QCOMPARE(obj.slotResult, QString("0x0"));
+
+ // this is not working
+// QString refStr("whatever");
+// QVERIFY(QMetaObject::invokeMethod(&obj, "testReference", Qt::BlockingQueuedConnection, refStr));
+// QCOMPARE(obj.slotResult, QString("testReference:whatever"));
+// QCOMPARE(refStr, QString("gotcha"));
+
+ qint64 ll1 = -1;
+ quint64 ll2 = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj,
+ "testLongLong",
+ Qt::BlockingQueuedConnection,
+ ll1,
+ ll2));
+ QCOMPARE(obj.slotResult, QString("testLongLong:-1,0"));
+
+ QString exp;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl1", Qt::BlockingQueuedConnection, qReturnArg(exp), QStringLiteral("bubu")));
+ QCOMPARE(exp, QString("yessir"));
+ QCOMPARE(obj.slotResult, QString("sl1:bubu"));
+
+ QObject *ptr = nullptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", Qt::BlockingQueuedConnection, qReturnArg(ptr)));
+ QCOMPARE(ptr, (QObject *)&obj);
+ QCOMPARE(obj.slotResult, QString("sl11"));
+ // try again with a space:
+ ptr = nullptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl11", Qt::BlockingQueuedConnection, qReturnArg(ptr)));
+ QCOMPARE(ptr, (QObject *)&obj);
+ QCOMPARE(obj.slotResult, QString("sl11"));
+
+ const char *ptr2 = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl12", Qt::BlockingQueuedConnection, qReturnArg(ptr2)));
+ QVERIFY(ptr2 != 0);
+ QCOMPARE(obj.slotResult, QString("sl12"));
+ // try again with a space:
+ ptr2 = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl12", Qt::BlockingQueuedConnection, qReturnArg(ptr2)));
+ QVERIFY(ptr2 != 0);
+ QCOMPARE(obj.slotResult, QString("sl12"));
+
+ // test w/ template args
+ QList<QString> returnValue, argument;
+ argument << QString("one") << QString("two") << QString("three");
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl13", Qt::BlockingQueuedConnection,
+ qReturnArg(returnValue),
+ argument));
+ QCOMPARE(returnValue, argument);
+ QCOMPARE(obj.slotResult, QString("sl13"));
+
+ // return qint64
+ qint64 return64;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl14", Qt::BlockingQueuedConnection,
+ qReturnArg(return64)));
+ QCOMPARE(return64, Q_INT64_C(123456789)*123456789);
+ QCOMPARE(obj.slotResult, QString("sl14"));
+
+ // pointers
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", Qt::BlockingQueuedConnection, &return64));
+ QCOMPARE(obj.slotResult, QString("sl15"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", Qt::BlockingQueuedConnection, getForwardDeclaredPointer()));
+ QCOMPARE(obj.slotResult, QString("sl16:notnull"));
+
+ obj.slotResult.clear();
+ qint64 *return64Ptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl15", Qt::BlockingQueuedConnection, qReturnArg(return64Ptr), &return64));
+ QCOMPARE(return64Ptr, &return64);
+ QCOMPARE(obj.slotResult, QString("sl15"));
+
+ obj.slotResult.clear();
+ MyForwardDeclaredType *forwardPtr = nullptr;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl16", Qt::BlockingQueuedConnection, qReturnArg(forwardPtr),
+ forwardPtr));
+ QCOMPARE(forwardPtr, getForwardDeclaredPointer());
+ QCOMPARE(obj.slotResult, QString("sl16:null"));
+
+ // test overloads
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::BlockingQueuedConnection));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::BlockingQueuedConnection, 1));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1"));
+ QVERIFY(QMetaObject::invokeMethod(&obj, "overloadedSlot", Qt::BlockingQueuedConnection, 1, 42));
+ QCOMPARE(obj.slotResult, QString("overloadedSlot:1,42"));
+
+ //test signals
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig0", Qt::BlockingQueuedConnection));
+ QCOMPARE(obj.slotResult, QString("sl0"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig1", Qt::BlockingQueuedConnection, QStringLiteral("baba")));
+ QCOMPARE(obj.slotResult, QString("sl1:baba"));
+
+ exp.clear();
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig1", Qt::BlockingQueuedConnection, qReturnArg(exp), QStringLiteral("hehe")));
+ QCOMPARE(exp, QString("yessir"));
+ QCOMPARE(obj.slotResult, QString("sl1:hehe"));
+
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::doesNotExist()");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "doesNotExist", Qt::BlockingQueuedConnection));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl1(QString)(QString)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "sl1(QString)", Qt::BlockingQueuedConnection, QStringLiteral("arg")));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl3(QString)\n"
+ "Candidates are:\n sl3(QString,QString,QString)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "sl3", Qt::BlockingQueuedConnection, QStringLiteral("arg")));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::sl1(QString,QString,QString)\n"
+ "Candidates are:\n sl1(QString)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "sl1", Qt::BlockingQueuedConnection, QStringLiteral("arg"), QStringLiteral("arg"), QStringLiteral("arg")));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::invokeMethod: No such method QtTestObject::testReference(QString)\n"
+ "Candidates are:\n testReference(QString&)");
+ QVERIFY(!QMetaObject::invokeMethod(&obj, "testReference", Qt::BlockingQueuedConnection, exp));
+ //should not have changed since last test.
+ QCOMPARE(exp, QString("yessir"));
+ QCOMPARE(obj.slotResult, QString("sl1:hehe"));
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, "moveToThread", Qt::BlockingQueuedConnection, QThread::currentThread()));
+ t.quit();
+ QVERIFY(t.wait());
}
void tst_QMetaObject::invokeBlockingQueuedPointer()
@@ -1144,7 +1877,6 @@ void tst_QMetaObject::invokeBlockingQueuedPointer()
QCOMPARE(exp, QString("yessir"));
QCOMPARE(obj.slotResult, QString("sl1:bubu"));
}
-#ifdef __cpp_init_captures
{
std::unique_ptr<int> ptr(new int);
QVERIFY(QMetaObject::invokeMethod(&obj,
@@ -1152,7 +1884,18 @@ void tst_QMetaObject::invokeBlockingQueuedPointer()
Qt::BlockingQueuedConnection));
QCOMPARE(obj.slotResult, QString("sl1:hehe"));
}
-#endif
+
+ // Test with parameters
+ QString result;
+ QVERIFY(QMetaObject::invokeMethod(&obj, &QtTestObject::sl1, Qt::BlockingQueuedConnection,
+ qReturnArg(result), u"bubu"_s));
+ QCOMPARE(result, u"yessir");
+ QCOMPARE(obj.slotResult, u"sl1:bubu");
+
+ QVERIFY(QMetaObject::invokeMethod(&obj, &QtTestObject::sl2, Qt::BlockingQueuedConnection,
+ u"bubu"_s, u"baba"_s));
+ QCOMPARE(obj.slotResult, u"sl2:bububaba");
+
QVERIFY(QMetaObject::invokeMethod(&obj, [&](){obj.moveToThread(QThread::currentThread());}, Qt::BlockingQueuedConnection));
t.quit();
QVERIFY(t.wait());
@@ -1209,6 +1952,10 @@ void tst_QMetaObject::invokeCustomTypes()
QCOMPARE(obj.sum, 0);
QVERIFY(QMetaObject::invokeMethod(&obj, "sl1", Q_ARG(MyType, tp)));
QCOMPARE(obj.sum, 3);
+
+ obj.sum = 0;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sl1", tp));
+ QCOMPARE(obj.sum, 3);
}
namespace NamespaceWithConstructibleClass
@@ -1218,19 +1965,22 @@ class ConstructibleClass : public QObject
{
Q_OBJECT
public:
- Q_INVOKABLE ConstructibleClass(QObject *parent = 0)
+ Q_INVOKABLE ConstructibleClass(QObject *parent = nullptr)
: QObject(parent) {}
};
}
+// this test is duplicated below
void tst_QMetaObject::invokeMetaConstructor()
{
const QMetaObject *mo = &QtTestObject::staticMetaObject;
+#ifdef USE_COMPAT_Q_ARG
{
- QObject *obj = mo->newInstance();
+ QObject *obj = mo->newInstance(QGenericArgument());
QVERIFY(!obj);
}
+#endif
{
QtTestObject obj;
QObject *obj2 = mo->newInstance(Q_ARG(QObject*, &obj));
@@ -1253,6 +2003,56 @@ void tst_QMetaObject::invokeMetaConstructor()
QTest::ignoreMessage(QtWarningMsg, "QMetaObject::newInstance: type MyGadget does not inherit QObject");
QVERIFY(!MyGadget::staticMetaObject.newInstance());
}
+
+ // overloaded constructors
+ QObject parent;
+ {
+ QObject *obj = mo->newInstance(Q_ARG(QObject*, &parent));
+ QVERIFY(obj);
+ QCOMPARE(static_cast<QtTestObject*>(obj)->slotResult, "");
+ }
+ {
+ QObject *obj = mo->newInstance(Q_ARG(QObject*, &parent), Q_ARG(int, 1));
+ QVERIFY(obj);
+ QCOMPARE(static_cast<QtTestObject*>(obj)->slotResult, "i");
+ }
+ {
+ QObject *obj = mo->newInstance(Q_ARG(QObject*, &parent), Q_ARG(int, 1), Q_ARG(int, 42));
+ QVERIFY(obj);
+ QCOMPARE(static_cast<QtTestObject*>(obj)->slotResult, "ii");
+ }
+}
+
+// this is a copy-paste-adapt of the above
+void tst_QMetaObject::invokeMetaConstructorNoMacro()
+{
+ const QMetaObject *mo = &QtTestObject::staticMetaObject;
+ {
+ QObject *obj = mo->newInstance();
+ QVERIFY(!obj);
+ }
+ {
+ QtTestObject obj;
+ QObject *obj2 = mo->newInstance(static_cast<QObject *>(&obj));
+ QVERIFY(obj2 != 0);
+ QCOMPARE(obj2->parent(), (QObject*)&obj);
+ QVERIFY(qobject_cast<QtTestObject*>(obj2) != 0);
+ }
+ // class in namespace
+ const QMetaObject *nsmo = &NamespaceWithConstructibleClass::ConstructibleClass::staticMetaObject;
+ {
+ QtTestObject obj;
+ QObject *obj2 = nsmo->newInstance(static_cast<QObject *>(&obj));
+ QVERIFY(obj2 != 0);
+ QCOMPARE(obj2->parent(), (QObject*)&obj);
+ QVERIFY(qobject_cast<NamespaceWithConstructibleClass::ConstructibleClass*>(obj2) != 0);
+ }
+ // gadget shouldn't return a valid pointer
+ {
+ QCOMPARE(MyGadget::staticMetaObject.constructorCount(), 1);
+ QTest::ignoreMessage(QtWarningMsg, "QMetaObject::newInstance: type MyGadget does not inherit QObject");
+ QVERIFY(!MyGadget::staticMetaObject.newInstance());
+ }
}
void tst_QMetaObject::invokeTypedefTypes()
@@ -1262,11 +2062,17 @@ void tst_QMetaObject::invokeTypedefTypes()
QSignalSpy spy(&obj, &QtTestCustomObject::sig_custom);
QVERIFY(spy.isValid());
- QCOMPARE(spy.count(), 0);
+ QCOMPARE(spy.size(), 0);
CustomString arg("hello");
QVERIFY(QMetaObject::invokeMethod(&obj, "sig_custom", Q_ARG(CustomString, arg)));
- QCOMPARE(spy.count(), 1);
- QCOMPARE(spy.at(0).count(), 1);
+ QCOMPARE(spy.size(), 1);
+ QCOMPARE(spy.at(0).size(), 1);
+ QCOMPARE(spy.at(0).at(0), QVariant(arg));
+
+ spy.clear();
+ QVERIFY(QMetaObject::invokeMethod(&obj, "sig_custom", arg));
+ QCOMPARE(spy.size(), 1);
+ QCOMPARE(spy.at(0).size(), 1);
QCOMPARE(spy.at(0).at(0), QVariant(arg));
}
@@ -1282,6 +2088,14 @@ void tst_QMetaObject::invokeException()
QFAIL("Did not throw");
} catch(ObjectException &) {}
QCOMPARE(countedStructObjectsCount, 0);
+
+ try {
+ CountedStruct s;
+ QVERIFY(QMetaObject::invokeMethod(&obj, "throwingSlot", qReturnArg(s),
+ s, s));
+ QFAIL("Did not throw");
+ } catch(ObjectException &) {}
+ QCOMPARE(countedStructObjectsCount, 0);
#else
QSKIP("Needs exceptions");
#endif
@@ -1303,6 +2117,61 @@ void tst_QMetaObject::invokeQueuedAutoRegister()
qApp->processEvents(QEventLoop::AllEvents);
QCOMPARE(obj.slotResult,
QString("slotWithRegistrableArgument:myShared-myShared-myShared-myShared-00"));
+
+ obj.slotResult.clear();
+ QVERIFY(QMetaObject::invokeMethod(
+ &obj, "slotWithRegistrableArgument", Qt::QueuedConnection,
+ shared.data(), QPointer<QtTestObject>(shared.data()),
+ QSharedPointer<QtTestObject>(shared), QWeakPointer<QtTestObject>(shared),
+ QList<QtTestObject *>(),
+ QList<QtTestObject *>()));
+ QVERIFY(obj.slotResult.isEmpty());
+ qApp->processEvents(QEventLoop::AllEvents);
+ QCOMPARE(obj.slotResult,
+ QString("slotWithRegistrableArgument:myShared-myShared-myShared-myShared-00"));
+}
+
+namespace FunctionTest {
+ static void function0() {}
+ static int functionNoExcept() noexcept
+ {
+ return 42;
+ }
+}
+
+void tst_QMetaObject::invokeFreeFunction()
+{
+ using namespace FunctionTest;
+ QtTestObject obj;
+ QMetaObject::invokeMethod(&obj, function0);
+ int retInt = -1;
+ QMetaObject::invokeMethod(&obj, functionNoExcept, &retInt);
+ QCOMPARE(retInt, functionNoExcept());
+}
+
+void tst_QMetaObject::invokeBind()
+{
+ QtTestObject obj;
+
+ struct {
+ int number;
+ QString string;
+ } results;
+
+ const auto function = [&results](int number, const QString &string) -> bool {
+ results.number = number;
+ results.string = string;
+ return true;
+ };
+
+ const int number = 42;
+ const QString string("Test");
+ const auto binding = std::bind(function, number, string);
+ bool ret = false;
+ QMetaObject::invokeMethod(&obj, binding, &ret);
+ QVERIFY(ret);
+ QCOMPARE(results.number, number);
+ QCOMPARE(results.string, string);
}
void tst_QMetaObject::normalizedSignature_data()
@@ -1402,15 +2271,15 @@ void tst_QMetaObject::normalizedType_data()
QTest::newRow("QVector") << "QVector<int>" << "QList<int>";
QTest::newRow("refref") << "X const*const&&" << "const X*const&&";
QTest::newRow("refref2") << "const X<T const&&>&&" << "const X<const T&&>&&";
- QTest::newRow("long1") << "long unsigned int long" << "unsigned long long";
+ QTest::newRow("long1") << "long unsigned int long" << "qulonglong";
QTest::newRow("long2") << "int signed long" << "long";
QTest::newRow("long3") << "long unsigned" << "ulong";
QTest::newRow("long double") << " long double" << "long double";
QTest::newRow("signed char") << "char signed" << "signed char";
- QTest::newRow("unsigned char") << "char unsigned" << "unsigned char";
+ QTest::newRow("unsigned char") << "char unsigned" << "uchar";
QTest::newRow("signed short") << "short signed" << "short";
- QTest::newRow("unsigned shot") << "short unsigned" << "unsigned short";
- QTest::newRow("unsigned shot") << "short unsigned" << "unsigned short";
+ QTest::newRow("unsigned short") << "unsigned short" << "ushort";
+ QTest::newRow("short unsigned") << "short unsigned" << "ushort";
QTest::newRow("array1") << "unsigned int [4]" << "uint[4]";
QTest::newRow("array2") << "unsigned int const [4][5]" << "const uint[4][5]";
QTest::newRow("array3") << "unsigned[] const" << "uint[]";
@@ -1447,7 +2316,15 @@ void tst_QMetaObject::customPropertyType()
{
QMetaProperty prop = metaObject()->property(metaObject()->indexOfProperty("value3"));
+#if QT_DEPRECATED_SINCE(6, 0)
+ QT_WARNING_PUSH
+ QT_WARNING_DISABLE_DEPRECATED
+
QCOMPARE(prop.type(), QVariant::UserType);
+
+ QT_WARNING_POP
+#endif
+
QCOMPARE(prop.userType(), QMetaType::fromType<MyStruct>().id());
QCOMPARE(prop.metaType(), QMetaType::fromType<MyStruct>());
@@ -1455,14 +2332,14 @@ void tst_QMetaObject::customPropertyType()
QCOMPARE(prop.userType(), QMetaType::fromName("MyStruct").id());
prop = metaObject()->property(metaObject()->indexOfProperty("value4"));
- QCOMPARE(prop.type(), QVariant::List);
+ QCOMPARE(prop.metaType().id(), QMetaType::QVariantList);
QCOMPARE(prop.metaType(), QMetaType::fromType<QList<QVariant>>());
prop = metaObject()->property(metaObject()->indexOfProperty("value5"));
- QCOMPARE(prop.type(), QVariant::List);
+ QCOMPARE(prop.metaType().id(), QMetaType::QVariantList);
}
-void tst_QMetaObject::checkScope_data()
+void tst_QMetaObject::keysToValue_data()
{
QTest::addColumn<QObject *>("object");
QTest::addColumn<QByteArray>("name");
@@ -1476,7 +2353,7 @@ void tst_QMetaObject::checkScope_data()
}
-void tst_QMetaObject::checkScope()
+void tst_QMetaObject::keysToValue()
{
QFETCH(QObject *, object);
QFETCH(QByteArray, name);
@@ -1489,6 +2366,8 @@ void tst_QMetaObject::checkScope()
QVERIFY(!me.isFlag());
QCOMPARE(QByteArray(me.scope()), QByteArray("MyNamespace::" + name));
QCOMPARE(me.keyToValue("MyNamespace::" + name + "::MyEnum2", &ok), 1);
+ // Fully qualified unscoped enumerator
+ QCOMPARE(me.keyToValue("MyNamespace::" + name + "::MyEnum::MyEnum2", &ok), 1);
QCOMPARE(ok, true);
QCOMPARE(me.keyToValue(name + "::MyEnum2", &ok), -1);
QCOMPARE(ok, false);
@@ -1518,6 +2397,9 @@ void tst_QMetaObject::checkScope()
QCOMPARE(QByteArray(mf.scope()), QByteArray("MyNamespace::" + name));
QCOMPARE(mf.keysToValue("MyNamespace::" + name + "::MyFlag2", &ok), 2);
QCOMPARE(ok, true);
+ // Fully qualified
+ QCOMPARE(mf.keysToValue("MyNamespace::" + name + "::MyFlag::MyFlag2", &ok), 2);
+ QCOMPARE(ok, true);
QCOMPARE(mf.keysToValue(name + "::MyFlag2", &ok), -1);
QCOMPARE(ok, false);
QCOMPARE(mf.keysToValue("MyNamespace::MyFlag2", &ok), -1);
@@ -1527,7 +2409,12 @@ void tst_QMetaObject::checkScope()
QCOMPARE(mf.keysToValue("MyFlag", &ok), -1);
QCOMPARE(ok, false);
QCOMPARE(QLatin1String(mf.valueToKey(2)), QLatin1String("MyFlag2"));
- QCOMPARE(mf.keysToValue("MyNamespace::" + name + "::MyFlag1|MyNamespace::" + name + "::MyFlag2", &ok), 3);
+
+ const QByteArray prefix = "MyNamespace::" + name;
+ QCOMPARE(mf.keysToValue(prefix + "::MyFlag1|" + prefix + "::MyFlag2", &ok), 3);
+ QCOMPARE(ok, true);
+ // Fully qualified
+ QCOMPARE(mf.keysToValue(prefix + "::MyFlag::MyFlag1|" + prefix + "::MyFlag::MyFlag2", &ok), 3);
QCOMPARE(ok, true);
QCOMPARE(mf.keysToValue(name + "::MyFlag1|" + name + "::MyFlag2", &ok), -1);
QCOMPARE(ok, false);
@@ -1539,9 +2426,34 @@ void tst_QMetaObject::checkScope()
QCOMPARE(ok, true);
QCOMPARE(mf.keysToValue("MyFlag1|MyNamespace::" + name + "::MyFlag2", &ok), 3);
QCOMPARE(ok, true);
- QCOMPARE(mf.keysToValue("MyNamespace::" + name + "::MyFlag2|MyNamespace::" + name + "::MyFlag2", &ok), 2);
+ QCOMPARE(mf.keysToValue(prefix + "::MyFlag2|" + prefix + "::MyFlag2", &ok), 2);
+ QCOMPARE(ok, true);
+ // Fully qualified
+ QCOMPARE(mf.keysToValue(prefix + "::MyFlag::MyFlag2|" + prefix + "::MyFlag::MyFlag2", &ok), 2);
QCOMPARE(ok, true);
QCOMPARE(QLatin1String(mf.valueToKeys(3)), QLatin1String("MyFlag1|MyFlag2"));
+
+ // Test flags with extra '|'
+ QTest::ignoreMessage(QtWarningMsg,
+ QRegularExpression(u"QMetaEnum::keysToValue: malformed keys string, ends with '|'.+"_s));
+ QCOMPARE(mf.keysToValue("MyFlag1|MyFlag2|", &ok), -1);
+ QCOMPARE(ok, false);
+
+ QTest::ignoreMessage(QtWarningMsg,
+ QRegularExpression(u"QMetaEnum::keysToValue: malformed keys string, starts with '|'.+"_s));
+ QCOMPARE(mf.keysToValue("|MyFlag1|MyFlag2|", &ok), -1);
+ QCOMPARE(ok, false);
+
+ QTest::ignoreMessage(QtWarningMsg,
+ QRegularExpression(
+ u"QMetaEnum::keysToValue: malformed keys string, has two consecutive '|'.+"_s));
+ QCOMPARE(mf.keysToValue("MyFlag1||MyFlag2", &ok), -1);
+ QCOMPARE(ok, false);
+
+ // Test empty string
+ QTest::ignoreMessage(QtWarningMsg, "QMetaEnum::keysToValue: empty keys string.");
+ QCOMPARE(mf.keysToValue("", &ok), -1);
+ QCOMPARE(ok, false);
}
void tst_QMetaObject::propertyNotify()
@@ -1599,6 +2511,15 @@ void tst_QMetaObject::propertyFinal()
QVERIFY(!prop.isFinal());
}
+void tst_QMetaObject::metaType()
+{
+ QCOMPARE(QObject::staticMetaObject.metaType(), QMetaType::fromType<QObject>());
+ QCOMPARE(MyGadget::staticMetaObject.metaType(), QMetaType::fromType<MyGadget>());
+ QCOMPARE(QAbstractProxyModel::staticMetaObject.metaType(), QMetaType::fromType<QAbstractProxyModel>());
+ auto qtNameSpaceMetaType = Qt::staticMetaObject.metaType();
+ QVERIFY2(!qtNameSpaceMetaType.isValid(), qtNameSpaceMetaType.name());
+}
+
class ClassInfoTestObjectA : public QObject
{
Q_OBJECT
@@ -1619,6 +2540,7 @@ void tst_QMetaObject::classInfo()
QCOMPARE(QLatin1String(b.metaObject()->classInfo(index).value()), QLatin1String("Christopher Pike"));
}
+// this test is duplicated below
void tst_QMetaObject::metaMethod()
{
QString str("foo");
@@ -1638,9 +2560,13 @@ void tst_QMetaObject::metaMethod()
QVERIFY(index > 0);
method = QtTestObject::staticMetaObject.method(index);
//wrong args
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: too few arguments (5) in call to QtTestObject::sl5(QString,QString,QString,QString,QString)");
QVERIFY(!method.invoke(&obj, Q_ARG(QString, "1"), Q_ARG(QString, "2"), Q_ARG(QString, "3"), Q_ARG(QString, "4")));
//QVERIFY(!method.invoke(&obj, Q_ARG(QString, "1"), Q_ARG(QString, "2"), Q_ARG(QString, "3"), Q_ARG(QString, "4"), Q_ARG(QString, "5"), Q_ARG(QString, "6")));
//QVERIFY(!method.invoke(&obj, Q_ARG(QString, "1"), Q_ARG(QString, "2"), Q_ARG(QString, "3"), Q_ARG(QString, "4"), Q_ARG(int, 5)));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invokeMethod: return type mismatch for method "
+ "QtTestObject::sl5(QString,QString,QString,QString,QString): "
+ "cannot convert from void to QString during invocation");
QVERIFY(!method.invoke(&obj, Q_RETURN_ARG(QString, ret), Q_ARG(QString, "1"), Q_ARG(QString, "2"), Q_ARG(QString, "3"), Q_ARG(QString, "4"), Q_ARG(QString, "5")));
//wrong object
@@ -1667,6 +2593,59 @@ void tst_QMetaObject::metaMethod()
QCOMPARE(obj.slotResult, QString("sl13"));
}
+// this is a copy-paste-adapt of the above
+void tst_QMetaObject::metaMethodNoMacro()
+{
+ QString str("foo");
+ QString ret("bar");
+ QMetaMethod method;
+ QVERIFY(!method.invoke(this));
+ QVERIFY(!method.invoke(this, str));
+ QVERIFY(!method.invoke(this, qReturnArg(ret), str));
+ QCOMPARE(str, QString("foo"));
+ QCOMPARE(ret, QString("bar"));
+
+ QtTestObject obj;
+ QString t1("1"); QString t2("2"); QString t3("3"); QString t4("4"); QString t5("5");
+ QString t6("6"); QString t7("7"); QString t8("8"); QString t9("9"); QString t10("X");
+
+ int index = QtTestObject::staticMetaObject.indexOfMethod("sl5(QString,QString,QString,QString,QString)");
+ QVERIFY(index > 0);
+ method = QtTestObject::staticMetaObject.method(index);
+ //wrong args
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invoke: too few arguments (5) in call to QtTestObject::sl5(QString,QString,QString,QString,QString)");
+ QVERIFY(!method.invoke(&obj, QStringLiteral("1"), QStringLiteral("2"), QStringLiteral("3"), QStringLiteral("4")));
+ //QVERIFY(!method.invoke(&obj, "1", "2", "3", "4", "5", "6"));
+ //QVERIFY(!method.invoke(&obj, "1", "2", "3", "4", 5));
+ QTest::ignoreMessage(QtWarningMsg, "QMetaMethod::invokeMethod: return type mismatch for method "
+ "QtTestObject::sl5(QString,QString,QString,QString,QString): "
+ "cannot convert from void to QString during invocation");
+ QVERIFY(!method.invoke(&obj, qReturnArg(ret), QStringLiteral("1"), QStringLiteral("2"), QStringLiteral("3"), QStringLiteral("4"), QStringLiteral("5")));
+
+ //wrong object
+ //QVERIFY(!method.invoke(this, "1", "2", "3", "4", "5"));
+ QVERIFY(!method.invoke(0, QStringLiteral("1"), QStringLiteral("2"), QStringLiteral("3"), QStringLiteral("4"), QStringLiteral("5")));
+ QCOMPARE(ret, QString("bar"));
+ QCOMPARE(obj.slotResult, QString());
+
+ QVERIFY(method.invoke(&obj, QStringLiteral("1"), QStringLiteral("2"), QStringLiteral("3"), QStringLiteral("4"), QStringLiteral("5")));
+ QCOMPARE(obj.slotResult, QString("sl5:12345"));
+
+ index = QtTestObject::staticMetaObject.indexOfMethod("sl13(QList<QString>)");
+ QVERIFY(index > 0);
+ QMetaMethod sl13 = QtTestObject::staticMetaObject.method(index);
+ QList<QString> returnValue, argument;
+ argument << QString("one") << QString("two") << QString("three");
+ //wrong object
+ //QVERIFY(!sl13.invoke(this, qReturnArg(returnValue), argument));
+ QVERIFY(!sl13.invoke(0, qReturnArg(returnValue), argument));
+ QVERIFY(returnValue.isEmpty());
+
+ QVERIFY(sl13.invoke(&obj, qReturnArg(returnValue), argument));
+ QCOMPARE(returnValue, argument);
+ QCOMPARE(obj.slotResult, QString("sl13"));
+}
+
void tst_QMetaObject::indexOfMethod_data()
{
QTest::addColumn<QObject *>("object");
@@ -1692,6 +2671,42 @@ void tst_QMetaObject::indexOfMethod()
QCOMPARE(object->metaObject()->indexOfSignal(name), !isSignal ? -1 : idx);
}
+class Base : public QObject {
+ Q_OBJECT
+public slots:
+ int test() {return 0;}
+ int baseOnly() {return 0;}
+};
+
+class Derived : public Base {
+ Q_OBJECT
+
+public slots:
+ int test() {return 1;}
+};
+
+void tst_QMetaObject::firstMethod_data()
+{
+ QTest::addColumn<QByteArray>("name");
+ QTest::addColumn<QMetaMethod>("method");
+
+ const QMetaObject &derived = Derived::staticMetaObject;
+ const QMetaObject &base = Base::staticMetaObject;
+
+ QTest::newRow("own method") << QByteArray("test") << derived.method(derived.indexOfMethod("test()"));
+ QTest::newRow("parent method") << QByteArray("baseOnly") << derived.method(base.indexOfMethod("baseOnly()"));
+ QTest::newRow("invalid") << QByteArray("invalid") << QMetaMethod();
+}
+
+void tst_QMetaObject::firstMethod()
+{
+ QFETCH(QByteArray, name);
+ QFETCH(QMetaMethod, method);
+
+ QMetaMethod firstMethod = QMetaObjectPrivate::firstMethod(&Derived::staticMetaObject, name);
+ QCOMPARE(firstMethod, method);
+}
+
void tst_QMetaObject::indexOfMethodPMF()
{
#define INDEXOFMETHODPMF_HELPER(ObjectType, Name, Arguments) { \
diff --git a/tests/auto/corelib/kernel/qmetaobjectbuilder/CMakeLists.txt b/tests/auto/corelib/kernel/qmetaobjectbuilder/CMakeLists.txt
index bae83c137f..8551749db3 100644
--- a/tests/auto/corelib/kernel/qmetaobjectbuilder/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qmetaobjectbuilder/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qmetaobjectbuilder.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qmetaobjectbuilder Test:
#####################################################################
-qt_add_test(tst_qmetaobjectbuilder
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qmetaobjectbuilder LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qmetaobjectbuilder
SOURCES
tst_qmetaobjectbuilder.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
)
diff --git a/tests/auto/corelib/kernel/qmetaobjectbuilder/qmetaobjectbuilder.pro b/tests/auto/corelib/kernel/qmetaobjectbuilder/qmetaobjectbuilder.pro
deleted file mode 100644
index 4da90c1096..0000000000
--- a/tests/auto/corelib/kernel/qmetaobjectbuilder/qmetaobjectbuilder.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qmetaobjectbuilder
-QT = core-private testlib
-SOURCES = tst_qmetaobjectbuilder.cpp
diff --git a/tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp b/tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp
index 333c7931d9..18e4e2a4a9 100644
--- a/tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp
+++ b/tests/auto/corelib/kernel/qmetaobjectbuilder/tst_qmetaobjectbuilder.cpp
@@ -1,32 +1,8 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
+#include <QSignalSpy>
#include <QtCore/qlocale.h>
#include <private/qmetaobjectbuilder_p.h>
@@ -50,8 +26,6 @@ private slots:
void relatedMetaObject();
void staticMetacall();
void copyMetaObject();
- void serialize();
- void relocatableData();
void removeNotifySignal();
void usage_signal();
@@ -64,13 +38,28 @@ private slots:
void classNameFirstInStringData();
+ void propertyMetaType();
+
+ void cleanupTestCase();
+
+ void ownMetaTypeNoProperties();
+
private:
static bool checkForSideEffects
(const QMetaObjectBuilder& builder,
QMetaObjectBuilder::AddMembers members);
- static bool sameMetaObject
- (const QMetaObject *meta1, const QMetaObject *meta2);
+ QList<QMetaObject *> dynamicMetaObjectsPendingFree;
+};
+
+struct MetaObjectComparison {
+ bool isSame = false;
+ QString details;
+ operator bool() {return isSame;}
+
+ static inline auto Ok() {return MetaObjectComparison{true, QString()}; }
+ static inline auto Failed(QStringView message) {return MetaObjectComparison{false, message.toString()}; }
};
+MetaObjectComparison sameMetaObject(const QMetaObject *meta1, const QMetaObject *meta2);
// Dummy class that has something of every type of thing moc can generate.
class SomethingOfEverything : public QObject
@@ -85,7 +74,7 @@ class SomethingOfEverything : public QObject
Q_PROPERTY(SomethingFlagEnum fprop READ fprop)
Q_PROPERTY(QLocale::Language language READ language)
Q_ENUMS(SomethingEnum)
- Q_FLAGS(SomethingFlagEnum)
+ Q_FLAGS(SomethingFlag)
public:
Q_INVOKABLE SomethingOfEverything() {}
~SomethingOfEverything() {}
@@ -101,6 +90,7 @@ public:
XYZ = 1,
UVW = 8
};
+ Q_DECLARE_FLAGS(SomethingFlag, SomethingFlagEnum)
Q_INVOKABLE Q_SCRIPTABLE void method1() {}
@@ -193,8 +183,8 @@ void tst_QMetaObjectBuilder::flags()
QCOMPARE(builder.flags(), 0);
// Set flags
- builder.setFlags(QMetaObjectBuilder::DynamicMetaObject);
- QCOMPARE(builder.flags(), QMetaObjectBuilder::DynamicMetaObject);
+ builder.setFlags(DynamicMetaObject);
+ QCOMPARE(builder.flags(), DynamicMetaObject);
}
void tst_QMetaObjectBuilder::method()
@@ -747,13 +737,12 @@ void tst_QMetaObjectBuilder::variantProperty()
QMetaObjectBuilder builder;
builder.addProperty("variant", "const QVariant &");
QMetaObject *meta = builder.toMetaObject();
+ dynamicMetaObjectsPendingFree.push_back(meta);
QMetaProperty prop = meta->property(meta->propertyOffset());
- QCOMPARE(QMetaType::Type(prop.type()), QMetaType::QVariant);
+ QCOMPARE(QMetaType::Type(prop.userType()), QMetaType::QVariant);
QCOMPARE(QMetaType::Type(prop.userType()), QMetaType::QVariant);
QCOMPARE(QByteArray(prop.typeName()), QByteArray("QVariant"));
-
- free(meta);
}
void tst_QMetaObjectBuilder::notifySignal()
@@ -790,6 +779,26 @@ void tst_QMetaObjectBuilder::notifySignal()
void tst_QMetaObjectBuilder::enumerator()
{
+ static const QtPrivate::QMetaTypeInterface fooFlagMetaType = {
+ 0,
+ 8,
+ 8,
+ QMetaType::IsEnumeration | QMetaType::IsUnsignedEnumeration | QMetaType::RelocatableType,
+ {},
+ nullptr,
+ "fooFlag",
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ };
+
QMetaObjectBuilder builder;
// Add an enumerator and check its attributes.
@@ -821,6 +830,7 @@ void tst_QMetaObjectBuilder::enumerator()
enum1.setIsFlag(true);
enum1.setIsScoped(true);
enum1.setEnumName(QByteArrayLiteral("fooFlag"));
+ enum1.setMetaType(QMetaType(&fooFlagMetaType));
QCOMPARE(enum1.addKey("ABC", 0), 0);
QCOMPARE(enum1.addKey("DEF", 1), 1);
QCOMPARE(enum1.addKey("GHI", -1), 2);
@@ -830,6 +840,7 @@ void tst_QMetaObjectBuilder::enumerator()
QVERIFY(enum1.isFlag());
QVERIFY(enum1.isScoped());
QCOMPARE(enum1.enumName(), QByteArray("fooFlag"));
+ QCOMPARE(enum1.metaType(), QMetaType(&fooFlagMetaType));
QCOMPARE(enum1.keyCount(), 3);
QCOMPARE(enum1.index(), 0);
QCOMPARE(enum1.key(0), QByteArray("ABC"));
@@ -997,106 +1008,23 @@ void tst_QMetaObjectBuilder::copyMetaObject()
{
QMetaObjectBuilder builder(&QObject::staticMetaObject);
QMetaObject *meta = builder.toMetaObject();
- QVERIFY(sameMetaObject(meta, &QObject::staticMetaObject));
- free(meta);
+ dynamicMetaObjectsPendingFree.push_back(meta);
+ auto compared = sameMetaObject(meta, &QObject::staticMetaObject);
+ QVERIFY2(compared, qPrintable(compared.details));
QMetaObjectBuilder builder2(&staticMetaObject);
meta = builder2.toMetaObject();
- QVERIFY(sameMetaObject(meta, &staticMetaObject));
- free(meta);
+ dynamicMetaObjectsPendingFree.push_back(meta);
+ compared = sameMetaObject(meta, &staticMetaObject);
+ QVERIFY2(compared, qPrintable(compared.details));
QMetaObjectBuilder builder3(&SomethingOfEverything::staticMetaObject);
meta = builder3.toMetaObject();
- QVERIFY(sameMetaObject(meta, &SomethingOfEverything::staticMetaObject));
- free(meta);
-}
-
-// Serialize and deserialize a meta object and check that
-// it round-trips to the exact same value.
-void tst_QMetaObjectBuilder::serialize()
-{
- // Full QMetaObjectBuilder
- {
- QMetaObjectBuilder builder(&SomethingOfEverything::staticMetaObject);
- QMetaObject *meta = builder.toMetaObject();
-
- QByteArray data;
- QDataStream stream(&data, QIODevice::WriteOnly | QIODevice::Append);
- builder.serialize(stream);
-
- QMetaObjectBuilder builder2;
- QDataStream stream2(data);
- QMap<QByteArray, const QMetaObject *> references;
- references.insert(QByteArray("QLocale"), &QLocale::staticMetaObject);
- builder2.deserialize(stream2, references);
- builder2.setStaticMetacallFunction(builder.staticMetacallFunction());
- QMetaObject *meta2 = builder2.toMetaObject();
-
- QVERIFY(sameMetaObject(meta, meta2));
- free(meta);
- free(meta2);
- }
-
- // Partial QMetaObjectBuilder
- {
- QMetaObjectBuilder builder;
- builder.setClassName("Test");
- builder.addProperty("foo", "int");
-
- QByteArray data;
- QDataStream stream(&data, QIODevice::WriteOnly | QIODevice::Append);
- builder.serialize(stream);
-
- QMetaObjectBuilder builder2;
- QDataStream stream2(data);
- builder2.deserialize(stream2, QMap<QByteArray, const QMetaObject *>());
-
- QCOMPARE(builder.superClass(), builder2.superClass());
- QCOMPARE(builder.className(), builder2.className());
- QCOMPARE(builder.propertyCount(), builder2.propertyCount());
- QCOMPARE(builder.property(0).name(), builder2.property(0).name());
- QCOMPARE(builder.property(0).type(), builder2.property(0).type());
- }
-}
-
-void tst_QMetaObjectBuilder::relocatableData()
-{
- QMetaObjectBuilder builder;
- builder.setClassName("TestObject");
-
- QMetaMethodBuilder intPropChanged = builder.addSignal("intPropChanged(int)");
- intPropChanged.setParameterNames(QList<QByteArray>() << "newIntPropValue");
-
- QMetaPropertyBuilder prop = builder.addProperty("intProp", "int");
- prop.setNotifySignal(intPropChanged);
-
- QMetaMethodBuilder voidSlotInt = builder.addSlot("voidSlotInt(int)");
- voidSlotInt.setParameterNames(QList<QByteArray>() << "slotIntArg");
-
- QMetaMethodBuilder listInvokableQRealQString = builder.addMethod("listInvokableQRealQString(qreal,QString)");
- listInvokableQRealQString.setReturnType("QVariantList");
- listInvokableQRealQString.setParameterNames(QList<QByteArray>() << "qrealArg" << "qstringArg");
-
- bool ok = false;
- QByteArray data = builder.toRelocatableData(&ok);
- QVERIFY(ok);
-
- QMetaObjectBuilder builder2;
- QMetaObject meta2;
- builder2.fromRelocatableData(&meta2, &QObject::staticMetaObject, data);
-
- QMetaObject *meta = builder.toMetaObject();
-
- QVERIFY(sameMetaObject(meta, &meta2));
-
- QVERIFY(!meta2.d.extradata);
- QVERIFY(!meta2.d.relatedMetaObjects);
- QVERIFY(!meta2.d.static_metacall);
-
- free(meta);
+ dynamicMetaObjectsPendingFree.push_back(meta);
+ compared = sameMetaObject(meta, &SomethingOfEverything::staticMetaObject);
+ QVERIFY2(compared, qPrintable(compared.details));
}
-
// Check that removing a method updates notify signals appropriately
void tst_QMetaObjectBuilder::removeNotifySignal()
{
@@ -1207,13 +1135,13 @@ static bool sameMethod(const QMetaMethod& method1, const QMetaMethod& method2)
return true;
}
-static bool sameProperty(const QMetaProperty& prop1, const QMetaProperty& prop2)
+static MetaObjectComparison sameProperty(const QMetaProperty& prop1, const QMetaProperty& prop2)
{
if (QByteArray(prop1.name()) != QByteArray(prop2.name()))
- return false;
+ return MetaObjectComparison::Failed(QStringLiteral("Property names differ: %1 vs %2").arg(prop1.name(), prop2.name()));
if (QByteArray(prop1.typeName()) != QByteArray(prop2.typeName()))
- return false;
+ return MetaObjectComparison::Failed(QStringLiteral("Property type names differ: %1 vs %2").arg(prop1.typeName(), prop2.typeName()));
if (prop1.isReadable() != prop2.isReadable() ||
prop1.isWritable() != prop2.isWritable() ||
@@ -1226,17 +1154,21 @@ static bool sameProperty(const QMetaProperty& prop1, const QMetaProperty& prop2)
prop1.isEnumType() != prop2.isEnumType() ||
prop1.hasNotifySignal() != prop2.hasNotifySignal() ||
prop1.hasStdCppSet() != prop2.hasStdCppSet())
- return false;
+ return MetaObjectComparison::Failed(u"Flags differ");
if (prop1.hasNotifySignal()) {
if (prop1.notifySignalIndex() != prop2.notifySignalIndex())
- return false;
+ return MetaObjectComparison::Failed(QStringLiteral("Notify signal index differ: %1 vs %2").arg(
+ QString::number(prop1.notifySignalIndex()),
+ QString::number(prop2.notifySignalIndex())));
}
- if (prop1.revision() != prop2.revision())
- return false;
+ const int revision1 = prop1.revision();
+ const int revision2 = prop2.revision();
+ if (revision1 != revision2)
+ return MetaObjectComparison::Failed(QStringLiteral("Revisions differ: %1 vs %2").arg(QString::number(revision1), QString::number(revision2)));
- return true;
+ return MetaObjectComparison::Ok();
}
static bool sameEnumerator(const QMetaEnum& enum1, const QMetaEnum& enum2)
@@ -1264,69 +1196,89 @@ static bool sameEnumerator(const QMetaEnum& enum1, const QMetaEnum& enum2)
}
// Determine if two meta objects are identical.
-bool tst_QMetaObjectBuilder::sameMetaObject
- (const QMetaObject *meta1, const QMetaObject *meta2)
+MetaObjectComparison sameMetaObject(const QMetaObject *meta1, const QMetaObject *meta2)
{
int index;
- if (strcmp(meta1->className(), meta2->className()) != 0)
- return false;
+ if (strcmp(meta1->className(), meta2->className()) != 0) {
+ QString message = QLatin1String("Class names differ: %1 %2").arg(meta1->className(), meta2->className());
+ return MetaObjectComparison::Failed(message);
+ }
if (meta1->superClass() != meta2->superClass())
- return false;
+ return MetaObjectComparison::Failed(QStringLiteral("Super classes differ"));
- if (meta1->constructorCount() != meta2->constructorCount() ||
- meta1->methodCount() != meta2->methodCount() ||
- meta1->enumeratorCount() != meta2->enumeratorCount() ||
- meta1->propertyCount() != meta2->propertyCount() ||
- meta1->classInfoCount() != meta2->classInfoCount())
- return false;
+ auto numCompare = [](int num1, int num2, const QString &message) {
+ if (num1 != num2)
+ return MetaObjectComparison::Failed(message.arg(QString::number(num1), QString::number(num2)));
+ return MetaObjectComparison::Ok();
+ };
+
+ auto compared = numCompare(meta1->constructorCount(), meta2->constructorCount(), QStringLiteral("Construct counts differ: %1 %2"));
+ if (!compared.isSame)
+ return compared;
+ compared = numCompare(meta1->methodCount(), meta2->methodCount(), QStringLiteral("Method counts differ: %1 %2"));
+ if (!compared.isSame)
+ return compared;
+ compared = numCompare(meta1->enumeratorCount(), meta2->enumeratorCount(), QStringLiteral("Enumerator counts differ: %1 %2"));
+ if (!compared.isSame)
+ return compared;
+ compared = numCompare(meta1->propertyCount(), meta2->propertyCount(), QStringLiteral("Property counts differ: %1 %2"));
+ if (!compared.isSame)
+ return compared;
+ compared = numCompare(meta1->classInfoCount(), meta2->classInfoCount(), QStringLiteral("ClassInfo counts differ: %1 %2"));
+ if (!compared.isSame)
+ return compared;
for (index = 0; index < meta1->constructorCount(); ++index) {
if (!sameMethod(meta1->constructor(index), meta2->constructor(index)))
- return false;
+ return MetaObjectComparison::Failed(QStringLiteral("Constructors difer at index %1").arg(index));
}
for (index = 0; index < meta1->methodCount(); ++index) {
if (!sameMethod(meta1->method(index), meta2->method(index)))
- return false;
+ return MetaObjectComparison::Failed(QStringLiteral("Methods difer at index %1").arg(index));
}
for (index = 0; index < meta1->propertyCount(); ++index) {
- if (!sameProperty(meta1->property(index), meta2->property(index)))
- return false;
+ if (auto compared = sameProperty(meta1->property(index), meta2->property(index)); !compared) {
+ compared.details += QStringLiteral(" at index %1").arg(index);
+ return compared;
+ }
}
for (index = 0; index < meta1->enumeratorCount(); ++index) {
if (!sameEnumerator(meta1->enumerator(index), meta2->enumerator(index)))
- return false;
+ return MetaObjectComparison::Failed(QStringLiteral("Enumerators difer at index %1").arg(index));
}
for (index = 0; index < meta1->classInfoCount(); ++index) {
- if (QByteArray(meta1->classInfo(index).name()) !=
- QByteArray(meta2->classInfo(index).name()))
- return false;
- if (QByteArray(meta1->classInfo(index).value()) !=
- QByteArray(meta2->classInfo(index).value()))
- return false;
+ const auto name1= QByteArray(meta1->classInfo(index).name());
+ const auto name2= QByteArray(meta1->classInfo(index).name());
+ if (name1 != name2)
+ return MetaObjectComparison::Failed(QStringLiteral("Class infos difer at index %1: %2 vs %3").arg(QString::number(index), name1, name2));
+ const auto value1 = QByteArray(meta1->classInfo(index).value());
+ const auto value2= QByteArray(meta2->classInfo(index).value());
+ if ( value1 != value2)
+ return MetaObjectComparison::Failed(QStringLiteral("Class infos difer at index %1: %2 vs %3").arg(QString::number(index), value1, value2));
}
const auto *objects1 = meta1->d.relatedMetaObjects;
const auto *objects2 = meta2->d.relatedMetaObjects;
if (objects1 && !objects2)
- return false;
+ return MetaObjectComparison::Failed(u"Metaobject 1 had related metaobjects, but Metaoject 2 did not");
if (objects2 && !objects1)
- return false;
+ return MetaObjectComparison::Failed(u"Metaobject 2 had related metaobjects, but Metaoject 1 did not");
if (objects1 && objects2) {
while (*objects1 != 0 && *objects2 != 0) {
if (*objects1 != *objects2)
- return false;
+ return MetaObjectComparison::Failed(QStringLiteral("Related metaobjects differ at index %1").arg(index));
++objects1;
++objects2;
}
}
- return true;
+ return MetaObjectComparison::Ok();
}
@@ -1350,7 +1302,7 @@ private:
//Q_PROPERTY(int intProp READ intProp WRITE setIntProp NOTIFY intPropChanged)
public:
- TestObject(QObject *parent = 0); // Q_INVOKABLE
+ TestObject(QObject *parent = nullptr); // Q_INVOKABLE
~TestObject();
// Property accessors
@@ -1529,9 +1481,7 @@ int TestObject::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
if (_id < ownMethodCount)
qt_static_metacall(this, _c, _id, _a);
_id -= ownMethodCount;
- }
-#ifndef QT_NO_PROPERTIES
- else if (_c == QMetaObject::ReadProperty) {
+ } else if (_c == QMetaObject::ReadProperty) {
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< int*>(_v) = intProp(); break;
@@ -1554,7 +1504,6 @@ int TestObject::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
} else if (_c == QMetaObject::ResetProperty) {
_id -= ownPropertyCount;
}
-#endif // QT_NO_PROPERTIES
return _id;
}
@@ -1572,8 +1521,8 @@ void tst_QMetaObjectBuilder::usage_signal()
QSignalSpy propChangedSpy(testObject.data(), &TestObject::intPropChanged);
testObject->emitIntPropChanged();
- QCOMPARE(propChangedSpy.count(), 1);
- QCOMPARE(propChangedSpy.at(0).count(), 1);
+ QCOMPARE(propChangedSpy.size(), 1);
+ QCOMPARE(propChangedSpy.at(0).size(), 1);
QCOMPARE(propChangedSpy.at(0).at(0).toInt(), testObject->intProp());
}
@@ -1582,15 +1531,15 @@ void tst_QMetaObjectBuilder::usage_property()
QScopedPointer<TestObject> testObject(new TestObject);
QVariant prop = testObject->property("intProp");
- QCOMPARE(prop.type(), QVariant::Int);
+ QCOMPARE(prop.metaType(), QMetaType(QMetaType::Int));
QCOMPARE(prop.toInt(), testObject->intProp());
QSignalSpy propChangedSpy(testObject.data(), &TestObject::intPropChanged);
QVERIFY(testObject->intProp() != 123);
testObject->setProperty("intProp", 123);
- QCOMPARE(propChangedSpy.count(), 1);
+ QCOMPARE(propChangedSpy.size(), 1);
prop = testObject->property("intProp");
- QCOMPARE(prop.type(), QVariant::Int);
+ QCOMPARE(prop.metaType(), QMetaType(QMetaType::Int));
QCOMPARE(prop.toInt(), 123);
}
@@ -1618,9 +1567,9 @@ void tst_QMetaObjectBuilder::usage_method()
QVERIFY(listInvokableQRealQString.invoke(testObject.data(), Q_RETURN_ARG(QVariantList, list),
Q_ARG(qreal, 123.0), Q_ARG(QString, "ciao")));
QCOMPARE(list.size(), 2);
- QCOMPARE(list.at(0).type(), QVariant::Type(QMetaType::QReal));
+ QCOMPARE(list.at(0).metaType(), QMetaType(QMetaType::QReal));
QCOMPARE(list.at(0).toDouble(), double(123));
- QCOMPARE(list.at(1).type(), QVariant::String);
+ QCOMPARE(list.at(1).metaType(), QMetaType(QMetaType::QString));
QCOMPARE(list.at(1).toString(), QString::fromLatin1("ciao"));
}
@@ -1688,6 +1637,42 @@ void tst_QMetaObjectBuilder::classNameFirstInStringData()
free(mo);
}
+struct MyFoo {};
+struct myParameter {};
+
+void tst_QMetaObjectBuilder::propertyMetaType()
+{
+ qRegisterMetaType<myParameter>();
+ QMetaType meta = QMetaType::fromType<MyFoo>();
+ auto metaId = meta.id();
+ QMetaObjectBuilder builder;
+ builder.setClassName("Test");
+ builder.addProperty("myParameter", "MyFoo");
+ auto mo = builder.toMetaObject();
+
+ QMetaProperty metaProp = mo->property(mo->indexOfProperty("myParameter"));
+ QCOMPARE(metaProp.typeName(), meta.name());
+ QCOMPARE(metaProp.typeId(), metaId);
+ QCOMPARE(metaProp.metaType(), meta);
+ free(mo);
+}
+
+void tst_QMetaObjectBuilder::ownMetaTypeNoProperties()
+{
+ QMetaObjectBuilder builder;
+ builder.setClassName("NoProperties");
+ auto mo = builder.toMetaObject();
+ auto cleanup = qScopeGuard([&](){ free(mo); });
+ // own metatype should be invalid, as the dynamic metaobject has not been registered
+ QVERIFY(!mo->metaType().isValid());// should not crash
+}
+
+void tst_QMetaObjectBuilder::cleanupTestCase()
+{
+ for (QMetaObject *obj: dynamicMetaObjectsPendingFree)
+ free(obj);
+}
+
QTEST_MAIN(tst_QMetaObjectBuilder)
#include "tst_qmetaobjectbuilder.moc"
diff --git a/tests/auto/corelib/kernel/qmetaproperty/CMakeLists.txt b/tests/auto/corelib/kernel/qmetaproperty/CMakeLists.txt
index 0c9c0a810c..49c07afd87 100644
--- a/tests/auto/corelib/kernel/qmetaproperty/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qmetaproperty/CMakeLists.txt
@@ -1,10 +1,17 @@
-# Generated from qmetaproperty.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qmetaproperty Test:
#####################################################################
-qt_add_test(tst_qmetaproperty
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qmetaproperty LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qmetaproperty
SOURCES
tst_qmetaproperty.cpp
)
diff --git a/tests/auto/corelib/kernel/qmetaproperty/qmetaproperty.pro b/tests/auto/corelib/kernel/qmetaproperty/qmetaproperty.pro
deleted file mode 100644
index 1f338a909b..0000000000
--- a/tests/auto/corelib/kernel/qmetaproperty/qmetaproperty.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qmetaproperty
-QT = core testlib
-SOURCES = tst_qmetaproperty.cpp
diff --git a/tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp b/tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp
index 06bca28001..c8053ca43a 100644
--- a/tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp
+++ b/tests/auto/corelib/kernel/qmetaproperty/tst_qmetaproperty.cpp
@@ -1,37 +1,14 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QtTest/QtTest>
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+
+#include <QTest>
#include <qobject.h>
#include <qmetaobject.h>
+#include <QMap>
+#include <QString>
struct CustomType
{
@@ -45,7 +22,14 @@ struct CustomType
Q_DECLARE_METATYPE(CustomType)
-class tst_QMetaProperty : public QObject
+class Base : public QObject
+{
+ Q_OBJECT
+signals:
+ void baseSignal(int);
+};
+
+class tst_QMetaProperty : public Base
{
Q_OBJECT
Q_PROPERTY(EnumType value WRITE setValue READ getValue)
@@ -56,6 +40,7 @@ class tst_QMetaProperty : public QObject
Q_PROPERTY(int value10 READ value10 FINAL)
Q_PROPERTY(QMap<int, int> map MEMBER map)
Q_PROPERTY(CustomType custom MEMBER custom)
+ Q_PROPERTY(int propWithInheritedSig READ propWithInheritedSig NOTIFY baseSignal)
private slots:
void hasStdCppSet();
@@ -66,6 +51,7 @@ private slots:
void mapProperty();
void conversion();
void enumsFlags();
+ void notifySignalIndex();
public:
enum EnumType { EnumType1 };
@@ -80,6 +66,8 @@ public:
int value9() const { return 1; }
int value10() const { return 1; }
+ int propWithInheritedSig() const { return 0; }
+
QString value7;
QMap<int, int> map;
CustomType custom;
@@ -297,5 +285,20 @@ void tst_QMetaProperty::enumsFlags()
QCOMPARE(t.flagProperty(), EnumFlagsTester::flag2);
}
+
+void tst_QMetaProperty::notifySignalIndex()
+{
+ auto mo = this->metaObject();
+ auto propIndex = mo->indexOfProperty("propWithInheritedSig");
+ auto propWithInheritedSig = mo->property(propIndex);
+ QVERIFY(propWithInheritedSig.isValid());
+ QVERIFY(propWithInheritedSig.hasNotifySignal());
+ QVERIFY(propWithInheritedSig.notifySignalIndex() != -1);
+ QMetaMethod notifySignal = propWithInheritedSig.notifySignal();
+ QVERIFY(notifySignal.isValid());
+ QCOMPARE(notifySignal.name(), "baseSignal");
+ QCOMPARE(notifySignal.parameterCount(), 1);
+}
+
QTEST_MAIN(tst_QMetaProperty)
#include "tst_qmetaproperty.moc"
diff --git a/tests/auto/corelib/kernel/qmetatype/.prev_CMakeLists.txt b/tests/auto/corelib/kernel/qmetatype/.prev_CMakeLists.txt
deleted file mode 100644
index 16188d2d33..0000000000
--- a/tests/auto/corelib/kernel/qmetatype/.prev_CMakeLists.txt
+++ /dev/null
@@ -1,38 +0,0 @@
-# Generated from qmetatype.pro.
-
-#####################################################################
-## tst_qmetatype Test:
-#####################################################################
-
-# Collect test data
-list(APPEND test_data "./typeFlags.bin")
-
-qt_add_test(tst_qmetatype
- SOURCES
- tst_qmetatype.cpp
- DEFINES
- QT_DISABLE_DEPRECATED_BEFORE=0
- INCLUDE_DIRECTORIES
- ../../../other/qvariant_common
- PUBLIC_LIBRARIES
- Qt::CorePrivate
- Qt::Gui
- TESTDATA ${test_data}
-)
-
-## Scopes:
-#####################################################################
-
-qt_extend_target(tst_qmetatype CONDITION MSVC
- COMPILE_OPTIONS
- /bigobj
-)
-
-#### Keys ignored in scope 3:.:.:qmetatype.pro:CLANG:
-# QMAKE_CFLAGS_RELEASE = "--O2" "--g"
-# QMAKE_CXXFLAGS_RELEASE = "--O2" "--g"
-
-qt_extend_target(tst_qmetatype CONDITION CLANG AND (TEST_architecture_arch STREQUAL "arm")
- DEFINES
- TST_QMETATYPE_BROKEN_COMPILER
-)
diff --git a/tests/auto/corelib/kernel/qmetatype/CMakeLists.txt b/tests/auto/corelib/kernel/qmetatype/CMakeLists.txt
index 16188d2d33..b93d961109 100644
--- a/tests/auto/corelib/kernel/qmetatype/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qmetatype/CMakeLists.txt
@@ -1,38 +1,63 @@
-# Generated from qmetatype.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qmetatype Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qmetatype LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
# Collect test data
list(APPEND test_data "./typeFlags.bin")
-qt_add_test(tst_qmetatype
+qt_internal_add_cmake_library(qmetatype_lib1
+ INSTALL_DIRECTORY "${INSTALL_TESTSDIR}/tst_qmetatype"
+ SOURCES
+ lib1.cpp
+ PUBLIC_LIBRARIES
+ Qt::Core
+)
+qt_internal_add_cmake_library(qmetatype_lib2
+ INSTALL_DIRECTORY "${INSTALL_TESTSDIR}/tst_qmetatype"
+ SOURCES
+ lib2.cpp
+ PUBLIC_LIBRARIES
+ Qt::Core
+)
+set_target_properties(qmetatype_lib1 PROPERTIES
+ VERSION 1.0.0
+ SOVERSION 0
+ C_VISIBILITY_PRESET "hidden"
+ CXX_VISIBILITY_PRESET "hidden"
+ VISIBILITY_INLINES_HIDDEN ON
+)
+set_target_properties(qmetatype_lib2 PROPERTIES
+ VERSION 1.0.0
+ SOVERSION 0
+ C_VISIBILITY_PRESET "hidden"
+ CXX_VISIBILITY_PRESET "hidden"
+ VISIBILITY_INLINES_HIDDEN ON
+)
+
+qt_internal_add_test(tst_qmetatype
SOURCES
- tst_qmetatype.cpp
- DEFINES
- QT_DISABLE_DEPRECATED_BEFORE=0
+ tst_qmetatype.h tst_qmetatype.cpp tst_qmetatype2.cpp
+ tst_qmetatype3.cpp
INCLUDE_DIRECTORIES
../../../other/qvariant_common
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::Gui
+ qmetatype_lib1
+ qmetatype_lib2
TESTDATA ${test_data}
)
-## Scopes:
-#####################################################################
-
-qt_extend_target(tst_qmetatype CONDITION MSVC
+qt_internal_extend_target(tst_qmetatype CONDITION MSVC
COMPILE_OPTIONS
/bigobj
)
-
-#### Keys ignored in scope 3:.:.:qmetatype.pro:CLANG:
-# QMAKE_CFLAGS_RELEASE = "--O2" "--g"
-# QMAKE_CXXFLAGS_RELEASE = "--O2" "--g"
-
-qt_extend_target(tst_qmetatype CONDITION CLANG AND (TEST_architecture_arch STREQUAL "arm")
- DEFINES
- TST_QMETATYPE_BROKEN_COMPILER
-)
diff --git a/tests/auto/corelib/kernel/qmetatype/lib1.cpp b/tests/auto/corelib/kernel/qmetatype/lib1.cpp
new file mode 100644
index 0000000000..e5478f87d9
--- /dev/null
+++ b/tests/auto/corelib/kernel/qmetatype/lib1.cpp
@@ -0,0 +1,5 @@
+// Copyright (C) 2022 Intel Corporation
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#define LIB_NAMESPACE Lib1
+#include "lib_common.cpp"
diff --git a/tests/auto/corelib/kernel/qmetatype/lib2.cpp b/tests/auto/corelib/kernel/qmetatype/lib2.cpp
new file mode 100644
index 0000000000..0a905e669a
--- /dev/null
+++ b/tests/auto/corelib/kernel/qmetatype/lib2.cpp
@@ -0,0 +1,5 @@
+// Copyright (C) 2022 Intel Corporation
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#define LIB_NAMESPACE Lib2
+#include "lib_common.cpp"
diff --git a/tests/auto/corelib/kernel/qmetatype/lib_common.cpp b/tests/auto/corelib/kernel/qmetatype/lib_common.cpp
new file mode 100644
index 0000000000..179f539ccc
--- /dev/null
+++ b/tests/auto/corelib/kernel/qmetatype/lib_common.cpp
@@ -0,0 +1,13 @@
+// Copyright (C) 2022 Intel Corporation
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <qcollator.h>
+#include "tst_qmetatype_libs.h"
+
+#define DECLARE_FUNCTION(TYPE, ID) \
+ Q_DECL_EXPORT QMetaType metatype_ ## TYPE() \
+ { return QMetaType::fromType<TYPE>(); }
+
+namespace LIB_NAMESPACE {
+FOR_EACH_METATYPE_LIBS(DECLARE_FUNCTION)
+}
diff --git a/tests/auto/corelib/kernel/qmetatype/qmetatype.pro b/tests/auto/corelib/kernel/qmetatype/qmetatype.pro
deleted file mode 100644
index f9c08377dd..0000000000
--- a/tests/auto/corelib/kernel/qmetatype/qmetatype.pro
+++ /dev/null
@@ -1,27 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qmetatype
-QT = core-private testlib gui
-INCLUDEPATH += $$PWD/../../../other/qvariant_common
-SOURCES = tst_qmetatype.cpp
-TESTDATA=./typeFlags.bin
-DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
-
-msvc {
- # Prevents "fatal error C1128: number of sections exceeded object file format limit".
- QMAKE_CXXFLAGS += /bigobj
-}
-
-clang {
- # clang has some performance problems with the test. Especially
- # with automaticTemplateRegistration which creates few thousands
- # template instantiations (QTBUG-37237). Removing -O2 and -g
- # improves the situation, but it is not solving the problem.
- QMAKE_CXXFLAGS_RELEASE -= -O2
- QMAKE_CFLAGS_RELEASE -= -O2
- QMAKE_CXXFLAGS_RELEASE -= -g
- QMAKE_CFLAGS_RELEASE -= -g
-
- # Building for ARM (eg iOS) is affected so much that we disable
- #the template part of the test
- contains(QT_ARCH, arm): DEFINES += TST_QMETATYPE_BROKEN_COMPILER
-}
diff --git a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp
index ca215386fb..81bf5d5ea8 100644
--- a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp
+++ b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp
@@ -1,38 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QtCore>
-#include <QtTest/QtTest>
-#include <QtCore/private/qmetaobjectbuilder_p.h>
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include "tst_qmetatype.h"
-#include "tst_qvariant_common.h"
+
+#include <QtCore/private/qmetaobjectbuilder_p.h>
#ifdef Q_OS_LINUX
# include <pthread.h>
@@ -40,13 +11,12 @@
#include <algorithm>
#include <memory>
+#include <vector>
-// mingw gcc 4.8 also takes way too long, letting the CI system abort the test
-#if defined(__MINGW32__)
-# define TST_QMETATYPE_BROKEN_COMPILER
-#endif
+#include <QtCore/qflags.h>
Q_DECLARE_METATYPE(QMetaType::Type)
+Q_DECLARE_METATYPE(QPartialOrdering)
namespace CheckTypeTraits
{
@@ -134,7 +104,9 @@ static_assert(!QTypeTraits::has_operator_less_than_v<std::map<int, NoOperators>>
// std::optional
static_assert(QTypeTraits::has_operator_equal_v<std::optional<QString>>);
+static_assert(QTypeTraits::has_operator_less_than_v<std::optional<QString>>);
static_assert(!QTypeTraits::has_operator_equal_v<std::optional<NoOperators>>);
+static_assert(!QTypeTraits::has_operator_less_than_v<std::optional<NoOperators>>);
// nested types
static_assert(QTypeTraits::has_operator_equal_v<Nested>);
@@ -151,91 +123,27 @@ static_assert(!QTypeTraits::has_operator_less_than_v<std::tuple<int, Nested2>>);
static_assert(QTypeTraits::has_operator_equal_v<std::tuple<int, Nested2>>);
static_assert(!QTypeTraits::has_operator_less_than_v<std::tuple<int, Nested2>>);
-}
-
+// optionals of nesteds
+static_assert(QTypeTraits::has_operator_equal_v<std::optional<std::variant<QString>>>);
+static_assert(QTypeTraits::has_operator_less_than_v<std::optional<std::variant<QString>>>);
+static_assert(!QTypeTraits::has_operator_equal_v<std::optional<std::variant<NoOperators>>>);
+static_assert(!QTypeTraits::has_operator_less_than_v<std::optional<std::variant<NoOperators>>>);
-class tst_QMetaType: public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QList<QVariant> prop READ prop WRITE setProp)
+static_assert(QTypeTraits::has_operator_equal_v<std::optional<Nested>>);
+static_assert(!QTypeTraits::has_operator_less_than_v<std::optional<Nested>>);
+static_assert(QTypeTraits::has_operator_equal_v<std::optional<std::tuple<int, Nested>>>);
+static_assert(!QTypeTraits::has_operator_less_than_v<std::optional<std::tuple<int, Nested>>>);
+static_assert(QTypeTraits::has_operator_equal_v<std::optional<std::tuple<int, Nested>>>);
+static_assert(!QTypeTraits::has_operator_less_than_v<std::optional<std::tuple<int, Nested>>>);
-public:
- struct GadgetPropertyType {
- QByteArray type;
- QByteArray name;
- QVariant testData;
- };
+static_assert(QTypeTraits::has_operator_equal_v<std::optional<Nested2>>);
+static_assert(!QTypeTraits::has_operator_less_than_v<std::optional<Nested2>>);
+static_assert(QTypeTraits::has_operator_equal_v<std::optional<std::tuple<int, Nested2>>>);
+static_assert(!QTypeTraits::has_operator_less_than_v<std::optional<std::tuple<int, Nested2>>>);
+static_assert(QTypeTraits::has_operator_equal_v<std::optional<std::tuple<int, Nested2>>>);
+static_assert(!QTypeTraits::has_operator_less_than_v<std::optional<std::tuple<int, Nested2>>>);
- tst_QMetaType() { propList << 42 << "Hello"; }
-
- QList<QVariant> prop() const { return propList; }
- void setProp(const QList<QVariant> &list) { propList = list; }
-
-private:
- void registerGadget(const char * name, const QList<GadgetPropertyType> &gadgetProperties);
- QList<QVariant> propList;
-
-private slots:
- void defined();
- void threadSafety();
- void namespaces();
- void id();
- void qMetaTypeId();
- void properties();
- void normalizedTypes();
- void typeName_data();
- void typeName();
- void type_data();
- void type();
- void type_fromSubString_data();
- void type_fromSubString();
- void create_data();
- void create();
- void createCopy_data();
- void createCopy();
- void sizeOf_data();
- void sizeOf();
- void sizeOfStaticLess_data();
- void sizeOfStaticLess();
- void alignOf_data();
- void alignOf();
- void flags_data();
- void flags();
- void flagsStaticLess_data();
- void flagsStaticLess();
- void flagsBinaryCompatibility6_0_data();
- void flagsBinaryCompatibility6_0();
- void construct_data();
- void construct();
- void typedConstruct();
- void constructCopy_data();
- void constructCopy();
- void typedefs();
- void registerType();
- void isRegistered_data();
- void isRegistered();
- void isRegisteredStaticLess_data();
- void isRegisteredStaticLess();
- void isEnum();
- void automaticTemplateRegistration();
- void saveAndLoadBuiltin_data();
- void saveAndLoadBuiltin();
- void saveAndLoadCustom();
- void metaObject_data();
- void metaObject();
- void constexprMetaTypeIds();
- void constRefs();
- void convertCustomType_data();
- void convertCustomType();
- void compareCustomEqualOnlyType();
- void customDebugStream();
- void unknownType();
- void fromType();
- void operatorEq_data();
- void operatorEq();
- void typesWithInaccessibleDTors();
- void voidIsNotUnknown();
-};
+}
struct BaseGenericType
{
@@ -328,6 +236,12 @@ struct GenericPODType : BaseGenericType
QByteArray podData;
};
+// The order of the next two statics matters!
+//
+// need to use shared_ptr, for its template ctor, since QMetaTypeInterface isn't polymorphic,
+// but the test derives from it
+static std::vector<std::shared_ptr<QtPrivate::QMetaTypeInterface>> s_metaTypeInterfaces;
+
using RegisteredType = QPair<std::shared_ptr<BaseGenericType>, std::shared_ptr<QMetaObject>>;
static QHash<int, RegisteredType> s_managedTypes;
@@ -367,7 +281,7 @@ class CustomQObject : public QObject
{
Q_OBJECT
public:
- CustomQObject(QObject *parent = 0)
+ CustomQObject(QObject *parent = nullptr)
: QObject(parent)
{
}
@@ -398,7 +312,7 @@ void tst_QMetaType::registerGadget(const char *name, const QList<GadgetPropertyT
{
QMetaObjectBuilder gadgetBuilder;
gadgetBuilder.setClassName(name);
- QMetaObjectBuilder::MetaObjectFlags metaObjectflags = QMetaObjectBuilder::DynamicMetaObject | QMetaObjectBuilder::PropertyAccessInStaticMetaCall;
+ MetaObjectFlags metaObjectflags = DynamicMetaObject | PropertyAccessInStaticMetaCall;
gadgetBuilder.setFlags(metaObjectflags);
auto dynamicGadgetProperties = std::make_shared<GenericGadgetType>();
for (const auto &prop : gadgetProperties) {
@@ -412,20 +326,31 @@ void tst_QMetaType::registerGadget(const char *name, const QList<GadgetPropertyT
meta->d.static_metacall = &GadgetsStaticMetacallFunction;
meta->d.superdata = nullptr;
const auto flags = QMetaType::IsGadget | QMetaType::NeedsConstruction | QMetaType::NeedsDestruction;
- using TypeInfo = QtPrivate::QMetaTypeInterface;
- auto typeInfo = new TypeInfo {
- 0, alignof(GenericGadgetType), sizeof(GenericGadgetType), uint(flags), 0, meta, name,
- [](const TypeInfo *self, void *where) { GadgetTypedConstructor(self->typeId, where, nullptr); },
- [](const TypeInfo *self, void *where, const void *copy) { GadgetTypedConstructor(self->typeId, where, copy); },
- [](const TypeInfo *self, void *where, void *copy) { GadgetTypedConstructor(self->typeId, where, copy); },
- [](const TypeInfo *self, void *ptr) { GadgetTypedDestructor(self->typeId, ptr); },
- nullptr,
- nullptr,
- nullptr,
- GadgetSaveOperator,
- GadgetLoadOperator,
- nullptr
+ struct TypeInfo : public QtPrivate::QMetaTypeInterface
+ {
+ QMetaObject *mo;
};
+
+ auto typeInfo = s_metaTypeInterfaces.emplace_back(new TypeInfo {
+ {
+ 0, alignof(GenericGadgetType), sizeof(GenericGadgetType), uint(flags), 0,
+ [](const QtPrivate::QMetaTypeInterface *self) -> const QMetaObject * {
+ return reinterpret_cast<const TypeInfo *>(self)->mo;
+ },
+ name,
+ [](const QtPrivate::QMetaTypeInterface *self, void *where) { GadgetTypedConstructor(self->typeId, where, nullptr); },
+ [](const QtPrivate::QMetaTypeInterface *self, void *where, const void *copy) { GadgetTypedConstructor(self->typeId, where, copy); },
+ [](const QtPrivate::QMetaTypeInterface *self, void *where, void *copy) { GadgetTypedConstructor(self->typeId, where, copy); },
+ [](const QtPrivate::QMetaTypeInterface *self, void *ptr) { GadgetTypedDestructor(self->typeId, ptr); },
+ nullptr,
+ nullptr,
+ nullptr,
+ GadgetSaveOperator,
+ GadgetLoadOperator,
+ nullptr
+ },
+ meta
+ }).get();
QMetaType gadgetMetaType(typeInfo);
dynamicGadgetProperties->m_metatype = gadgetMetaType;
int gadgetTypeId = QMetaType(typeInfo).id();
@@ -473,6 +398,7 @@ public:
int Bar::failureCount = 0;
+#if QT_CONFIG(thread)
class MetaTypeTorturer: public QThread
{
Q_OBJECT
@@ -489,63 +415,70 @@ protected:
const QByteArray name = "Bar" + QByteArray::number(i) + postFix;
const char *nm = name.constData();
int tp = qRegisterMetaType<Bar>(nm);
-#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
- pthread_yield();
-#endif
QMetaType info(tp);
if (!info.isValid()) {
++failureCount;
qWarning() << "Wrong typeInfo returned for" << tp;
}
- if (!info.isRegistered()) {
+ if (info.flags() != (QMetaType::NeedsConstruction | QMetaType::NeedsDestruction |
+ QMetaType::NeedsCopyConstruction | QMetaType::NeedsMoveConstruction)) {
++failureCount;
- qWarning() << name << "is not a registered metatype";
+ qWarning() << "Wrong typeInfo returned for" << tp << "got"
+ << Qt::showbase << Qt::hex << info.flags();
}
- if (QMetaType::typeFlags(tp) != (QMetaType::NeedsConstruction | QMetaType::NeedsDestruction)) {
+ if (!info.isRegistered()) {
++failureCount;
- qWarning() << "Wrong typeInfo returned for" << tp;
+ qWarning() << name << "is not a registered metatype";
}
if (!QMetaType::isRegistered(tp)) {
++failureCount;
qWarning() << name << "is not a registered metatype";
}
- if (QMetaType::type(nm) != tp) {
+ if (QMetaType::fromName(nm).id() != tp) {
++failureCount;
qWarning() << "Wrong metatype returned for" << name;
}
- void *buf1 = QMetaType::create(tp, 0);
- void *buf2 = QMetaType::create(tp, buf1);
- void *buf3 = info.create(tp, 0);
- void *buf4 = info.create(tp, buf1);
- QMetaType::construct(tp, space, 0);
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ void *buf1 = QMetaType::create(tp, nullptr);
+ void *buf2 = QMetaType::create(tp, buf1);
+ QMetaType::construct(tp, space, nullptr);
QMetaType::destruct(tp, space);
QMetaType::construct(tp, space, buf1);
QMetaType::destruct(tp, space);
- info.construct(space, 0);
- info.destruct(space);
- info.construct(space, buf1);
- info.destruct(space);
-
if (!buf1) {
++failureCount;
- qWarning() << "Null buffer returned by QMetaType::create(tp, 0)";
+ qWarning() << "Null buffer returned by QMetaType::create(tp, nullptr)";
}
if (!buf2) {
++failureCount;
qWarning() << "Null buffer returned by QMetaType::create(tp, buf)";
}
+
+ QMetaType::destroy(tp, buf1);
+ QMetaType::destroy(tp, buf2);
+QT_WARNING_POP
+#endif
+
+ void *buf3 = info.create(nullptr);
+ void *buf4 = info.create(buf3);
+
+ info.construct(space, nullptr);
+ info.destruct(space);
+ info.construct(space, buf3);
+ info.destruct(space);
+
if (!buf3) {
++failureCount;
- qWarning() << "Null buffer returned by info.create(tp, 0)";
+ qWarning() << "Null buffer returned by info.create(nullptr)";
}
if (!buf4) {
++failureCount;
- qWarning() << "Null buffer returned by infocreate(tp, buf)";
+ qWarning() << "Null buffer returned by info.create(buf)";
}
- QMetaType::destroy(tp, buf1);
- QMetaType::destroy(tp, buf2);
+
info.destroy(buf3);
info.destroy(buf4);
}
@@ -575,6 +508,7 @@ void tst_QMetaType::threadSafety()
QCOMPARE(t3.failureCount, 0);
QCOMPARE(Bar::failureCount, 0);
}
+#endif
namespace TestSpace
{
@@ -593,7 +527,7 @@ void tst_QMetaType::namespaces()
QCOMPARE(qvariant_cast<TestSpace::Foo>(v).d, 11.12);
int qungTfuId = qRegisterMetaType<ADD_TESTSPACE(QungTfu)>();
- QCOMPARE(QMetaType::typeName(qungTfuId), "TestSpace::QungTfu");
+ QCOMPARE(QMetaType(qungTfuId).name(), "TestSpace::QungTfu");
}
void tst_QMetaType::id()
@@ -607,13 +541,13 @@ void tst_QMetaType::qMetaTypeId()
{
QCOMPARE(::qMetaTypeId<QString>(), int(QMetaType::QString));
QCOMPARE(::qMetaTypeId<int>(), int(QMetaType::Int));
- QCOMPARE(::qMetaTypeId<TestSpace::Foo>(), QMetaType::type("TestSpace::Foo"));
+ QCOMPARE(::qMetaTypeId<TestSpace::Foo>(), QMetaType::fromType<TestSpace::Foo>().id());
- QCOMPARE(::qMetaTypeId<char>(), QMetaType::type("char"));
- QCOMPARE(::qMetaTypeId<uchar>(), QMetaType::type("unsigned char"));
- QCOMPARE(::qMetaTypeId<signed char>(), QMetaType::type("signed char"));
+ QCOMPARE(::qMetaTypeId<char>(), QMetaType::fromType<char>().id());
+ QCOMPARE(::qMetaTypeId<uchar>(), QMetaType::fromType<unsigned char>().id());
+ QCOMPARE(::qMetaTypeId<signed char>(), QMetaType::fromType<signed char>().id());
QVERIFY(::qMetaTypeId<signed char>() != ::qMetaTypeId<char>());
- QCOMPARE(::qMetaTypeId<qint8>(), QMetaType::type("qint8"));
+ QCOMPARE(::qMetaTypeId<qint8>(), QMetaType::fromType<qint8>().id());
}
void tst_QMetaType::properties()
@@ -625,40 +559,28 @@ void tst_QMetaType::properties()
QCOMPARE(v.typeName(), "QVariantList");
QList<QVariant> values = v.toList();
- QCOMPARE(values.count(), 2);
+ QCOMPARE(values.size(), 2);
QCOMPARE(values.at(0).toInt(), 42);
values << 43 << "world";
QVERIFY(setProperty("prop", values));
v = property("prop");
- QCOMPARE(v.toList().count(), 4);
+ QCOMPARE(v.toList().size(), 4);
}
-template <typename T>
-struct Whity { T t; Whity() {} };
-
-Q_DECLARE_METATYPE( Whity < int > )
-Q_DECLARE_METATYPE(Whity<double>)
-
-#if !defined(Q_CC_CLANG) && defined(Q_CC_GNU) && Q_CC_GNU < 501
-QT_BEGIN_NAMESPACE
-Q_DECLARE_TYPEINFO(Whity<double>, Q_MOVABLE_TYPE);
-QT_END_NAMESPACE
-#endif
-
void tst_QMetaType::normalizedTypes()
{
int WhityIntId = ::qMetaTypeId<Whity<int> >();
int WhityDoubleId = ::qMetaTypeId<Whity<double> >();
- QCOMPARE(QMetaType::type("Whity<int>"), WhityIntId);
- QCOMPARE(QMetaType::type(" Whity < int > "), WhityIntId);
- QCOMPARE(QMetaType::type("Whity<int >"), WhityIntId);
+ QCOMPARE(QMetaType::fromName("Whity<int>").id(), WhityIntId);
+ QCOMPARE(QMetaType::fromName(" Whity < int > ").id(), WhityIntId);
+ QCOMPARE(QMetaType::fromName("Whity<int >").id(), WhityIntId);
- QCOMPARE(QMetaType::type("Whity<double>"), WhityDoubleId);
- QCOMPARE(QMetaType::type(" Whity< double > "), WhityDoubleId);
- QCOMPARE(QMetaType::type("Whity<double >"), WhityDoubleId);
+ QCOMPARE(QMetaType::fromName("Whity<double>").id(), WhityDoubleId);
+ QCOMPARE(QMetaType::fromName(" Whity< double > ").id(), WhityDoubleId);
+ QCOMPARE(QMetaType::fromName("Whity<double >").id(), WhityDoubleId);
QCOMPARE(qRegisterMetaType<Whity<int> >(" Whity < int > "), WhityIntId);
QCOMPARE(qRegisterMetaType<Whity<int> >("Whity<int>"), WhityIntId);
@@ -672,6 +594,21 @@ void tst_QMetaType::normalizedTypes()
#define TYPENAME_DATA(MetaTypeName, MetaTypeId, RealType)\
QTest::newRow(#RealType) << int(QMetaType::MetaTypeName) << #RealType;
+namespace enumerations {
+ enum Test { a = 0 };
+}
+
+static void ignoreInvalidMetaTypeWarning(int typeId)
+{
+ if (typeId < 0 || typeId > QMetaType::User + 500 ||
+ (typeId > QMetaType::LastCoreType && typeId < QMetaType::FirstGuiType) ||
+ (typeId > QMetaType::LastGuiType && typeId < QMetaType::FirstWidgetsType) ||
+ (typeId > QMetaType::LastWidgetsType && typeId < QMetaType::User)) {
+ QTest::ignoreMessage(QtWarningMsg, "Trying to construct an instance of an invalid type, type id: "
+ + QByteArray::number(typeId));
+ }
+}
+
void tst_QMetaType::typeName_data()
{
QTest::addColumn<int>("aType");
@@ -708,6 +645,8 @@ void tst_QMetaType::typeName_data()
// template instance class derived from Q_GADGET enabled class
QTest::newRow("GadgetDerivedAndTyped<int>") << ::qMetaTypeId<GadgetDerivedAndTyped<int>>() << QString::fromLatin1("GadgetDerivedAndTyped<int>");
QTest::newRow("GadgetDerivedAndTyped<int>*") << ::qMetaTypeId<GadgetDerivedAndTyped<int>*>() << QString::fromLatin1("GadgetDerivedAndTyped<int>*");
+
+ QTest::newRow("msvcKeywordPartOfName") << ::qMetaTypeId<enumerations::Test>() << QString::fromLatin1("enumerations::Test");
}
void tst_QMetaType::typeName()
@@ -718,13 +657,15 @@ void tst_QMetaType::typeName()
if (aType >= QMetaType::FirstWidgetsType)
QSKIP("The test doesn't link against QtWidgets.");
- const char *rawname = QMetaType::typeName(aType);
+ ignoreInvalidMetaTypeWarning(aType);
+ const char *rawname = QMetaType(aType).name();
QString name = QString::fromLatin1(rawname);
QCOMPARE(name, aTypeName);
QCOMPARE(name.toLatin1(), QMetaObject::normalizedType(name.toLatin1().constData()));
QCOMPARE(rawname == nullptr, aTypeName.isNull());
+ ignoreInvalidMetaTypeWarning(aType);
QMetaType mt(aType);
if (mt.isValid()) { // Gui type are not valid
QCOMPARE(QString::fromLatin1(QMetaType(aType).name()), aTypeName);
@@ -758,10 +699,8 @@ void tst_QMetaType::type()
if (aType >= QMetaType::FirstWidgetsType)
QSKIP("The test doesn't link against QtWidgets.");
- // QMetaType::type(QByteArray)
- QCOMPARE(QMetaType::type(aTypeName), aType);
- // QMetaType::type(const char *)
- QCOMPARE(QMetaType::type(aTypeName.constData()), aType);
+ QCOMPARE(QMetaType::fromName(aTypeName).id(), aType);
+ QCOMPARE(QMetaType::fromName(aTypeName.constData()).id(), aType);
}
void tst_QMetaType::type_fromSubString_data()
@@ -786,7 +725,7 @@ void tst_QMetaType::type_fromSubString()
QFETCH(int, size);
QFETCH(int, expectedType);
QByteArray ba = QByteArray::fromRawData(types + offset, size);
- QCOMPARE(QMetaType::type(ba), expectedType);
+ QCOMPARE(QMetaType::fromName(ba).id(), expectedType);
}
namespace {
@@ -811,8 +750,9 @@ static_assert((!QMetaTypeId2<QMetaType::Type>::IsBuiltIn));
void tst_QMetaType::create_data()
{
QTest::addColumn<int>("type");
+ QTest::newRow("unknown-type") << int(QMetaType::UnknownType);
#define ADD_METATYPE_TEST_ROW(MetaTypeName, MetaTypeId, RealType) \
- QTest::newRow(QMetaType::typeName(QMetaType::MetaTypeName)) << int(QMetaType::MetaTypeName);
+ QTest::newRow(QMetaType(QMetaType::MetaTypeName).name()) << int(QMetaType::MetaTypeName);
FOR_EACH_CORE_METATYPE(ADD_METATYPE_TEST_ROW)
#undef ADD_METATYPE_TEST_ROW
}
@@ -821,27 +761,36 @@ template<int ID>
static void testCreateHelper()
{
typedef typename MetaEnumToType<ID>::Type Type;
- QMetaType info(ID);
+ auto expected = std::unique_ptr<Type>(DefaultValueFactory<ID>::create());
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
void *actual1 = QMetaType::create(ID);
+ auto cleanup1 = qScopeGuard([actual1]() {
+ QMetaType::destroy(ID, actual1);
+ });
+ QCOMPARE(*static_cast<Type *>(actual1), *expected);
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
+ QMetaType info(ID);
void *actual2 = info.create();
- if (DefaultValueTraits<ID>::IsInitialized) {
- Type *expected = DefaultValueFactory<ID>::create();
- QCOMPARE(*static_cast<Type *>(actual1), *expected);
- QCOMPARE(*static_cast<Type *>(actual2), *expected);
- delete expected;
- }
- QMetaType::destroy(ID, actual1);
- info.destroy(actual2);
+ auto cleanup2 = qScopeGuard([&info, actual2]() {
+ info.destroy(actual2);
+ });
+ QCOMPARE(*static_cast<Type *>(actual2), *expected);
}
template<>
void testCreateHelper<QMetaType::Void>()
{
- void *actual = QMetaType::create(QMetaType::Void);
- if (DefaultValueTraits<QMetaType::Void>::IsInitialized) {
- QVERIFY(DefaultValueFactory<QMetaType::Void>::create());
- }
- QMetaType::destroy(QMetaType::Void, actual);
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ void *actual1 = QMetaType::create(QMetaType::Void);
+ QMetaType::destroy(QMetaType::Void, actual1);
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
+ QMetaType info(QMetaType::Void);
+ void *actual2 = info.create();
+ info.destroy(actual2);
}
@@ -854,6 +803,10 @@ void tst_QMetaType::create()
static TypeTestFunction get(int type)
{
switch (type) {
+ case QMetaType::UnknownType:
+ return []() {
+ QCOMPARE(QMetaType().create(), nullptr);
+ };
#define RETURN_CREATE_FUNCTION(MetaTypeName, MetaTypeId, RealType) \
case QMetaType::MetaTypeName: \
return testCreateHelper<QMetaType::MetaTypeName>;
@@ -872,15 +825,22 @@ template<int ID>
static void testCreateCopyHelper()
{
typedef typename MetaEnumToType<ID>::Type Type;
- Type *expected = TestValueFactory<ID>::create();
- QMetaType info(ID);
- void *actual1 = QMetaType::create(ID, expected);
- void *actual2 = info.create(expected);
+ auto expected = std::unique_ptr<Type>(TestValueFactory<ID>::create());
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ void *actual1 = QMetaType::create(ID, expected.get());
+ auto cleanup1 = qScopeGuard([actual1]() {
+ QMetaType::destroy(ID, actual1);
+ });
QCOMPARE(*static_cast<Type *>(actual1), *expected);
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
+ QMetaType info(ID);
+ void *actual2 = info.create(expected.get());
+ auto cleanup2 = qScopeGuard([&info, actual2]() {
+ info.destroy(actual2);
+ });
QCOMPARE(*static_cast<Type *>(actual2), *expected);
- QMetaType::destroy(ID, actual1);
- info.destroy(actual2);
- delete expected;
}
template<>
@@ -888,9 +848,22 @@ void testCreateCopyHelper<QMetaType::Void>()
{
typedef MetaEnumToType<QMetaType::Void>::Type Type;
Type *expected = TestValueFactory<QMetaType::Void>::create();
- void *actual = QMetaType::create(QMetaType::Void, expected);
- QCOMPARE(static_cast<Type *>(actual), expected);
- QMetaType::destroy(QMetaType::Void, actual);
+ QCOMPARE(expected, nullptr); // we do not need to delete it
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ void *actual1 = QMetaType::create(QMetaType::Void, expected);
+ auto cleanup1 = qScopeGuard([actual1]() {
+ QMetaType::destroy(QMetaType::Void, actual1);
+ });
+ QCOMPARE(static_cast<Type *>(actual1), expected);
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
+ QMetaType info(QMetaType::Void);
+ void *actual2 = info.create(expected);
+ auto cleanup2 = qScopeGuard([&info, actual2]() {
+ info.destroy(actual2);
+ });
+ QCOMPARE(static_cast<Type *>(actual2), expected);
}
void tst_QMetaType::createCopy_data()
@@ -905,6 +878,11 @@ void tst_QMetaType::createCopy()
static TypeTestFunction get(int type)
{
switch (type) {
+ case QMetaType::UnknownType:
+ return []() {
+ char buf[1] = {};
+ QCOMPARE(QMetaType().create(&buf), nullptr);
+ };
#define RETURN_CREATE_COPY_FUNCTION(MetaTypeName, MetaTypeId, RealType) \
case QMetaType::MetaTypeName: \
return testCreateCopyHelper<QMetaType::MetaTypeName>;
@@ -948,7 +926,9 @@ void tst_QMetaType::sizeOf()
{
QFETCH(int, type);
QFETCH(size_t, size);
- QCOMPARE(size_t(QMetaType::sizeOf(type)), size);
+ ignoreInvalidMetaTypeWarning(type);
+ QMetaType metaType(type);
+ QCOMPARE(size_t(metaType.sizeOf()), size);
}
void tst_QMetaType::sizeOfStaticLess_data()
@@ -960,6 +940,7 @@ void tst_QMetaType::sizeOfStaticLess()
{
QFETCH(int, type);
QFETCH(size_t, size);
+ ignoreInvalidMetaTypeWarning(type);
QCOMPARE(size_t(QMetaType(type).sizeOf()), size);
}
@@ -996,28 +977,15 @@ void tst_QMetaType::alignOf()
{
QFETCH(int, type);
QFETCH(size_t, size);
+ ignoreInvalidMetaTypeWarning(type);
QCOMPARE(size_t(QMetaType(type).alignOf()), size);
}
-struct CustomMovable { CustomMovable() {} };
-
-// needed for QSet<CustomMovable>. We actually check that it makes sense.
-bool operator==(const CustomMovable &, const CustomMovable &) { return true; }
-qsizetype qHash(const CustomMovable &, qsizetype seed = 0) { return seed; }
-
-#if !defined(Q_CC_CLANG) && defined(Q_CC_GNU) && Q_CC_GNU < 501
-QT_BEGIN_NAMESPACE
-Q_DECLARE_TYPEINFO(CustomMovable, Q_MOVABLE_TYPE);
-QT_END_NAMESPACE
-#endif
-
-Q_DECLARE_METATYPE(CustomMovable);
-
class CustomObject : public QObject
{
Q_OBJECT
public:
- CustomObject(QObject *parent = 0)
+ CustomObject(QObject *parent = nullptr)
: QObject(parent)
{
@@ -1031,7 +999,7 @@ class CustomMultiInheritanceObject : public QObject, SecondBase
{
Q_OBJECT
public:
- CustomMultiInheritanceObject(QObject *parent = 0)
+ CustomMultiInheritanceObject(QObject *parent = nullptr)
: QObject(parent)
{
@@ -1045,7 +1013,7 @@ class P { Q_DECL_UNUSED_MEMBER char _[4]; };
QT_BEGIN_NAMESPACE
#if defined(Q_CC_GNU) && Q_CC_GNU < 501
-Q_DECLARE_TYPEINFO(M, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(M, Q_RELOCATABLE_TYPE);
Q_DECLARE_TYPEINFO(P, Q_PRIMITIVE_TYPE);
#endif
QT_END_NAMESPACE
@@ -1074,76 +1042,157 @@ Q_DECLARE_METATYPE(QPairPP)
enum FlagsDataEnum {};
Q_DECLARE_METATYPE(FlagsDataEnum);
+template <typename T> void addFlagsRow(const char *name, int id = qMetaTypeId<T>())
+{
+ QTest::newRow(name)
+ << id
+ << bool(QTypeInfo<T>::isRelocatable)
+ << bool(!std::is_default_constructible_v<T> || !QTypeInfo<T>::isValueInitializationBitwiseZero)
+ << bool(!std::is_trivially_copy_constructible_v<T>)
+ << bool(!std::is_trivially_destructible_v<T>)
+ << bool(QtPrivate::IsPointerToTypeDerivedFromQObject<T>::Value)
+ << bool(std::is_enum<T>::value)
+ << false;
+}
+
void tst_QMetaType::flags_data()
{
QTest::addColumn<int>("type");
- QTest::addColumn<bool>("isMovable");
- QTest::addColumn<bool>("isComplex");
+ QTest::addColumn<bool>("isRelocatable");
+ QTest::addColumn<bool>("needsConstruction");
+ QTest::addColumn<bool>("needsCopyConstruction");
+ QTest::addColumn<bool>("needsDestruction");
QTest::addColumn<bool>("isPointerToQObject");
QTest::addColumn<bool>("isEnum");
+ QTest::addColumn<bool>("isQmlList");
+
+ // invalid ids.
+ QTest::newRow("-1") << -1 << false << false << false << false << false << false << false;
+ QTest::newRow("-124125534") << -124125534 << false << false << false << false << false << false << false;
+ QTest::newRow("124125534") << 124125534 << false << false << false << false << false << false << false;
#define ADD_METATYPE_TEST_ROW(MetaTypeName, MetaTypeId, RealType) \
- QTest::newRow(#RealType) << MetaTypeId \
- << bool(QTypeInfo<RealType>::isRelocatable) \
- << bool(QTypeInfo<RealType>::isComplex) \
- << bool(QtPrivate::IsPointerToTypeDerivedFromQObject<RealType>::Value) \
- << bool(std::is_enum<RealType>::value);
+ addFlagsRow<RealType>(#RealType, MetaTypeId);
+QT_FOR_EACH_STATIC_PRIMITIVE_NON_VOID_TYPE(ADD_METATYPE_TEST_ROW)
QT_FOR_EACH_STATIC_CORE_CLASS(ADD_METATYPE_TEST_ROW)
QT_FOR_EACH_STATIC_PRIMITIVE_POINTER(ADD_METATYPE_TEST_ROW)
QT_FOR_EACH_STATIC_CORE_POINTER(ADD_METATYPE_TEST_ROW)
#undef ADD_METATYPE_TEST_ROW
- QTest::newRow("TestSpace::Foo") << ::qMetaTypeId<TestSpace::Foo>() << false << true << false << false;
- QTest::newRow("Whity<double>") << ::qMetaTypeId<Whity<double> >() << true << true << false << false;
- QTest::newRow("CustomMovable") << ::qMetaTypeId<CustomMovable>() << true << true << false << false;
- QTest::newRow("CustomObject*") << ::qMetaTypeId<CustomObject*>() << true << false << true << false;
- QTest::newRow("CustomMultiInheritanceObject*") << ::qMetaTypeId<CustomMultiInheritanceObject*>() << true << false << true << false;
- QTest::newRow("QPair<C,C>") << ::qMetaTypeId<QPair<C,C> >() << false << true << false << false;
- QTest::newRow("QPair<C,M>") << ::qMetaTypeId<QPair<C,M> >() << false << true << false << false;
- QTest::newRow("QPair<C,P>") << ::qMetaTypeId<QPair<C,P> >() << false << true << false << false;
- QTest::newRow("QPair<M,C>") << ::qMetaTypeId<QPair<M,C> >() << false << true << false << false;
- QTest::newRow("QPair<M,M>") << ::qMetaTypeId<QPair<M,M> >() << true << true << false << false;
- QTest::newRow("QPair<M,P>") << ::qMetaTypeId<QPair<M,P> >() << true << true << false << false;
- QTest::newRow("QPair<P,C>") << ::qMetaTypeId<QPair<P,C> >() << false << true << false << false;
- QTest::newRow("QPair<P,M>") << ::qMetaTypeId<QPair<P,M> >() << true << true << false << false;
- QTest::newRow("QPair<P,P>") << ::qMetaTypeId<QPair<P,P> >() << true << false << false << false;
- QTest::newRow("FlagsDataEnum") << ::qMetaTypeId<FlagsDataEnum>() << true << false << false << true;
-
- // invalid ids.
- QTest::newRow("-1") << -1 << false << false << false << false;
- QTest::newRow("-124125534") << -124125534 << false << false << false << false;
- QTest::newRow("124125534") << 124125534 << false << false << false << false;
+ addFlagsRow<TestSpace::Foo>("TestSpace::Foo");
+ addFlagsRow<Whity<double> >("Whity<double> ");
+ addFlagsRow<CustomMovable>("CustomMovable");
+ addFlagsRow<CustomObject*>("CustomObject*");
+ addFlagsRow<CustomMultiInheritanceObject*>("CustomMultiInheritanceObject*");
+ addFlagsRow<QPair<C,C> >("QPair<C,C>");
+ addFlagsRow<QPair<C,M> >("QPair<C,M>");
+ addFlagsRow<QPair<C,P> >("QPair<C,P>");
+ addFlagsRow<QPair<M,C> >("QPair<M,C>");
+ addFlagsRow<QPair<M,M> >("QPair<M,M>");
+ addFlagsRow<QPair<M,P> >("QPair<M,P>");
+ addFlagsRow<QPair<P,C> >("QPair<P,C>");
+ addFlagsRow<QPair<P,M> >("QPair<P,M>");
+ addFlagsRow<QPair<P,P> >("QPair<P,P>");
+ addFlagsRow<FlagsDataEnum>("FlagsDataEnum");
}
void tst_QMetaType::flags()
{
QFETCH(int, type);
- QFETCH(bool, isMovable);
- QFETCH(bool, isComplex);
+ QFETCH(bool, isRelocatable);
+ QFETCH(bool, needsConstruction);
+ QFETCH(bool, needsCopyConstruction);
+ QFETCH(bool, needsDestruction);
QFETCH(bool, isPointerToQObject);
QFETCH(bool, isEnum);
+ QFETCH(bool, isQmlList);
+
+ ignoreInvalidMetaTypeWarning(type);
+ QMetaType meta(type);
- QCOMPARE(bool(QMetaType::typeFlags(type) & QMetaType::NeedsConstruction), isComplex);
- QCOMPARE(bool(QMetaType::typeFlags(type) & QMetaType::NeedsDestruction), isComplex);
- QCOMPARE(bool(QMetaType::typeFlags(type) & QMetaType::MovableType), isMovable);
- QCOMPARE(bool(QMetaType::typeFlags(type) & QMetaType::PointerToQObject), isPointerToQObject);
- QCOMPARE(bool(QMetaType::typeFlags(type) & QMetaType::IsEnumeration), isEnum);
+ QCOMPARE(bool(meta.flags() & QMetaType::NeedsConstruction), needsConstruction);
+ QCOMPARE(bool(meta.flags() & QMetaType::NeedsCopyConstruction), needsCopyConstruction);
+ QCOMPARE(bool(meta.flags() & QMetaType::NeedsDestruction), needsDestruction);
+ QCOMPARE(bool(meta.flags() & QMetaType::RelocatableType), isRelocatable);
+ QCOMPARE(bool(meta.flags() & QMetaType::PointerToQObject), isPointerToQObject);
+ QCOMPARE(bool(meta.flags() & QMetaType::IsEnumeration), isEnum);
+ QCOMPARE(bool(meta.flags() & QMetaType::IsQmlList), isQmlList);
}
-void tst_QMetaType::flagsStaticLess_data()
+class NonDefaultConstructible
+{
+ NonDefaultConstructible(int) {}
+};
+
+struct MoveOnly
{
- flags_data();
+ MoveOnly() = default;
+ MoveOnly(const MoveOnly &) = delete;
+ MoveOnly(MoveOnly &&) = default;
+ MoveOnly &operator=(const MoveOnly &) = delete;
+ MoveOnly &operator=(MoveOnly &&) = default;
+};
+
+class Indestructible
+{
+protected:
+ ~Indestructible() {}
+};
+
+template <typename T> static void addFlags2Row(QMetaType metaType = QMetaType::fromType<T>())
+{
+ QTest::newRow(metaType.name() ? metaType.name() : "UnknownType")
+ << metaType
+ << std::is_default_constructible_v<T>
+ << std::is_copy_constructible_v<T>
+ << std::is_move_constructible_v<T>
+ << std::is_destructible_v<T>
+ << (QTypeTraits::has_operator_equal<T>::value || QTypeTraits::has_operator_less_than<T>::value)
+ << QTypeTraits::has_operator_less_than<T>::value;
+};
+
+void tst_QMetaType::flags2_data()
+{
+ QTest::addColumn<QMetaType>("type");
+ QTest::addColumn<bool>("isDefaultConstructible");
+ QTest::addColumn<bool>("isCopyConstructible");
+ QTest::addColumn<bool>("isMoveConstructible");
+ QTest::addColumn<bool>("isDestructible");
+ QTest::addColumn<bool>("isEqualityComparable");
+ QTest::addColumn<bool>("isOrdered");
+
+ addFlags2Row<void>(QMetaType());
+ addFlags2Row<void>();
+
+#define ADD_METATYPE_TEST_ROW(MetaTypeName, MetaTypeId, RealType) \
+ addFlags2Row<RealType>();
+ QT_FOR_EACH_STATIC_PRIMITIVE_NON_VOID_TYPE(ADD_METATYPE_TEST_ROW)
+ QT_FOR_EACH_STATIC_CORE_CLASS(ADD_METATYPE_TEST_ROW)
+ QT_FOR_EACH_STATIC_PRIMITIVE_POINTER(ADD_METATYPE_TEST_ROW)
+ QT_FOR_EACH_STATIC_CORE_POINTER(ADD_METATYPE_TEST_ROW)
+#undef ADD_METATYPE_TEST_ROW
+
+ addFlags2Row<NonDefaultConstructible>();
+ addFlags2Row<MoveOnly>();
+ addFlags2Row<QObject>();
+ addFlags2Row<Indestructible>();
}
-void tst_QMetaType::flagsStaticLess()
+void tst_QMetaType::flags2()
{
- QFETCH(int, type);
- QFETCH(bool, isMovable);
- QFETCH(bool, isComplex);
+ QFETCH(QMetaType, type);
+ QFETCH(bool, isDefaultConstructible);
+ QFETCH(bool, isCopyConstructible);
+ QFETCH(bool, isMoveConstructible);
+ QFETCH(bool, isDestructible);
+ QFETCH(bool, isEqualityComparable);
+ QFETCH(bool, isOrdered);
- int flags = QMetaType(type).flags();
- QCOMPARE(bool(flags & QMetaType::NeedsConstruction), isComplex);
- QCOMPARE(bool(flags & QMetaType::NeedsDestruction), isComplex);
- QCOMPARE(bool(flags & QMetaType::MovableType), isMovable);
+ QCOMPARE(type.isDefaultConstructible(), isDefaultConstructible);
+ QCOMPARE(type.isCopyConstructible(), isCopyConstructible);
+ QCOMPARE(type.isMoveConstructible(), isMoveConstructible);
+ QCOMPARE(type.isDestructible(), isDestructible);
+ QCOMPARE(type.isEqualityComparable(), isEqualityComparable);
+ QCOMPARE(type.isOrdered(), isOrdered);
}
void tst_QMetaType::flagsBinaryCompatibility6_0_data()
@@ -1171,7 +1220,7 @@ void tst_QMetaType::flagsBinaryCompatibility6_0_data()
QTest::addColumn<quint32>("flags");
QFile file(QFINDTESTDATA("typeFlags.bin"));
- file.open(QIODevice::ReadOnly);
+ QVERIFY(file.open(QIODevice::ReadOnly));
QList<quint32> buffer;
QDataStream ds(&file);
ds >> buffer;
@@ -1182,7 +1231,7 @@ void tst_QMetaType::flagsBinaryCompatibility6_0_data()
if (id > QMetaType::LastCoreType)
continue; // We do not link against QtGui, so we do longer consider such type as registered
QVERIFY2(QMetaType::isRegistered(id), "A type could not be removed in BC way");
- QTest::newRow(QMetaType::typeName(id)) << id << flags;
+ QTest::newRow(QMetaType(id).name()) << id << flags;
}
}
@@ -1191,9 +1240,16 @@ void tst_QMetaType::flagsBinaryCompatibility6_0()
QFETCH(quint32, id);
QFETCH(quint32, flags);
- quint32 mask_5_0 = 0x1fb; // Only compare the values that were already defined in 5.0
+ const auto currentFlags = QMetaType(id).flags();
+ auto expectedFlags = QMetaType::TypeFlags(flags);
- QCOMPARE(quint32(QMetaType::typeFlags(id)) & mask_5_0, flags & mask_5_0);
+ // Only compare the values that were already defined in 5.0.
+ // In 6.5, some types lost NeedsConstruction and NeedsDestruction, but
+ // that's acceptable if that's because they were trivial
+ quint32 mask_5_0 = 0x1ff & ~quint32(QMetaType::NeedsConstruction | QMetaType::NeedsDestruction
+ | QMetaType::RelocatableType);
+
+ QCOMPARE(quint32(currentFlags) & mask_5_0, quint32(expectedFlags) & mask_5_0);
}
void tst_QMetaType::construct_data()
@@ -1205,47 +1261,61 @@ template<int ID>
static void testConstructHelper()
{
typedef typename MetaEnumToType<ID>::Type Type;
+ auto expected = std::unique_ptr<Type>(DefaultValueFactory<ID>::create());
QMetaType info(ID);
int size = info.sizeOf();
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
void *storage1 = qMallocAligned(size, alignof(Type));
- void *actual1 = QMetaType::construct(ID, storage1, /*copy=*/0);
- void *storage2 = qMallocAligned(size, alignof(Type));
- void *actual2 = info.construct(storage2, /*copy=*/0);
+ void *actual1 = QMetaType::construct(ID, storage1, /*copy=*/nullptr);
+ auto cleanup1 = qScopeGuard([storage1, actual1]() {
+ QMetaType::destruct(ID, actual1);
+ qFreeAligned(storage1);
+ });
QCOMPARE(actual1, storage1);
+ QCOMPARE(*static_cast<Type *>(actual1), *expected);
+ QCOMPARE(QMetaType::construct(ID, nullptr, /*copy=*/nullptr), nullptr);
+ QMetaType::destruct(ID, nullptr);
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
+ void *storage2 = qMallocAligned(size, alignof(Type));
+ void *actual2 = info.construct(storage2, /*copy=*/nullptr);
+ auto cleanup2 = qScopeGuard([&info, storage2, actual2]() {
+ info.destruct(actual2);
+ qFreeAligned(storage2);
+ });
QCOMPARE(actual2, storage2);
- if (DefaultValueTraits<ID>::IsInitialized) {
- Type *expected = DefaultValueFactory<ID>::create();
- QCOMPARE(*static_cast<Type *>(actual1), *expected);
- QCOMPARE(*static_cast<Type *>(actual2), *expected);
- delete expected;
- }
- QMetaType::destruct(ID, actual1);
- qFreeAligned(storage1);
- info.destruct(actual2);
- qFreeAligned(storage2);
-
- QVERIFY(QMetaType::construct(ID, 0, /*copy=*/0) == 0);
- QMetaType::destruct(ID, 0);
-
- QVERIFY(info.construct(0, /*copy=*/0) == 0);
- info.destruct(0);
+ QCOMPARE(*static_cast<Type *>(actual2), *expected);
+ QCOMPARE(info.construct(nullptr, /*copy=*/nullptr), nullptr);
+ info.destruct(nullptr);
}
template<>
void testConstructHelper<QMetaType::Void>()
{
- /*int size = */ QMetaType::sizeOf(QMetaType::Void);
- void *storage = 0;
- void *actual = QMetaType::construct(QMetaType::Void, storage, /*copy=*/0);
- QCOMPARE(actual, storage);
- if (DefaultValueTraits<QMetaType::Void>::IsInitialized) {
- QVERIFY(DefaultValueFactory<QMetaType::Void>::create());
- }
- QMetaType::destruct(QMetaType::Void, actual);
- qFreeAligned(storage);
-
- QVERIFY(QMetaType::construct(QMetaType::Void, 0, /*copy=*/0) == 0);
- QMetaType::destruct(QMetaType::Void, 0);
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ void *storage1 = nullptr;
+ void *actual1 = QMetaType::construct(QMetaType::Void, storage1, /*copy=*/nullptr);
+ auto cleanup1 = qScopeGuard([storage1, actual1]() {
+ QMetaType::destruct(QMetaType::Void, actual1);
+ qFreeAligned(storage1);
+ });
+ QCOMPARE(actual1, storage1);
+ QCOMPARE(QMetaType::construct(QMetaType::Void, nullptr, /*copy=*/nullptr), nullptr);
+ QMetaType::destruct(QMetaType::Void, nullptr);
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
+ QMetaType info(QMetaType::Void);
+ void *storage2 = nullptr;
+ void *actual2 = info.construct(storage2, /*copy=*/nullptr);
+ auto cleanup2 = qScopeGuard([&info, storage2, actual2]() {
+ info.destruct(actual2);
+ qFreeAligned(storage2);
+ });
+ QCOMPARE(actual2, storage2);
+ QVERIFY(info.construct(nullptr, /*copy=*/nullptr) == nullptr);
+ info.destruct(nullptr);
}
void tst_QMetaType::construct()
@@ -1255,6 +1325,11 @@ void tst_QMetaType::construct()
static TypeTestFunction get(int type)
{
switch (type) {
+ case QMetaType::UnknownType:
+ return []() {
+ char buf[1];
+ QCOMPARE(QMetaType().construct(&buf), nullptr);
+ };
#define RETURN_CONSTRUCT_FUNCTION(MetaTypeName, MetaTypeId, RealType) \
case QMetaType::MetaTypeName: \
return testConstructHelper<QMetaType::MetaTypeName>;
@@ -1269,11 +1344,137 @@ FOR_EACH_CORE_METATYPE(RETURN_CONSTRUCT_FUNCTION)
TypeTestFunctionGetter::get(type)();
}
+
+namespace TriviallyConstructibleTests {
+
+enum Enum0 {};
+enum class Enum1 {};
+
+static_assert(QTypeInfo<int>::isValueInitializationBitwiseZero);
+static_assert(QTypeInfo<double>::isValueInitializationBitwiseZero);
+static_assert(QTypeInfo<Enum0>::isValueInitializationBitwiseZero);
+static_assert(QTypeInfo<Enum1>::isValueInitializationBitwiseZero);
+static_assert(QTypeInfo<int *>::isValueInitializationBitwiseZero);
+static_assert(QTypeInfo<void *>::isValueInitializationBitwiseZero);
+static_assert(QTypeInfo<std::nullptr_t>::isValueInitializationBitwiseZero);
+
+struct A {};
+struct B { B() {} };
+struct C { ~C() {} };
+struct D { D(int) {} };
+struct E { E() {} ~E() {} };
+struct F { int i; };
+struct G { G() : i(0) {} int i; };
+struct H { constexpr H() : i(0) {} int i; };
+struct I { I() : i(42) {} int i; };
+struct J { constexpr J() : i(42) {} int i; };
+struct K { K() : i(0) {} ~K() {} int i; };
+
+static_assert(!QTypeInfo<A>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<B>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<C>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<D>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<E>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<F>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<G>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<H>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<I>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<J>::isValueInitializationBitwiseZero);
+static_assert(!QTypeInfo<K>::isValueInitializationBitwiseZero);
+
+} // namespace TriviallyConstructibleTests
+
+// Value-initializing these trivially constructible types cannot be achieved by
+// memset(0) into their storage. For instance, on Itanium, a pointer to a data
+// member needs to be value-initialized by setting it to -1.
+
+// Fits into QVariant
+struct TrivialTypeNotZeroInitableSmall {
+ int TrivialTypeNotZeroInitableSmall::*pdm;
+};
+
+static_assert(std::is_trivially_default_constructible_v<TrivialTypeNotZeroInitableSmall>);
+static_assert(!QTypeInfo<TrivialTypeNotZeroInitableSmall>::isValueInitializationBitwiseZero);
+static_assert(sizeof(TrivialTypeNotZeroInitableSmall) < sizeof(QVariant)); // also checked more thoroughly below
+
+// Does not fit into QVariant internal storage
+struct TrivialTypeNotZeroInitableBig {
+ int a;
+ double b;
+ char c;
+ int array[42];
+ void (TrivialTypeNotZeroInitableBig::*pmf)();
+ int TrivialTypeNotZeroInitableBig::*pdm;
+};
+
+static_assert(std::is_trivially_default_constructible_v<TrivialTypeNotZeroInitableBig>);
+static_assert(!QTypeInfo<TrivialTypeNotZeroInitableSmall>::isValueInitializationBitwiseZero);
+static_assert(sizeof(TrivialTypeNotZeroInitableBig) > sizeof(QVariant)); // also checked more thoroughly below
+
+void tst_QMetaType::defaultConstructTrivial_QTBUG_109594()
+{
+ // MSVC miscompiles value-initialization of pointers to data members,
+ // https://developercommunity.visualstudio.com/t/Pointer-to-data-member-is-not-initialize/10238905
+ {
+ QMetaType mt = QMetaType::fromType<TrivialTypeNotZeroInitableSmall>();
+ QVERIFY(mt.isDefaultConstructible());
+ auto ptr = static_cast<TrivialTypeNotZeroInitableSmall *>(mt.create());
+ const auto cleanup = qScopeGuard([=] {
+ mt.destroy(ptr);
+ });
+#ifdef Q_CC_MSVC_ONLY
+ QEXPECT_FAIL("", "MSVC compiler bug", Continue);
+#endif
+ QCOMPARE(ptr->pdm, nullptr);
+
+ QVariant v(mt);
+ QVERIFY(QVariant::Private::canUseInternalSpace(mt.iface()));
+ auto obj = v.value<TrivialTypeNotZeroInitableSmall>();
+#ifdef Q_CC_MSVC_ONLY
+ QEXPECT_FAIL("", "MSVC compiler bug", Continue);
+#endif
+ QCOMPARE(obj.pdm, nullptr);
+ }
+
+ {
+ QMetaType mt = QMetaType::fromType<TrivialTypeNotZeroInitableBig>();
+ QVERIFY(mt.isDefaultConstructible());
+ auto ptr = static_cast<TrivialTypeNotZeroInitableBig *>(mt.create());
+ const auto cleanup = qScopeGuard([=] {
+ mt.destroy(ptr);
+ });
+ QCOMPARE(ptr->a, 0);
+ QCOMPARE(ptr->b, 0.0);
+ QCOMPARE(ptr->c, '\0');
+ QCOMPARE(ptr->pmf, nullptr);
+ for (int i : ptr->array)
+ QCOMPARE(i, 0);
+#ifdef Q_CC_MSVC_ONLY
+ QEXPECT_FAIL("", "MSVC compiler bug", Continue);
+#endif
+ QCOMPARE(ptr->pdm, nullptr);
+
+ QVariant v(mt);
+ QVERIFY(!QVariant::Private::canUseInternalSpace(mt.iface()));
+ auto obj = v.value<TrivialTypeNotZeroInitableBig>();
+ QCOMPARE(obj.a, 0);
+ QCOMPARE(obj.b, 0.0);
+ QCOMPARE(obj.c, '\0');
+ QCOMPARE(obj.pmf, nullptr);
+ for (int i : obj.array)
+ QCOMPARE(i, 0);
+#ifdef Q_CC_MSVC_ONLY
+ QEXPECT_FAIL("", "MSVC compiler bug", Continue);
+#endif
+ QCOMPARE(obj.pdm, nullptr);
+ }
+}
+
void tst_QMetaType::typedConstruct()
{
auto testMetaObjectWriteOnGadget = [](QVariant &gadget, const QList<GadgetPropertyType> &properties)
{
- auto metaObject = QMetaType::metaObjectForType(gadget.userType());
+ auto metaObject = QMetaType(gadget.userType()).metaObject();
QVERIFY(metaObject != nullptr);
QCOMPARE(metaObject->methodCount(), 0);
QCOMPARE(metaObject->propertyCount(), properties.size());
@@ -1287,7 +1488,7 @@ void tst_QMetaType::typedConstruct()
auto testMetaObjectReadOnGadget = [](QVariant gadget, const QList<GadgetPropertyType> &properties)
{
- auto metaObject = QMetaType::metaObjectForType(gadget.userType());
+ auto metaObject = QMetaType(gadget.userType()).metaObject();
QVERIFY(metaObject != nullptr);
QCOMPARE(metaObject->methodCount(), 0);
QCOMPARE(metaObject->propertyCount(), properties.size());
@@ -1295,7 +1496,7 @@ void tst_QMetaType::typedConstruct()
auto prop = metaObject->property(i);
QCOMPARE(properties[i].name, prop.name());
QCOMPARE(properties[i].type, prop.typeName());
- if (!QMetaType::typeFlags(prop.userType()).testFlag(QMetaType::IsGadget))
+ if (!QMetaType(prop.userType()).flags().testFlag(QMetaType::IsGadget))
QCOMPARE(properties[i].testData, prop.readOnGadget(gadget.constData()));
}
};
@@ -1307,7 +1508,7 @@ void tst_QMetaType::typedConstruct()
};
registerGadget("DynamicGadget1", dynamicGadget1);
- QVariant testGadget1(QMetaType(QMetaType::type("DynamicGadget1")));
+ QVariant testGadget1(QMetaType::fromName("DynamicGadget1"));
testMetaObjectWriteOnGadget(testGadget1, dynamicGadget1);
testMetaObjectReadOnGadget(testGadget1, dynamicGadget1);
@@ -1319,10 +1520,10 @@ void tst_QMetaType::typedConstruct()
{"DynamicGadget1", "dynamicGadget1_prop", testGadget1}
};
registerGadget("DynamicGadget2", dynamicGadget2);
- QVariant testGadget2(QMetaType(QMetaType::type("DynamicGadget2")));
+ QVariant testGadget2(QMetaType::fromName("DynamicGadget2"));
testMetaObjectWriteOnGadget(testGadget2, dynamicGadget2);
testMetaObjectReadOnGadget(testGadget2, dynamicGadget2);
- auto g2mo = QMetaType::metaObjectForType(testGadget2.userType());
+ auto g2mo = QMetaType(testGadget2.userType()).metaObject();
auto dynamicGadget1_prop = g2mo->property(g2mo->indexOfProperty("dynamicGadget1_prop"));
testMetaObjectReadOnGadget(dynamicGadget1_prop.readOnGadget(testGadget2.constData()), dynamicGadget1);
@@ -1334,7 +1535,7 @@ void tst_QMetaType::typedConstruct()
dynamicGadgetProperties->podData = myPodTesData;
const auto flags = QMetaType::NeedsConstruction | QMetaType::NeedsDestruction;
using TypeInfo = QtPrivate::QMetaTypeInterface;
- auto typeInfo = new TypeInfo {
+ auto typeInfo = s_metaTypeInterfaces.emplace_back(new TypeInfo {
0, alignof(GenericGadgetType), sizeof(GenericGadgetType), uint(flags), 0, nullptr, podTypeName,
[](const TypeInfo *self, void *where) { GadgetTypedConstructor(self->typeId, where, nullptr); },
[](const TypeInfo *self, void *where, const void *copy) { GadgetTypedConstructor(self->typeId, where, copy); },
@@ -1346,7 +1547,7 @@ void tst_QMetaType::typedConstruct()
GadgetSaveOperator,
GadgetLoadOperator,
nullptr
- };
+ }).get();
QMetaType metatype(typeInfo);
dynamicGadgetProperties->m_metatype = metatype;
int podTypeId = metatype.id();
@@ -1354,7 +1555,7 @@ void tst_QMetaType::typedConstruct()
s_managedTypes[podTypeId] = qMakePair(dynamicGadgetProperties, std::shared_ptr<QMetaObject>{});
// Test POD
- QCOMPARE(podTypeId, QMetaType::type(podTypeName));
+ QCOMPARE(podTypeId, QMetaType::fromName(podTypeName).id());
QVariant podVariant{QMetaType(podTypeId)};
QCOMPARE(myPodTesData, static_cast<const GenericPODType *>(reinterpret_cast<const BaseGenericType *>(podVariant.constData()))->podData);
@@ -1368,27 +1569,32 @@ template<int ID>
static void testConstructCopyHelper()
{
typedef typename MetaEnumToType<ID>::Type Type;
- Type *expected = TestValueFactory<ID>::create();
+ auto expected = std::unique_ptr<Type>(TestValueFactory<ID>::create());
QMetaType info(ID);
- int size = QMetaType::sizeOf(ID);
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ const int size = QMetaType::sizeOf(ID);
QCOMPARE(info.sizeOf(), size);
void *storage1 = qMallocAligned(size, alignof(Type));
- void *actual1 = QMetaType::construct(ID, storage1, expected);
- void *storage2 = qMallocAligned(size, alignof(Type));
- void *actual2 = info.construct(storage2, expected);
+ void *actual1 = QMetaType::construct(ID, storage1, expected.get());
+ auto cleanup1 = qScopeGuard([storage1, actual1]() {
+ QMetaType::destruct(ID, actual1);
+ qFreeAligned(storage1);
+ });
QCOMPARE(actual1, storage1);
- QCOMPARE(actual2, storage2);
QCOMPARE(*static_cast<Type *>(actual1), *expected);
+ QCOMPARE(QMetaType::construct(ID, nullptr, nullptr), nullptr);
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
+ void *storage2 = qMallocAligned(info.sizeOf(), alignof(Type));
+ void *actual2 = info.construct(storage2, expected.get());
+ auto cleanup2 = qScopeGuard([&info, storage2, actual2]() {
+ info.destruct(actual2);
+ qFreeAligned(storage2);
+ });
+ QCOMPARE(actual2, storage2);
QCOMPARE(*static_cast<Type *>(actual2), *expected);
- QMetaType::destruct(ID, actual1);
- qFreeAligned(storage1);
- info.destruct(actual2);
- qFreeAligned(storage2);
-
- QVERIFY(QMetaType::construct(ID, 0, expected) == 0);
- QVERIFY(info.construct(0, expected) == 0);
-
- delete expected;
+ QCOMPARE(info.construct(nullptr, expected.get()), nullptr);
}
template<>
@@ -1396,14 +1602,28 @@ void testConstructCopyHelper<QMetaType::Void>()
{
typedef MetaEnumToType<QMetaType::Void>::Type Type;
Type *expected = TestValueFactory<QMetaType::Void>::create();
- /* int size = */QMetaType::sizeOf(QMetaType::Void);
- void *storage = 0;
- void *actual = QMetaType::construct(QMetaType::Void, storage, expected);
- QCOMPARE(actual, storage);
- QMetaType::destruct(QMetaType::Void, actual);
- qFreeAligned(storage);
-
- QVERIFY(QMetaType::construct(QMetaType::Void, 0, expected) == 0);
+ QCOMPARE(expected, nullptr); // we do not need to delete it
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ void *storage1 = nullptr;
+ void *actual1 = QMetaType::construct(QMetaType::Void, storage1, expected);
+ auto cleanup1 = qScopeGuard([storage1, actual1]() {
+ QMetaType::destruct(QMetaType::Void, actual1);
+ qFreeAligned(storage1);
+ });
+ QCOMPARE(actual1, storage1);
+ QCOMPARE(QMetaType::construct(QMetaType::Void, nullptr, nullptr), nullptr);
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
+ QMetaType info(QMetaType::Void);
+ void *storage2 = nullptr;
+ void *actual2 = info.construct(storage2, expected);
+ auto cleanup2 = qScopeGuard([&info, storage2, actual2]() {
+ info.destruct(actual2);
+ qFreeAligned(storage2);
+ });
+ QCOMPARE(actual2, storage2);
+ QCOMPARE(info.construct(nullptr, expected), nullptr);
}
void tst_QMetaType::constructCopy_data()
@@ -1418,6 +1638,11 @@ void tst_QMetaType::constructCopy()
static TypeTestFunction get(int type)
{
switch (type) {
+ case QMetaType::UnknownType:
+ return []() {
+ char buf[1], buf2[1] = {};
+ QCOMPARE(QMetaType().construct(&buf, &buf2), nullptr);
+ };
#define RETURN_CONSTRUCT_COPY_FUNCTION(MetaTypeName, MetaTypeId, RealType) \
case QMetaType::MetaTypeName: \
return testConstructCopyHelper<QMetaType::MetaTypeName>;
@@ -1432,47 +1657,106 @@ FOR_EACH_CORE_METATYPE(RETURN_CONSTRUCT_COPY_FUNCTION)
TypeTestFunctionGetter::get(type)();
}
+void tst_QMetaType::selfCompare_data()
+{
+ qRegisterMetaType<QPartialOrdering>();
+ QTest::addColumn<int>("type");
+ QTest::addColumn<QPartialOrdering>("order");
+
+ auto orderingFor = [](QMetaType::Type t) {
+ if (t == QMetaType::UnknownType || t == QMetaType::Void)
+ return QPartialOrdering::Unordered;
+ return QPartialOrdering::Equivalent;
+ };
+
+ QTest::newRow("unknown-type") << int(QMetaType::UnknownType) << orderingFor(QMetaType::UnknownType);
+
+#define ADD_METATYPE_TEST_ROW(MetaTypeName, MetaTypeId, RealType) \
+ QTest::newRow(QMetaType(QMetaType::MetaTypeName).name()) << int(QMetaType::MetaTypeName) << orderingFor(QMetaType::MetaTypeName);
+FOR_EACH_CORE_METATYPE(ADD_METATYPE_TEST_ROW)
+#undef ADD_METATYPE_TEST_ROW
+}
+
+void tst_QMetaType::selfCompare()
+{
+ QFETCH(int, type);
+ QFETCH(QPartialOrdering, order);
+
+ QMetaType t(type);
+ void *v1 = t.create(nullptr);
+ void *v2 = t.create(nullptr);
+ auto scope = qScopeGuard([=] {
+ t.destroy(v1);
+ t.destroy(v2);
+ });
+
+ // all these types have an equality comparator
+ QCOMPARE(t.equals(v1, v2), order == QPartialOrdering::Equivalent);
+
+ if (t.iface() && t.iface()->lessThan)
+ QCOMPARE(t.compare(v1, v2), order);
+
+ // for the primitive types, do a memcmp() too
+ switch (type) {
+ default:
+ break;
+
+#define ADD_METATYPE_CASE(MetaTypeName, MetaTypeId, RealType) \
+ case QMetaType::MetaTypeName:
+FOR_EACH_PRIMITIVE_METATYPE(ADD_METATYPE_CASE)
+#undef ADD_METATYPE_CASE
+ QCOMPARE(memcmp(v1, v2, t.sizeOf()), 0);
+ }
+}
+
typedef QString CustomString;
Q_DECLARE_METATYPE(CustomString) //this line is useless
void tst_QMetaType::typedefs()
{
- QCOMPARE(QMetaType::type("long long"), int(QMetaType::LongLong));
- QCOMPARE(QMetaType::type("unsigned long long"), int(QMetaType::ULongLong));
- QCOMPARE(QMetaType::type("qint8"), int(QMetaType::SChar));
- QCOMPARE(QMetaType::type("quint8"), int(QMetaType::UChar));
- QCOMPARE(QMetaType::type("qint16"), int(QMetaType::Short));
- QCOMPARE(QMetaType::type("quint16"), int(QMetaType::UShort));
- QCOMPARE(QMetaType::type("qint32"), int(QMetaType::Int));
- QCOMPARE(QMetaType::type("quint32"), int(QMetaType::UInt));
- QCOMPARE(QMetaType::type("qint64"), int(QMetaType::LongLong));
- QCOMPARE(QMetaType::type("quint64"), int(QMetaType::ULongLong));
+ QCOMPARE(QMetaType::fromName("long long").id(), int(QMetaType::LongLong));
+ QCOMPARE(QMetaType::fromName("unsigned long long").id(), int(QMetaType::ULongLong));
+ QCOMPARE(QMetaType::fromName("qint8").id(), int(QMetaType::SChar));
+ QCOMPARE(QMetaType::fromName("quint8").id(), int(QMetaType::UChar));
+ QCOMPARE(QMetaType::fromName("qint16").id(), int(QMetaType::Short));
+ QCOMPARE(QMetaType::fromName("quint16").id(), int(QMetaType::UShort));
+ QCOMPARE(QMetaType::fromName("qint32").id(), int(QMetaType::Int));
+ QCOMPARE(QMetaType::fromName("quint32").id(), int(QMetaType::UInt));
+ QCOMPARE(QMetaType::fromName("qint64").id(), int(QMetaType::LongLong));
+ QCOMPARE(QMetaType::fromName("quint64").id(), int(QMetaType::ULongLong));
// make sure the qreal typeId is the type id of the type it's defined to
- QCOMPARE(QMetaType::type("qreal"), ::qMetaTypeId<qreal>());
+ QCOMPARE(QMetaType::fromName("qreal").id(), ::qMetaTypeId<qreal>());
qRegisterMetaType<CustomString>("CustomString");
- QCOMPARE(QMetaType::type("CustomString"), ::qMetaTypeId<CustomString>());
+ QCOMPARE(QMetaType::fromName("CustomString").id(), ::qMetaTypeId<CustomString>());
typedef Whity<double> WhityDouble;
qRegisterMetaType<WhityDouble>("WhityDouble");
- QCOMPARE(QMetaType::type("WhityDouble"), ::qMetaTypeId<WhityDouble>());
+ QCOMPARE(QMetaType::fromName("WhityDouble").id(), ::qMetaTypeId<WhityDouble>());
}
+struct RegisterTypeType {};
+
void tst_QMetaType::registerType()
{
// Built-in
QCOMPARE(qRegisterMetaType<QString>("QString"), int(QMetaType::QString));
QCOMPARE(qRegisterMetaType<QString>("QString"), int(QMetaType::QString));
+ qRegisterMetaType(QMetaType::fromType<QString>());
// Custom
int fooId = qRegisterMetaType<TestSpace::Foo>("TestSpace::Foo");
QVERIFY(fooId >= int(QMetaType::User));
QCOMPARE(qRegisterMetaType<TestSpace::Foo>("TestSpace::Foo"), fooId);
+ qRegisterMetaType(QMetaType::fromType<TestSpace::Foo>());
int movableId = qRegisterMetaType<CustomMovable>("CustomMovable");
QVERIFY(movableId >= int(QMetaType::User));
QCOMPARE(qRegisterMetaType<CustomMovable>("CustomMovable"), movableId);
+ qRegisterMetaType(QMetaType::fromType<CustomMovable>());
+
+ // Aliases are deprecated
// Alias to built-in
typedef QString MyString;
@@ -1480,7 +1764,7 @@ void tst_QMetaType::registerType()
QCOMPARE(qRegisterMetaType<MyString>("MyString"), int(QMetaType::QString));
QCOMPARE(qRegisterMetaType<MyString>("MyString"), int(QMetaType::QString));
- QCOMPARE(QMetaType::type("MyString"), int(QMetaType::QString));
+ QCOMPARE(QMetaType::fromType<MyString>().id(), int(QMetaType::QString));
// Alias to custom type
typedef CustomMovable MyMovable;
@@ -1489,12 +1773,29 @@ void tst_QMetaType::registerType()
QCOMPARE(qRegisterMetaType<MyMovable>("MyMovable"), movableId);
QCOMPARE(qRegisterMetaType<MyMovable>("MyMovable"), movableId);
- QCOMPARE(QMetaType::type("MyMovable"), movableId);
+ QCOMPARE(QMetaType::fromType<MyMovable>().id(), movableId);
QCOMPARE(qRegisterMetaType<MyFoo>("MyFoo"), fooId);
QCOMPARE(qRegisterMetaType<MyFoo>("MyFoo"), fooId);
- QCOMPARE(QMetaType::type("MyFoo"), fooId);
+ QCOMPARE(QMetaType::fromType<MyFoo>().id(), fooId);
+
+ // this portion of the test can only be run once
+ static bool typeWasRegistered = false;
+ if (!typeWasRegistered) {
+ QMetaType mt = QMetaType::fromType<RegisterTypeType>();
+ QVERIFY(mt.isValid());
+ QCOMPARE_NE(mt.name(), nullptr);
+
+ QVERIFY(!mt.isRegistered());
+ QVERIFY(!QMetaType::fromName(mt.name()).isValid());
+
+ QCOMPARE_GT(qRegisterMetaType(mt), 0);
+ typeWasRegistered = true;
+
+ QVERIFY(mt.isRegistered());
+ QVERIFY(QMetaType::fromName(mt.name()).isValid());
+ }
}
class IsRegisteredDummyType { };
@@ -1515,7 +1816,7 @@ void tst_QMetaType::isRegistered_data()
// unknown types
QTest::newRow("-1") << -1 << false;
QTest::newRow("-42") << -42 << false;
- QTest::newRow("IsRegisteredDummyType + 1") << (dummyTypeId + 1) << false;
+ QTest::newRow("IsRegisteredDummyType + 1000") << (dummyTypeId + 1000) << false;
QTest::newRow("QMetaType::UnknownType") << int(QMetaType::UnknownType) << false;
}
@@ -1538,25 +1839,77 @@ Q_DECLARE_METATYPE(isEnumTest_Enum1)
void tst_QMetaType::isEnum()
{
int type0 = qRegisterMetaType<int>("int");
- QVERIFY((QMetaType::typeFlags(type0) & QMetaType::IsEnumeration) == 0);
+ QVERIFY((QMetaType(type0).flags() & QMetaType::IsEnumeration) == 0);
int type1 = qRegisterMetaType<isEnumTest_Enum0>("isEnumTest_Enum0");
- QVERIFY((QMetaType::typeFlags(type1) & QMetaType::IsEnumeration) == QMetaType::IsEnumeration);
+ QVERIFY((QMetaType(type1).flags() & QMetaType::IsEnumeration) == QMetaType::IsEnumeration);
int type2 = qRegisterMetaType<isEnumTest_Struct0>("isEnumTest_Struct0");
- QVERIFY((QMetaType::typeFlags(type2) & QMetaType::IsEnumeration) == 0);
+ QVERIFY((QMetaType(type2).flags() & QMetaType::IsEnumeration) == 0);
int type3 = qRegisterMetaType<isEnumTest_Enum0 *>("isEnumTest_Enum0 *");
- QVERIFY((QMetaType::typeFlags(type3) & QMetaType::IsEnumeration) == 0);
+ QVERIFY((QMetaType(type3).flags() & QMetaType::IsEnumeration) == 0);
int type4 = qRegisterMetaType<isEnumTest_Struct0::A>("isEnumTest_Struct0::A");
- QVERIFY((QMetaType::typeFlags(type4) & QMetaType::IsEnumeration) == QMetaType::IsEnumeration);
+ QVERIFY((QMetaType(type4).flags() & QMetaType::IsEnumeration) == QMetaType::IsEnumeration);
int type5 = ::qMetaTypeId<isEnumTest_Struct1>();
- QVERIFY((QMetaType::typeFlags(type5) & QMetaType::IsEnumeration) == 0);
+ QVERIFY((QMetaType(type5).flags() & QMetaType::IsEnumeration) == 0);
int type6 = ::qMetaTypeId<isEnumTest_Enum1>();
- QVERIFY((QMetaType::typeFlags(type6) & QMetaType::IsEnumeration) == QMetaType::IsEnumeration);
+ QVERIFY((QMetaType(type6).flags() & QMetaType::IsEnumeration) == QMetaType::IsEnumeration);
+}
+
+enum E1 : unsigned char {};
+enum E2 : qlonglong {};
+enum class E3 : unsigned short {};
+
+namespace myflags {
+
+ Q_NAMESPACE
+
+ enum Flag1 : int { A, B };
+ enum Flag2 : short { X, Y };
+
+ Q_DECLARE_FLAGS(Flags1, myflags::Flag1);
+ Q_FLAG_NS(Flags1)
+ Q_DECLARE_FLAGS(Flags2, myflags::Flag2);
+ Q_FLAG_NS(Flags2)
+
+}
+
+template <typename T>
+using getUnderlyingTypeNormalized = std::conditional_t<
+ std::is_signed_v<std::underlying_type_t<T>>,
+ typename QIntegerForSize<sizeof(T)>::Signed,
+ typename QIntegerForSize<sizeof(T)>::Unsigned
+>;
+
+void tst_QMetaType::underlyingType_data()
+{
+ QTest::addColumn<QMetaType>("source");
+ QTest::addColumn<QMetaType>("underlying");
+
+ QTest::newRow("invalid") << QMetaType() << QMetaType();
+ QTest::newRow("plain") << QMetaType::fromType<isEnumTest_Enum1>()
+ << QMetaType::fromType<getUnderlyingTypeNormalized<isEnumTest_Enum1>>();
+ QTest::newRow("uchar") << QMetaType::fromType<E1>()
+ << QMetaType::fromType<getUnderlyingTypeNormalized<E1>>();
+ QTest::newRow("long") << QMetaType::fromType<E2>()
+ << QMetaType::fromType<getUnderlyingTypeNormalized<E2>>();
+ QTest::newRow("class_ushort") << QMetaType::fromType<E3>()
+ << QMetaType::fromType<getUnderlyingTypeNormalized<E3>>();
+ QTest::newRow("flags_int") << QMetaType::fromType<myflags::Flags1>()
+ << QMetaType::fromType<int>();
+ QTest::newRow("flags_short") << QMetaType::fromType<myflags::Flags2>()
+ << QMetaType::fromType<int>(); // sic, not short!
+}
+
+void tst_QMetaType::underlyingType()
+{
+ QFETCH(QMetaType, source);
+ QFETCH(QMetaType, underlying);
+ QCOMPARE(source.underlyingType(), underlying);
}
void tst_QMetaType::isRegisteredStaticLess_data()
@@ -1568,9 +1921,16 @@ void tst_QMetaType::isRegisteredStaticLess()
{
QFETCH(int, typeId);
QFETCH(bool, registered);
+ ignoreInvalidMetaTypeWarning(typeId);
QCOMPARE(QMetaType(typeId).isRegistered(), registered);
}
+struct NotARegisteredType {};
+void tst_QMetaType::isNotRegistered()
+{
+ QVERIFY(!QMetaType::fromType<NotARegisteredType>().isRegistered());
+}
+
typedef QHash<int, uint> IntUIntHash;
Q_DECLARE_METATYPE(IntUIntHash)
typedef QMap<int, uint> IntUIntMap;
@@ -1605,7 +1965,7 @@ class AutoMetaTypeObject : public QObject
Q_PROPERTY(IntIntHash someHash READ someHash CONSTANT)
Q_PROPERTY(NaturalNumber someInt READ someInt CONSTANT)
public:
- AutoMetaTypeObject(QObject *parent = 0)
+ AutoMetaTypeObject(QObject *parent = nullptr)
: QObject(parent), m_int(42)
{
m_hash.insert(4, 2);
@@ -1630,7 +1990,7 @@ class MyObject : public QObject
{
Q_OBJECT
public:
- MyObject(QObject *parent = 0)
+ MyObject(QObject *parent = nullptr)
: QObject(parent)
{
}
@@ -1638,30 +1998,7 @@ public:
typedef MyObject* MyObjectPtr;
Q_DECLARE_METATYPE(MyObjectPtr)
-#if !defined(TST_QMETATYPE_BROKEN_COMPILER)
-static QByteArray createTypeName(const char *begin, const char *va)
-{
- QByteArray tn(begin);
- const QList<QByteArray> args = QByteArray(va).split(',');
- tn += args.first().trimmed();
- if (args.size() > 1) {
- QList<QByteArray>::const_iterator it = args.constBegin() + 1;
- const QList<QByteArray>::const_iterator end = args.constEnd();
- for (; it != end; ++it) {
- tn += ",";
- tn += it->trimmed();
- }
- }
- if (tn.endsWith('>'))
- tn += ' ';
- tn += '>';
- return tn;
-}
-#endif
-
-Q_DECLARE_METATYPE(const void*)
-
-void tst_QMetaType::automaticTemplateRegistration()
+void tst_QMetaType::automaticTemplateRegistration_1()
{
#define TEST_SEQUENTIAL_CONTAINER(CONTAINER, VALUE_TYPE) \
{ \
@@ -1781,7 +2118,7 @@ void tst_QMetaType::automaticTemplateRegistration()
{
typedef std::map<int, CustomObject*> StdMapIntCustomObject ;
StdMapIntCustomObject intComparableMap;
- CustomObject *o = 0;
+ CustomObject *o = nullptr;
intComparableMap[4] = o;
QCOMPARE(QVariant::fromValue(intComparableMap).value<StdMapIntCustomObject >()[4], o);
}
@@ -1822,7 +2159,7 @@ void tst_QMetaType::automaticTemplateRegistration()
}
{
typedef std::pair<int, CustomQObject*> StdIntComparablePair;
- CustomQObject* o = 0;
+ CustomQObject *o = nullptr;
StdIntComparablePair intComparablePair = std::make_pair(4, o);
QCOMPARE(QVariant::fromValue(intComparablePair).value<StdIntComparablePair>().first, 4);
QCOMPARE(QVariant::fromValue(intComparablePair).value<StdIntComparablePair>().second, o);
@@ -1836,62 +2173,6 @@ void tst_QMetaType::automaticTemplateRegistration()
QVERIFY(qRegisterMetaType<UnregisteredTypeList>("UnregisteredTypeList") > 0);
}
-#if !defined(TST_QMETATYPE_BROKEN_COMPILER)
-
- #define FOR_EACH_STATIC_PRIMITIVE_TYPE(F) \
- F(bool) \
- F(int) \
- F(qulonglong) \
- F(double) \
- F(short) \
- F(char) \
- F(ulong) \
- F(uchar) \
- F(float) \
- F(QObject*) \
- F(QString) \
- F(CustomMovable)
-
- #define FOR_EACH_STATIC_PRIMITIVE_TYPE2(F, SecondaryRealName) \
- F(uint, SecondaryRealName) \
- F(qlonglong, SecondaryRealName) \
- F(char, SecondaryRealName) \
- F(uchar, SecondaryRealName) \
- F(QObject*, SecondaryRealName)
-
- #define CREATE_AND_VERIFY_CONTAINER(CONTAINER, ...) \
- { \
- CONTAINER< __VA_ARGS__ > t; \
- const QVariant v = QVariant::fromValue(t); \
- QByteArray tn = createTypeName(#CONTAINER "<", #__VA_ARGS__); \
- const int expectedType = ::qMetaTypeId<CONTAINER< __VA_ARGS__ > >(); \
- const int type = QMetaType::type(tn); \
- QCOMPARE(type, expectedType); \
- QCOMPARE((QMetaType::fromType<CONTAINER< __VA_ARGS__ >>().id()), expectedType); \
- }
-
- #define FOR_EACH_1ARG_TEMPLATE_TYPE(F, TYPE) \
- F(QList, TYPE) \
- F(QQueue, TYPE) \
- F(QStack, TYPE) \
- F(QSet, TYPE)
-
- #define PRINT_1ARG_TEMPLATE(RealName) \
- FOR_EACH_1ARG_TEMPLATE_TYPE(CREATE_AND_VERIFY_CONTAINER, RealName)
-
- #define FOR_EACH_2ARG_TEMPLATE_TYPE(F, RealName1, RealName2) \
- F(QHash, RealName1, RealName2) \
- F(QMap, RealName1, RealName2) \
- F(std::pair, RealName1, RealName2)
-
- #define PRINT_2ARG_TEMPLATE_INTERNAL(RealName1, RealName2) \
- FOR_EACH_2ARG_TEMPLATE_TYPE(CREATE_AND_VERIFY_CONTAINER, RealName1, RealName2)
-
- #define PRINT_2ARG_TEMPLATE(RealName) \
- FOR_EACH_STATIC_PRIMITIVE_TYPE2(PRINT_2ARG_TEMPLATE_INTERNAL, RealName)
-
- #define REGISTER_TYPEDEF(TYPE, ARG1, ARG2) \
- qRegisterMetaType<TYPE <ARG1, ARG2>>(#TYPE "<" #ARG1 "," #ARG2 ">");
REGISTER_TYPEDEF(QHash, int, uint)
REGISTER_TYPEDEF(QMap, int, uint)
@@ -1900,9 +2181,6 @@ void tst_QMetaType::automaticTemplateRegistration()
FOR_EACH_STATIC_PRIMITIVE_TYPE(
PRINT_1ARG_TEMPLATE
)
- FOR_EACH_STATIC_PRIMITIVE_TYPE(
- PRINT_2ARG_TEMPLATE
- )
CREATE_AND_VERIFY_CONTAINER(QList, QList<QMap<int, QHash<char, QList<QVariant>>>>)
CREATE_AND_VERIFY_CONTAINER(QList, void*)
@@ -1912,15 +2190,13 @@ void tst_QMetaType::automaticTemplateRegistration()
CREATE_AND_VERIFY_CONTAINER(QHash, void*, void*)
CREATE_AND_VERIFY_CONTAINER(QHash, const void*, const void*)
-#endif // !defined(TST_QMETATYPE_BROKEN_COMPILER)
-
#define TEST_OWNING_SMARTPOINTER(SMARTPOINTER, ELEMENT_TYPE, FLAG_TEST, FROMVARIANTFUNCTION) \
{ \
SMARTPOINTER < ELEMENT_TYPE > sp(new ELEMENT_TYPE); \
sp.data()->setObjectName("Test name"); \
QVariant v = QVariant::fromValue(sp); \
QCOMPARE(v.typeName(), #SMARTPOINTER "<" #ELEMENT_TYPE ">"); \
- QVERIFY(QMetaType::typeFlags(::qMetaTypeId<SMARTPOINTER < ELEMENT_TYPE > >()) & QMetaType::FLAG_TEST); \
+ QVERIFY(QMetaType(::qMetaTypeId<SMARTPOINTER < ELEMENT_TYPE > >()).flags() & QMetaType::FLAG_TEST); \
SMARTPOINTER < QObject > extractedPtr = FROMVARIANTFUNCTION<QObject>(v); \
QCOMPARE(extractedPtr.data()->objectName(), sp.data()->objectName()); \
}
@@ -1938,7 +2214,7 @@ void tst_QMetaType::automaticTemplateRegistration()
sp.data()->setObjectName("Test name"); \
QVariant v = QVariant::fromValue(sp); \
QCOMPARE(v.typeName(), #SMARTPOINTER "<" #ELEMENT_TYPE ">"); \
- QVERIFY(QMetaType::typeFlags(::qMetaTypeId<SMARTPOINTER < ELEMENT_TYPE > >()) & QMetaType::FLAG_TEST); \
+ QVERIFY(QMetaType(::qMetaTypeId<SMARTPOINTER < ELEMENT_TYPE > >()).flags() & QMetaType::FLAG_TEST); \
SMARTPOINTER < QObject > extractedPtr = FROMVARIANTFUNCTION<QObject>(v); \
QCOMPARE(extractedPtr.data()->objectName(), sp.data()->objectName()); \
}
@@ -1958,7 +2234,7 @@ void tst_QMetaType::automaticTemplateRegistration()
sp.toStrongRef()->setObjectName("Test name"); \
QVariant v = QVariant::fromValue(sp); \
QCOMPARE(v.typeName(), "QWeakPointer<" #ELEMENT_TYPE ">"); \
- QVERIFY(QMetaType::typeFlags(::qMetaTypeId<QWeakPointer < ELEMENT_TYPE > >()) & QMetaType::FLAG_TEST); \
+ QVERIFY(QMetaType(::qMetaTypeId<QWeakPointer < ELEMENT_TYPE > >()).flags() & QMetaType::FLAG_TEST); \
}
TEST_WEAK_SMARTPOINTER(QObject, WeakPointerToQObject)
@@ -1998,6 +2274,8 @@ void tst_QMetaType::saveAndLoadBuiltin_data()
QTest::addColumn<int>("type");
QTest::addColumn<bool>("isStreamable");
+ QTest::newRow("unknown-type") << int(QMetaType::UnknownType) << false;
+
#define ADD_METATYPE_TEST_ROW(MetaTypeName, MetaTypeId, RealType) \
QTest::newRow(#RealType) << MetaTypeId << bool(StreamingTraits<RealType>::isStreamable);
QT_FOR_EACH_STATIC_TYPE(ADD_METATYPE_TEST_ROW)
@@ -2009,35 +2287,39 @@ void tst_QMetaType::saveAndLoadBuiltin()
QFETCH(int, type);
QFETCH(bool, isStreamable);
- void *value = QMetaType::create(type);
+ QMetaType metaType(type);
+ void *value = metaType.create();
QByteArray ba;
QDataStream stream(&ba, QIODevice::ReadWrite);
- QCOMPARE(QMetaType::save(stream, type, value), isStreamable);
+ QCOMPARE(metaType.save(stream, value), isStreamable);
QCOMPARE(stream.status(), QDataStream::Ok);
if (isStreamable) {
- QVERIFY(QMetaType::load(stream, type, value)); // Hmmm, shouldn't it return false?
+ QVERIFY(metaType.hasRegisteredDataStreamOperators());
+ QVERIFY(metaType.load(stream, value)); // Hmmm, shouldn't it return false?
// std::nullptr_t is nullary: it doesn't actually read anything
if (type != QMetaType::Nullptr)
QCOMPARE(stream.status(), QDataStream::ReadPastEnd);
+ } else {
+ QVERIFY(!metaType.hasRegisteredDataStreamOperators());
}
stream.device()->seek(0);
stream.resetStatus();
- QCOMPARE(QMetaType::load(stream, type, value), isStreamable);
+ QCOMPARE(metaType.load(stream, value), isStreamable);
QCOMPARE(stream.status(), QDataStream::Ok);
if (isStreamable) {
- QVERIFY(QMetaType::load(stream, type, value)); // Hmmm, shouldn't it return false?
+ QVERIFY(metaType.load(stream, value)); // Hmmm, shouldn't it return false?
// std::nullptr_t is nullary: it doesn't actually read anything
if (type != QMetaType::Nullptr)
QCOMPARE(stream.status(), QDataStream::ReadPastEnd);
}
- QMetaType::destroy(type, value);
+ metaType.destroy(value);
}
struct CustomStreamableType
@@ -2066,25 +2348,27 @@ void tst_QMetaType::saveAndLoadCustom()
t.a = 123;
int id = ::qMetaTypeId<CustomStreamableType>();
+ QMetaType metaType(id);
+
QByteArray ba;
QDataStream stream(&ba, QIODevice::ReadWrite);
- QVERIFY(QMetaType::save(stream, id, &t));
+ QVERIFY(metaType.save(stream, &t));
QCOMPARE(stream.status(), QDataStream::Ok);
CustomStreamableType t2;
t2.a = -1;
- QVERIFY(QMetaType::load(stream, id, &t2)); // Hmmm, shouldn't it return false?
+ QVERIFY(metaType.load(stream, &t2)); // Hmmm, shouldn't it return false?
QCOMPARE(stream.status(), QDataStream::ReadPastEnd);
QCOMPARE(t2.a, -1);
stream.device()->seek(0);
stream.resetStatus();
- QVERIFY(QMetaType::load(stream, id, &t2));
+ QVERIFY(metaType.load(stream, &t2));
QCOMPARE(stream.status(), QDataStream::Ok);
QCOMPARE(t2.a, t.a);
- QVERIFY(QMetaType::load(stream, id, &t2)); // Hmmm, shouldn't it return false?
+ QVERIFY(metaType.load(stream, &t2)); // Hmmm, shouldn't it return false?
QCOMPARE(stream.status(), QDataStream::ReadPastEnd);
}
@@ -2099,7 +2383,7 @@ class MyQObjectFromGadget : public QObject, public MyGadget
{
Q_OBJECT
public:
- MyQObjectFromGadget(QObject *parent = 0)
+ MyQObjectFromGadget(QObject *parent = nullptr)
: QObject(parent)
{}
};
@@ -2119,8 +2403,10 @@ void tst_QMetaType::metaObject_data()
QTest::addColumn<bool>("isGadgetPtr");
QTest::addColumn<bool>("isQObjectPtr");
+ QTest::newRow("unknown-type") << int(QMetaType::UnknownType) << static_cast<const QMetaObject *>(0) << false << false << false;
QTest::newRow("QObject") << int(QMetaType::QObjectStar) << &QObject::staticMetaObject << false << false << true;
QTest::newRow("QFile*") << ::qMetaTypeId<QFile*>() << &QFile::staticMetaObject << false << false << true;
+ QTest::newRow("MyObject") << ::qMetaTypeId<MyObject>() << &MyObject::staticMetaObject << false << false << false;
QTest::newRow("MyObject*") << ::qMetaTypeId<MyObject*>() << &MyObject::staticMetaObject << false << false << true;
QTest::newRow("int") << int(QMetaType::Int) << static_cast<const QMetaObject *>(0) << false << false << false;
QTest::newRow("QEasingCurve") << ::qMetaTypeId<QEasingCurve>() << &QEasingCurve::staticMetaObject << true << false << false;
@@ -2143,7 +2429,6 @@ void tst_QMetaType::metaObject()
QFETCH(bool, isGadgetPtr);
QFETCH(bool, isQObjectPtr);
- QCOMPARE(QMetaType::metaObjectForType(type), result);
QMetaType mt(type);
QCOMPARE(mt.metaObject(), result);
QCOMPARE(!!(mt.flags() & QMetaType::IsGadget), isGadget);
@@ -2181,7 +2466,6 @@ struct RegisterMetaTypeStruct<qRegisterMetaType< Name >()> \
enum { Value = qRegisterMetaType< Name >() }; \
};
-#if defined(Q_COMPILER_CONSTEXPR)
QT_FOR_EACH_STATIC_TYPE(METATYPE_ID_STRUCT)
QT_FOR_EACH_STATIC_TYPE(REGISTER_METATYPE_STRUCT)
@@ -2196,11 +2480,9 @@ struct RegisterMetaTypeStructDefaultTemplateValue
{
enum { Value };
};
-#endif
void tst_QMetaType::constexprMetaTypeIds()
{
-#if defined(Q_COMPILER_CONSTEXPR)
int id = 0;
int metaType;
@@ -2216,519 +2498,17 @@ void tst_QMetaType::constexprMetaTypeIds()
default:;
}
Q_UNUSED(metaType);
-#else
- QSKIP("The test needs a compiler supporting constexpr");
-#endif
}
-void tst_QMetaType::constRefs()
-{
- QCOMPARE(::qMetaTypeId<const int &>(), ::qMetaTypeId<int>());
- QCOMPARE(::qMetaTypeId<const QString &>(), ::qMetaTypeId<QString>());
- QCOMPARE(::qMetaTypeId<const CustomMovable &>(), ::qMetaTypeId<CustomMovable>());
- QCOMPARE(::qMetaTypeId<const QList<CustomMovable> &>(), ::qMetaTypeId<QList<CustomMovable> >());
-#if defined(Q_COMPILER_CONSTEXPR)
- static_assert(::qMetaTypeId<const int &>() == ::qMetaTypeId<int>());
-#endif
-}
-
-struct CustomConvertibleType
-{
- explicit CustomConvertibleType(const QVariant &foo = QVariant()) : m_foo(foo) {}
- virtual ~CustomConvertibleType() {}
- QString toString() const { return m_foo.toString(); }
- operator QPoint() const { return QPoint(12, 34); }
- template<typename To>
- To convert() const { return s_value.value<To>();}
- template<typename To>
- To convertOk(bool *ok) const { *ok = s_ok; return s_value.value<To>();}
-
- QVariant m_foo;
- static QVariant s_value;
- static bool s_ok;
-};
-
-bool operator<(const CustomConvertibleType &lhs, const CustomConvertibleType &rhs)
-{ return lhs.m_foo.toString() < rhs.m_foo.toString(); }
-bool operator==(const CustomConvertibleType &lhs, const CustomConvertibleType &rhs)
-{ return lhs.m_foo == rhs.m_foo; }
-bool operator!=(const CustomConvertibleType &lhs, const CustomConvertibleType &rhs)
-{ return !operator==(lhs, rhs); }
-
-QVariant CustomConvertibleType::s_value;
-bool CustomConvertibleType::s_ok = true;
-
-struct CustomConvertibleType2
-{
- // implicit
- CustomConvertibleType2(const CustomConvertibleType &t = CustomConvertibleType())
- : m_foo(t.m_foo) {}
- virtual ~CustomConvertibleType2() {}
-
- QVariant m_foo;
-};
-
-struct CustomDebugStreamableType
-{
- QString toString() const { return "test"; }
-};
-
-struct CustomDebugStreamableType2
-{
- QString toString() const { return "test"; }
-};
-
-QDebug operator<<(QDebug dbg, const CustomDebugStreamableType&)
-{
- return dbg << "string-content";
-}
-
-bool operator==(const CustomConvertibleType2 &lhs, const CustomConvertibleType2 &rhs)
-{ return lhs.m_foo == rhs.m_foo; }
-bool operator!=(const CustomConvertibleType2 &lhs, const CustomConvertibleType2 &rhs)
-{ return !operator==(lhs, rhs); }
-
-
-struct CustomEqualsOnlyType
-{
- explicit CustomEqualsOnlyType(int value = 0) : val(value) {}
- virtual ~CustomEqualsOnlyType() {}
-
- int val;
+struct S {
+ using value_type = S; // used to cause compilation error with Qt6
+ int begin();
+ int end();
};
-bool operator==(const CustomEqualsOnlyType &lhs, const CustomEqualsOnlyType &rhs)
-{ return lhs.val == rhs.val;}
-bool operator!=(const CustomEqualsOnlyType &lhs, const CustomEqualsOnlyType &rhs)
-{ return !operator==(lhs, rhs); }
-
-static_assert(QTypeTraits::has_operator_equal_v<CustomEqualsOnlyType>);
-static_assert(!QTypeTraits::has_operator_less_than_v<CustomEqualsOnlyType>);
-
-Q_DECLARE_METATYPE(CustomConvertibleType);
-Q_DECLARE_METATYPE(CustomConvertibleType2);
-Q_DECLARE_METATYPE(CustomDebugStreamableType);
-Q_DECLARE_METATYPE(CustomEqualsOnlyType);
-
-template<typename T, typename U>
-U convert(const T &t)
-{
- return t;
-}
-
-template<typename From>
-struct ConvertFunctor
-{
- CustomConvertibleType operator()(const From& f) const
- {
- return CustomConvertibleType(QVariant::fromValue(f));
- }
-};
-
-template<typename From, typename To>
-bool hasRegisteredConverterFunction()
-{
- return QMetaType::hasRegisteredConverterFunction<From, To>();
-}
-
-template<typename From, typename To>
-void testCustomTypeNotYetConvertible()
-{
- QVERIFY((!hasRegisteredConverterFunction<From, To>()));
- QVERIFY((!QVariant::fromValue<From>(From()).template canConvert<To>()));
-}
-
-template<typename From, typename To>
-void testCustomTypeConvertible()
-{
- QVERIFY((hasRegisteredConverterFunction<From, To>()));
- QVERIFY((QVariant::fromValue<From>(From()).template canConvert<To>()));
-}
-
-void customTypeNotYetConvertible()
-{
- testCustomTypeNotYetConvertible<CustomConvertibleType, QString>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, bool>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, int>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, double>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, float>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, QRect>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, QRectF>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, QPoint>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, QPointF>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, QSize>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, QSizeF>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, QLine>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, QLineF>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, QChar>();
- testCustomTypeNotYetConvertible<QString, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<bool, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<int, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<double, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<float, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<QRect, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<QRectF, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<QPoint, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<QPointF, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<QSize, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<QSizeF, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<QLine, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<QLineF, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<QChar, CustomConvertibleType>();
- testCustomTypeNotYetConvertible<CustomConvertibleType, CustomConvertibleType2>();
-}
-
-void registerCustomTypeConversions()
-{
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QString>(&CustomConvertibleType::convertOk<QString>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, bool>(&CustomConvertibleType::convert<bool>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, int>(&CustomConvertibleType::convertOk<int>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, double>(&CustomConvertibleType::convert<double>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, float>(&CustomConvertibleType::convertOk<float>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QRect>(&CustomConvertibleType::convert<QRect>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QRectF>(&CustomConvertibleType::convertOk<QRectF>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QPoint>(convert<CustomConvertibleType,QPoint>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QPointF>(&CustomConvertibleType::convertOk<QPointF>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QSize>(&CustomConvertibleType::convert<QSize>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QSizeF>(&CustomConvertibleType::convertOk<QSizeF>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QLine>(&CustomConvertibleType::convert<QLine>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QLineF>(&CustomConvertibleType::convertOk<QLineF>)));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QChar>(&CustomConvertibleType::convert<QChar>)));
- QVERIFY((QMetaType::registerConverter<QString, CustomConvertibleType>(ConvertFunctor<QString>())));
- QVERIFY((QMetaType::registerConverter<bool, CustomConvertibleType>(ConvertFunctor<bool>())));
- QVERIFY((QMetaType::registerConverter<int, CustomConvertibleType>(ConvertFunctor<int>())));
- QVERIFY((QMetaType::registerConverter<double, CustomConvertibleType>(ConvertFunctor<double>())));
- QVERIFY((QMetaType::registerConverter<float, CustomConvertibleType>(ConvertFunctor<float>())));
- QVERIFY((QMetaType::registerConverter<QRect, CustomConvertibleType>(ConvertFunctor<QRect>())));
- QVERIFY((QMetaType::registerConverter<QRectF, CustomConvertibleType>(ConvertFunctor<QRectF>())));
- QVERIFY((QMetaType::registerConverter<QPoint, CustomConvertibleType>(ConvertFunctor<QPoint>())));
- QVERIFY((QMetaType::registerConverter<QPointF, CustomConvertibleType>(ConvertFunctor<QPointF>())));
- QVERIFY((QMetaType::registerConverter<QSize, CustomConvertibleType>(ConvertFunctor<QSize>())));
- QVERIFY((QMetaType::registerConverter<QSizeF, CustomConvertibleType>(ConvertFunctor<QSizeF>())));
- QVERIFY((QMetaType::registerConverter<QLine, CustomConvertibleType>(ConvertFunctor<QLine>())));
- QVERIFY((QMetaType::registerConverter<QLineF, CustomConvertibleType>(ConvertFunctor<QLineF>())));
- QVERIFY((QMetaType::registerConverter<QChar, CustomConvertibleType>(ConvertFunctor<QChar>())));
- QVERIFY((QMetaType::registerConverter<CustomConvertibleType, CustomConvertibleType2>()));
- QTest::ignoreMessage(QtWarningMsg, "Type conversion already registered from type CustomConvertibleType to type CustomConvertibleType2");
- QVERIFY((!QMetaType::registerConverter<CustomConvertibleType, CustomConvertibleType2>()));
-}
-
-void tst_QMetaType::convertCustomType_data()
-{
- customTypeNotYetConvertible();
- registerCustomTypeConversions();
-
- QTest::addColumn<bool>("ok");
- QTest::addColumn<QString>("testQString");
- QTest::addColumn<bool>("testBool");
- QTest::addColumn<int>("testInt");
- QTest::addColumn<double>("testDouble");
- QTest::addColumn<float>("testFloat");
- QTest::addColumn<QRect>("testQRect");
- QTest::addColumn<QRectF>("testQRectF");
- QTest::addColumn<QPoint>("testQPoint");
- QTest::addColumn<QPointF>("testQPointF");
- QTest::addColumn<QSize>("testQSize");
- QTest::addColumn<QSizeF>("testQSizeF");
- QTest::addColumn<QLine>("testQLine");
- QTest::addColumn<QLineF>("testQLineF");
- QTest::addColumn<QChar>("testQChar");
- QTest::addColumn<CustomConvertibleType>("testCustom");
-
- QTest::newRow("default") << true
- << QString::fromLatin1("string") << true << 15
- << double(3.14) << float(3.6) << QRect(1, 2, 3, 4)
- << QRectF(1.4, 1.9, 10.9, 40.2) << QPoint(12, 34)
- << QPointF(9.2, 2.7) << QSize(4, 9) << QSizeF(3.3, 9.8)
- << QLine(3, 9, 29, 4) << QLineF(38.9, 28.9, 102.3, 0.0)
- << QChar('Q') << CustomConvertibleType(QString::fromLatin1("test"));
- QTest::newRow("not ok") << false
- << QString::fromLatin1("string") << true << 15
- << double(3.14) << float(3.6) << QRect(1, 2, 3, 4)
- << QRectF(1.4, 1.9, 10.9, 40.2) << QPoint(12, 34)
- << QPointF(9.2, 2.7) << QSize(4, 9) << QSizeF(3.3, 9.8)
- << QLine(3, 9, 29, 4) << QLineF()
- << QChar('Q') << CustomConvertibleType(42);
-}
-
-void tst_QMetaType::convertCustomType()
-{
- QFETCH(bool, ok);
- CustomConvertibleType::s_ok = ok;
-
- CustomConvertibleType t;
- QVariant v = QVariant::fromValue(t);
- QFETCH(QString, testQString);
- CustomConvertibleType::s_value = testQString;
- QCOMPARE(v.toString(), ok ? testQString : QString());
- QCOMPARE(v.value<QString>(), ok ? testQString : QString());
- QVERIFY(CustomConvertibleType::s_value.canConvert<CustomConvertibleType>());
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toString()), testQString);
-
- QFETCH(bool, testBool);
- CustomConvertibleType::s_value = testBool;
- QCOMPARE(v.toBool(), testBool);
- QCOMPARE(v.value<bool>(), testBool);
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toBool()), testBool);
-
- QFETCH(int, testInt);
- CustomConvertibleType::s_value = testInt;
- QCOMPARE(v.toInt(), ok ? testInt : 0);
- QCOMPARE(v.value<int>(), ok ? testInt : 0);
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toInt()), testInt);
-
- QFETCH(double, testDouble);
- CustomConvertibleType::s_value = testDouble;
- QCOMPARE(v.toDouble(), testDouble);
- QCOMPARE(v.value<double>(), testDouble);
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toDouble()), testDouble);
-
- QFETCH(float, testFloat);
- CustomConvertibleType::s_value = testFloat;
- QCOMPARE(v.toFloat(), ok ? testFloat : 0.0);
- QCOMPARE(v.value<float>(), ok ? testFloat : 0.0);
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toFloat()), testFloat);
-
- QFETCH(QRect, testQRect);
- CustomConvertibleType::s_value = testQRect;
- QCOMPARE(v.toRect(), testQRect);
- QCOMPARE(v.value<QRect>(), testQRect);
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toRect()), testQRect);
-
- QFETCH(QRectF, testQRectF);
- CustomConvertibleType::s_value = testQRectF;
- QCOMPARE(v.toRectF(), ok ? testQRectF : QRectF());
- QCOMPARE(v.value<QRectF>(), ok ? testQRectF : QRectF());
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toRectF()), testQRectF);
-
- QFETCH(QPoint, testQPoint);
- CustomConvertibleType::s_value = testQPoint;
- QCOMPARE(v.toPoint(), testQPoint);
- QCOMPARE(v.value<QPoint>(), testQPoint);
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toPoint()), testQPoint);
-
- QFETCH(QPointF, testQPointF);
- CustomConvertibleType::s_value = testQPointF;
- QCOMPARE(v.toPointF(), ok ? testQPointF : QPointF());
- QCOMPARE(v.value<QPointF>(), ok ? testQPointF : QPointF());
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toPointF()), testQPointF);
-
- QFETCH(QSize, testQSize);
- CustomConvertibleType::s_value = testQSize;
- QCOMPARE(v.toSize(), testQSize);
- QCOMPARE(v.value<QSize>(), testQSize);
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toSize()), testQSize);
-
- QFETCH(QSizeF, testQSizeF);
- CustomConvertibleType::s_value = testQSizeF;
- QCOMPARE(v.toSizeF(), ok ? testQSizeF : QSizeF());
- QCOMPARE(v.value<QSizeF>(), ok ? testQSizeF : QSizeF());
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toSizeF()), testQSizeF);
-
- QFETCH(QLine, testQLine);
- CustomConvertibleType::s_value = testQLine;
- QCOMPARE(v.toLine(), testQLine);
- QCOMPARE(v.value<QLine>(), testQLine);
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toLine()), testQLine);
-
- QFETCH(QLineF, testQLineF);
- CustomConvertibleType::s_value = testQLineF;
- QCOMPARE(v.toLineF(), ok ? testQLineF : QLineF());
- QCOMPARE(v.value<QLineF>(), ok ? testQLineF : QLineF());
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toLineF()), testQLineF);
-
- QFETCH(QChar, testQChar);
- CustomConvertibleType::s_value = testQChar;
- QCOMPARE(v.toChar(), testQChar);
- QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toChar()), testQChar);
-
- QFETCH(CustomConvertibleType, testCustom);
- v = QVariant::fromValue(testCustom);
- QVERIFY(v.canConvert(::qMetaTypeId<CustomConvertibleType2>()));
- QCOMPARE(v.value<CustomConvertibleType2>().m_foo, testCustom.m_foo);
-}
-
-void tst_QMetaType::compareCustomEqualOnlyType()
-{
- QMetaType type = QMetaType::fromType<CustomEqualsOnlyType>();
-
- CustomEqualsOnlyType val50(50);
- CustomEqualsOnlyType val100(100);
- CustomEqualsOnlyType val100x(100);
-
- QVariant variant50 = QVariant::fromValue(val50);
- QVariant variant100 = QVariant::fromValue(val100);
- QVariant variant100x = QVariant::fromValue(val100x);
-
- QVERIFY(variant50 != variant100);
- QVERIFY(variant50 != variant100x);
- QVERIFY(variant100 != variant50);
- QVERIFY(variant100x != variant50);
- QCOMPARE(variant100, variant100x);
- QCOMPARE(variant100, variant100);
-
- // check QMetaType::compare works/doesn't crash for equals only comparators
- auto cmp = type.compare(variant50.constData(), variant50.constData());
- QVERIFY(!cmp);
- bool equals = type.equals(variant50.constData(), variant50.constData());
- QVERIFY(equals);
-
- cmp = type.compare(variant100.constData(), variant100x.constData());
- QVERIFY(!cmp);
- equals = type.equals(variant100.constData(), variant100x.constData());
- QVERIFY(equals);
-
- cmp = type.compare(variant50.constData(), variant100.constData());
- QVERIFY(!cmp);
- equals = type.equals(variant50.constData(), variant100.constData());
- QVERIFY(!equals);
-
- //check QMetaType::equals for type w/o equals comparator being registered
- CustomMovable movable1;
- CustomMovable movable2;
- type = QMetaType::fromType<CustomMovable>();
- equals = type.equals(&movable1, &movable2);
-}
-
-struct MessageHandlerCustom : public MessageHandler
-{
- MessageHandlerCustom(const int typeId)
- : MessageHandler(typeId, handler)
- {}
- static void handler(QtMsgType, const QMessageLogContext &, const QString &msg)
- {
- QCOMPARE(msg.trimmed(), expectedMessage.trimmed());
- }
- static QString expectedMessage;
-};
-
-QString MessageHandlerCustom::expectedMessage;
-
-void tst_QMetaType::customDebugStream()
-{
- MessageHandlerCustom handler(::qMetaTypeId<CustomDebugStreamableType>());
- QVariant v1 = QVariant::fromValue(CustomDebugStreamableType());
- handler.expectedMessage = "QVariant(CustomDebugStreamableType, string-content)";
- qDebug() << v1;
-
- MessageHandlerCustom handler2(::qMetaTypeId<CustomDebugStreamableType2>());
- QMetaType::registerConverter<CustomDebugStreamableType2, QString>(&CustomDebugStreamableType2::toString);
- handler2.expectedMessage = "QVariant(CustomDebugStreamableType2, \"test\")";
- QVariant v2 = QVariant::fromValue(CustomDebugStreamableType2());
- qDebug() << v2;
-}
-
-void tst_QMetaType::unknownType()
-{
- QMetaType invalid(QMetaType::UnknownType);
- QVERIFY(!invalid.create());
- QVERIFY(!invalid.sizeOf());
- QVERIFY(!invalid.metaObject());
- int buffer = 0xBAD;
- invalid.construct(&buffer);
- QCOMPARE(buffer, 0xBAD);
-}
-
-void tst_QMetaType::fromType()
-{
- #define FROMTYPE_CHECK(MetaTypeName, MetaTypeId, RealType) \
- QCOMPARE(QMetaType::fromType<RealType>(), QMetaType(MetaTypeId)); \
- QVERIFY(QMetaType::fromType<RealType>() == QMetaType(MetaTypeId)); \
- QVERIFY(!(QMetaType::fromType<RealType>() != QMetaType(MetaTypeId))); \
- if (MetaTypeId != QMetaType::Void) \
- QCOMPARE(QMetaType::fromType<RealType>().id(), MetaTypeId);
-
- FOR_EACH_CORE_METATYPE(FROMTYPE_CHECK)
-
- QVERIFY(QMetaType::fromType<QString>() != QMetaType());
- QCOMPARE(QMetaType(), QMetaType());
- QCOMPARE(QMetaType(QMetaType::UnknownType), QMetaType());
-
- FROMTYPE_CHECK(_, ::qMetaTypeId<Whity<int>>(), Whity<int>)
- #undef FROMTYPE_CHECK
-}
-
-template<char X, typename T = void>
-struct CharTemplate
-{
- struct
- {
- int a;
- } x;
-};
-
-void tst_QMetaType::operatorEq_data()
-{
- QTest::addColumn<QMetaType>("typeA");
- QTest::addColumn<QMetaType>("typeB");
- QTest::addColumn<bool>("eq");
-
- QTest::newRow("String") << QMetaType(QMetaType::QString)
- << QMetaType::fromType<const QString &>() << true;
- QTest::newRow("void1") << QMetaType(QMetaType::UnknownType) << QMetaType::fromType<void>()
- << false;
- QTest::newRow("void2") << QMetaType::fromType<const void>() << QMetaType::fromType<void>()
- << true;
- QTest::newRow("list1") << QMetaType::fromType<QList<const int *>>()
- << QMetaType::fromType<QList<const int *>>() << true;
- QTest::newRow("list2") << QMetaType::fromType<QList<const int *>>()
- << QMetaType::fromType<QList<int *>>() << false;
- QTest::newRow("char1") << QMetaType::fromType<CharTemplate<'>'>>()
- << QMetaType::fromType<CharTemplate<'>', void>>() << true;
- QTest::newRow("annon1") << QMetaType::fromType<decltype(CharTemplate<'>'>::x)>()
- << QMetaType::fromType<decltype(CharTemplate<'>'>::x)>() << true;
- QTest::newRow("annon2") << QMetaType::fromType<decltype(CharTemplate<'>'>::x)>()
- << QMetaType::fromType<decltype(CharTemplate<'<'>::x)>() << false;
-}
-
-void tst_QMetaType::operatorEq()
-{
- QFETCH(QMetaType, typeA);
- QFETCH(QMetaType, typeB);
- QFETCH(bool, eq);
-
- QCOMPARE(typeA == typeB, eq);
- QCOMPARE(typeB == typeA, eq);
- QCOMPARE(typeA != typeB, !eq);
- QCOMPARE(typeB != typeA, !eq);
-}
-
-class WithPrivateDTor {
- ~WithPrivateDTor(){};
-};
-
-struct WithDeletedDtor {
- ~WithDeletedDtor() = delete;
-};
-
-void tst_QMetaType::typesWithInaccessibleDTors()
-{
- // should compile
- Q_UNUSED(QMetaType::fromType<WithPrivateDTor>());
- Q_UNUSED(QMetaType::fromType<WithDeletedDtor>());
-}
-
-void tst_QMetaType::voidIsNotUnknown()
-{
- QMetaType voidType = QMetaType::fromType<void>();
- QMetaType voidType2 = QMetaType(QMetaType::Void);
- QCOMPARE(voidType, voidType2);
- QVERIFY(voidType != QMetaType(QMetaType::UnknownType));
-}
-
-// Compile-time test, it should be possible to register function pointer types
-class Undefined;
-
-typedef Undefined (*UndefinedFunction0)();
-typedef Undefined (*UndefinedFunction1)(Undefined);
-typedef Undefined (*UndefinedFunction2)(Undefined, Undefined);
-typedef Undefined (*UndefinedFunction3)(Undefined, Undefined, Undefined);
-typedef Undefined (*UndefinedFunction4)(Undefined, Undefined, Undefined, Undefined, Undefined, Undefined, Undefined, Undefined);
-Q_DECLARE_METATYPE(UndefinedFunction0);
-Q_DECLARE_METATYPE(UndefinedFunction1);
-Q_DECLARE_METATYPE(UndefinedFunction2);
-Q_DECLARE_METATYPE(UndefinedFunction3);
-Q_DECLARE_METATYPE(UndefinedFunction4);
+// should not cause a compilation failure
+// used to cause issues due to S being equal to S::value_type
+Q_DECLARE_METATYPE(S)
QTEST_MAIN(tst_QMetaType)
#include "tst_qmetatype.moc"
diff --git a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.h b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.h
index 43a099de17..1694e49491 100644
--- a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.h
+++ b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.h
@@ -1,298 +1,326 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// Used by both tst_qmetatype and tst_qsettings
-
-#ifndef TST_QMETATYPE_H
-#define TST_QMETATYPE_H
-
-#include <qmetatype.h>
-#include <float.h>
-
-#define FOR_EACH_PRIMITIVE_METATYPE(F) \
- QT_FOR_EACH_STATIC_PRIMITIVE_TYPE(F) \
- QT_FOR_EACH_STATIC_CORE_POINTER(F) \
-
-#define FOR_EACH_COMPLEX_CORE_METATYPE(F) \
- QT_FOR_EACH_STATIC_CORE_CLASS(F) \
- QT_FOR_EACH_STATIC_CORE_TEMPLATE(F)
-
-#define FOR_EACH_CORE_METATYPE(F) \
- FOR_EACH_PRIMITIVE_METATYPE(F) \
- FOR_EACH_COMPLEX_CORE_METATYPE(F) \
-
-template <int ID>
-struct MetaEnumToType {};
-
-#define DEFINE_META_ENUM_TO_TYPE(MetaTypeName, MetaTypeId, RealType) \
-template<> \
-struct MetaEnumToType<QMetaType::MetaTypeName> { \
- typedef RealType Type; \
-};
-FOR_EACH_CORE_METATYPE(DEFINE_META_ENUM_TO_TYPE)
-#undef DEFINE_META_ENUM_TO_TYPE
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
+#include "tst_qmetatype_common.h"
+#include "tst_qvariant_common.h"
-template <int ID>
-struct DefaultValueFactory
+struct Derived : QObject
{
- typedef typename MetaEnumToType<ID>::Type Type;
- static Type *create() { return new Type; }
+ Q_OBJECT
};
-template <>
-struct DefaultValueFactory<QMetaType::Void>
+struct MessageHandlerCustom : public MessageHandler
{
- typedef MetaEnumToType<QMetaType::Void>::Type Type;
- static Type *create() { return 0; }
+ MessageHandlerCustom(const int typeId)
+ : MessageHandler(typeId, handler)
+ {}
+ static void handler(QtMsgType, const QMessageLogContext &, const QString &msg)
+ {
+ QCOMPARE(msg.trimmed(), expectedMessage.trimmed());
+ }
+ inline static QString expectedMessage;
};
-template <int ID>
-struct DefaultValueTraits
+class tst_QMetaType: public QObject
{
- // By default we assume that a default-constructed value (new T) is
- // initialized; e.g. QCOMPARE(*(new T), *(new T)) should succeed
- enum { IsInitialized = true };
-};
+ Q_OBJECT
+ Q_PROPERTY(QList<QVariant> prop READ prop WRITE setProp)
-#define DEFINE_NON_INITIALIZED_DEFAULT_VALUE_TRAITS(MetaTypeName, MetaTypeId, RealType) \
-template<> struct DefaultValueTraits<QMetaType::MetaTypeName> { \
- enum { IsInitialized = false }; \
-};
-// Primitive types (int et al) aren't initialized
-FOR_EACH_PRIMITIVE_METATYPE(DEFINE_NON_INITIALIZED_DEFAULT_VALUE_TRAITS)
-#undef DEFINE_NON_INITIALIZED_DEFAULT_VALUE_TRAITS
+public:
+ struct GadgetPropertyType {
+ QByteArray type;
+ QByteArray name;
+ QVariant testData;
+ };
-template <int ID>
-struct TestValueFactory {};
+ tst_QMetaType() { propList << 42 << "Hello"; }
-template<> struct TestValueFactory<QMetaType::Void> {
- static void *create() { return 0; }
-};
+ QList<QVariant> prop() const { return propList; }
+ void setProp(const QList<QVariant> &list) { propList = list; }
-template<> struct TestValueFactory<QMetaType::QString> {
- static QString *create() { return new QString(QString::fromLatin1("QString")); }
-};
-template<> struct TestValueFactory<QMetaType::Int> {
- static int *create() { return new int(INT_MIN); }
-};
-template<> struct TestValueFactory<QMetaType::UInt> {
- static uint *create() { return new uint(UINT_MAX); }
-};
-template<> struct TestValueFactory<QMetaType::Bool> {
- static bool *create() { return new bool(true); }
-};
-template<> struct TestValueFactory<QMetaType::Double> {
- static double *create() { return new double(DBL_MIN); }
-};
-template<> struct TestValueFactory<QMetaType::QByteArray> {
- static QByteArray *create() { return new QByteArray(QByteArray("QByteArray")); }
-};
-template<> struct TestValueFactory<QMetaType::QByteArrayList> {
- static QByteArrayList *create() { return new QByteArrayList(QByteArrayList() << "Q" << "Byte" << "Array" << "List"); }
-};
-template<> struct TestValueFactory<QMetaType::QVariantMap> {
- static QVariantMap *create() { return new QVariantMap(); }
-};
-template<> struct TestValueFactory<QMetaType::QVariantHash> {
- static QVariantHash *create() { return new QVariantHash(); }
-};
-template<> struct TestValueFactory<QMetaType::QVariantPair> {
- static QVariantPair *create() { return new QVariantPair(); }
-};
+private:
+ void registerGadget(const char * name, const QList<GadgetPropertyType> &gadgetProperties);
+ QList<QVariant> propList;
-template<> struct TestValueFactory<QMetaType::QVariantList> {
- static QVariantList *create() { return new QVariantList(QVariantList() << 123 << "Q" << "Variant" << "List"); }
-};
-template<> struct TestValueFactory<QMetaType::QChar> {
- static QChar *create() { return new QChar(QChar('q')); }
-};
-template<> struct TestValueFactory<QMetaType::Long> {
- static long *create() { return new long(LONG_MIN); }
-};
-template<> struct TestValueFactory<QMetaType::Short> {
- static short *create() { return new short(SHRT_MIN); }
-};
-template<> struct TestValueFactory<QMetaType::Char> {
- static char *create() { return new char('c'); }
-};
-template<> struct TestValueFactory<QMetaType::Char16> {
- static char16_t *create() { return new char16_t('c'); }
-};
-template<> struct TestValueFactory<QMetaType::Char32> {
- static char32_t *create() { return new char32_t('c'); }
-};
-template<> struct TestValueFactory<QMetaType::ULong> {
- static ulong *create() { return new ulong(ULONG_MAX); }
-};
-template<> struct TestValueFactory<QMetaType::UShort> {
- static ushort *create() { return new ushort(USHRT_MAX); }
-};
-template<> struct TestValueFactory<QMetaType::SChar> {
- static signed char *create() { return new signed char(CHAR_MIN); }
-};
-template<> struct TestValueFactory<QMetaType::UChar> {
- static uchar *create() { return new uchar(UCHAR_MAX); }
-};
-template<> struct TestValueFactory<QMetaType::Float> {
- static float *create() { return new float(FLT_MIN); }
-};
-template<> struct TestValueFactory<QMetaType::QObjectStar> {
- static QObject * *create() { return new QObject *(0); }
-};
-template<> struct TestValueFactory<QMetaType::VoidStar> {
- static void * *create() { return new void *(0); }
-};
-template<> struct TestValueFactory<QMetaType::LongLong> {
- static qlonglong *create() { return new qlonglong(LLONG_MIN); }
-};
-template<> struct TestValueFactory<QMetaType::ULongLong> {
- static qulonglong *create() { return new qulonglong(ULLONG_MAX); }
-};
-template<> struct TestValueFactory<QMetaType::QStringList> {
- static QStringList *create() { return new QStringList(QStringList() << "Q" << "t"); }
-};
-template<> struct TestValueFactory<QMetaType::QBitArray> {
- static QBitArray *create() { return new QBitArray(QBitArray(256, true)); }
-};
-template<> struct TestValueFactory<QMetaType::QDate> {
- static QDate *create() { return new QDate(QDate::currentDate()); }
-};
-template<> struct TestValueFactory<QMetaType::QTime> {
- static QTime *create() { return new QTime(QTime::currentTime()); }
-};
-template<> struct TestValueFactory<QMetaType::QDateTime> {
- static QDateTime *create() { return new QDateTime(QDateTime::currentDateTime()); }
-};
-template<> struct TestValueFactory<QMetaType::QUrl> {
- static QUrl *create() { return new QUrl("http://www.example.org"); }
-};
-template<> struct TestValueFactory<QMetaType::QLocale> {
- static QLocale *create() { return new QLocale(QLocale::c()); }
-};
-template<> struct TestValueFactory<QMetaType::QRect> {
- static QRect *create() { return new QRect(10, 20, 30, 40); }
-};
-template<> struct TestValueFactory<QMetaType::QRectF> {
- static QRectF *create() { return new QRectF(10, 20, 30, 40); }
-};
-template<> struct TestValueFactory<QMetaType::QSize> {
- static QSize *create() { return new QSize(10, 20); }
-};
-template<> struct TestValueFactory<QMetaType::QSizeF> {
- static QSizeF *create() { return new QSizeF(10, 20); }
-};
-template<> struct TestValueFactory<QMetaType::QLine> {
- static QLine *create() { return new QLine(10, 20, 30, 40); }
-};
-template<> struct TestValueFactory<QMetaType::QLineF> {
- static QLineF *create() { return new QLineF(10, 20, 30, 40); }
-};
-template<> struct TestValueFactory<QMetaType::QPoint> {
- static QPoint *create() { return new QPoint(10, 20); }
-};
-template<> struct TestValueFactory<QMetaType::QPointF> {
- static QPointF *create() { return new QPointF(10, 20); }
-};
-template<> struct TestValueFactory<QMetaType::QEasingCurve> {
- static QEasingCurve *create() { return new QEasingCurve(QEasingCurve::InOutElastic); }
-};
-template<> struct TestValueFactory<QMetaType::QUuid> {
- static QUuid *create() { return new QUuid(); }
-};
-template<> struct TestValueFactory<QMetaType::QModelIndex> {
- static QModelIndex *create() { return new QModelIndex(); }
-};
-template<> struct TestValueFactory<QMetaType::QPersistentModelIndex> {
- static QPersistentModelIndex *create() { return new QPersistentModelIndex(); }
-};
-template<> struct TestValueFactory<QMetaType::Nullptr> {
- static std::nullptr_t *create() { return new std::nullptr_t; }
+private slots:
+ void defined();
+#if QT_CONFIG(thread)
+ void threadSafety();
+#endif
+ void namespaces();
+ void id();
+ void qMetaTypeId();
+ void properties();
+ void normalizedTypes();
+ void typeName_data();
+ void typeName();
+ void type_data();
+ void type();
+ void type_fromSubString_data();
+ void type_fromSubString();
+ void create_data();
+ void create();
+ void createCopy_data();
+ void createCopy();
+ void sizeOf_data();
+ void sizeOf();
+ void sizeOfStaticLess_data();
+ void sizeOfStaticLess();
+ void alignOf_data();
+ void alignOf();
+ void flags_data();
+ void flags();
+ void flags2_data();
+ void flags2();
+ void flagsBinaryCompatibility6_0_data();
+ void flagsBinaryCompatibility6_0();
+ void construct_data();
+ void construct();
+ void defaultConstructTrivial_QTBUG_109594();
+ void typedConstruct();
+ void constructCopy_data();
+ void constructCopy();
+ void selfCompare_data();
+ void selfCompare();
+ void typedefs();
+ void registerType();
+ void isRegistered_data();
+ void isRegistered();
+ void isRegisteredStaticLess_data();
+ void isRegisteredStaticLess();
+ void isNotRegistered();
+ void isEnum();
+ void underlyingType_data();
+ void underlyingType();
+ void automaticTemplateRegistration_1();
+ void automaticTemplateRegistration_2(); // defined in tst_qmetatype3.cpp
+ void saveAndLoadBuiltin_data();
+ void saveAndLoadBuiltin();
+ void saveAndLoadCustom();
+ void metaObject_data();
+ void metaObject();
+ void constexprMetaTypeIds();
+
+ // tst_qmetatype2.cpp
+ void constRefs();
+ void convertCustomType_data();
+ void convertCustomType();
+ void convertConstNonConst();
+ void compareCustomEqualOnlyType();
+ void customDebugStream();
+ void unknownType();
+ void fromType();
+ void operatorEq_data();
+ void operatorEq();
+ void operatorEq2_data();
+ void operatorEq2();
+ void operatorEqAcrossLibs_data();
+ void operatorEqAcrossLibs();
+ void typesWithInaccessibleDTors();
+ void voidIsNotUnknown();
+ void typeNameNormalization();
+ void typeNameInQtPrivate();
+
+ // Tests for deprecated APIs
+#if QT_DEPRECATED_SINCE(6, 0)
+ void testDeprecatedGetters_data() { type_data(); }
+ void testDeprecatedGetters();
+ void testDeprecatedLoadSave_data() { saveAndLoadBuiltin_data(); }
+ void testDeprecatedLoadSave();
+#endif
};
-template<> struct TestValueFactory<QMetaType::QRegularExpression> {
- static QRegularExpression *create()
- {
-#if QT_CONFIG(regularexpression)
- return new QRegularExpression("abc.*def");
-#else
- return 0;
+
+template <typename T>
+struct Whity { T t; Whity() {} };
+
+Q_DECLARE_METATYPE(Whity<int>)
+Q_DECLARE_METATYPE(Whity<double>)
+
+#if !defined(Q_CC_CLANG) && defined(Q_CC_GNU) && Q_CC_GNU < 501
+QT_BEGIN_NAMESPACE
+Q_DECLARE_TYPEINFO(Whity<double>, Q_RELOCATABLE_TYPE);
+QT_END_NAMESPACE
#endif
- }
+
+struct CustomConvertibleType
+{
+ explicit CustomConvertibleType(const QVariant &foo = QVariant()) : m_foo(foo) {}
+ virtual ~CustomConvertibleType() {}
+ QString toString() const { return m_foo.toString(); }
+ operator QPoint() const { return QPoint(12, 34); }
+ template<typename To>
+ To convert() const { return s_value.value<To>();}
+ template<typename To>
+ To convertOk(bool *ok) const { *ok = s_ok; return s_value.value<To>();}
+
+ QVariant m_foo;
+ inline static QVariant s_value;
+ inline static bool s_ok = true;
+
+ friend bool operator<(const CustomConvertibleType &lhs, const CustomConvertibleType &rhs)
+ { return lhs.m_foo.toString() < rhs.m_foo.toString(); }
+ friend bool operator==(const CustomConvertibleType &lhs, const CustomConvertibleType &rhs)
+ { return lhs.m_foo == rhs.m_foo; }
+ friend bool operator!=(const CustomConvertibleType &lhs, const CustomConvertibleType &rhs)
+ { return !operator==(lhs, rhs); }
};
-template<> struct TestValueFactory<QMetaType::QJsonValue> {
- static QJsonValue *create() { return new QJsonValue(123.); }
+
+struct CustomConvertibleType2
+{
+ // implicit
+ CustomConvertibleType2(const CustomConvertibleType &t = CustomConvertibleType())
+ : m_foo(t.m_foo) {}
+ virtual ~CustomConvertibleType2() {}
+
+ QVariant m_foo;
+
+ friend bool operator==(const CustomConvertibleType2 &lhs, const CustomConvertibleType2 &rhs)
+ { return lhs.m_foo == rhs.m_foo; }
+ friend bool operator!=(const CustomConvertibleType2 &lhs, const CustomConvertibleType2 &rhs)
+ { return !operator==(lhs, rhs); }
};
-template<> struct TestValueFactory<QMetaType::QJsonObject> {
- static QJsonObject *create() {
- QJsonObject *o = new QJsonObject();
- o->insert("a", 123.);
- o->insert("b", true);
- o->insert("c", QJsonValue::Null);
- o->insert("d", QLatin1String("ciao"));
- return o;
+
+struct CustomDebugStreamableType
+{
+ QString toString() const { return "test"; }
+
+ friend QDebug operator<<(QDebug dbg, const CustomDebugStreamableType&)
+ {
+ return dbg << "string-content";
}
};
-template<> struct TestValueFactory<QMetaType::QJsonArray> {
- static QJsonArray *create() {
- QJsonArray *a = new QJsonArray();
- a->append(123.);
- a->append(true);
- a->append(QJsonValue::Null);
- a->append(QLatin1String("ciao"));
- return a;
- }
+
+struct CustomDebugStreamableType2
+{
+ QString toString() const { return "test"; }
};
-template<> struct TestValueFactory<QMetaType::QJsonDocument> {
- static QJsonDocument *create() {
- return new QJsonDocument(
- QJsonDocument::fromJson("{ 'foo': 123, 'bar': [true, null, 'ciao'] }")
- );
- }
+
+struct CustomEqualsOnlyType
+{
+ explicit CustomEqualsOnlyType(int value = 0) : val(value) {}
+ virtual ~CustomEqualsOnlyType() {}
+
+ int val;
+
+ friend bool operator==(const CustomEqualsOnlyType &lhs, const CustomEqualsOnlyType &rhs)
+ { return lhs.val == rhs.val;}
+ friend bool operator!=(const CustomEqualsOnlyType &lhs, const CustomEqualsOnlyType &rhs)
+ { return !operator==(lhs, rhs); }
};
-template<> struct TestValueFactory<QMetaType::QCborSimpleType> {
- static QCborSimpleType *create() { return new QCborSimpleType(QCborSimpleType::True); }
+static_assert(QTypeTraits::has_operator_equal_v<CustomEqualsOnlyType>);
+static_assert(!QTypeTraits::has_operator_less_than_v<CustomEqualsOnlyType>);
+
+struct BaseGadgetType
+{
+ Q_GADGET
+public:
+ explicit BaseGadgetType(QVariant foo = QVariant()) : m_foo(std::move(foo)) {}
+ QVariant m_foo;
};
-template<> struct TestValueFactory<QMetaType::QCborValue> {
- static QCborValue *create() { return new QCborValue(123.); }
+
+struct DerivedGadgetType : public BaseGadgetType
+{
+ Q_GADGET
+public:
+ explicit DerivedGadgetType(QVariant foo = QVariant()) : BaseGadgetType(std::move(foo)) {}
+ int bar = 25;
};
-template<> struct TestValueFactory<QMetaType::QCborMap> {
- static QCborMap *create() {
- return new QCborMap{{0, 0}, {"Hello", 1}, {1, nullptr}};
- }
+
+Q_DECLARE_METATYPE(CustomConvertibleType);
+Q_DECLARE_METATYPE(CustomConvertibleType2);
+Q_DECLARE_METATYPE(CustomDebugStreamableType);
+Q_DECLARE_METATYPE(CustomEqualsOnlyType);
+
+struct CustomMovable {
+ CustomMovable() {}
+
+ friend bool operator==(const CustomMovable &, const CustomMovable &) { return true; }
+ // needed for QSet<CustomMovable>. We actually check that it makes sense.
+ friend qsizetype qHash(const CustomMovable &, qsizetype seed = 0) { return seed; }
};
-template<> struct TestValueFactory<QMetaType::QCborArray> {
- static QCborArray *create() {
- return new QCborArray{0, 1, -2, 2.5, false, nullptr, "Hello", QByteArray("World") };
+
+#if !defined(Q_CC_CLANG) && defined(Q_CC_GNU) && Q_CC_GNU < 501
+QT_BEGIN_NAMESPACE
+Q_DECLARE_TYPEINFO(CustomMovable, Q_RELOCATABLE_TYPE);
+QT_END_NAMESPACE
+#endif
+
+Q_DECLARE_METATYPE(CustomMovable);
+
+#define FOR_EACH_STATIC_PRIMITIVE_TYPE(F) \
+ F(bool) \
+ F(int) \
+ F(qulonglong) \
+ F(double) \
+ F(short) \
+ F(char) \
+ F(ulong) \
+ F(uchar) \
+ F(float) \
+ F(QObject*) \
+ F(QString) \
+ F(CustomMovable)
+
+#define FOR_EACH_STATIC_PRIMITIVE_TYPE2(F, SecondaryRealName) \
+ F(uint, SecondaryRealName) \
+ F(qlonglong, SecondaryRealName) \
+ F(char, SecondaryRealName) \
+ F(uchar, SecondaryRealName) \
+ F(QObject*, SecondaryRealName)
+
+#define CREATE_AND_VERIFY_CONTAINER(CONTAINER, ...) \
+ { \
+ CONTAINER< __VA_ARGS__ > t; \
+ const QVariant v = QVariant::fromValue(t); \
+ QByteArray tn = createTypeName(#CONTAINER "<", #__VA_ARGS__); \
+ const int expectedType = ::qMetaTypeId<CONTAINER< __VA_ARGS__ > >(); \
+ const int type = QMetaType::fromName(tn).id(); \
+ QCOMPARE(type, expectedType); \
+ QCOMPARE((QMetaType::fromType<CONTAINER< __VA_ARGS__ >>().id()), expectedType); \
}
-};
-template<> struct TestValueFactory<QMetaType::QVariant> {
- static QVariant *create() { return new QVariant(QStringList(QStringList() << "Q" << "t")); }
-};
+#define FOR_EACH_1ARG_TEMPLATE_TYPE(F, TYPE) \
+ F(QList, TYPE) \
+ F(QQueue, TYPE) \
+ F(QStack, TYPE) \
+ F(QSet, TYPE)
+
+#define PRINT_1ARG_TEMPLATE(RealName) \
+ FOR_EACH_1ARG_TEMPLATE_TYPE(CREATE_AND_VERIFY_CONTAINER, RealName)
+
+#define FOR_EACH_2ARG_TEMPLATE_TYPE(F, RealName1, RealName2) \
+ F(QHash, RealName1, RealName2) \
+ F(QMap, RealName1, RealName2) \
+ F(std::pair, RealName1, RealName2)
+
+#define PRINT_2ARG_TEMPLATE_INTERNAL(RealName1, RealName2) \
+ FOR_EACH_2ARG_TEMPLATE_TYPE(CREATE_AND_VERIFY_CONTAINER, RealName1, RealName2)
+
+#define PRINT_2ARG_TEMPLATE(RealName) \
+ FOR_EACH_STATIC_PRIMITIVE_TYPE2(PRINT_2ARG_TEMPLATE_INTERNAL, RealName)
+
+#define REGISTER_TYPEDEF(TYPE, ARG1, ARG2) \
+ qRegisterMetaType<TYPE <ARG1, ARG2>>(#TYPE "<" #ARG1 "," #ARG2 ">");
+
+static inline QByteArray createTypeName(const char *begin, const char *va)
+{
+ QByteArray tn(begin);
+ const QList<QByteArray> args = QByteArray(va).split(',');
+ tn += args.first().trimmed();
+ if (args.size() > 1) {
+ QList<QByteArray>::const_iterator it = args.constBegin() + 1;
+ const QList<QByteArray>::const_iterator end = args.constEnd();
+ for (; it != end; ++it) {
+ tn += ",";
+ tn += it->trimmed();
+ }
+ }
+ if (tn.endsWith('>'))
+ tn += ' ';
+ tn += '>';
+ return tn;
+}
-#endif // TST_QMETATYPE_H
+Q_DECLARE_METATYPE(const void*)
diff --git a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype2.cpp b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype2.cpp
new file mode 100644
index 0000000000..68bcb53056
--- /dev/null
+++ b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype2.cpp
@@ -0,0 +1,733 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include "tst_qmetatype.h"
+#include "tst_qmetatype_libs.h"
+
+#include <QtCore/private/qmetaobjectbuilder_p.h>
+
+void tst_QMetaType::constRefs()
+{
+ QCOMPARE(::qMetaTypeId<const int &>(), ::qMetaTypeId<int>());
+ QCOMPARE(::qMetaTypeId<const QString &>(), ::qMetaTypeId<QString>());
+ QCOMPARE(::qMetaTypeId<const CustomMovable &>(), ::qMetaTypeId<CustomMovable>());
+ QCOMPARE(::qMetaTypeId<const QList<CustomMovable> &>(), ::qMetaTypeId<QList<CustomMovable> >());
+ static_assert(::qMetaTypeId<const int &>() == ::qMetaTypeId<int>());
+}
+
+template<typename T, typename U>
+U convert(const T &t)
+{
+ return t;
+}
+
+template<typename From>
+struct ConvertFunctor
+{
+ CustomConvertibleType operator()(const From& f) const
+ {
+ return CustomConvertibleType(QVariant::fromValue(f));
+ }
+};
+
+template<typename T>
+struct OptionalWrapper
+{
+ std::optional<T> operator()(const T& t) const
+ {
+ if (!CustomConvertibleType::s_ok)
+ return std::nullopt;
+
+ return t;
+ }
+};
+
+template<typename From>
+struct ConvertFunctorWithOptional
+{
+ std::optional<CustomConvertibleType> operator()(const From& f) const
+ {
+ if (!CustomConvertibleType::s_ok)
+ return std::nullopt;
+
+ return CustomConvertibleType(QVariant::fromValue(f));
+ }
+};
+
+template<typename From, typename To>
+bool hasRegisteredConverterFunction()
+{
+ return QMetaType::hasRegisteredConverterFunction<From, To>();
+}
+
+template<typename From, typename To>
+void testCustomTypeNotYetConvertible()
+{
+ QVERIFY((!hasRegisteredConverterFunction<From, To>()));
+ QVERIFY((!QVariant::fromValue<From>(From()).template canConvert<To>()));
+}
+
+template<typename From, typename To>
+void testCustomTypeConvertible()
+{
+ QVERIFY((hasRegisteredConverterFunction<From, To>()));
+ QVERIFY((QVariant::fromValue<From>(From()).template canConvert<To>()));
+}
+
+void customTypeNotYetConvertible()
+{
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QString>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, bool>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, int>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, double>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, float>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QRect>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QRectF>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QPoint>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QPointF>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QSize>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QSizeF>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QLine>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QLineF>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, QChar>();
+ testCustomTypeNotYetConvertible<QString, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<bool, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<int, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<double, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<float, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<QRect, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<QRectF, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<QPoint, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<QPointF, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<QSize, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<QSizeF, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<QLine, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<QLineF, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<QChar, CustomConvertibleType>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, CustomConvertibleType2>();
+ testCustomTypeNotYetConvertible<CustomConvertibleType, std::optional<CustomConvertibleType>>();
+}
+
+void registerCustomTypeConversions()
+{
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QString>(&CustomConvertibleType::convertOk<QString>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, bool>(&CustomConvertibleType::convert<bool>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, int>(&CustomConvertibleType::convertOk<int>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, double>(&CustomConvertibleType::convert<double>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, float>(&CustomConvertibleType::convertOk<float>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QRect>(&CustomConvertibleType::convert<QRect>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QRectF>(&CustomConvertibleType::convertOk<QRectF>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QPoint>(convert<CustomConvertibleType,QPoint>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QPointF>(&CustomConvertibleType::convertOk<QPointF>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QSize>(&CustomConvertibleType::convert<QSize>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QSizeF>(&CustomConvertibleType::convertOk<QSizeF>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QLine>(&CustomConvertibleType::convert<QLine>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QLineF>(&CustomConvertibleType::convertOk<QLineF>)));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, QChar>(&CustomConvertibleType::convert<QChar>)));
+ QVERIFY((QMetaType::registerConverter<QString, CustomConvertibleType>(ConvertFunctorWithOptional<QString>())));
+ QVERIFY((QMetaType::registerConverter<bool, CustomConvertibleType>(ConvertFunctor<bool>())));
+ QVERIFY((QMetaType::registerConverter<int, CustomConvertibleType>(ConvertFunctorWithOptional<int>())));
+ QVERIFY((QMetaType::registerConverter<double, CustomConvertibleType>(ConvertFunctor<double>())));
+ QVERIFY((QMetaType::registerConverter<float, CustomConvertibleType>(ConvertFunctorWithOptional<float>())));
+ QVERIFY((QMetaType::registerConverter<QRect, CustomConvertibleType>(ConvertFunctor<QRect>())));
+ QVERIFY((QMetaType::registerConverter<QRectF, CustomConvertibleType>(ConvertFunctorWithOptional<QRectF>())));
+ QVERIFY((QMetaType::registerConverter<QPoint, CustomConvertibleType>(ConvertFunctor<QPoint>())));
+ QVERIFY((QMetaType::registerConverter<QPointF, CustomConvertibleType>(ConvertFunctorWithOptional<QPointF>())));
+ QVERIFY((QMetaType::registerConverter<QSize, CustomConvertibleType>(ConvertFunctor<QSize>())));
+ QVERIFY((QMetaType::registerConverter<QSizeF, CustomConvertibleType>(ConvertFunctorWithOptional<QSizeF>())));
+ QVERIFY((QMetaType::registerConverter<QLine, CustomConvertibleType>(ConvertFunctor<QLine>())));
+ QVERIFY((QMetaType::registerConverter<QLineF, CustomConvertibleType>(ConvertFunctorWithOptional<QLineF>())));
+ QVERIFY((QMetaType::registerConverter<QChar, CustomConvertibleType>(ConvertFunctor<QChar>())));
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, std::optional<CustomConvertibleType>>(OptionalWrapper<CustomConvertibleType>())));
+
+ QVERIFY((QMetaType::registerConverter<CustomConvertibleType, CustomConvertibleType2>()));
+ QTest::ignoreMessage(QtWarningMsg, "Type conversion already registered from type CustomConvertibleType to type CustomConvertibleType2");
+ QVERIFY((!QMetaType::registerConverter<CustomConvertibleType, CustomConvertibleType2>()));
+}
+
+void tst_QMetaType::convertCustomType_data()
+{
+ customTypeNotYetConvertible();
+ registerCustomTypeConversions();
+
+ QTest::addColumn<bool>("ok");
+ QTest::addColumn<QString>("testQString");
+ QTest::addColumn<bool>("testBool");
+ QTest::addColumn<int>("testInt");
+ QTest::addColumn<double>("testDouble");
+ QTest::addColumn<float>("testFloat");
+ QTest::addColumn<QRect>("testQRect");
+ QTest::addColumn<QRectF>("testQRectF");
+ QTest::addColumn<QPoint>("testQPoint");
+ QTest::addColumn<QPointF>("testQPointF");
+ QTest::addColumn<QSize>("testQSize");
+ QTest::addColumn<QSizeF>("testQSizeF");
+ QTest::addColumn<QLine>("testQLine");
+ QTest::addColumn<QLineF>("testQLineF");
+ QTest::addColumn<QChar>("testQChar");
+ QTest::addColumn<CustomConvertibleType>("testCustom");
+ QTest::addColumn<DerivedGadgetType>("testDerived");
+
+ QTest::newRow("default") << true
+ << QString::fromLatin1("string") << true << 15
+ << double(3.14) << float(3.6) << QRect(1, 2, 3, 4)
+ << QRectF(1.4, 1.9, 10.9, 40.2) << QPoint(12, 34)
+ << QPointF(9.2, 2.7) << QSize(4, 9) << QSizeF(3.3, 9.8)
+ << QLine(3, 9, 29, 4) << QLineF(38.9, 28.9, 102.3, 0.0)
+ << QChar('Q') << CustomConvertibleType(QString::fromLatin1("test"))
+ << DerivedGadgetType(QString::fromLatin1("test"));
+ QTest::newRow("not ok") << false
+ << QString::fromLatin1("string") << true << 15
+ << double(3.14) << float(3.6) << QRect(1, 2, 3, 4)
+ << QRectF(1.4, 1.9, 10.9, 40.2) << QPoint(12, 34)
+ << QPointF(9.2, 2.7) << QSize(4, 9) << QSizeF(3.3, 9.8)
+ << QLine(3, 9, 29, 4) << QLineF()
+ << QChar('Q') << CustomConvertibleType(42)
+ << DerivedGadgetType(42);
+}
+
+void tst_QMetaType::convertCustomType()
+{
+ QFETCH(bool, ok);
+ CustomConvertibleType::s_ok = ok;
+
+ CustomConvertibleType t;
+ QVariant v = QVariant::fromValue(t);
+ QFETCH(QString, testQString);
+ CustomConvertibleType::s_value = testQString;
+ QCOMPARE(v.toString(), ok ? testQString : QString());
+ QCOMPARE(v.value<QString>(), ok ? testQString : QString());
+ QVERIFY(CustomConvertibleType::s_value.canConvert<CustomConvertibleType>());
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toString()), ok ? testQString : QString());
+
+ QFETCH(bool, testBool);
+ CustomConvertibleType::s_value = testBool;
+ QCOMPARE(v.toBool(), testBool);
+ QCOMPARE(v.value<bool>(), testBool);
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toBool()), testBool);
+
+ QFETCH(int, testInt);
+ CustomConvertibleType::s_value = testInt;
+ QCOMPARE(v.toInt(), ok ? testInt : 0);
+ QCOMPARE(v.value<int>(), ok ? testInt : 0);
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toInt()), ok ? testInt : 0);
+
+ QFETCH(double, testDouble);
+ CustomConvertibleType::s_value = testDouble;
+ QCOMPARE(v.toDouble(), testDouble);
+ QCOMPARE(v.value<double>(), testDouble);
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toDouble()), testDouble);
+
+ QFETCH(float, testFloat);
+ CustomConvertibleType::s_value = testFloat;
+ QCOMPARE(v.toFloat(), ok ? testFloat : 0.0);
+ QCOMPARE(v.value<float>(), ok ? testFloat : 0.0);
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toFloat()), ok ? testFloat : 0);
+
+ QFETCH(QRect, testQRect);
+ CustomConvertibleType::s_value = testQRect;
+ QCOMPARE(v.toRect(), testQRect);
+ QCOMPARE(v.value<QRect>(), testQRect);
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toRect()), testQRect);
+
+ QFETCH(QRectF, testQRectF);
+ CustomConvertibleType::s_value = testQRectF;
+ QCOMPARE(v.toRectF(), ok ? testQRectF : QRectF());
+ QCOMPARE(v.value<QRectF>(), ok ? testQRectF : QRectF());
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toRectF()), ok ? testQRectF : QRectF());
+
+ QFETCH(QPoint, testQPoint);
+ CustomConvertibleType::s_value = testQPoint;
+ QCOMPARE(v.toPoint(), testQPoint);
+ QCOMPARE(v.value<QPoint>(), testQPoint);
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toPoint()), testQPoint);
+
+ QFETCH(QPointF, testQPointF);
+ CustomConvertibleType::s_value = testQPointF;
+ QCOMPARE(v.toPointF(), ok ? testQPointF : QPointF());
+ QCOMPARE(v.value<QPointF>(), ok ? testQPointF : QPointF());
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toPointF()), ok ? testQPointF : QPointF());
+
+ QFETCH(QSize, testQSize);
+ CustomConvertibleType::s_value = testQSize;
+ QCOMPARE(v.toSize(), testQSize);
+ QCOMPARE(v.value<QSize>(), testQSize);
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toSize()), testQSize);
+
+ QFETCH(QSizeF, testQSizeF);
+ CustomConvertibleType::s_value = testQSizeF;
+ QCOMPARE(v.toSizeF(), ok ? testQSizeF : QSizeF());
+ QCOMPARE(v.value<QSizeF>(), ok ? testQSizeF : QSizeF());
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toSizeF()), ok ? testQSizeF : QSizeF());
+
+ QFETCH(QLine, testQLine);
+ CustomConvertibleType::s_value = testQLine;
+ QCOMPARE(v.toLine(), testQLine);
+ QCOMPARE(v.value<QLine>(), testQLine);
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toLine()), testQLine);
+
+ QFETCH(QLineF, testQLineF);
+ CustomConvertibleType::s_value = testQLineF;
+ QCOMPARE(v.toLineF(), ok ? testQLineF : QLineF());
+ QCOMPARE(v.value<QLineF>(), ok ? testQLineF : QLineF());
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toLineF()), ok ? testQLineF : QLineF());
+
+ QFETCH(QChar, testQChar);
+ CustomConvertibleType::s_value = testQChar;
+ QCOMPARE(v.toChar(), testQChar);
+ QCOMPARE((CustomConvertibleType::s_value.value<CustomConvertibleType>().m_foo.toChar()), testQChar);
+
+ QFETCH(CustomConvertibleType, testCustom);
+ v = QVariant::fromValue(testCustom);
+ QVERIFY(v.canConvert(QMetaType(::qMetaTypeId<CustomConvertibleType2>())));
+ QCOMPARE(v.value<CustomConvertibleType2>().m_foo, testCustom.m_foo);
+
+ // Check that converters that actually convert to std::optional<T> are not
+ // taken to indicate success or failure of the conversion. In these cases,
+ // the conversion must always succeed, even if the converter has returned a
+ // nullopt.
+ v = QVariant::fromValue(testCustom);
+ QVERIFY(v.canConvert(QMetaType::fromType<std::optional<CustomConvertibleType>>()));
+ QVERIFY(v.convert(QMetaType::fromType<std::optional<CustomConvertibleType>>()));
+ QCOMPARE(v.value<std::optional<CustomConvertibleType>>().has_value(), ok);
+ if (ok) {
+ QCOMPARE(v.value<std::optional<CustomConvertibleType>>().value().m_foo, testCustom.m_foo);
+ }
+
+ QFETCH(DerivedGadgetType, testDerived);
+ v = QVariant::fromValue(testDerived);
+ QCOMPARE(v.metaType(), QMetaType::fromType<DerivedGadgetType>());
+ QCOMPARE(v.value<DerivedGadgetType>().m_foo, testDerived.m_foo);
+ QVERIFY(v.canConvert(QMetaType::fromType<BaseGadgetType>()));
+ QVERIFY(v.convert(QMetaType::fromType<BaseGadgetType>()));
+ QCOMPARE(v.metaType(), QMetaType::fromType<BaseGadgetType>());
+ QCOMPARE(v.value<BaseGadgetType>().m_foo, testDerived.m_foo);
+}
+
+void tst_QMetaType::convertConstNonConst()
+{
+ auto mtConstObj = QMetaType::fromType<QObject const*>();
+ auto mtObj = QMetaType::fromType<QObject *>();
+ auto mtConstDerived = QMetaType::fromType<Derived const*>();
+ auto mtDerived = QMetaType::fromType<Derived *>();
+
+ QVERIFY(QMetaType::canConvert(mtConstObj, mtObj));
+ QVERIFY(QMetaType::canConvert(mtObj, mtConstObj)); // casting const away is allowed (but can lead to UB)
+ QVERIFY(QMetaType::canConvert(mtConstDerived, mtObj));
+ QVERIFY(QMetaType::canConvert(mtDerived, mtConstObj));
+ QVERIFY(QMetaType::canConvert(mtObj, mtConstDerived));
+}
+
+void tst_QMetaType::compareCustomEqualOnlyType()
+{
+ QMetaType type = QMetaType::fromType<CustomEqualsOnlyType>();
+
+ CustomEqualsOnlyType val50(50);
+ CustomEqualsOnlyType val100(100);
+ CustomEqualsOnlyType val100x(100);
+
+ QVariant variant50 = QVariant::fromValue(val50);
+ QVariant variant100 = QVariant::fromValue(val100);
+ QVariant variant100x = QVariant::fromValue(val100x);
+
+ QVERIFY(variant50 != variant100);
+ QVERIFY(variant50 != variant100x);
+ QVERIFY(variant100 != variant50);
+ QVERIFY(variant100x != variant50);
+ QCOMPARE(variant100, variant100x);
+ QCOMPARE(variant100, variant100);
+
+ // check QMetaType::compare works/doesn't crash for equals only comparators
+ auto cmp = type.compare(variant50.constData(), variant50.constData());
+ QCOMPARE(cmp, QPartialOrdering::Unordered);
+ bool equals = type.equals(variant50.constData(), variant50.constData());
+ QVERIFY(equals);
+
+ cmp = type.compare(variant100.constData(), variant100x.constData());
+ QCOMPARE(cmp, QPartialOrdering::Unordered);
+ equals = type.equals(variant100.constData(), variant100x.constData());
+ QVERIFY(equals);
+
+ cmp = type.compare(variant50.constData(), variant100.constData());
+ QCOMPARE(cmp, QPartialOrdering::Unordered);
+ equals = type.equals(variant50.constData(), variant100.constData());
+ QVERIFY(!equals);
+
+ //check QMetaType::equals for type w/o equals comparator being registered
+ CustomMovable movable1;
+ CustomMovable movable2;
+ type = QMetaType::fromType<CustomMovable>();
+ equals = type.equals(&movable1, &movable2);
+}
+
+void tst_QMetaType::customDebugStream()
+{
+ MessageHandlerCustom handler(::qMetaTypeId<CustomDebugStreamableType>());
+ QVariant v1 = QVariant::fromValue(CustomDebugStreamableType());
+ handler.expectedMessage = "QVariant(CustomDebugStreamableType, string-content)";
+ qDebug() << v1;
+
+ MessageHandlerCustom handler2(::qMetaTypeId<CustomDebugStreamableType2>());
+ QMetaType::registerConverter<CustomDebugStreamableType2, QString>(&CustomDebugStreamableType2::toString);
+ handler2.expectedMessage = "QVariant(CustomDebugStreamableType2, \"test\")";
+ QVariant v2 = QVariant::fromValue(CustomDebugStreamableType2());
+ qDebug() << v2;
+}
+
+void tst_QMetaType::unknownType()
+{
+ QMetaType invalid(QMetaType::UnknownType);
+ QVERIFY(!invalid.create());
+ QVERIFY(!invalid.sizeOf());
+ QVERIFY(!invalid.metaObject());
+ int buffer = 0xBAD;
+ invalid.construct(&buffer);
+ QCOMPARE(buffer, 0xBAD);
+}
+
+void tst_QMetaType::fromType()
+{
+ #define FROMTYPE_CHECK(MetaTypeName, MetaTypeId, RealType) \
+ QCOMPARE(QMetaType::fromType<RealType>(), QMetaType(MetaTypeId)); \
+ QVERIFY(QMetaType::fromType<RealType>() == QMetaType(MetaTypeId)); \
+ QVERIFY(!(QMetaType::fromType<RealType>() != QMetaType(MetaTypeId))); \
+ if (MetaTypeId != QMetaType::Void) \
+ QCOMPARE(QMetaType::fromType<RealType>().id(), MetaTypeId);
+
+ FOR_EACH_CORE_METATYPE(FROMTYPE_CHECK)
+
+ QVERIFY(QMetaType::fromType<QString>() != QMetaType());
+ QCOMPARE(QMetaType(), QMetaType());
+ QCOMPARE(QMetaType(QMetaType::UnknownType), QMetaType());
+
+ FROMTYPE_CHECK(_, ::qMetaTypeId<Whity<int>>(), Whity<int>)
+ #undef FROMTYPE_CHECK
+}
+
+template<char X, typename T = void>
+struct CharTemplate
+{
+ struct
+ {
+ int a;
+ } x;
+
+ union
+ {
+ int a;
+ } y;
+};
+
+void tst_QMetaType::operatorEq_data()
+{
+ QTest::addColumn<QMetaType>("typeA");
+ QTest::addColumn<QMetaType>("typeB");
+ QTest::addColumn<bool>("eq");
+ QTest::newRow("String") << QMetaType(QMetaType::QString)
+ << QMetaType::fromType<const QString &>() << true;
+ QTest::newRow("void1") << QMetaType(QMetaType::UnknownType) << QMetaType::fromType<void>()
+ << false;
+ QTest::newRow("void2") << QMetaType::fromType<const void>() << QMetaType::fromType<void>()
+ << true;
+ QTest::newRow("list1") << QMetaType::fromType<QList<const int *>>()
+ << QMetaType::fromType<QList<const int *>>() << true;
+ QTest::newRow("list2") << QMetaType::fromType<QList<const int *>>()
+ << QMetaType::fromType<QList<int *>>() << false;
+ QTest::newRow("char1") << QMetaType::fromType<CharTemplate<'>'>>()
+ << QMetaType::fromType<CharTemplate<'>', void>>() << true;
+ QTest::newRow("annon1") << QMetaType::fromType<decltype(CharTemplate<'>'>::x)>()
+ << QMetaType::fromType<decltype(CharTemplate<'>'>::x)>() << true;
+ QTest::newRow("annon2") << QMetaType::fromType<decltype(CharTemplate<'>'>::x)>()
+ << QMetaType::fromType<decltype(CharTemplate<'<'>::x)>() << false;
+}
+
+void tst_QMetaType::operatorEq()
+{
+ QFETCH(QMetaType, typeA);
+ QFETCH(QMetaType, typeB);
+ QFETCH(bool, eq);
+
+ QCOMPARE(typeA == typeB, eq);
+ QCOMPARE(typeB == typeA, eq);
+ QCOMPARE(typeA != typeB, !eq);
+ QCOMPARE(typeB != typeA, !eq);
+
+#if !defined(Q_OS_WIN) && !defined(Q_OS_INTEGRITY)
+ // for built-in types or locally-defined types, this must also hold true
+ if (eq)
+ QCOMPARE(typeA.iface(), typeB.iface());
+#endif
+}
+
+void tst_QMetaType::operatorEq2_data()
+{
+ create_data();
+}
+
+void tst_QMetaType::operatorEq2()
+{
+ QFETCH(int, type);
+ QMetaType fromType1, fromType2;
+ QMetaType fromId1(type), fromId2(type);
+
+ switch (type) {
+ case QMetaType::UnknownType:
+ break;
+#define GET_METATYPE_FROM_TYPE(MetaTypeName, MetaTypeId, RealType) \
+ case QMetaType::MetaTypeName: \
+ fromType1 = QMetaType::fromType<RealType>(); \
+ fromType2 = QMetaType::fromType<RealType>(); \
+ break;
+FOR_EACH_CORE_METATYPE(GET_METATYPE_FROM_TYPE)
+#undef GET_METATYPE_FROM_TYPE
+ }
+
+ // sanity check
+ QCOMPARE(fromId1.id(), type);
+ QCOMPARE(fromId2.id(), type);
+
+ // confirm that they're all equal
+ QCOMPARE(fromId1, fromId2);
+ QCOMPARE(fromType1, fromType2);
+ QCOMPARE(fromType1, fromId1);
+ QCOMPARE(fromType2, fromId2);
+
+#if !defined(Q_OS_WIN) && !defined(Q_OS_INTEGRITY)
+ // for built-in types (other than void), this must be true
+ if (type != QMetaType::Void) {
+ QCOMPARE(fromType1.iface(), fromId1.iface());
+ QCOMPARE(fromType2.iface(), fromId1.iface());
+ }
+#endif
+}
+
+#define DECLARE_LIB_FUNCTION(TYPE, ID) \
+ Q_DECL_IMPORT QMetaType metatype_ ## TYPE();
+namespace Lib1 { FOR_EACH_METATYPE_LIBS(DECLARE_LIB_FUNCTION) }
+namespace Lib2 { FOR_EACH_METATYPE_LIBS(DECLARE_LIB_FUNCTION) }
+#undef DECLARE_LIB_FUNCTION
+
+using LibMetatypeFunction = QMetaType (*)();
+void tst_QMetaType::operatorEqAcrossLibs_data()
+{
+ QTest::addColumn<int>("builtinTypeId");
+ QTest::addColumn<QMetaType>("localType");
+ QTest::addColumn<LibMetatypeFunction>("lib1Function");
+ QTest::addColumn<LibMetatypeFunction>("lib2Function");
+
+#define ADD_ROW(TYPE, ID) \
+ QTest::addRow(QT_STRINGIFY(TYPE)) << int(ID) \
+ << QMetaType::fromType<TYPE>() \
+ << &Lib1::metatype_ ## TYPE \
+ << &Lib2::metatype_ ## TYPE;
+FOR_EACH_METATYPE_LIBS(ADD_ROW)
+#undef ADD_ROW
+}
+
+void tst_QMetaType::operatorEqAcrossLibs()
+{
+ QFETCH(int, builtinTypeId);
+ QFETCH(QMetaType, localType);
+ QFETCH(LibMetatypeFunction, lib1Function);
+ QFETCH(LibMetatypeFunction, lib2Function);
+
+ QMetaType lib1Type = lib1Function();
+ QMetaType lib2Type = lib2Function();
+
+ const QtPrivate::QMetaTypeInterface *localIface = localType.iface();
+ const QtPrivate::QMetaTypeInterface *lib1Iface = lib1Type.iface();
+ const QtPrivate::QMetaTypeInterface *lib2Iface = lib2Type.iface();
+
+ // DO THIS FIRST:
+ // if this isn't a built-in type, then the QMetaTypeInterface::typeId is
+ // initially set to 0
+ QCOMPARE(lib1Type, lib2Type);
+
+ int actualTypeId = localType.id();
+ bool builtinTypeExpected = builtinTypeId != QMetaType::UnknownType;
+ bool builtinTypeActually = actualTypeId < QMetaType::User;
+
+ qDebug() << "QMetaType for type" << QByteArray(localType.name())
+ << "(type ID" << (actualTypeId >= 0x1000 ? Qt::hex : Qt::dec) << actualTypeId << ')'
+ << (builtinTypeActually ? "IS" : "is NOT") << "a built-in type;"
+ << "local interface:" << static_cast<const void *>(localIface)
+ << "lib1 interface:" << static_cast<const void *>(lib1Iface)
+ << "lib2 interface:" << static_cast<const void *>(lib2Iface);
+
+ QCOMPARE(builtinTypeActually, builtinTypeExpected);
+ QCOMPARE(lib1Type.id(), actualTypeId);
+ QCOMPARE(lib2Type.id(), actualTypeId);
+ QCOMPARE(QByteArray(lib1Type.name()), QByteArray(localType.name()));
+ QCOMPARE(QByteArray(lib2Type.name()), QByteArray(localType.name()));
+ QCOMPARE(lib1Type, localType);
+ QCOMPARE(lib2Type, localType);
+
+#if !defined(Q_OS_WIN) && !defined(Q_OS_INTEGRITY)
+ if (actualTypeId < QMetaType::FirstGuiType && actualTypeId != QMetaType::Void) {
+ // for built-in QtCore types, we expect the interfaces to be the same too
+ QCOMPARE(lib1Iface, localIface);
+ QCOMPARE(lib2Iface, localIface);
+ }
+#endif
+}
+
+class WithPrivateDTor {
+ ~WithPrivateDTor(){};
+};
+
+struct WithDeletedDtor {
+ ~WithDeletedDtor() = delete;
+};
+
+void tst_QMetaType::typesWithInaccessibleDTors()
+{
+ // should compile
+ Q_UNUSED(QMetaType::fromType<WithPrivateDTor>());
+ Q_UNUSED(QMetaType::fromType<WithDeletedDtor>());
+}
+
+void tst_QMetaType::voidIsNotUnknown()
+{
+ QMetaType voidType = QMetaType::fromType<void>();
+ QMetaType voidType2 = QMetaType(QMetaType::Void);
+ QCOMPARE(voidType, voidType2);
+ QVERIFY(voidType != QMetaType(QMetaType::UnknownType));
+}
+
+void tst_QMetaType::typeNameNormalization()
+{
+ // check the we normalize types the right way
+#define CHECK_TYPE_NORMALIZATION(Normalized, ...) \
+ do { \
+ /*QCOMPARE(QtPrivate::typenameHelper<Type>(), Normalized);*/ \
+ QByteArray typeName = QMetaObject::normalizedType(#__VA_ARGS__); \
+ QCOMPARE(typeName, Normalized); \
+ typeName = QMetaType::fromType<__VA_ARGS__>().name(); \
+ QCOMPARE(typeName, Normalized); \
+ } while (0)
+
+ CHECK_TYPE_NORMALIZATION("QList<QString*const>", QList<QString * const>);
+ CHECK_TYPE_NORMALIZATION("QList<const QString*>", QList<const QString * >);
+ CHECK_TYPE_NORMALIZATION("QList<const QString*const>", QList<const QString * const>);
+ CHECK_TYPE_NORMALIZATION("QList<const QString*>", QList<QString const *>);
+ CHECK_TYPE_NORMALIZATION("QList<signed char>", QList<signed char>);
+ CHECK_TYPE_NORMALIZATION("QList<uint>", QList<unsigned>);
+ CHECK_TYPE_NORMALIZATION("uint", uint);
+ CHECK_TYPE_NORMALIZATION("QList<QHash<uint,QString*>>", QList<QHash<unsigned, QString *>>);
+ CHECK_TYPE_NORMALIZATION("QList<qlonglong>", QList<qlonglong>);
+ CHECK_TYPE_NORMALIZATION("QList<qulonglong>", QList<qulonglong>);
+ CHECK_TYPE_NORMALIZATION("QList<qlonglong>", QList<long long>);
+ CHECK_TYPE_NORMALIZATION("QList<qulonglong>", QList<unsigned long long>);
+ CHECK_TYPE_NORMALIZATION("QList<qulonglong*>", QList<unsigned long long *>);
+ CHECK_TYPE_NORMALIZATION("QList<ulong>", QList<long unsigned >);
+#ifdef Q_CC_MSVC
+ CHECK_TYPE_NORMALIZATION("qulonglong", __int64 unsigned);
+#endif
+ CHECK_TYPE_NORMALIZATION("std::pair<const QString&&,short>", QPair<const QString &&, signed short>);
+
+ // The string based normalization doesn't handle aliases, QMetaType::fromType() does
+// CHECK_TYPE_NORMALIZATION("qulonglong", quint64);
+ QCOMPARE(QMetaType::fromType<quint64>().name(), "qulonglong");
+
+ // noramlizedType and metatype name agree
+ {
+ auto type = QMetaType::fromType<decltype(CharTemplate<'<'>::x)>();
+ QCOMPARE(type.name(), QMetaObject::normalizedType(type.name()));
+ }
+ {
+ auto type = QMetaType::fromType<decltype(CharTemplate<'<'>::y)>();
+ QCOMPARE(type.name(), QMetaObject::normalizedType(type.name()));
+ }
+}
+
+QT_BEGIN_NAMESPACE
+namespace QtPrivate { struct tst_QMetaType_TestType {}; }
+QT_END_NAMESPACE
+
+void tst_QMetaType::typeNameInQtPrivate()
+{
+ using T = QT_PREPEND_NAMESPACE(QtPrivate::tst_QMetaType_TestType);
+
+ // some compilers (GCC) are known to suppress the namespace prefix if the
+ // type and the function where it is expanded on are on the same namespace
+ static constexpr char expectedName[] = "QtPrivate::tst_QMetaType_TestType";
+ QMetaType mt = QMetaType::fromType<T>();
+ QCOMPARE(mt.name(), expectedName);
+}
+
+#if QT_DEPRECATED_SINCE(6, 0)
+void tst_QMetaType::testDeprecatedGetters()
+{
+ QFETCH(int, aType);
+ QFETCH(QByteArray, aTypeName);
+
+ if (aType >= QMetaType::FirstWidgetsType)
+ QSKIP("The test doesn't link against QtWidgets.");
+
+ // QMetaType::type("name") -> QMetaType::fromName("name").id()
+ QT_IGNORE_DEPRECATIONS(QCOMPARE(QMetaType::type(aTypeName),
+ QMetaType::fromName(aTypeName).id());)
+ // QMetaType::typeName(int) -> QMetaType(int).name()
+ QT_IGNORE_DEPRECATIONS(QCOMPARE(QLatin1String(QMetaType::typeName(aType)),
+ QLatin1String(QMetaType(aType).name()));)
+ // QMetaType::typeFlags(int) -> QMetaType(int).flags()
+ QT_IGNORE_DEPRECATIONS(QCOMPARE(QMetaType::typeFlags(aType),
+ QMetaType(aType).flags());)
+ // QMetaType::metaObjectForType(int) -> QMetaType(int).metaObject()
+ QT_IGNORE_DEPRECATIONS(QCOMPARE(QMetaType::metaObjectForType(aType),
+ QMetaType(aType).metaObject());)
+}
+
+void tst_QMetaType::testDeprecatedLoadSave()
+{
+ QFETCH(int, type);
+ QFETCH(bool, isStreamable);
+
+ if (!isStreamable)
+ return;
+
+ QMetaType metaType(type);
+ void *value = metaType.create();
+ auto cleanup = qScopeGuard([&metaType, value]() {
+ metaType.destroy(value);
+ });
+
+ QByteArray ba;
+ QDataStream stream(&ba, QIODevice::ReadWrite);
+
+ // Write using deprecated API
+ QT_IGNORE_DEPRECATIONS(QVERIFY(QMetaType::save(stream, type, value));)
+ QCOMPARE(stream.status(), QDataStream::Ok);
+
+ // Read using non-deprecated API
+ stream.device()->seek(0);
+ QVERIFY(metaType.load(stream, value));
+ QCOMPARE(stream.status(), QDataStream::Ok);
+
+ // Write using non-deprecated API
+ stream.device()->seek(0);
+ ba.clear();
+ QVERIFY(metaType.save(stream, value));
+ QCOMPARE(stream.status(), QDataStream::Ok);
+
+ // Read using deprecated API
+ stream.device()->seek(0);
+ QT_IGNORE_DEPRECATIONS(QVERIFY(QMetaType::load(stream, type, value));)
+ QCOMPARE(stream.status(), QDataStream::Ok);
+}
+#endif // QT_DEPRECATED_SINCE(6, 0)
+
+// Compile-time test, it should be possible to register function pointer types
+class Undefined;
+
+typedef Undefined (*UndefinedFunction0)();
+typedef Undefined (*UndefinedFunction1)(Undefined);
+typedef Undefined (*UndefinedFunction2)(Undefined, Undefined);
+typedef Undefined (*UndefinedFunction3)(Undefined, Undefined, Undefined);
+typedef Undefined (*UndefinedFunction4)(Undefined, Undefined, Undefined, Undefined, Undefined, Undefined, Undefined, Undefined);
+
+Q_DECLARE_METATYPE(UndefinedFunction0);
+Q_DECLARE_METATYPE(UndefinedFunction1);
+Q_DECLARE_METATYPE(UndefinedFunction2);
+Q_DECLARE_METATYPE(UndefinedFunction3);
+Q_DECLARE_METATYPE(UndefinedFunction4);
diff --git a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype3.cpp b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype3.cpp
new file mode 100644
index 0000000000..779044589c
--- /dev/null
+++ b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype3.cpp
@@ -0,0 +1,14 @@
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include "tst_qmetatype.h"
+
+#include <QtCore/private/qmetaobjectbuilder_p.h>
+
+
+void tst_QMetaType::automaticTemplateRegistration_2()
+{
+ FOR_EACH_STATIC_PRIMITIVE_TYPE(
+ PRINT_2ARG_TEMPLATE
+ )
+}
diff --git a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype_common.h b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype_common.h
new file mode 100644
index 0000000000..ea59b5cd02
--- /dev/null
+++ b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype_common.h
@@ -0,0 +1,269 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+// Used by both tst_qmetatype and tst_qsettings
+
+#ifndef TST_QMETATYPE_H
+#define TST_QMETATYPE_H
+
+#include <QtCore>
+
+#include <float.h>
+
+#define FOR_EACH_PRIMITIVE_METATYPE(F) \
+ QT_FOR_EACH_STATIC_PRIMITIVE_TYPE(F) \
+ QT_FOR_EACH_STATIC_CORE_POINTER(F) \
+
+#define FOR_EACH_COMPLEX_CORE_METATYPE(F) \
+ QT_FOR_EACH_STATIC_CORE_CLASS(F) \
+ QT_FOR_EACH_STATIC_CORE_TEMPLATE(F)
+
+#define FOR_EACH_CORE_METATYPE(F) \
+ FOR_EACH_PRIMITIVE_METATYPE(F) \
+ FOR_EACH_COMPLEX_CORE_METATYPE(F) \
+
+template <int ID>
+struct MetaEnumToType {};
+
+#define DEFINE_META_ENUM_TO_TYPE(MetaTypeName, MetaTypeId, RealType) \
+template<> \
+struct MetaEnumToType<QMetaType::MetaTypeName> { \
+ typedef RealType Type; \
+};
+FOR_EACH_CORE_METATYPE(DEFINE_META_ENUM_TO_TYPE)
+#undef DEFINE_META_ENUM_TO_TYPE
+
+template <int ID>
+struct DefaultValueFactory
+{
+ typedef typename MetaEnumToType<ID>::Type Type;
+ static Type *create() { return new Type(); }
+};
+
+template <>
+struct DefaultValueFactory<QMetaType::Void>
+{
+ typedef MetaEnumToType<QMetaType::Void>::Type Type;
+ static Type *create() { return nullptr; }
+};
+
+template <int ID>
+struct DefaultValueTraits
+{
+ // By default we assume that a default-constructed value (new T) is
+ // initialized; e.g. QCOMPARE(*(new T), *(new T)) should succeed
+ enum { IsInitialized = true };
+};
+
+template <int ID>
+struct TestValueFactory {};
+
+template<> struct TestValueFactory<QMetaType::Void> {
+ static void *create() { return 0; }
+};
+
+template<> struct TestValueFactory<QMetaType::QString> {
+ static QString *create() { return new QString(QString::fromLatin1("QString")); }
+};
+template<> struct TestValueFactory<QMetaType::Int> {
+ static int *create() { return new int(INT_MIN); }
+};
+template<> struct TestValueFactory<QMetaType::UInt> {
+ static uint *create() { return new uint(UINT_MAX); }
+};
+template<> struct TestValueFactory<QMetaType::Bool> {
+ static bool *create() { return new bool(true); }
+};
+template<> struct TestValueFactory<QMetaType::Double> {
+ static double *create() { return new double(DBL_MIN); }
+};
+template<> struct TestValueFactory<QMetaType::QByteArray> {
+ static QByteArray *create() { return new QByteArray(QByteArray("QByteArray")); }
+};
+template<> struct TestValueFactory<QMetaType::QByteArrayList> {
+ static QByteArrayList *create() { return new QByteArrayList(QByteArrayList() << "Q" << "Byte" << "Array" << "List"); }
+};
+template<> struct TestValueFactory<QMetaType::QVariantMap> {
+ static QVariantMap *create() { return new QVariantMap(); }
+};
+template<> struct TestValueFactory<QMetaType::QVariantHash> {
+ static QVariantHash *create() { return new QVariantHash(); }
+};
+template<> struct TestValueFactory<QMetaType::QVariantPair> {
+ static QVariantPair *create() { return new QVariantPair(); }
+};
+
+template<> struct TestValueFactory<QMetaType::QVariantList> {
+ static QVariantList *create() { return new QVariantList(QVariantList() << 123 << "Q" << "Variant" << "List"); }
+};
+template<> struct TestValueFactory<QMetaType::QChar> {
+ static QChar *create() { return new QChar(QChar('q')); }
+};
+template<> struct TestValueFactory<QMetaType::Long> {
+ static long *create() { return new long(LONG_MIN); }
+};
+template<> struct TestValueFactory<QMetaType::Short> {
+ static short *create() { return new short(SHRT_MIN); }
+};
+template<> struct TestValueFactory<QMetaType::Char> {
+ static char *create() { return new char('c'); }
+};
+template<> struct TestValueFactory<QMetaType::Char16> {
+ static char16_t *create() { return new char16_t('c'); }
+};
+template<> struct TestValueFactory<QMetaType::Char32> {
+ static char32_t *create() { return new char32_t('c'); }
+};
+template<> struct TestValueFactory<QMetaType::ULong> {
+ static ulong *create() { return new ulong(ULONG_MAX); }
+};
+template<> struct TestValueFactory<QMetaType::UShort> {
+ static ushort *create() { return new ushort(USHRT_MAX); }
+};
+template<> struct TestValueFactory<QMetaType::SChar> {
+ static signed char *create() { return new signed char(CHAR_MIN); }
+};
+template<> struct TestValueFactory<QMetaType::UChar> {
+ static uchar *create() { return new uchar(UCHAR_MAX); }
+};
+template<> struct TestValueFactory<QMetaType::Float> {
+ static float *create() { return new float(FLT_MIN); }
+};
+template<> struct TestValueFactory<QMetaType::Float16> {
+ static auto create() { return new qfloat16(std::numeric_limits<qfloat16>::min()); }
+};
+template<> struct TestValueFactory<QMetaType::QObjectStar> {
+ static QObject * *create() { return new QObject *(0); }
+};
+template<> struct TestValueFactory<QMetaType::VoidStar> {
+ static void * *create() { return new void *(0); }
+};
+template<> struct TestValueFactory<QMetaType::LongLong> {
+ static qlonglong *create() { return new qlonglong(LLONG_MIN); }
+};
+template<> struct TestValueFactory<QMetaType::ULongLong> {
+ static qulonglong *create() { return new qulonglong(ULLONG_MAX); }
+};
+template<> struct TestValueFactory<QMetaType::QStringList> {
+ static QStringList *create() { return new QStringList(QStringList() << "Q" << "t"); }
+};
+template<> struct TestValueFactory<QMetaType::QBitArray> {
+ static QBitArray *create() { return new QBitArray(QBitArray(256, true)); }
+};
+template<> struct TestValueFactory<QMetaType::QDate> {
+ static QDate *create() { return new QDate(QDate::currentDate()); }
+};
+template<> struct TestValueFactory<QMetaType::QTime> {
+ static QTime *create() { return new QTime(QTime::currentTime()); }
+};
+template<> struct TestValueFactory<QMetaType::QDateTime> {
+ static QDateTime *create() { return new QDateTime(QDateTime::currentDateTime()); }
+};
+template<> struct TestValueFactory<QMetaType::QUrl> {
+ static QUrl *create() { return new QUrl("http://www.example.org"); }
+};
+template<> struct TestValueFactory<QMetaType::QLocale> {
+ static QLocale *create() { return new QLocale(QLocale::c()); }
+};
+template<> struct TestValueFactory<QMetaType::QRect> {
+ static QRect *create() { return new QRect(10, 20, 30, 40); }
+};
+template<> struct TestValueFactory<QMetaType::QRectF> {
+ static QRectF *create() { return new QRectF(10, 20, 30, 40); }
+};
+template<> struct TestValueFactory<QMetaType::QSize> {
+ static QSize *create() { return new QSize(10, 20); }
+};
+template<> struct TestValueFactory<QMetaType::QSizeF> {
+ static QSizeF *create() { return new QSizeF(10, 20); }
+};
+template<> struct TestValueFactory<QMetaType::QLine> {
+ static QLine *create() { return new QLine(10, 20, 30, 40); }
+};
+template<> struct TestValueFactory<QMetaType::QLineF> {
+ static QLineF *create() { return new QLineF(10, 20, 30, 40); }
+};
+template<> struct TestValueFactory<QMetaType::QPoint> {
+ static QPoint *create() { return new QPoint(10, 20); }
+};
+template<> struct TestValueFactory<QMetaType::QPointF> {
+ static QPointF *create() { return new QPointF(10, 20); }
+};
+template<> struct TestValueFactory<QMetaType::QEasingCurve> {
+ static QEasingCurve *create() { return new QEasingCurve(QEasingCurve::InOutElastic); }
+};
+template<> struct TestValueFactory<QMetaType::QUuid> {
+ static QUuid *create() { return new QUuid(); }
+};
+template<> struct TestValueFactory<QMetaType::QModelIndex> {
+ static QModelIndex *create() { return new QModelIndex(); }
+};
+template<> struct TestValueFactory<QMetaType::QPersistentModelIndex> {
+ static QPersistentModelIndex *create() { return new QPersistentModelIndex(); }
+};
+template<> struct TestValueFactory<QMetaType::Nullptr> {
+ static std::nullptr_t *create() { return new std::nullptr_t; }
+};
+template<> struct TestValueFactory<QMetaType::QRegularExpression> {
+ static QRegularExpression *create()
+ {
+#if QT_CONFIG(regularexpression)
+ return new QRegularExpression("abc.*def");
+#else
+ return 0;
+#endif
+ }
+};
+template<> struct TestValueFactory<QMetaType::QJsonValue> {
+ static QJsonValue *create() { return new QJsonValue(123.); }
+};
+template<> struct TestValueFactory<QMetaType::QJsonObject> {
+ static QJsonObject *create() {
+ QJsonObject *o = new QJsonObject();
+ o->insert("a", 123.);
+ o->insert("b", true);
+ o->insert("c", QJsonValue::Null);
+ o->insert("d", QLatin1String("ciao"));
+ return o;
+ }
+};
+template<> struct TestValueFactory<QMetaType::QJsonArray> {
+ static QJsonArray *create() {
+ QJsonArray *a = new QJsonArray();
+ a->append(123.);
+ a->append(true);
+ a->append(QJsonValue::Null);
+ a->append(QLatin1String("ciao"));
+ return a;
+ }
+};
+template<> struct TestValueFactory<QMetaType::QJsonDocument> {
+ static QJsonDocument *create() {
+ return new QJsonDocument(
+ QJsonDocument::fromJson("{ 'foo': 123, 'bar': [true, null, 'ciao'] }")
+ );
+ }
+};
+
+template<> struct TestValueFactory<QMetaType::QCborSimpleType> {
+ static QCborSimpleType *create() { return new QCborSimpleType(QCborSimpleType::True); }
+};
+template<> struct TestValueFactory<QMetaType::QCborValue> {
+ static QCborValue *create() { return new QCborValue(123.); }
+};
+template<> struct TestValueFactory<QMetaType::QCborMap> {
+ static QCborMap *create() {
+ return new QCborMap{{0, 0}, {"Hello", 1}, {1, nullptr}};
+ }
+};
+template<> struct TestValueFactory<QMetaType::QCborArray> {
+ static QCborArray *create() {
+ return new QCborArray{0, 1, -2, 2.5, false, nullptr, "Hello", QByteArray("World") };
+ }
+};
+
+template<> struct TestValueFactory<QMetaType::QVariant> {
+ static QVariant *create() { return new QVariant(QStringList(QStringList() << "Q" << "t")); }
+};
+
+#endif // TST_QMETATYPE_H
diff --git a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype_libs.h b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype_libs.h
new file mode 100644
index 0000000000..673fc9083c
--- /dev/null
+++ b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype_libs.h
@@ -0,0 +1,24 @@
+// Copyright (C) 2022 Intel Corporation
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#ifndef TST_QMETATYPE_LIBS_H
+#define TST_QMETATYPE_LIBS_H
+
+#include <qmetatype.h>
+
+#include <stdlib.h> // for div_t
+
+// void: builtin metatype, special
+// int: builtin metatype, primitive type
+// QString: builtin metatype, class
+// QCollator: not builtin, class, Q_CORE_EXPORT
+// div_t: not builtin, class, no export
+#define FOR_EACH_METATYPE_LIBS(F) \
+ F(void, QMetaType::Void) \
+ F(int, QMetaType::Int) \
+ F(QString, QMetaType::QString) \
+ F(QCollator, QMetaType::UnknownType) \
+ F(div_t, QMetaType::UnknownType) \
+ /**/
+
+#endif // TST_QMETATYPE_LIBS_H
diff --git a/tests/auto/corelib/kernel/qmimedata/CMakeLists.txt b/tests/auto/corelib/kernel/qmimedata/CMakeLists.txt
index 4400dfd46e..ba1d5e12cd 100644
--- a/tests/auto/corelib/kernel/qmimedata/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qmimedata/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qmimedata.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qmimedata Test:
#####################################################################
-qt_add_test(tst_qmimedata
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qmimedata LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qmimedata
SOURCES
tst_qmimedata.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Gui
)
diff --git a/tests/auto/corelib/kernel/qmimedata/qmimedata.pro b/tests/auto/corelib/kernel/qmimedata/qmimedata.pro
deleted file mode 100644
index 502ec78024..0000000000
--- a/tests/auto/corelib/kernel/qmimedata/qmimedata.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qmimedata
-QT += testlib
-SOURCES = tst_qmimedata.cpp
diff --git a/tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp b/tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp
index 380755127e..e28a2e98cc 100644
--- a/tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp
+++ b/tests/auto/corelib/kernel/qmimedata/tst_qmimedata.cpp
@@ -1,32 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
#include <QMimeData>
@@ -96,13 +71,28 @@ void tst_QMimeData::data() const
// set text, verify
mimeData.setData("text/plain", "pirates");
QCOMPARE(mimeData.data("text/plain"), QByteArray("pirates"));
- QCOMPARE(mimeData.data("text/html").length(), 0);
+ QCOMPARE(mimeData.data("text/html").size(), 0);
+ QCOMPARE(mimeData.data("text/markdown").size(), 0);
// html time
mimeData.setData("text/html", "ninjas");
QCOMPARE(mimeData.data("text/html"), QByteArray("ninjas"));
QCOMPARE(mimeData.data("text/plain"), QByteArray("pirates")); // make sure text not damaged
QCOMPARE(mimeData.data("text/html"), mimeData.html().toLatin1());
+
+ // markdown time
+ mimeData.setData("text/markdown", "vikings");
+ QCOMPARE(mimeData.data("text/markdown"), QByteArray("vikings"));
+ QCOMPARE(mimeData.data("text/html"), QByteArray("ninjas"));
+ QCOMPARE(mimeData.data("text/plain"), QByteArray("pirates"));
+
+ // URI list
+ QByteArray list = "https://example.com/\r\nhttps://example.net/\r\nhttps://example.org/\r\n";
+ mimeData.setData("text/uri-list", list);
+ QCOMPARE(mimeData.data("text/uri-list"), list);
+
+ mimeData.setData("text/uri-list", list.chopped(2)); // without the ending CRLF
+ QCOMPARE(mimeData.data("text/uri-list"), list);
}
void tst_QMimeData::formats() const
@@ -117,6 +107,10 @@ void tst_QMimeData::formats() const
mimeData.setData("text/html", "ninjas");
QCOMPARE(mimeData.formats(), QStringList() << "text/plain" << "text/html");
+ // set markdown, verify
+ mimeData.setData("text/markdown", "vikings");
+ QCOMPARE(mimeData.formats(), QStringList() << "text/plain" << "text/html" << "text/markdown");
+
// clear, verify
mimeData.clear();
QCOMPARE(mimeData.formats(), QStringList());
@@ -324,7 +318,8 @@ void tst_QMimeData::setUrls() const
QCOMPARE(mimeData.text(), QString("http://qt-project.org\nhttp://www.google.com\n"));
// test and verify that setData doesn't corrupt url content
- foreach (const QString &format, mimeData.formats()) {
+ const auto allFormats = mimeData.formats();
+ for (const QString &format : allFormats) {
QVariant before = mimeData.retrieveData(format, QMetaType(QMetaType::QByteArray));
mimeData.setData(format, mimeData.data(format));
QVariant after = mimeData.retrieveData(format, QMetaType(QMetaType::QByteArray));
diff --git a/tests/auto/corelib/kernel/qobject/.prev_CMakeLists.txt b/tests/auto/corelib/kernel/qobject/.prev_CMakeLists.txt
deleted file mode 100644
index ea894ff3d3..0000000000
--- a/tests/auto/corelib/kernel/qobject/.prev_CMakeLists.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-# Generated from qobject.pro.
-
-#####################################################################
-## tst_qobject Test:
-#####################################################################
-
-qt_add_test(tst_qobject
- SOURCES
- tst_qobject.cpp
- DEFINES
- QT_DISABLE_DEPRECATED_BEFORE=0
- PUBLIC_LIBRARIES
- Qt::CorePrivate
- Qt::Network
-)
-
-## Scopes:
-#####################################################################
-add_subdirectory(signalbug)
diff --git a/tests/auto/corelib/kernel/qobject/CMakeLists.txt b/tests/auto/corelib/kernel/qobject/CMakeLists.txt
index 47179410b0..46b8e2d238 100644
--- a/tests/auto/corelib/kernel/qobject/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qobject/CMakeLists.txt
@@ -1,20 +1,26 @@
-# Generated from qobject.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qobject Test:
#####################################################################
-qt_add_test(tst_qobject
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qobject LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qobject
SOURCES
tst_qobject.cpp
- DEFINES
- QT_DISABLE_DEPRECATED_BEFORE=0
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::Network
+ Qt::TestPrivate
)
## Scopes:
#####################################################################
add_subdirectory(signalbug)
-add_dependencies(tst_qobject signalbug_helper) # special case
+add_dependencies(tst_qobject signalbug_helper)
diff --git a/tests/auto/corelib/kernel/qobject/qobject.pro b/tests/auto/corelib/kernel/qobject/qobject.pro
deleted file mode 100644
index bdbec1e9f8..0000000000
--- a/tests/auto/corelib/kernel/qobject/qobject.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-TEMPLATE = subdirs
-
-SUBDIRS += test.pro \
- signalbug
diff --git a/tests/auto/corelib/kernel/qobject/signalbug/CMakeLists.txt b/tests/auto/corelib/kernel/qobject/signalbug/CMakeLists.txt
index 9dadd94f04..aefa1554b6 100644
--- a/tests/auto/corelib/kernel/qobject/signalbug/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qobject/signalbug/CMakeLists.txt
@@ -1,10 +1,11 @@
-# Generated from signalbug.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## signalbug_helper Binary:
#####################################################################
-qt_add_test_helper(signalbug_helper
+qt_internal_add_test_helper(signalbug_helper
SOURCES
signalbug.cpp signalbug.h
)
diff --git a/tests/auto/corelib/kernel/qobject/signalbug/signalbug.cpp b/tests/auto/corelib/kernel/qobject/signalbug/signalbug.cpp
index 57fb1eb836..bb8d7984f4 100644
--- a/tests/auto/corelib/kernel/qobject/signalbug/signalbug.cpp
+++ b/tests/auto/corelib/kernel/qobject/signalbug/signalbug.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include "signalbug.h"
diff --git a/tests/auto/corelib/kernel/qobject/signalbug/signalbug.h b/tests/auto/corelib/kernel/qobject/signalbug/signalbug.h
index e6e40c35d9..ac124c2a1c 100644
--- a/tests/auto/corelib/kernel/qobject/signalbug/signalbug.h
+++ b/tests/auto/corelib/kernel/qobject/signalbug/signalbug.h
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#ifndef SIGNAL_BUG_H
#define SIGNAL_BUG_H
diff --git a/tests/auto/corelib/kernel/qobject/signalbug/signalbug.pro b/tests/auto/corelib/kernel/qobject/signalbug/signalbug.pro
deleted file mode 100644
index d21b3a62a9..0000000000
--- a/tests/auto/corelib/kernel/qobject/signalbug/signalbug.pro
+++ /dev/null
@@ -1,6 +0,0 @@
-QT = core
-
-HEADERS += signalbug.h
-SOURCES += signalbug.cpp
-
-load(qt_test_helper)
diff --git a/tests/auto/corelib/kernel/qobject/test.pro b/tests/auto/corelib/kernel/qobject/test.pro
deleted file mode 100644
index af5203e152..0000000000
--- a/tests/auto/corelib/kernel/qobject/test.pro
+++ /dev/null
@@ -1,10 +0,0 @@
-CONFIG += testcase console
-
-QT = core-private network testlib
-TARGET = tst_qobject
-SOURCES = tst_qobject.cpp
-
-# Force C++17 if available (needed due to P0012R1)
-contains(QT_CONFIG, c++1z): CONFIG += c++1z
-
-DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
diff --git a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
index 51df41f5ac..6c387fde96 100644
--- a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
+++ b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
@@ -1,36 +1,22 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2021 The Qt Company Ltd.
+// Copyright (C) 2020 Olivier Goffart <ogoffart@woboq.com>
+// Copyright (C) 2021 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+// This test actually wants to practice narrowing conditions, so never define this.
+#ifdef QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
+#undef QT_NO_NARROWING_CONVERSIONS_IN_CONNECT
+#endif
+
+#include <QTest>
+#include <QtTest/private/qpropertytesthelper_p.h>
+#include <QStringListModel>
+#include <QAbstractEventDispatcher>
+#include <QScopedValueRollback>
#include <qcoreapplication.h>
#include <qpointer.h>
+#include <qproperty.h>
#include <qtimer.h>
#include <qregularexpression.h>
#include <qmetaobject.h>
@@ -53,6 +39,8 @@
#include <math.h>
+using namespace Qt::StringLiterals;
+
class tst_QObject : public QObject
{
Q_OBJECT
@@ -71,6 +59,8 @@ private slots:
void disconnectNotify_metaObjConnection();
void connectNotify_connectSlotsByName();
void connectDisconnectNotify_shadowing();
+ void connectReferenceToIncompleteTypes();
+ void connectAutoQueuedIncomplete();
void emitInDefinedOrder();
void customTypes();
void streamCustomTypes();
@@ -92,10 +82,13 @@ private slots:
void signalBlocking();
void blockingQueuedConnection();
void childEvents();
+ void parentEvents();
void installEventFilter();
+ void installEventFilterOrder();
void deleteSelfInSlot();
void disconnectSelfInSlotAndDeleteAfterEmit();
void dumpObjectInfo();
+ void dumpObjectTree();
void connectToSender();
void qobjectConstCast();
void uniqConnection();
@@ -148,8 +141,8 @@ private slots:
void connectBase();
void connectWarnings();
void qmlConnect();
+ void qmlConnectToQObjectReceiver();
void exceptions();
- void noDeclarativeParentChangedOnDestruction();
void deleteLaterInAboutToBlockHandler();
void mutableFunctor();
void checkArgumentsForNarrowing();
@@ -157,6 +150,10 @@ private slots:
void functorReferencesConnection();
void disconnectDisconnects();
void singleShotConnection();
+ void objectNameBinding();
+ void emitToDestroyedClass();
+ void declarativeData();
+ void asyncCallbackHelper();
};
struct QObjectCreatedOnShutdown
@@ -514,6 +511,12 @@ void tst_QObject::qobject_castTemplate()
QVERIFY(!::qobject_cast<ReceiverObject*>(o.data()));
}
+class DerivedObj : public QObject {
+ Q_OBJECT
+public:
+ using QObject::QObject;
+};
+
void tst_QObject::findChildren()
{
QObject o;
@@ -526,6 +529,10 @@ void tst_QObject::findChildren()
QTimer t1(&o);
QTimer t121(&o12);
QTimer emptyname(&o);
+ QObject oo;
+ QObject o21(&oo);
+ QObject o22(&oo);
+ QObject o23(&oo);
Q_SET_OBJECT_NAME(o);
Q_SET_OBJECT_NAME(o1);
@@ -536,8 +543,15 @@ void tst_QObject::findChildren()
Q_SET_OBJECT_NAME(t1);
Q_SET_OBJECT_NAME(t121);
emptyname.setObjectName("");
+ Q_SET_OBJECT_NAME(oo);
+ const QUtf8StringView utf8_name = u8"utf8 ⁎ obj";
+ o21.setObjectName(utf8_name);
+ const QStringView utf16_name = u"utf16 ⁎ obj";
+ o22.setObjectName(utf16_name);
+ constexpr QLatin1StringView L1_name("L1 ⁎ obj");
+ o23.setObjectName(L1_name);
- QObject *op = 0;
+ QObject *op = nullptr;
op = o.findChild<QObject*>("o1");
QCOMPARE(op, &o1);
@@ -566,6 +580,27 @@ void tst_QObject::findChildren()
op = o.findChild<QObject*>("o1");
QCOMPARE(op, &o1);
+ op = oo.findChild<QObject*>(utf8_name);
+ QCOMPARE(op, &o21);
+ op = oo.findChild<QObject*>(utf8_name.chopped(1));
+ QCOMPARE(op, nullptr);
+ const QUtf8StringView utf8_name_with_trailing_data = u8"utf8 ⁎ obj_data";
+ op = oo.findChild<QObject*>(utf8_name_with_trailing_data.chopped(5));
+ QCOMPARE(op, &o21);
+ op = oo.findChild<QObject*>(utf16_name);
+ QCOMPARE(op, &o22);
+ op = oo.findChild<QObject*>(utf16_name.chopped(1));
+ QCOMPARE(op, nullptr);
+ const QStringView utf16_name_with_trailing_data = u"utf16 ⁎ obj_data";
+ op = oo.findChild<QObject*>(utf16_name_with_trailing_data.chopped(5));
+ QCOMPARE(op, &o22);
+ op = oo.findChild<QObject*>(L1_name);
+ QCOMPARE(op, &o23);
+ op = oo.findChild<QObject*>(L1_name.chopped(1));
+ QCOMPARE(op, nullptr);
+ op = oo.findChild<QObject*>((L1_name + "_data"_L1).chopped(5));
+ QCOMPARE(op, &o23);
+
QList<QObject*> l;
QList<QTimer*> tl;
@@ -741,7 +776,20 @@ void tst_QObject::findChildren()
l = o.findChildren<QObject*>(QRegularExpression("^harry$"), Qt::FindDirectChildrenOnly);
QCOMPARE(l.size(), 0);
+ DerivedObj dr1(&o111);
+ DerivedObj dr2(&o111);
+ Q_SET_OBJECT_NAME(dr1);
+ Q_SET_OBJECT_NAME(dr2);
+
// empty and null string check
+ op = o.findChild<QObject*>(Qt::FindDirectChildrenOnly);
+ QCOMPARE(op, &o1);
+ op = o.findChild<QTimer*>(Qt::FindDirectChildrenOnly);
+ QCOMPARE(op, &t1);
+ op = o.findChild<DerivedObj*>(Qt::FindDirectChildrenOnly);
+ QCOMPARE(op, nullptr);
+ op = o.findChild<DerivedObj*>(Qt::FindChildrenRecursively);
+ QCOMPARE(op, &dr1);
op = o.findChild<QObject*>(QString(), Qt::FindDirectChildrenOnly);
QCOMPARE(op, &o1);
op = o.findChild<QObject*>("", Qt::FindDirectChildrenOnly);
@@ -749,6 +797,8 @@ void tst_QObject::findChildren()
op = o.findChild<QObject*>("unnamed", Qt::FindDirectChildrenOnly);
QCOMPARE(op, static_cast<QObject *>(0));
+ l = o.findChildren<QObject*>(Qt::FindDirectChildrenOnly);
+ QCOMPARE(l.size(), 5);
l = o.findChildren<QObject*>(QString(), Qt::FindDirectChildrenOnly);
QCOMPARE(l.size(), 5);
l = o.findChildren<QObject*>("", Qt::FindDirectChildrenOnly);
@@ -881,6 +931,61 @@ void tst_QObject::connectDisconnectNotify()
QCOMPARE(s.connectedSignals.size(), 1);
}
+struct Incomplete;
+class QObjectWithIncomplete : public QObject {
+ Q_OBJECT
+
+public:
+ QObjectWithIncomplete(QObject *parent=nullptr) : QObject(parent) {}
+signals:
+ void signalWithIncomplete(const Incomplete &);
+public slots:
+ void slotWithIncomplete(const Incomplete &) {}
+};
+
+void tst_QObject::connectReferenceToIncompleteTypes() {
+ QObjectWithIncomplete withIncomplete;
+ auto connection = QObject::connect(&withIncomplete, &QObjectWithIncomplete::signalWithIncomplete,
+ &withIncomplete, &QObjectWithIncomplete::slotWithIncomplete);
+ QVERIFY(connection);
+}
+
+struct Incomplete2;
+class QObjectWithIncomplete2 : public QObject {
+ Q_OBJECT
+
+public:
+ QObjectWithIncomplete2(QObject *parent=nullptr) : QObject(parent) {}
+signals:
+ void signalWithIncomplete(Incomplete2 *ptr);
+public slots:
+ void slotWithIncomplete(Incomplete2 *) { calledSlot = true; }
+ void run() { Q_EMIT signalWithIncomplete(nullptr); }
+public:
+ bool calledSlot = false;
+};
+
+void tst_QObject::connectAutoQueuedIncomplete()
+{
+ auto objectWithIncomplete1 = new QObjectWithIncomplete2();
+ auto objectWithIncomplete2 = new QObjectWithIncomplete2();
+ auto t = new QThread(this);
+ auto cleanup = qScopeGuard([&](){
+ t->quit();
+ QVERIFY(t->wait());
+ delete objectWithIncomplete1;
+ delete objectWithIncomplete2;
+ });
+
+ t->start();
+ objectWithIncomplete2->moveToThread(t);
+
+ connect(objectWithIncomplete2, &QObjectWithIncomplete2::signalWithIncomplete,
+ objectWithIncomplete1, &QObjectWithIncomplete2::slotWithIncomplete);
+ QMetaObject::invokeMethod(objectWithIncomplete2, "run", Qt::QueuedConnection);
+ QTRY_VERIFY(objectWithIncomplete1->calledSlot);
+}
+
static void connectDisconnectNotifyTestSlot() {}
void tst_QObject::connectDisconnectNotifyPMF()
@@ -948,7 +1053,7 @@ void tst_QObject::disconnectNotify_receiverDestroyed()
QVERIFY(QObject::connect((SenderObject *)&s, SIGNAL(signal1()),
(ReceiverObject *)&r, SLOT(slot1())));
}
- QCOMPARE(s.disconnectedSignals.count(), 1);
+ QCOMPARE(s.disconnectedSignals.size(), 1);
QCOMPARE(s.disconnectedSignals.at(0), QMetaMethod::fromSignal(&SenderObject::signal1));
s.disconnectedSignals.clear();
@@ -959,7 +1064,7 @@ void tst_QObject::disconnectNotify_receiverDestroyed()
(ReceiverObject *)&r, SLOT(slot3())));
}
- QCOMPARE(s.disconnectedSignals.count(), 1);
+ QCOMPARE(s.disconnectedSignals.size(), 1);
QCOMPARE(s.disconnectedSignals.at(0), QMetaMethod::fromSignal(&SenderObject::signal3));
s.disconnectedSignals.clear();
@@ -969,7 +1074,7 @@ void tst_QObject::disconnectNotify_receiverDestroyed()
QVERIFY(QObject::connect((SenderObject *)&s, SIGNAL(destroyed()), (ReceiverObject *)&r, SLOT(slot3())));
}
- QCOMPARE(s.disconnectedSignals.count(), 1);
+ QCOMPARE(s.disconnectedSignals.size(), 1);
QCOMPARE(s.disconnectedSignals.at(0), QMetaMethod::fromSignal(&QObject::destroyed));
}
@@ -984,10 +1089,10 @@ void tst_QObject::disconnectNotify_metaObjConnection()
QVERIFY(c);
QVERIFY(QObject::disconnect(c));
- QCOMPARE(s.disconnectedSignals.count(), 1);
+ QCOMPARE(s.disconnectedSignals.size(), 1);
QCOMPARE(s.disconnectedSignals.at(0), QMetaMethod::fromSignal(&SenderObject::signal1));
- QCOMPARE(s.disconnectedSignals.count(), 1);
+ QCOMPARE(s.disconnectedSignals.size(), 1);
}
}
@@ -1430,7 +1535,7 @@ class QCustomTypeChecker: public QObject
Q_OBJECT
public:
- QCustomTypeChecker(QObject *parent = 0): QObject(parent) {}
+ QCustomTypeChecker(QObject *parent = nullptr): QObject(parent) {}
void doEmit(CustomType ct)
{ emit signal1(ct); }
@@ -1469,8 +1574,7 @@ void tst_QObject::customTypes()
QCOMPARE(checker.received.value(), t1.value());
checker.received = t0;
- int idx = qRegisterMetaType<CustomType>("CustomType");
- QCOMPARE(QMetaType::type("CustomType"), idx);
+ qRegisterMetaType<CustomType>();
checker.disconnect();
connect(&checker, SIGNAL(signal1(CustomType)), &checker, SLOT(slot1(CustomType)),
@@ -1483,11 +1587,6 @@ void tst_QObject::customTypes()
QCoreApplication::processEvents();
QCOMPARE(checker.received.value(), t2.value());
QCOMPARE(instanceCount, 4);
-
- QVERIFY(QMetaType::isRegistered(idx));
- QCOMPARE(qRegisterMetaType<CustomType>("CustomType"), idx);
- QCOMPARE(QMetaType::type("CustomType"), idx);
- QVERIFY(QMetaType::isRegistered(idx));
}
QCOMPARE(instanceCount, 3);
}
@@ -1496,13 +1595,15 @@ void tst_QObject::streamCustomTypes()
{
QByteArray ba;
- int idx = qRegisterMetaType<CustomType>("CustomType");
+ qRegisterMetaType<CustomType>();
+
+ QMetaType metaType = QMetaType::fromType<CustomType>();
{
CustomType t1(1, 2, 3);
QCOMPARE(instanceCount, 1);
QDataStream stream(&ba, (QIODevice::OpenMode)QIODevice::WriteOnly);
- QMetaType::save(stream, idx, &t1);
+ metaType.save(stream, &t1);
}
QCOMPARE(instanceCount, 0);
@@ -1511,7 +1612,7 @@ void tst_QObject::streamCustomTypes()
CustomType t2;
QCOMPARE(instanceCount, 1);
QDataStream stream(&ba, (QIODevice::OpenMode)QIODevice::ReadOnly);
- QMetaType::load(stream, idx, &t2);
+ metaType.load(stream, &t2);
QCOMPARE(instanceCount, 1);
QCOMPARE(t2.i1, 1);
QCOMPARE(t2.i2, 2);
@@ -1638,8 +1739,8 @@ void tst_QObject::thread()
QCOMPARE(child.thread(), object.thread());
}
- QObject *object = 0;
- QObject *child = 0;
+ QObject *object = nullptr;
+ QObject *child = nullptr;
{
TestThread thr;
@@ -1681,12 +1782,12 @@ class MoveToThreadObject : public QObject
{
Q_OBJECT
public:
- QThread *timerEventThread;
- QThread *customEventThread;
- QThread *slotThread;
+ QThread *timerEventThread = nullptr;
+ QThread *customEventThread = nullptr;
+ QThread *slotThread = nullptr;
- MoveToThreadObject(QObject *parent = 0)
- : QObject(parent), timerEventThread(0), customEventThread(0), slotThread(0)
+ MoveToThreadObject(QObject *parent = nullptr)
+ : QObject(parent)
{ }
void customEvent(QEvent *) override
@@ -1770,13 +1871,15 @@ void tst_QObject::moveToThread()
QObject *child = new QObject(object);
QCOMPARE(object->thread(), currentThread);
QCOMPARE(child->thread(), currentThread);
- object->moveToThread(0);
+ QVERIFY(object->moveToThread(nullptr));
QCOMPARE(object->thread(), (QThread *)0);
QCOMPARE(child->thread(), (QThread *)0);
- object->moveToThread(currentThread);
+ QVERIFY(object->moveToThread(currentThread));
QCOMPARE(object->thread(), currentThread);
QCOMPARE(child->thread(), currentThread);
- object->moveToThread(0);
+ QTest::ignoreMessage(QtWarningMsg, "QObject::moveToThread: Cannot move objects with a parent");
+ QVERIFY(!child->moveToThread(nullptr));
+ QVERIFY(object->moveToThread(nullptr));
QCOMPARE(object->thread(), (QThread *)0);
QCOMPARE(child->thread(), (QThread *)0);
// can delete an object with no thread anywhere
@@ -1913,7 +2016,7 @@ void tst_QObject::property()
QVERIFY(mo->indexOfProperty("alpha") != -1);
property = mo->property(mo->indexOfProperty("alpha"));
QVERIFY(property.isEnumType());
- QCOMPARE(property.typeName(), "Alpha");
+ QCOMPARE(property.typeName(), "PropertyObject::Alpha");
QCOMPARE(property.userType(), QMetaType::fromType<PropertyObject::Alpha>().id());
QVariant var = object.property("alpha");
@@ -1947,7 +2050,7 @@ void tst_QObject::property()
const int idx = mo->indexOfProperty("variant");
QVERIFY(idx != -1);
- QCOMPARE(QMetaType::Type(mo->property(idx).type()), QMetaType::QVariant);
+ QCOMPARE(mo->property(idx).userType(), QMetaType::QVariant);
QCOMPARE(object.property("variant"), QVariant());
QVariant variant1(42);
QVariant variant2("string");
@@ -1966,10 +2069,10 @@ void tst_QObject::property()
QVERIFY(!property.isEnumType());
QCOMPARE(property.typeName(), "CustomType*");
qRegisterMetaType<CustomType*>();
- QCOMPARE(property.type(), QVariant::UserType);
+ QCOMPARE_GE(property.typeId(), QMetaType::User);
QCOMPARE(property.userType(), qMetaTypeId<CustomType*>());
- CustomType *customPointer = 0;
+ CustomType *customPointer = nullptr;
QVariant customVariant = object.property("custom");
customPointer = qvariant_cast<CustomType *>(customVariant);
QCOMPARE(customPointer, object.custom());
@@ -1981,7 +2084,7 @@ void tst_QObject::property()
property = mo->property(mo->indexOfProperty("custom"));
QVERIFY(property.isWritable());
QCOMPARE(property.typeName(), "CustomType*");
- QCOMPARE(property.type(), QVariant::UserType);
+ QCOMPARE_GE(property.typeId(), QMetaType::User);
QCOMPARE(property.userType(), qMetaTypeId<CustomType*>());
QVERIFY(object.setProperty("custom", customVariant));
@@ -1995,7 +2098,7 @@ void tst_QObject::property()
QVERIFY(mo->indexOfProperty("priority") != -1);
property = mo->property(mo->indexOfProperty("priority"));
QVERIFY(property.isEnumType());
- QCOMPARE(property.typeName(), "Priority");
+ QCOMPARE(property.typeName(), "PropertyObject::Priority");
QCOMPARE(property.userType(), QMetaType::fromType<PropertyObject::Priority>().id());
var = object.property("priority");
@@ -2011,13 +2114,13 @@ void tst_QObject::property()
QCOMPARE(object.property("priority").toInt(), 0);
// now it's registered, so it works as expected
- int priorityMetaTypeId = qRegisterMetaType<PropertyObject::Priority>("PropertyObject::Priority");
+ int priorityMetaTypeId = qRegisterMetaType<PropertyObject::Priority>();
QVERIFY(mo->indexOfProperty("priority") != -1);
property = mo->property(mo->indexOfProperty("priority"));
QVERIFY(property.isEnumType());
- QCOMPARE(property.typeName(), "Priority");
- QCOMPARE(property.type(), QVariant::UserType);
+ QCOMPARE(property.typeName(), "PropertyObject::Priority");
+ QCOMPARE_GE(property.typeId(), QMetaType::User);
QCOMPARE(property.userType(), priorityMetaTypeId);
var = object.property("priority");
@@ -2040,7 +2143,7 @@ void tst_QObject::property()
object.setProperty("priority", var);
QCOMPARE(qvariant_cast<PropertyObject::Priority>(object.property("priority")), PropertyObject::High);
- qRegisterMetaType<CustomString>("CustomString");
+ qRegisterMetaType<CustomString>();
QVERIFY(mo->indexOfProperty("customString") != -1);
QCOMPARE(object.property("customString").toString(), QString());
object.setCustomString("String1");
@@ -2113,18 +2216,18 @@ void tst_QObject::metamethod()
QVERIFY(!(m.attributes() & QMetaMethod::Compatibility));
m = mobj->method(mobj->indexOfMethod("invoke1()"));
- QCOMPARE(m.parameterNames().count(), 0);
- QCOMPARE(m.parameterTypes().count(), 0);
+ QCOMPARE(m.parameterNames().size(), 0);
+ QCOMPARE(m.parameterTypes().size(), 0);
m = mobj->method(mobj->indexOfMethod("invoke2(int)"));
- QCOMPARE(m.parameterNames().count(), 1);
- QCOMPARE(m.parameterTypes().count(), 1);
+ QCOMPARE(m.parameterNames().size(), 1);
+ QCOMPARE(m.parameterTypes().size(), 1);
QCOMPARE(m.parameterTypes().at(0), QByteArray("int"));
QVERIFY(m.parameterNames().at(0).isEmpty());
m = mobj->method(mobj->indexOfMethod("invoke3(int,int)"));
- QCOMPARE(m.parameterNames().count(), 2);
- QCOMPARE(m.parameterTypes().count(), 2);
+ QCOMPARE(m.parameterNames().size(), 2);
+ QCOMPARE(m.parameterTypes().size(), 2);
QCOMPARE(m.parameterTypes().at(0), QByteArray("int"));
QCOMPARE(m.parameterNames().at(0), QByteArray("hinz"));
QCOMPARE(m.parameterTypes().at(1), QByteArray("int"));
@@ -2166,7 +2269,7 @@ public:
SuperObject()
{
- theSender = 0;
+ theSender = nullptr;
theSignalId = 0;
}
@@ -2230,7 +2333,7 @@ void tst_QObject::senderTest()
QCOMPARE(receiver->sender(), (QObject *)0);
QCOMPARE(receiver->senderSignalIndex(), -1);
- receiver->theSender = 0;
+ receiver->theSender = nullptr;
receiver->theSignalId = -1;
thread.start();
emit sender->theSignal();
@@ -2879,7 +2982,7 @@ void tst_QObject::floatProperty()
QVERIFY(idx > 0);
QMetaProperty prop = obj.metaObject()->property(idx);
QVERIFY(prop.isValid());
- QCOMPARE(int(prop.type()), QMetaType::type("float"));
+ QCOMPARE(prop.typeId(), QMetaType::fromType<float>().id());
QVERIFY(!prop.write(&obj, QVariant("Hello")));
QVERIFY(prop.write(&obj, QVariant::fromValue(128.0f)));
QVariant v = prop.read(&obj);
@@ -2894,7 +2997,7 @@ void tst_QObject::qrealProperty()
QVERIFY(idx > 0);
QMetaProperty prop = obj.metaObject()->property(idx);
QVERIFY(prop.isValid());
- QCOMPARE(int(prop.type()), QMetaType::type("qreal"));
+ QCOMPARE(prop.typeId(), QMetaType::fromType<qreal>().id());
QVERIFY(!prop.write(&obj, QVariant("Hello")));
QVERIFY(prop.write(&obj, QVariant::fromValue(128.0f)));
@@ -2939,31 +3042,31 @@ void tst_QObject::dynamicProperties()
// set a dynamic property
QVERIFY(!obj.setProperty("myuserproperty", "Hello"));
- QCOMPARE(obj.changedDynamicProperties.count(), 1);
+ QCOMPARE(obj.changedDynamicProperties.size(), 1);
QCOMPARE(obj.changedDynamicProperties.first(), QByteArray("myuserproperty"));
//check if there is no redundant DynamicPropertyChange events
QVERIFY(!obj.setProperty("myuserproperty", "Hello"));
- QCOMPARE(obj.changedDynamicProperties.count(), 1);
+ QCOMPARE(obj.changedDynamicProperties.size(), 1);
- QCOMPARE(obj.property("myuserproperty").type(), QVariant::String);
+ QCOMPARE(obj.property("myuserproperty").typeId(), QMetaType::QString);
QCOMPARE(obj.property("myuserproperty").toString(), QString("Hello"));
- QCOMPARE(obj.dynamicPropertyNames().count(), 1);
+ QCOMPARE(obj.dynamicPropertyNames().size(), 1);
QCOMPARE(obj.dynamicPropertyNames().first(), QByteArray("myuserproperty"));
// change type of the dynamic property
obj.changedDynamicProperties.clear();
QVERIFY(!obj.setProperty("myuserproperty", QByteArray("Hello")));
- QCOMPARE(obj.changedDynamicProperties.count(), 1);
+ QCOMPARE(obj.changedDynamicProperties.size(), 1);
QCOMPARE(obj.changedDynamicProperties.first(), QByteArray("myuserproperty"));
- QCOMPARE(obj.property("myuserproperty").type(), QVariant::ByteArray);
+ QCOMPARE(obj.property("myuserproperty").typeId(), QMetaType::QByteArray);
QCOMPARE(obj.property("myuserproperty").toString(), QByteArray("Hello"));
// unset the property
obj.changedDynamicProperties.clear();
QVERIFY(!obj.setProperty("myuserproperty", QVariant()));
- QCOMPARE(obj.changedDynamicProperties.count(), 1);
+ QCOMPARE(obj.changedDynamicProperties.size(), 1);
QCOMPARE(obj.changedDynamicProperties.first(), QByteArray("myuserproperty"));
obj.changedDynamicProperties.clear();
@@ -3039,6 +3142,8 @@ void tst_QObject::blockingQueuedConnection()
}
}
+static int s_eventSpyCounter = -1;
+
class EventSpy : public QObject
{
Q_OBJECT
@@ -3046,7 +3151,7 @@ class EventSpy : public QObject
public:
typedef QList<QPair<QObject *, QEvent::Type> > EventList;
- EventSpy(QObject *parent = 0)
+ EventSpy(QObject *parent = nullptr)
: QObject(parent)
{ }
@@ -3058,14 +3163,17 @@ public:
void clear()
{
events.clear();
+ thisCounter = -1;
}
bool eventFilter(QObject *object, QEvent *event) override
{
events.append(qMakePair(object, event->type()));
+ thisCounter = ++s_eventSpyCounter;
return false;
}
+ int thisCounter = -1;
private:
EventList events;
};
@@ -3154,6 +3262,78 @@ void tst_QObject::childEvents()
}
}
+void tst_QObject::parentEvents()
+{
+#ifdef QT_BUILD_INTERNAL
+ EventSpy::EventList expected;
+
+ {
+ // Parent events not enabled
+ QObject parent;
+ QObject child;
+
+ EventSpy spy;
+ child.installEventFilter(&spy);
+
+ QCoreApplication::postEvent(&child, new QEvent(QEvent::Type(QEvent::User + 1)));
+
+ child.setParent(&parent);
+
+ QCoreApplication::postEvent(&child, new QEvent(QEvent::Type(QEvent::User + 2)));
+
+ expected =
+ EventSpy::EventList();
+ QCOMPARE(spy.eventList(), expected);
+ spy.clear();
+
+ QCoreApplication::processEvents();
+
+ expected =
+ EventSpy::EventList()
+ << qMakePair(&child, QEvent::Type(QEvent::User + 1))
+ << qMakePair(&child, QEvent::Type(QEvent::User + 2));
+ QCOMPARE(spy.eventList(), expected);
+ }
+
+ {
+ // Parent events enabled
+ QObject parent;
+ QObject child;
+ auto *childPrivate = QObjectPrivate::get(&child);
+ childPrivate->receiveParentEvents = true;
+
+ EventSpy spy;
+ child.installEventFilter(&spy);
+
+ QCoreApplication::postEvent(&child, new QEvent(QEvent::Type(QEvent::User + 1)));
+
+ child.setParent(&parent);
+ child.setParent(nullptr);
+
+ QCoreApplication::postEvent(&child, new QEvent(QEvent::Type(QEvent::User + 2)));
+
+ expected =
+ EventSpy::EventList()
+ << qMakePair(&child, QEvent::ParentAboutToChange)
+ << qMakePair(&child, QEvent::ParentChange)
+ << qMakePair(&child, QEvent::ParentAboutToChange)
+ << qMakePair(&child, QEvent::ParentChange);
+ QCOMPARE(spy.eventList(), expected);
+ spy.clear();
+
+ QCoreApplication::processEvents();
+
+ expected =
+ EventSpy::EventList()
+ << qMakePair(&child, QEvent::Type(QEvent::User + 1))
+ << qMakePair(&child, QEvent::Type(QEvent::User + 2));
+ QCOMPARE(spy.eventList(), expected);
+ }
+#else
+ QSKIP("Needs QT_BUILD_INTERNAL");
+#endif
+}
+
void tst_QObject::installEventFilter()
{
QEvent event(QEvent::User);
@@ -3195,6 +3375,70 @@ void tst_QObject::installEventFilter()
QVERIFY(spy.eventList().isEmpty());
}
+#define CHECK_FAIL(message) \
+do {\
+ if (QTest::currentTestFailed())\
+ QFAIL("failed one line above on " message);\
+} while (false)
+
+void tst_QObject::installEventFilterOrder()
+{
+ // installEventFilter() adds new objects to d_func()->extraData->eventFilters, which
+ // affects the order of calling each object's eventFilter() when processing the events.
+
+ QObject object;
+ EventSpy spy1, spy2, spy3;
+
+ auto clearSignalSpies = [&] {
+ for (auto *s : {&spy1, &spy2, &spy3})
+ s->clear();
+ s_eventSpyCounter = -1;
+ };
+
+ const EventSpy::EventList expected = { { &object, QEvent::Type(QEvent::User + 1) } };
+
+ // Call Order: from first to last
+ auto checkCallOrder = [&expected](const QList<EventSpy *> &spies) {
+ for (int i = 0; i < spies.size(); ++i) {
+ EventSpy *spy = spies.at(i);
+ QVERIFY2(spy->eventList() == expected,
+ QString("The spy %1 wasn't triggered exactly once.").arg(i).toLatin1());
+ QCOMPARE(spy->thisCounter, i);
+ }
+ };
+
+ // Install event filters and check the order of invocations:
+ // The last installed = the first called.
+ object.installEventFilter(&spy1);
+ object.installEventFilter(&spy2);
+ object.installEventFilter(&spy3);
+ clearSignalSpies();
+ QCoreApplication::postEvent(&object, new QEvent(QEvent::Type(QEvent::User + 1)));
+ QCoreApplication::processEvents();
+ checkCallOrder({ &spy3, &spy2, &spy1 });
+ CHECK_FAIL("checkCallOrder() - 1st round");
+
+ // Install event filter for `spy1` again, which reorders spy1 in `eventFilters`
+ // (the list doesn't have duplicates).
+ object.installEventFilter(&spy1);
+ clearSignalSpies();
+ QCoreApplication::postEvent(&object, new QEvent(QEvent::Type(QEvent::User + 1)));
+ QCoreApplication::processEvents();
+ checkCallOrder({ &spy1, &spy3, &spy2 });
+ CHECK_FAIL("checkCallOrder() - 2nd round");
+
+ // Remove event filter for `spy3`, ensure it's not called anymore and the
+ // existing filters order is preserved.
+ object.removeEventFilter(&spy3);
+ clearSignalSpies();
+ QCoreApplication::postEvent(&object, new QEvent(QEvent::Type(QEvent::User + 1)));
+ QCoreApplication::processEvents();
+ checkCallOrder({ &spy1, &spy2 });
+ CHECK_FAIL("checkCallOrder() - 3rd round");
+ QVERIFY(spy3.eventList().isEmpty());
+ QCOMPARE(spy3.thisCounter, -1);
+}
+
class EmitThread : public QThread
{ Q_OBJECT
public:
@@ -3378,6 +3622,32 @@ void tst_QObject::dumpObjectInfo()
a.dumpObjectInfo(); // should not crash
}
+void tst_QObject::dumpObjectTree()
+{
+ QObject a;
+ Q_SET_OBJECT_NAME(a);
+
+ QTimer b(&a);
+ Q_SET_OBJECT_NAME(b);
+
+ QObject c(&b);
+ Q_SET_OBJECT_NAME(c);
+
+ QFile f(&a);
+ Q_SET_OBJECT_NAME(f);
+
+ const char * const output[] = {
+ "QObject::a ",
+ " QTimer::b ",
+ " QObject::c ",
+ " QFile::f ",
+ };
+ for (const char *line : output)
+ QTest::ignoreMessage(QtDebugMsg, line);
+
+ a.dumpObjectTree();
+}
+
class ConnectToSender : public QObject
{ Q_OBJECT
public slots:
@@ -3555,8 +3825,6 @@ void tst_QObject::interfaceIid()
QByteArray(Bleh_iid));
QCOMPARE(QByteArray(qobject_interface_iid<Foo::Bar *>()),
QByteArray("com.qtest.foobar"));
- QCOMPARE(QByteArray(qobject_interface_iid<FooObject *>()),
- QByteArray());
}
void tst_QObject::deleteQObjectWhenDeletingEvent()
@@ -3582,9 +3850,9 @@ class OverloadObject : public QObject
signals:
void sig(int i, char c, qreal m = 12);
void sig(int i, int j = 12);
- void sig(QObject *o, QObject *p, QObject *q = 0, QObject *r = 0) const;
+ void sig(QObject *o, QObject *p, QObject *q = nullptr, QObject *r = nullptr) const;
void other(int a = 0);
- void sig(QObject *o, OverloadObject *p = 0, QObject *q = 0, QObject *r = nullptr);
+ void sig(QObject *o, OverloadObject *p = nullptr, QObject *q = nullptr, QObject *r = nullptr);
void sig(double r = 0.5);
public slots:
void slo(int i, int j = 43)
@@ -4473,6 +4741,17 @@ void tst_QObject::pointerConnect()
con = connect(&r1, &ReceiverObject::slot4 , &s, &SenderObject::signal4);
QVERIFY(!con);
QVERIFY(!QObject::disconnect(con));
+
+ //connect an arbitrary PMF to a slot
+ QTest::ignoreMessage(QtWarningMsg, "QObject::connect: signal not found in ReceiverObject");
+ con = connect(&r1, &ReceiverObject::reset, &r1, &ReceiverObject::slot1);
+ QVERIFY(!con);
+ QVERIFY(!QObject::disconnect(con));
+
+ QTest::ignoreMessage(QtWarningMsg, "QObject::connect: signal not found in ReceiverObject");
+ con = connect(&r1, &ReceiverObject::reset, &r1, [](){});
+ QVERIFY(!con);
+ QVERIFY(!QObject::disconnect(con));
}
void tst_QObject::pointerDisconnect()
@@ -4655,8 +4934,7 @@ void tst_QObject::customTypesPointer()
checker.disconnect();
- int idx = qRegisterMetaType<CustomType>("CustomType");
- QCOMPARE(QMetaType::type("CustomType"), idx);
+ qRegisterMetaType<CustomType>();
connect(&checker, &QCustomTypeChecker::signal1, &checker, &QCustomTypeChecker::slot1,
Qt::QueuedConnection);
@@ -4669,11 +4947,6 @@ void tst_QObject::customTypesPointer()
QCOMPARE(checker.received.value(), t2.value());
QCOMPARE(instanceCount, 4);
- QVERIFY(QMetaType::isRegistered(idx));
- QCOMPARE(qRegisterMetaType<CustomType>("CustomType"), idx);
- QCOMPARE(QMetaType::type("CustomType"), idx);
- QVERIFY(QMetaType::isRegistered(idx));
-
// Test auto registered type (QList<CustomType>)
QList<CustomType> list;
QCOMPARE(instanceCount, 4);
@@ -5194,7 +5467,7 @@ namespace ManyArgumentNamespace {
}
};
- struct Funct6 {
+ struct Funct6 final {
void operator()(const QString &a, const QString &b, const QString &c, const QString&d, const QString&e, const QString&f) {
MANYARGUMENT_COMPARE(a); MANYARGUMENT_COMPARE(b); MANYARGUMENT_COMPARE(c);
MANYARGUMENT_COMPARE(d); MANYARGUMENT_COMPARE(e); MANYARGUMENT_COMPARE(f);
@@ -5908,10 +6181,10 @@ class ConnectToPrivateSlotPrivate;
class ConnectToPrivateSlot :public QObject {
Q_OBJECT
+ Q_DECLARE_PRIVATE(ConnectToPrivateSlot)
public:
ConnectToPrivateSlot();
void test(SenderObject *obj1) ;
- Q_DECLARE_PRIVATE(ConnectToPrivateSlot)
};
class ConnectToPrivateSlotPrivate : public QObjectPrivate {
@@ -5928,6 +6201,8 @@ public:
receivedCount++;
receivedValue = v;
};
+
+ void testFromPrivate(SenderObject *obj);
};
ConnectToPrivateSlot::ConnectToPrivateSlot(): QObject(*new ConnectToPrivateSlotPrivate) {}
@@ -5954,6 +6229,14 @@ void ConnectToPrivateSlot::test(SenderObject* obj1) {
QVERIFY(!QObjectPrivate::disconnect(obj1, &SenderObject::signal2, d, &ConnectToPrivateSlotPrivate::thisIsAPrivateSlot));
}
+// Compile test to verify that we can use QObjectPrivate::connect in
+// the code of the private class, even if Q_DECLARE_PUBLIC is used in the
+// private section of the private class.
+void ConnectToPrivateSlotPrivate::testFromPrivate(SenderObject *obj)
+{
+ QVERIFY(QObjectPrivate::connect(obj, &SenderObject::signal1, this, &ConnectToPrivateSlotPrivate::thisIsAPrivateSlot));
+}
+
void tst_QObject::connectPrivateSlots()
{
SenderObject sender;
@@ -5990,6 +6273,7 @@ void tst_QObject::connectFunctorArgDifference()
connect(&timer, &QTimer::timeout, [=](){});
connect(&timer, &QTimer::objectNameChanged, [=](const QString &){});
+ connect(&timer, &QTimer::objectNameChanged, this, [](){});
connect(qApp, &QCoreApplication::aboutToQuit, [=](){});
connect(&timer, &QTimer::objectNameChanged, [=](){});
@@ -6160,7 +6444,7 @@ public slots:
{
if (abouttoblock) {
abouttoblock->deleteLater();
- abouttoblock = 0;
+ abouttoblock = nullptr;
}
++m_aboutToBlocks;
}
@@ -6168,7 +6452,7 @@ public slots:
{
if (awake) {
awake->deleteLater();
- awake = 0;
+ awake = nullptr;
}
++m_awakes;
@@ -6214,13 +6498,49 @@ void tst_QObject::connectFunctorWithContextUnique()
SenderObject sender;
ReceiverObject receiver;
- QObject::connect(&sender, &SenderObject::signal1, &receiver, &ReceiverObject::slot1);
+ QVERIFY(QObject::connect(&sender, &SenderObject::signal1, &receiver, &ReceiverObject::slot1));
receiver.count_slot1 = 0;
- QObject::connect(&sender, &SenderObject::signal1, &receiver, SlotFunctor(), Qt::UniqueConnection);
+ QVERIFY(QObject::connect(&sender, &SenderObject::signal2, &receiver, &ReceiverObject::slot2));
+ receiver.count_slot2 = 0;
+
+ const auto oredType = Qt::ConnectionType(Qt::DirectConnection | Qt::UniqueConnection);
+
+ // Will assert in debug builds, so only test in release builds
+#if defined(QT_NO_DEBUG) && !defined(QT_FORCE_ASSERTS)
+ auto ignoreMsg = [] {
+ QTest::ignoreMessage(QtWarningMsg,
+ "QObject::connect(SenderObject, ReceiverObject): unique connections "
+ "require a pointer to member function of a QObject subclass");
+ };
+
+ ignoreMsg();
+ QVERIFY(!QObject::connect(&sender, &SenderObject::signal1, &receiver, [&](){ receiver.slot1(); }, Qt::UniqueConnection));
+
+ ignoreMsg();
+ QVERIFY(!QObject::connect(
+ &sender, &SenderObject::signal2, &receiver, [&]() { receiver.slot2(); }, oredType));
+#endif
sender.emitSignal1();
QCOMPARE(receiver.count_slot1, 1);
+
+ sender.emitSignal2();
+ QCOMPARE(receiver.count_slot2, 1);
+
+ // Check connecting to PMF doesn't hit the assert
+
+ QVERIFY(QObject::connect(&sender, &SenderObject::signal3, &receiver, &ReceiverObject::slot3,
+ Qt::UniqueConnection));
+ receiver.count_slot3 = 0;
+ sender.emitSignal3();
+ QCOMPARE(receiver.count_slot3, 1);
+
+ QVERIFY(QObject::connect(&sender, &SenderObject::signal4, &receiver, &ReceiverObject::slot4,
+ oredType));
+ receiver.count_slot4 = 0;
+ sender.emitSignal4();
+ QCOMPARE(receiver.count_slot4, 1);
}
class MyFunctor
@@ -6727,7 +7047,11 @@ struct QmlReceiver : public QtPrivate::QSlotObjectBase
, magic(0)
{}
+#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
static void impl(int which, QSlotObjectBase *this_, QObject *, void **metaArgs, bool *ret)
+#else
+ static void impl(QSlotObjectBase *this_, QObject *, void **metaArgs, int which, bool *ret)
+#endif
{
switch (which) {
case Destroy: delete static_cast<QmlReceiver*>(this_); return;
@@ -6767,6 +7091,33 @@ void tst_QObject::qmlConnect()
#endif
}
+void tst_QObject::qmlConnectToQObjectReceiver()
+{
+#ifdef QT_BUILD_INTERNAL
+ SenderObject sender;
+ QScopedPointer<QObject> receiver(new QObject);
+ QmlReceiver *slotObject = new QmlReceiver;
+ slotObject->magic = slotObject;
+ slotObject->ref(); // extra ref so that slot object is not implicitly deleted
+
+ QVERIFY(QObjectPrivate::connect(&sender, sender.metaObject()->indexOfSignal("signal1()"),
+ receiver.get(), slotObject, Qt::AutoConnection));
+
+ QCOMPARE(slotObject->callCount, 0);
+ sender.emitSignal1();
+ QCOMPARE(slotObject->callCount, 1);
+
+ receiver.reset(); // this should disconnect the slotObject
+
+ sender.emitSignal1();
+ QCOMPARE(slotObject->callCount, 1);
+
+ slotObject->destroyIfLastRef();
+#else
+ QSKIP("Needs QT_BUILD_INTERNAL");
+#endif
+}
+
#ifndef QT_NO_EXCEPTIONS
class ObjectException : public std::exception { };
@@ -6942,42 +7293,6 @@ void tst_QObject::exceptions()
#endif
}
-#ifdef QT_BUILD_INTERNAL
-static bool parentChangeCalled = false;
-
-static void testParentChanged(QAbstractDeclarativeData *, QObject *, QObject *)
-{
- parentChangeCalled = true;
-}
-#endif
-
-void tst_QObject::noDeclarativeParentChangedOnDestruction()
-{
-#ifdef QT_BUILD_INTERNAL
- typedef void (*ParentChangedCallback)(QAbstractDeclarativeData *, QObject *, QObject *);
- QScopedValueRollback<ParentChangedCallback> rollback(QAbstractDeclarativeData::parentChanged);
- QAbstractDeclarativeData::parentChanged = testParentChanged;
-
- QObject *parent = new QObject;
- QObject *child = new QObject;
-
- QAbstractDeclarativeData dummy;
- QObjectPrivate::get(child)->declarativeData = &dummy;
-
- parentChangeCalled = false;
- child->setParent(parent);
-
- QVERIFY(parentChangeCalled);
- parentChangeCalled = false;
-
- delete child;
- QVERIFY(!parentChangeCalled);
-
- delete parent;
-#else
- QSKIP("Needs QT_BUILD_INTERNAL");
-#endif
-}
struct MutableFunctor {
int count;
@@ -6999,6 +7314,12 @@ void tst_QObject::mutableFunctor()
void tst_QObject::checkArgumentsForNarrowing()
{
+ // Clang and ICC masquerade as GCC, so introduce a more strict define
+ // for exactly GCC (to exclude/include it from some tests).
+#if defined(Q_CC_GNU) && !defined(Q_CC_CLANG)
+#define Q_CC_EXACTLY_GCC Q_CC_GNU
+#endif
+
enum UnscopedEnum { UnscopedEnumV1 = INT_MAX, UnscopedEnumV2 };
enum SignedUnscopedEnum { SignedUnscopedEnumV1 = INT_MIN, SignedUnscopedEnumV2 = INT_MAX };
@@ -7016,7 +7337,7 @@ void tst_QObject::checkArgumentsForNarrowing()
// GCC < 9 does not consider floating point to bool to be narrowing,
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65043
-#if !defined(Q_CC_GNU) || Q_CC_GNU >= 900
+#if !defined(Q_CC_EXACTLY_GCC) || Q_CC_EXACTLY_GCC >= 900
NARROWS(float, bool);
NARROWS(double, bool);
NARROWS(long double, bool);
@@ -7049,10 +7370,10 @@ void tst_QObject::checkArgumentsForNarrowing()
FITS(float, double);
FITS(float, long double);
- // GCC thinks this is narrowing only on architectures where
+ // GCC < 11 thinks this is narrowing only on architectures where
// sizeof(long double) > sizeof(double)
- // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92856
-#if defined(Q_CC_GNU)
+ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94590
+#if defined(Q_CC_EXACTLY_GCC) && (Q_CC_EXACTLY_GCC < 1100)
NARROWS_IF(long double, double, sizeof(long double) > sizeof(double));
#else
NARROWS(long double, double);
@@ -7202,11 +7523,14 @@ void tst_QObject::checkArgumentsForNarrowing()
// integral to integral with different signedness. smaller ones tested above
NARROWS(signed char, unsigned char);
+
+ // Issue is reported to Green Hills, 2021-09-14.
+#if !defined(Q_CC_GHS)
NARROWS(signed char, unsigned short);
NARROWS(signed char, unsigned int);
NARROWS(signed char, unsigned long);
NARROWS(signed char, unsigned long long);
-
+#endif // Q_CC_GHS
NARROWS(unsigned char, signed char);
FITS(unsigned char, short);
FITS(unsigned char, int);
@@ -7214,19 +7538,23 @@ void tst_QObject::checkArgumentsForNarrowing()
FITS(unsigned char, long long);
NARROWS(short, unsigned short);
+#if !defined(Q_CC_GHS)
NARROWS(short, unsigned int);
NARROWS(short, unsigned long);
- NARROWS(short, unsigned long long);
+ NARROWS(short, unsigned long long);
+#endif // Q_CC_GHS
NARROWS(unsigned short, short);
+
FITS(unsigned short, int);
FITS(unsigned short, long);
FITS(unsigned short, long long);
NARROWS(int, unsigned int);
+#if !defined(Q_CC_GHS)
NARROWS(int, unsigned long);
NARROWS(int, unsigned long long);
-
+#endif // Q_CC_GHS
NARROWS(unsigned int, int);
NARROWS_IF(unsigned int, long, (sizeof(int) >= sizeof(long)));
FITS(unsigned int, long long);
@@ -7284,18 +7612,22 @@ void tst_QObject::checkArgumentsForNarrowing()
/* implicit */ operator double() const { return 42.0; }
};
+#if !defined(Q_CC_GHS)
NARROWS(ConvertingToDouble, char);
NARROWS(ConvertingToDouble, short);
NARROWS(ConvertingToDouble, int);
NARROWS(ConvertingToDouble, long);
NARROWS(ConvertingToDouble, long long);
NARROWS(ConvertingToDouble, float);
+#endif // Q_CC_GHS
FITS(ConvertingToDouble, double);
FITS(ConvertingToDouble, long double);
- // no compiler still implements this properly.
-#if 0
+ // GCC, GHS and clang don't implement this properly yet:
+ // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99625
+ // https://bugs.llvm.org/show_bug.cgi?id=49676
+#if defined(Q_CC_MSVC) && !defined(Q_CC_CLANG) // at least since VS2017
struct ConstructibleFromInt {
/* implicit */ ConstructibleFromInt(int) {}
};
@@ -7314,7 +7646,9 @@ void tst_QObject::checkArgumentsForNarrowing()
class ForwardDeclared;
FITS(ForwardDeclared, ForwardDeclared);
-#if 0 // waiting for official compiler releases that implement P1957...
+#if (defined(Q_CC_EXACTLY_GCC) && Q_CC_EXACTLY_GCC >= 1100) \
+ || (defined(Q_CC_CLANG) && Q_CC_CLANG >= 1100) \
+ || defined(Q_CC_MSVC) // at least since VS2017
{
// wg21.link/P1957
NARROWS(char*, bool);
@@ -7326,6 +7660,10 @@ void tst_QObject::checkArgumentsForNarrowing()
#undef FITS_IF
#undef NARROWS
#undef FITS
+
+#ifdef Q_CC_EXACTLY_GCC
+#undef Q_CC_EXACTLY_GCC
+#endif
}
void tst_QObject::nullReceiver()
@@ -8087,9 +8425,409 @@ void tst_QObject::singleShotConnection()
}
}
+void tst_QObject::objectNameBinding()
+{
+ QObject obj;
+ QTestPrivate::testReadWritePropertyBasics<QObject, QString>(obj, "test1", "test2",
+ "objectName");
+}
+
+namespace EmitToDestroyedClass {
+static int assertionCallCount = 0;
+static int wouldHaveAssertedCount = 0;
+struct WouldAssert : std::exception {};
+class Base : public QObject
+{
+ Q_OBJECT
+public:
+ ~Base()
+ {
+ try {
+ emit theSignal();
+ } catch (const WouldAssert &) {
+ ++wouldHaveAssertedCount;
+ }
+ }
+
+signals:
+ void theSignal();
+};
+
+class Derived : public Base
+{
+ Q_OBJECT
+public:
+ ~Derived() { }
+
+public slots:
+ void doNothing() {}
+};
+} // namespace EmitToDestroyedClass
+
+QT_BEGIN_NAMESPACE
+namespace QtPrivate {
+template<> void assertObjectType<EmitToDestroyedClass::Derived>(QObject *o)
+{
+ // override the assertion so we don't assert and so something does happen
+ // when assertions are disabled. By throwing, we also prevent the UB from
+ // happening.
+ using namespace EmitToDestroyedClass;
+ ++assertionCallCount;
+ if (!qobject_cast<Derived *>(o))
+ throw WouldAssert();
+}
+}
+QT_END_NAMESPACE
+
+void tst_QObject::emitToDestroyedClass()
+{
+ using namespace EmitToDestroyedClass;
+ std::unique_ptr ptr = std::make_unique<Derived>();
+ QObject::connect(ptr.get(), &Base::theSignal, ptr.get(), &Derived::doNothing);
+ QCOMPARE(assertionCallCount, 0);
+ QCOMPARE(wouldHaveAssertedCount, 0);
+
+ // confirm our replacement function did get called
+ emit ptr->theSignal();
+ QCOMPARE(assertionCallCount, 1);
+ QCOMPARE(wouldHaveAssertedCount, 0);
+
+ ptr.reset();
+ QCOMPARE(assertionCallCount, 2);
+ QCOMPARE(wouldHaveAssertedCount, 1);
+}
+
// Test for QtPrivate::HasQ_OBJECT_Macro
static_assert(QtPrivate::HasQ_OBJECT_Macro<tst_QObject>::Value);
static_assert(!QtPrivate::HasQ_OBJECT_Macro<SiblingDeleter>::Value);
+Q_DECLARE_SMART_POINTER_METATYPE(std::shared_ptr)
+Q_DECLARE_SMART_POINTER_METATYPE(std::unique_ptr)
+
+
+// QTBUG-103741: OK to use smart pointers to const QObject in signals/slots
+class SenderWithSharedPointerConstQObject : public QObject
+{
+ Q_OBJECT
+
+signals:
+ void aSignal1(const QSharedPointer<const QObject> &);
+ void aSignal2(const QWeakPointer<const QObject> &);
+ void aSignal3(const QPointer<const QObject> &);
+ void aSignal4(const std::shared_ptr<const QObject> &);
+ void aSignal5(const std::unique_ptr<const QObject> &);
+};
+
+#ifdef QT_BUILD_INTERNAL
+/*
+ Since QObjectPrivate stores the declarativeData pointer in a union with the pointer
+ to the currently destroyed child, calls to the QtDeclarative handlers need to be
+ correctly guarded. QTBUG-105286
+*/
+namespace QtDeclarative {
+static QAbstractDeclarativeData *theData;
+
+static void destroyed(QAbstractDeclarativeData *data, QObject *)
+{
+ QCOMPARE(data, theData);
+}
+static void signalEmitted(QAbstractDeclarativeData *data, QObject *, int, void **)
+{
+ QCOMPARE(data, theData);
+}
+// we can't use QCOMPARE in the next two functions, as they don't return void
+static int receivers(QAbstractDeclarativeData *data, const QObject *, int)
+{
+ QTest::qCompare(data, theData, "data", "theData", __FILE__, __LINE__);
+ return 0;
+}
+static bool isSignalConnected(QAbstractDeclarativeData *data, const QObject *, int)
+{
+ QTest::qCompare(data, theData, "data", "theData", __FILE__, __LINE__);
+ return true;
+}
+
+class Object : public QObject
+{
+ Q_OBJECT
+public:
+ using QObject::QObject;
+ ~Object()
+ {
+ if (Object *p = static_cast<Object *>(parent()))
+ p->emitSignal();
+ }
+
+ void emitSignal()
+ {
+ emit theSignal();
+ }
+
+signals:
+ void theSignal();
+};
+
+}
+#endif
+
+void tst_QObject::declarativeData()
+{
+#ifdef QT_BUILD_INTERNAL
+ QScopedValueRollback destroyed(QAbstractDeclarativeData::destroyed,
+ QtDeclarative::destroyed);
+ QScopedValueRollback signalEmitted(QAbstractDeclarativeData::signalEmitted,
+ QtDeclarative::signalEmitted);
+ QScopedValueRollback receivers(QAbstractDeclarativeData::receivers,
+ QtDeclarative::receivers);
+ QScopedValueRollback isSignalConnected(QAbstractDeclarativeData::isSignalConnected,
+ QtDeclarative::isSignalConnected);
+
+ QtDeclarative::Object p;
+ QObjectPrivate *priv = QObjectPrivate::get(&p);
+ priv->declarativeData = QtDeclarative::theData = new QAbstractDeclarativeData;
+
+ connect(&p, &QtDeclarative::Object::theSignal, &p, []{
+ });
+
+ QtDeclarative::Object *child = new QtDeclarative::Object;
+ child->setParent(&p);
+#endif
+}
+
+/*
+ Compile-time test for the helpers in qobjectdefs_impl.h.
+*/
+class AsyncCaller : public QObject
+{
+ Q_OBJECT
+public:
+ ~AsyncCaller()
+ {
+ if (slotObject)
+ slotObject->destroyIfLastRef();
+ }
+ void callback0() {}
+ void callback1(const QString &) {}
+ void callbackInt(int) {}
+ int returnInt() const { return 0; }
+
+ static int staticCallback0() { return 0; }
+ static void staticCallback1(const QString &) {}
+
+ using Prototype0 = int(*)();
+ using Prototype1 = void(*)(QString);
+
+ template<typename Functor>
+ bool callMe0(const typename QtPrivate::ContextTypeForFunctor<Functor>::ContextType *, Functor &&func)
+ {
+ if (slotObject) {
+ slotObject->destroyIfLastRef();
+ slotObject = nullptr;
+ }
+ QtPrivate::AssertCompatibleFunctions<Prototype0, Functor>();
+ slotObject = QtPrivate::makeCallableObject<Prototype0>(std::forward<Functor>(func));
+ return true;
+ }
+
+ template<typename Functor>
+ bool callMe0(Functor &&func)
+ {
+ return callMe0(nullptr, std::forward<Functor>(func));
+ }
+
+ template<typename Functor>
+ bool callMe1(const typename QtPrivate::ContextTypeForFunctor<Functor>::ContextType *, Functor &&func)
+ {
+ if (slotObject) {
+ slotObject->destroyIfLastRef();
+ slotObject = nullptr;
+ }
+ QtPrivate::AssertCompatibleFunctions<Prototype1, Functor>();
+ slotObject = QtPrivate::makeCallableObject<Prototype1>(std::forward<Functor>(func));
+ return true;
+ }
+
+ template<typename Functor>
+ bool callMe1(Functor &&func)
+ {
+ return callMe1(nullptr, std::forward<Functor>(func));
+ }
+
+ QtPrivate::QSlotObjectBase *slotObject = nullptr;
+};
+
+static void freeFunction0() {}
+static void freeFunction1(QString) {}
+static void freeFunctionVariant(QVariant) {}
+
+template<typename Prototype, typename Functor>
+inline constexpr bool compiles(Functor &&) {
+ return QtPrivate::AreFunctionsCompatible<Prototype, Functor>::value;
+}
+
+void tst_QObject::asyncCallbackHelper()
+{
+ int result = 0;
+ QString arg1 = "Parameter";
+ void *argv[] = { &result, &arg1 };
+
+ auto lambda0 = []{};
+ auto lambda1 = [](const QString &) {};
+ auto lambda2 = [](const QString &, int) {};
+ const auto constLambda = [](const QString &) {};
+ auto moveOnlyLambda = [u = std::unique_ptr<int>()]{};
+ auto moveOnlyLambda1 = [u = std::unique_ptr<int>()](const QString &){};
+
+ SlotFunctor functor0;
+ SlotFunctorString functor1;
+
+ // no parameters provided or needed
+ static_assert(compiles<AsyncCaller::Prototype0>(&AsyncCaller::callback0));
+ static_assert(compiles<AsyncCaller::Prototype0>(&AsyncCaller::staticCallback0));
+ static_assert(compiles<AsyncCaller::Prototype0>(lambda0));
+ static_assert(compiles<AsyncCaller::Prototype0>(std::move(moveOnlyLambda)));
+ static_assert(compiles<AsyncCaller::Prototype0>(freeFunction0));
+ static_assert(compiles<AsyncCaller::Prototype0>(functor0));
+
+ // more parameters than needed
+ static_assert(compiles<AsyncCaller::Prototype1>(&AsyncCaller::callback0));
+ static_assert(compiles<AsyncCaller::Prototype1>(&AsyncCaller::staticCallback0));
+ static_assert(compiles<AsyncCaller::Prototype1>(lambda0));
+ static_assert(compiles<AsyncCaller::Prototype1>(freeFunction0));
+ static_assert(compiles<AsyncCaller::Prototype1>(functor0));
+
+ // matching parameter
+ static_assert(compiles<AsyncCaller::Prototype1>(&AsyncCaller::callback1));
+ static_assert(compiles<AsyncCaller::Prototype1>(&AsyncCaller::staticCallback1));
+ static_assert(compiles<AsyncCaller::Prototype1>(lambda1));
+ static_assert(compiles<AsyncCaller::Prototype1>(std::move(moveOnlyLambda1)));
+ static_assert(compiles<AsyncCaller::Prototype1>(constLambda));
+ static_assert(compiles<AsyncCaller::Prototype1>(freeFunction1));
+ static_assert(compiles<AsyncCaller::Prototype1>(functor1));
+
+ // not enough parameters
+ static_assert(!compiles<AsyncCaller::Prototype0>(&AsyncCaller::callback1));
+ static_assert(!compiles<AsyncCaller::Prototype0>(&AsyncCaller::staticCallback1));
+ static_assert(!compiles<AsyncCaller::Prototype0>(lambda1));
+ static_assert(!compiles<AsyncCaller::Prototype0>(constLambda));
+ static_assert(!compiles<AsyncCaller::Prototype0>(lambda2));
+ static_assert(!compiles<AsyncCaller::Prototype0>(freeFunction1));
+ static_assert(!compiles<AsyncCaller::Prototype0>(functor1));
+
+ // wrong parameter type
+ static_assert(!compiles<AsyncCaller::Prototype1>(&AsyncCaller::callbackInt));
+
+ // old-style slot name
+ static_assert(!compiles<AsyncCaller::Prototype0>("callback1"));
+
+ // slot with return value is ok, we just don't pass
+ // the return value through to anything.
+ static_assert(compiles<AsyncCaller::Prototype0>(&AsyncCaller::returnInt));
+
+ static_assert(compiles<AsyncCaller::Prototype1>(freeFunctionVariant));
+
+ std::function<int()> stdFunction0(&AsyncCaller::staticCallback0);
+ std::function<void(QString)> stdFunction1(&AsyncCaller::staticCallback1);
+ static_assert(compiles<AsyncCaller::Prototype0>(stdFunction0));
+ static_assert(compiles<AsyncCaller::Prototype1>(stdFunction1));
+
+ AsyncCaller caller;
+ // with context
+ QVERIFY(caller.callMe0(&caller, &AsyncCaller::callback0));
+ QVERIFY(caller.callMe0(&caller, &AsyncCaller::returnInt));
+ QVERIFY(caller.callMe0(&caller, &AsyncCaller::staticCallback0));
+ QVERIFY(caller.callMe0(&caller, lambda0));
+ QVERIFY(caller.callMe0(&caller, freeFunction0));
+ QVERIFY(caller.callMe0(&caller, std::move(moveOnlyLambda)));
+ QVERIFY(caller.callMe0(&caller, stdFunction0));
+
+ QVERIFY(caller.callMe1(&caller, &AsyncCaller::callback1));
+ QVERIFY(caller.callMe1(&caller, &AsyncCaller::staticCallback1));
+ QVERIFY(caller.callMe1(&caller, lambda1));
+ QVERIFY(caller.callMe1(&caller, freeFunction1));
+ QVERIFY(caller.callMe1(&caller, constLambda));
+ QVERIFY(caller.callMe1(&caller, stdFunction1));
+
+ // without context
+ QVERIFY(caller.callMe0(&AsyncCaller::staticCallback0));
+ QVERIFY(caller.callMe0(lambda0));
+ QVERIFY(caller.callMe0(freeFunction0));
+ QVERIFY(caller.callMe0(stdFunction0));
+
+ QVERIFY(caller.callMe1(&AsyncCaller::staticCallback1));
+ QVERIFY(caller.callMe1(lambda1));
+ QVERIFY(caller.callMe1(constLambda));
+ QVERIFY(caller.callMe1(std::move(moveOnlyLambda1)));
+ QVERIFY(caller.callMe1(freeFunction1));
+ QVERIFY(caller.callMe1(stdFunction1));
+
+ static const char *expectedPayload = "Hello World!";
+ {
+ struct MoveOnlyFunctor {
+ MoveOnlyFunctor() = default;
+ MoveOnlyFunctor(MoveOnlyFunctor &&) = default;
+ MoveOnlyFunctor(const MoveOnlyFunctor &) = delete;
+ ~MoveOnlyFunctor() = default;
+
+ int operator()() const {
+ qDebug().noquote() << payload;
+ return int(payload.length());
+ }
+ QString payload = expectedPayload;
+ } moveOnlyFunctor;
+ QVERIFY(caller.callMe0(std::move(moveOnlyFunctor)));
+ }
+ QTest::ignoreMessage(QtDebugMsg, expectedPayload);
+ caller.slotObject->call(nullptr, argv);
+ QCOMPARE(result, QLatin1String(expectedPayload).length());
+
+ // mutable lambda; same behavior as mutableFunctor - we copy the functor
+ // in the QCallableObject, so the original is not modified
+ int status = 0;
+ auto mutableLambda1 = [&status, calls = 0]() mutable { status = ++calls; };
+
+ mutableLambda1();
+ QCOMPARE(status, 1);
+ QVERIFY(caller.callMe0(mutableLambda1)); // this copies the lambda with count == 1
+ caller.slotObject->call(nullptr, argv); // this doesn't change mutableLambda1, but the copy
+ QCOMPARE(status, 2);
+ mutableLambda1();
+ QCOMPARE(status, 2); // and we are still at two
+
+ auto mutableLambda2 = [calls = 0]() mutable { return ++calls; };
+ QCOMPARE(mutableLambda2(), 1);
+ QVERIFY(caller.callMe0(mutableLambda2)); // this copies the lambda
+ caller.slotObject->call(nullptr, argv); // this call doesn't change mutableLambda2
+ QCOMPARE(mutableLambda2(), 2); // so we are still at 2
+
+ {
+ int called = -1;
+ struct MutableFunctor {
+ void operator()() { called = 0; }
+ int &called;
+ };
+ struct ConstFunctor
+ {
+ void operator()() const { called = 1; }
+ int &called;
+ };
+
+ MutableFunctor mf{called};
+ QMetaObject::invokeMethod(this, mf);
+ QCOMPARE(called, 0);
+ ConstFunctor cf{called};
+ QMetaObject::invokeMethod(this, cf);
+ QCOMPARE(called, 1);
+ QMetaObject::invokeMethod(this, [&called, u = std::unique_ptr<int>()]{ called = 2; });
+ QCOMPARE(called, 2);
+ QMetaObject::invokeMethod(this, [&called, count = 0]() mutable {
+ if (!count)
+ called = 3;
+ ++count;
+ });
+ QCOMPARE(called, 3);
+ }
+}
+
QTEST_MAIN(tst_QObject)
#include "tst_qobject.moc"
diff --git a/tests/auto/corelib/kernel/qpermission/.gitignore b/tests/auto/corelib/kernel/qpermission/.gitignore
new file mode 100644
index 0000000000..56a6bf0795
--- /dev/null
+++ b/tests/auto/corelib/kernel/qpermission/.gitignore
@@ -0,0 +1 @@
+tst_qpermission
diff --git a/tests/auto/corelib/kernel/qpermission/CMakeLists.txt b/tests/auto/corelib/kernel/qpermission/CMakeLists.txt
new file mode 100644
index 0000000000..1af0331186
--- /dev/null
+++ b/tests/auto/corelib/kernel/qpermission/CMakeLists.txt
@@ -0,0 +1,19 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qpermission LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+if (NOT QT_FEATURE_permissions)
+ return()
+endif()
+
+qt_internal_add_test(tst_qpermission
+ SOURCES
+ tst_qpermission.cpp
+ LIBRARIES
+ Qt::Core
+)
diff --git a/tests/auto/corelib/kernel/qpermission/tst_qpermission.cpp b/tests/auto/corelib/kernel/qpermission/tst_qpermission.cpp
new file mode 100644
index 0000000000..dbf1d2dd84
--- /dev/null
+++ b/tests/auto/corelib/kernel/qpermission/tst_qpermission.cpp
@@ -0,0 +1,284 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QPermission>
+
+#include <QTest>
+
+struct DummyPermission // a minimal QPermission-compatible type
+{
+ using QtPermissionHelper = void;
+ int state = 0;
+};
+Q_DECLARE_METATYPE(DummyPermission)
+
+class tst_QPermission : public QObject
+{
+ Q_OBJECT
+private Q_SLOTS:
+ void converting_Dummy() const { return converting_impl<DummyPermission>(); }
+ void converting_Location() const { return converting_impl<QLocationPermission>(); }
+ void converting_Calendar() const { return converting_impl<QCalendarPermission>(); }
+ void converting_Contacts() const { return converting_impl<QContactsPermission>(); }
+ void converting_Camera() const { return converting_impl<QCameraPermission>(); }
+ void converting_Microphone() const { return converting_impl<QMicrophonePermission>(); }
+ void converting_Bluetooth() const { return converting_impl<QBluetoothPermission>(); }
+
+ void conversionMaintainsState() const;
+
+ void functorWithoutContext();
+ void functorWithContextInThread();
+ void receiverInThread();
+ void destroyedContextObject();
+private:
+ template <typename T>
+ void converting_impl() const;
+};
+
+template <typename T>
+void tst_QPermission::converting_impl() const
+{
+ T concrete;
+ const T cconcrete = concrete;
+ const auto metaType = QMetaType::fromType<T>();
+
+ // construction is implicit:
+ // from rvalue:
+ {
+ QPermission p = T();
+ QCOMPARE_EQ(p.type(), metaType);
+ }
+ // from mutable lvalue:
+ {
+ QPermission p = concrete;
+ QCOMPARE_EQ(p.type(), metaType);
+ }
+ // from const lvalue:
+ {
+ QPermission p = cconcrete;
+ QCOMPARE_EQ(p.type(), metaType);
+ }
+
+ // value<>() compiles:
+ {
+ const QPermission p = concrete;
+ auto v = p.value<T>();
+ static_assert(std::is_same_v<decltype(v), std::optional<T>>);
+ QCOMPARE_NE(v, std::nullopt);
+ }
+}
+
+void tst_QPermission::conversionMaintainsState() const
+{
+ DummyPermission dummy{42}, dummy_default;
+ QCOMPARE_NE(dummy.state, dummy_default.state);
+
+ QLocationPermission loc, loc_default;
+ QCOMPARE_EQ(loc_default.accuracy(), QLocationPermission::Accuracy::Approximate);
+ QCOMPARE_EQ(loc_default.availability(), QLocationPermission::Availability::WhenInUse);
+
+ loc.setAccuracy(QLocationPermission::Accuracy::Precise);
+ loc.setAvailability(QLocationPermission::Availability::Always);
+
+ QCOMPARE_EQ(loc.accuracy(), QLocationPermission::Accuracy::Precise);
+ QCOMPARE_EQ(loc.availability(), QLocationPermission::Availability::Always);
+
+ QCalendarPermission cal, cal_default;
+ QCOMPARE_EQ(cal_default.accessMode(), QCalendarPermission::AccessMode::ReadOnly);
+
+ cal.setAccessMode(QCalendarPermission::AccessMode::ReadWrite);
+
+ QCOMPARE_EQ(cal.accessMode(), QCalendarPermission::AccessMode::ReadWrite);
+
+ QContactsPermission con, con_default;
+ QCOMPARE_EQ(con_default.accessMode(), QContactsPermission::AccessMode::ReadOnly);
+
+ con.setAccessMode(QContactsPermission::AccessMode::ReadWrite);
+
+ QCOMPARE_EQ(con.accessMode(), QContactsPermission::AccessMode::ReadWrite);
+
+ //
+ // QCameraPermission, QMicrophonePermission, QBluetoothPermission don't have
+ // state at the time of writing
+ //
+
+ QPermission p; // maintain state between the blocks below to test reset behavior
+
+ {
+ p = dummy;
+ auto v = p.value<DummyPermission>();
+ QCOMPARE_NE(v, std::nullopt);
+ auto &r = *v;
+ QCOMPARE_EQ(r.state, dummy.state);
+ // check mismatched returns nullopt:
+ QCOMPARE_EQ(p.value<QCalendarPermission>(), std::nullopt);
+ }
+
+ {
+ p = loc;
+ auto v = p.value<QLocationPermission>();
+ QCOMPARE_NE(v, std::nullopt);
+ auto &r = *v;
+ QCOMPARE_EQ(r.accuracy(), loc.accuracy());
+ QCOMPARE_EQ(r.availability(), loc.availability());
+ // check mismatched returns nullopt:
+ QCOMPARE_EQ(p.value<DummyPermission>(), std::nullopt);
+ }
+
+ {
+ p = con;
+ auto v = p.value<QContactsPermission>();
+ QCOMPARE_NE(v, std::nullopt);
+ auto &r = *v;
+ QCOMPARE_EQ(r.accessMode(), con.accessMode());
+ // check mismatched returns nullopt:
+ QCOMPARE_EQ(p.value<QLocationPermission>(), std::nullopt);
+ }
+
+ {
+ p = cal;
+ auto v = p.value<QCalendarPermission>();
+ QCOMPARE_NE(v, std::nullopt);
+ auto &r = *v;
+ QCOMPARE_EQ(r.accessMode(), cal.accessMode());
+ // check mismatched returns nullopt:
+ QCOMPARE_EQ(p.value<QContactsPermission>(), std::nullopt);
+ }
+}
+
+template <typename Func,
+ typename T = std::void_t<decltype(qApp->requestPermission(std::declval<DummyPermission>(),
+ std::declval<Func>()))>
+ >
+void wrapRequestPermission(const QPermission &p, Func &&f)
+{
+ qApp->requestPermission(p, std::forward<Func>(f));
+}
+
+template <typename Functor>
+using CompatibleTest = decltype(wrapRequestPermission(std::declval<QPermission>(), std::declval<Functor>()));
+
+
+// Compile test for context-less functor overloads
+void tst_QPermission::functorWithoutContext()
+{
+ int argc = 0;
+ char *argv = nullptr;
+ QCoreApplication app(argc, &argv);
+
+ DummyPermission dummy;
+#ifdef Q_OS_DARWIN
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*Could not find permission plugin for DummyPermission.*"));
+#endif
+
+ qApp->requestPermission(dummy, [](const QPermission &permission){
+ QVERIFY(permission.value<DummyPermission>());
+ });
+ wrapRequestPermission(dummy, [](const QPermission &permission){
+ QVERIFY(permission.value<DummyPermission>());
+ });
+
+ auto compatible = [](const QPermission &) {};
+ using Compatible = decltype(compatible);
+ auto incompatible = [](const QString &) {};
+ using Incompatible = decltype(incompatible);
+
+ static_assert(qxp::is_detected_v<CompatibleTest, Compatible>);
+ static_assert(!qxp::is_detected_v<CompatibleTest, Incompatible>);
+}
+
+void tst_QPermission::functorWithContextInThread()
+{
+ int argc = 0;
+ char *argv = nullptr;
+ QCoreApplication app(argc, &argv);
+ QThread::currentThread()->setObjectName("main thread");
+ QThread receiverThread;
+ receiverThread.setObjectName("receiverThread");
+ QObject receiver;
+ receiver.moveToThread(&receiverThread);
+ receiverThread.start();
+ auto guard = qScopeGuard([&receiverThread]{
+ receiverThread.quit();
+ QVERIFY(receiverThread.wait(1000));
+ });
+
+ DummyPermission dummy;
+#ifdef Q_OS_DARWIN
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*Could not find permission plugin for DummyPermission.*"));
+#endif
+ QThread *permissionReceiverThread = nullptr;
+ qApp->requestPermission(dummy, &receiver, [&](const QPermission &permission){
+ auto dummy = permission.value<DummyPermission>();
+ QVERIFY(dummy);
+ permissionReceiverThread = QThread::currentThread();
+ });
+ QTRY_COMPARE(permissionReceiverThread, &receiverThread);
+}
+
+void tst_QPermission::receiverInThread()
+{
+ int argc = 0;
+ char *argv = nullptr;
+ QCoreApplication app(argc, &argv);
+ QThread::currentThread()->setObjectName("main thread");
+ QThread receiverThread;
+ receiverThread.setObjectName("receiverThread");
+ class Receiver : public QObject
+ {
+ public:
+ using QObject::QObject;
+ void handlePermission(const QPermission &permission)
+ {
+ auto dummy = permission.value<DummyPermission>();
+ QVERIFY(dummy);
+ permissionReceiverThread = QThread::currentThread();
+ }
+
+ QThread *permissionReceiverThread = nullptr;
+ } receiver;
+ receiver.moveToThread(&receiverThread);
+ receiverThread.start();
+ auto guard = qScopeGuard([&receiverThread]{
+ receiverThread.quit();
+ QVERIFY(receiverThread.wait(1000));
+ });
+
+ DummyPermission dummy;
+#ifdef Q_OS_DARWIN
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*Could not find permission plugin for DummyPermission.*"));
+#endif
+
+ qApp->requestPermission(dummy, &receiver, &Receiver::handlePermission);
+ QTRY_COMPARE(receiver.permissionReceiverThread, &receiverThread);
+
+ // compile tests: none of these work and the error output isn't horrible
+ // qApp->requestPermission(dummy, &receiver, "&tst_QPermission::receiverInThread");
+ // qApp->requestPermission(dummy, &receiver, &tst_QPermission::receiverInThread);
+ // qApp->requestPermission(dummy, &receiver, &QObject::destroyed);
+}
+
+void tst_QPermission::destroyedContextObject()
+{
+ int argc = 0;
+ char *argv = nullptr;
+ QCoreApplication app(argc, &argv);
+
+ QObject *context = new QObject;
+
+ DummyPermission dummy;
+#ifdef Q_OS_DARWIN
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression(".*Could not find permission plugin for DummyPermission.*"));
+#endif
+ bool permissionReceived = false;
+ qApp->requestPermission(dummy, context, [&]{
+ permissionReceived = true;
+ });
+ QVERIFY2(!permissionReceived, "Permission received synchronously");
+ delete context;
+ QTest::qWait(100);
+ QVERIFY(!permissionReceived);
+}
+
+QTEST_APPLESS_MAIN(tst_QPermission)
+#include "tst_qpermission.moc"
diff --git a/tests/auto/corelib/kernel/qpointer/CMakeLists.txt b/tests/auto/corelib/kernel/qpointer/CMakeLists.txt
index a24f25b087..b1570b8cef 100644
--- a/tests/auto/corelib/kernel/qpointer/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qpointer/CMakeLists.txt
@@ -1,18 +1,31 @@
-# Generated from qpointer.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qpointer Test:
#####################################################################
-qt_add_test(tst_qpointer
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qpointer LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+if (NOT QT_FEATURE_thread)
+ return()
+endif()
+
+qt_internal_add_test(tst_qpointer
SOURCES
tst_qpointer.cpp
+ LIBRARIES
+ Qt::Gui
)
## Scopes:
#####################################################################
-qt_extend_target(tst_qpointer CONDITION TARGET Qt::Widgets
- PUBLIC_LIBRARIES
+qt_internal_extend_target(tst_qpointer CONDITION TARGET Qt::Widgets
+ LIBRARIES
Qt::Widgets
)
diff --git a/tests/auto/corelib/kernel/qpointer/qpointer.pro b/tests/auto/corelib/kernel/qpointer/qpointer.pro
deleted file mode 100644
index 02765efdbd..0000000000
--- a/tests/auto/corelib/kernel/qpointer/qpointer.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qpointer
-QT = core testlib
-qtHaveModule(widgets): QT += widgets
-SOURCES = tst_qpointer.cpp
diff --git a/tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp b/tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp
index ba973910a7..7365fee819 100644
--- a/tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp
+++ b/tests/auto/corelib/kernel/qpointer/tst_qpointer.cpp
@@ -1,32 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
+#include <QRunnable>
+#include <QThreadPool>
#include <QPointer>
#ifndef QT_NO_WIDGETS
@@ -42,6 +19,8 @@ public:
private slots:
void constructors();
+ void ctad();
+ void conversion();
void destructor();
void assignment_operators();
void equality_operators();
@@ -57,14 +36,114 @@ private slots:
void constQPointer();
};
+// check that nullptr QPointer construction is Q_CONSTINIT:
+[[maybe_unused]] Q_CONSTINIT static QPointer<QFile> s_file1;
+[[maybe_unused]] Q_CONSTINIT static QPointer<QFile> s_file2 = {};
+[[maybe_unused]] Q_CONSTINIT static QPointer<QFile> s_file3 = nullptr;
+[[maybe_unused]] Q_CONSTINIT static QPointer<QFile> s_file4 = 0; // legacy nullptr
+
void tst_QPointer::constructors()
{
+ struct Derived : QObject {};
+ Derived derived;
+
QPointer<QObject> p1;
QPointer<QObject> p2(this);
QPointer<QObject> p3(p2);
+ QPointer<QObject> p4 = &derived;
QCOMPARE(p1, QPointer<QObject>(0));
QCOMPARE(p2, QPointer<QObject>(this));
QCOMPARE(p3, QPointer<QObject>(this));
+ QCOMPARE(p4, &derived);
+}
+
+void tst_QPointer::ctad()
+{
+
+ {
+ QObject o;
+ QPointer po = &o;
+ static_assert(std::is_same_v<decltype(po), QPointer<QObject>>);
+ QPointer poc = po;
+ static_assert(std::is_same_v<decltype(poc), QPointer<QObject>>);
+ QPointer pom = std::move(po);
+ static_assert(std::is_same_v<decltype(pom), QPointer<QObject>>);
+ }
+ {
+ const QObject co;
+ QPointer pco = &co;
+ static_assert(std::is_same_v<decltype(pco), QPointer<const QObject>>);
+ QPointer pcoc = pco;
+ static_assert(std::is_same_v<decltype(pcoc), QPointer<const QObject>>);
+ QPointer pcom = std::move(pco);
+ static_assert(std::is_same_v<decltype(pcom), QPointer<const QObject>>);
+ }
+ {
+ QFile f;
+ QPointer pf = &f;
+ static_assert(std::is_same_v<decltype(pf), QPointer<QFile>>);
+ QPointer pfc = pf;
+ static_assert(std::is_same_v<decltype(pfc), QPointer<QFile>>);
+ QPointer pfm = std::move(pf);
+ static_assert(std::is_same_v<decltype(pfm), QPointer<QFile>>);
+ }
+ {
+ const QFile cf;
+ QPointer pcf = &cf;
+ static_assert(std::is_same_v<decltype(pcf), QPointer<const QFile>>);
+ QPointer pcfc = pcf;
+ static_assert(std::is_same_v<decltype(pcfc), QPointer<const QFile>>);
+ QPointer pcfm = std::move(pcf);
+ static_assert(std::is_same_v<decltype(pcfm), QPointer<const QFile>>);
+ }
+}
+
+void tst_QPointer::conversion()
+{
+ // copy-conversion:
+ {
+ QFile file;
+ QPointer<QFile> pf = &file;
+ QCOMPARE_EQ(pf, &file);
+ QPointer<const QIODevice> pio = pf;
+ QCOMPARE_EQ(pio, &file);
+ QCOMPARE_EQ(pio.get(), &file);
+ QCOMPARE_EQ(pio, pf);
+ QCOMPARE_EQ(pio.get(), pf.get());
+
+ // reset
+ pio = nullptr;
+ QCOMPARE_EQ(pio, nullptr);
+ QCOMPARE_EQ(pio.get(), nullptr);
+
+ // copy-assignment
+ QCOMPARE_EQ(pf, &file);
+ pio = pf;
+ QCOMPARE_EQ(pio, &file);
+ QCOMPARE_EQ(pio.get(), &file);
+ QCOMPARE_EQ(pio, pf);
+ QCOMPARE_EQ(pio.get(), pf.get());
+ }
+ // move-conversion:
+ {
+ QFile file;
+ QPointer<QFile> pf = &file;
+ QCOMPARE_EQ(pf, &file);
+ QPointer<const QIODevice> pio = std::move(pf);
+ QCOMPARE_EQ(pf, nullptr);
+ QCOMPARE_EQ(pio, &file);
+ QCOMPARE_EQ(pio.get(), &file);
+
+ // reset
+ pio = nullptr;
+ QCOMPARE_EQ(pio, nullptr);
+ QCOMPARE_EQ(pio.get(), nullptr);
+
+ // move-assignment
+ pio = QPointer<QFile>(&file);
+ QCOMPARE_EQ(pio, &file);
+ QCOMPARE_EQ(pio.get(), &file);
+ }
}
void tst_QPointer::destructor()
@@ -98,7 +177,7 @@ void tst_QPointer::assignment_operators()
QCOMPARE(p1, QPointer<QObject>(p2));
// Test assignment with a null pointer
- p1 = 0;
+ p1 = nullptr;
p2 = p1;
QCOMPARE(p1, QPointer<QObject>(0));
QCOMPARE(p2, QPointer<QObject>(0));
@@ -131,9 +210,9 @@ void tst_QPointer::equality_operators()
QVERIFY(p1 == p2);
- QObject *object = 0;
+ QObject *object = nullptr;
#ifndef QT_NO_WIDGETS
- QWidget *widget = 0;
+ QWidget *widget = nullptr;
#endif
p1 = object;
@@ -149,11 +228,15 @@ void tst_QPointer::equality_operators()
QVERIFY(p1 == p2);
// compare to zero
- p1 = 0;
+ p1 = nullptr;
QVERIFY(p1 == 0);
QVERIFY(0 == p1);
QVERIFY(p2 != 0);
QVERIFY(0 != p2);
+ QVERIFY(p1 == nullptr);
+ QVERIFY(nullptr == p1);
+ QVERIFY(p2 != nullptr);
+ QVERIFY(nullptr != p2);
QVERIFY(p1 == object);
QVERIFY(object == p1);
QVERIFY(p2 != object);
@@ -188,7 +271,7 @@ void tst_QPointer::isNull()
QVERIFY(p1.isNull());
p1 = this;
QVERIFY(!p1.isNull());
- p1 = 0;
+ p1 = nullptr;
QVERIFY(p1.isNull());
}
diff --git a/tests/auto/corelib/kernel/qproperty/CMakeLists.txt b/tests/auto/corelib/kernel/qproperty/CMakeLists.txt
index 5521111ef8..177465d2ee 100644
--- a/tests/auto/corelib/kernel/qproperty/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qproperty/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qproperty.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qproperty Test:
#####################################################################
-qt_add_test(tst_qproperty
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qproperty LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qproperty
SOURCES
tst_qproperty.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
)
diff --git a/tests/auto/corelib/kernel/qproperty/qproperty.pro b/tests/auto/corelib/kernel/qproperty/qproperty.pro
deleted file mode 100644
index bae67e70a4..0000000000
--- a/tests/auto/corelib/kernel/qproperty/qproperty.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qproperty
-QT = core core-private testlib
-SOURCES = tst_qproperty.cpp
diff --git a/tests/auto/corelib/kernel/qproperty/tst_qproperty.cpp b/tests/auto/corelib/kernel/qproperty/tst_qproperty.cpp
index 9bc2ce26b6..cc7edb8bf2 100644
--- a/tests/auto/corelib/kernel/qproperty/tst_qproperty.cpp
+++ b/tests/auto/corelib/kernel/qproperty/tst_qproperty.cpp
@@ -1,57 +1,49 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QObject>
+#include <QSignalSpy>
#include <qtest.h>
#include <qproperty.h>
#include <private/qproperty_p.h>
+#include <private/qobject_p.h>
+
+#if __has_include(<source_location>) && __cplusplus >= 202002L && !defined(Q_QDOC)
+#include <source_location>
+#define QT_SOURCE_LOCATION_NAMESPACE std
+#elif __has_include(<experimental/source_location>) && !defined(Q_QDOC)
+#include <experimental/source_location>
+#define QT_SOURCE_LOCATION_NAMESPACE std::experimental
+#endif
using namespace QtPrivate;
+using namespace Qt::StringLiterals;
+
+struct DtorCounter {
+ static inline int counter = 0;
+ bool shouldIncrement = false;
+ ~DtorCounter() {if (shouldIncrement) ++counter;}
+};
class tst_QProperty : public QObject
{
Q_OBJECT
private slots:
+ void inheritQUntypedPropertyData();
void functorBinding();
void basicDependencies();
void multipleDependencies();
void bindingWithDeletedDependency();
+ void dependencyChangeDuringDestruction();
void recursiveDependency();
void bindingAfterUse();
+ void bindingFunctionDtorCalled();
void switchBinding();
void avoidDependencyAllocationAfterFirstEval();
- void propertyArrays();
void boolProperty();
void takeBinding();
+ void stickyBinding();
void replaceBinding();
- void swap();
- void moveNotifies();
- void moveCtor();
void changeHandler();
void propertyChangeHandlerApi();
void subscribe();
@@ -60,6 +52,7 @@ private slots:
void bindingSourceLocation();
void bindingError();
void bindingLoop();
+ void realloc();
void changePropertyFromWithinChangeHandler();
void changePropertyFromWithinChangeHandlerThroughDependency();
void changePropertyFromWithinChangeHandler2();
@@ -68,19 +61,110 @@ private slots:
void genericPropertyBindingBool();
void setBindingFunctor();
void multipleObservers();
- void propertyAlias();
void arrowAndStarOperator();
void notifiedProperty();
void typeNoOperatorEqual();
void bindingValueReplacement();
+ void quntypedBindableApi();
+ void readonlyConstQBindable();
+ void qobjectBindableManualNotify();
+ void qobjectBindableReallocatedBindingStorage();
+ void qobjectBindableSignalTakingNewValue();
void testNewStuff();
void qobjectObservers();
void compatBindings();
void metaProperty();
- void aliasOnMetaProperty();
+
+ void modifyObserverListWhileIterating();
+ void noDoubleCapture();
+ void compatPropertyNoDobuleNotification();
+ void compatPropertySignals();
+
+ void noFakeDependencies();
+#if QT_CONFIG(thread)
+ void threadSafety();
+ void threadSafety2();
+#endif // QT_CONFIG(thread)
+
+ void bindablePropertyWithInitialization();
+ void noDoubleNotification();
+ void groupedNotifications();
+ void groupedNotificationConsistency();
+ void bindingGroupMovingBindingData();
+ void bindingGroupBindingDeleted();
+ void uninstalledBindingDoesNotEvaluate();
+
+ void notify();
+
+ void bindableInterfaceOfCompatPropertyUsesSetter();
+
+ void selfBindingShouldNotCrash();
+
+ void qpropertyAlias();
+ void scheduleNotify();
+
+ void notifyAfterAllDepsGone();
+
+ void propertyAdaptorBinding();
+ void propertyUpdateViaSignaledProperty();
+
+ void derefFromObserver();
};
+namespace {
+template <class T>
+constexpr auto isDerivedFromQUntypedPropertyData = std::is_base_of_v<QUntypedPropertyData, T>;
+
+template <typename Property>
+constexpr auto isDerivedFromQUntypedPropertyDataFunc(const Property &property)
+{
+ Q_UNUSED(property);
+ return isDerivedFromQUntypedPropertyData<Property>;
+}
+
+template <typename Property>
+constexpr auto isDerivedFromQUntypedPropertyDataFunc(Property *property)
+{
+ Q_UNUSED(property);
+ return isDerivedFromQUntypedPropertyData<Property>;
+}
+} // namespace
+
+void tst_QProperty::inheritQUntypedPropertyData()
+{
+ class propertyPublic : public QUntypedPropertyData
+ {
+ };
+ class propertyPrivate : private QUntypedPropertyData
+ {
+ };
+
+ // Compile time test
+ static_assert(isDerivedFromQUntypedPropertyData<propertyPublic>);
+ static_assert(isDerivedFromQUntypedPropertyData<propertyPrivate>);
+ static_assert(isDerivedFromQUntypedPropertyData<QPropertyData<int>>);
+ static_assert(isDerivedFromQUntypedPropertyData<QProperty<int>>);
+
+ // Run time test
+ propertyPublic _propertyPublic;
+ propertyPrivate _propertyPrivate;
+ QPropertyData<int> qpropertyData;
+ QProperty<int> qproperty;
+ std::unique_ptr<propertyPublic> _propertyPublicPtr{ new propertyPublic };
+ std::unique_ptr<propertyPrivate> _propertyPrivatePtr{ new propertyPrivate };
+ std::unique_ptr<QPropertyData<int>> qpropertyDataPtr{ new QPropertyData<int> };
+ std::unique_ptr<QProperty<int>> qpropertyPtr{ new QProperty<int> };
+ QVERIFY(isDerivedFromQUntypedPropertyDataFunc(_propertyPublic));
+ QVERIFY(isDerivedFromQUntypedPropertyDataFunc(_propertyPrivate));
+ QVERIFY(isDerivedFromQUntypedPropertyDataFunc(qpropertyData));
+ QVERIFY(isDerivedFromQUntypedPropertyDataFunc(qproperty));
+ QVERIFY(isDerivedFromQUntypedPropertyDataFunc(_propertyPublicPtr.get()));
+ QVERIFY(isDerivedFromQUntypedPropertyDataFunc(_propertyPrivatePtr.get()));
+ QVERIFY(isDerivedFromQUntypedPropertyDataFunc(qpropertyDataPtr.get()));
+ QVERIFY(isDerivedFromQUntypedPropertyDataFunc(qpropertyPtr.get()));
+}
+
void tst_QProperty::functorBinding()
{
QProperty<int> property([]() { return 42; });
@@ -112,8 +196,8 @@ void tst_QProperty::multipleDependencies()
QProperty<int> sum;
sum.setBinding([&]() { return firstDependency + secondDependency; });
- QCOMPARE(QPropertyBindingDataPointer::get(firstDependency).observerCount(), 0);
- QCOMPARE(QPropertyBindingDataPointer::get(secondDependency).observerCount(), 0);
+ QCOMPARE(QPropertyBindingDataPointer::get(firstDependency).observerCount(), 1);
+ QCOMPARE(QPropertyBindingDataPointer::get(secondDependency).observerCount(), 1);
QCOMPARE(sum.value(), int(3));
QCOMPARE(QPropertyBindingDataPointer::get(firstDependency).observerCount(), 1);
@@ -168,6 +252,35 @@ void tst_QProperty::bindingWithDeletedDependency()
QCOMPARE(propertySelector.value(), staticProperty.value());
}
+class ChangeDuringDtorTester : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int prop READ prop WRITE setProp BINDABLE bindableProp)
+
+public:
+ void setProp(int i) { m_prop = i;}
+ int prop() const { return m_prop; }
+ QBindable<int> bindableProp() { return &m_prop; }
+private:
+ Q_OBJECT_COMPAT_PROPERTY(ChangeDuringDtorTester, int, m_prop, &ChangeDuringDtorTester::setProp)
+};
+
+void tst_QProperty::dependencyChangeDuringDestruction()
+{
+ auto tester = std::make_unique<ChangeDuringDtorTester>();
+ QProperty<int> iprop {42};
+ tester->bindableProp().setBinding(Qt::makePropertyBinding(iprop));
+ QObject::connect(tester.get(), &QObject::destroyed, [&](){
+ iprop = 12;
+ });
+ bool failed = false;
+ auto handler = tester->bindableProp().onValueChanged([&](){
+ failed = true;
+ });
+ tester.reset();
+ QVERIFY(!failed);
+}
+
void tst_QProperty::recursiveDependency()
{
QProperty<int> first(1);
@@ -202,6 +315,21 @@ void tst_QProperty::bindingAfterUse()
QCOMPARE(QPropertyBindingDataPointer::get(propWithBindingLater).observerCount(), 1);
}
+void tst_QProperty::bindingFunctionDtorCalled()
+{
+ DtorCounter::counter = 0;
+ DtorCounter dc;
+ {
+ QProperty<int> prop;
+ prop.setBinding([dc]() mutable {
+ dc.shouldIncrement = true;
+ return 42;
+ });
+ QCOMPARE(prop.value(), 42);
+ }
+ QCOMPARE(DtorCounter::counter, 1);
+}
+
void tst_QProperty::switchBinding()
{
QProperty<int> first(1);
@@ -229,33 +357,12 @@ void tst_QProperty::avoidDependencyAllocationAfterFirstEval()
QCOMPARE(propWithBinding.value(), int(11));
- QVERIFY(QPropertyBindingDataPointer::get(propWithBinding).bindingPtr());
- QCOMPARE(QPropertyBindingDataPointer::get(propWithBinding).bindingPtr()->dependencyObserverCount, 2u);
+ QVERIFY(QPropertyBindingDataPointer::get(propWithBinding).binding());
+ QCOMPARE(QPropertyBindingDataPointer::get(propWithBinding).binding()->dependencyObserverCount, 2u);
firstDependency = 100;
QCOMPARE(propWithBinding.value(), int(110));
- QCOMPARE(QPropertyBindingDataPointer::get(propWithBinding).bindingPtr()->dependencyObserverCount, 2u);
-}
-
-void tst_QProperty::propertyArrays()
-{
- std::vector<QProperty<int>> properties;
-
- int expectedSum = 0;
- for (int i = 0; i < 10; ++i) {
- properties.emplace_back(i);
- expectedSum += i;
- }
-
- QProperty<int> sum([&]() {
- return std::accumulate(properties.begin(), properties.end(), 0);
- });
-
- QCOMPARE(sum.value(), expectedSum);
-
- properties[4] = properties[4] + 42;
- expectedSum += 42;
- QCOMPARE(sum.value(), expectedSum);
+ QCOMPARE(QPropertyBindingDataPointer::get(propWithBinding).binding()->dependencyObserverCount, 2u);
}
void tst_QProperty::boolProperty()
@@ -295,6 +402,30 @@ void tst_QProperty::takeBinding()
QVERIFY(!existingBinding.isNull());
}
+void tst_QProperty::stickyBinding()
+{
+ QProperty<int> prop;
+ QProperty<int> prop2 {2};
+ prop.setBinding([&](){ return prop2.value(); });
+ QCOMPARE(prop.value(), 2);
+ auto privBinding = QPropertyBindingPrivate::get(prop.binding());
+ // If we make a binding sticky,
+ privBinding->setSticky();
+ // then writing to the property does not remove it
+ prop = 1;
+ QVERIFY(prop.hasBinding());
+ // but the value still changes.
+ QCOMPARE(prop.value(), 1);
+ // The binding continues to work normally.
+ prop2 = 3;
+ QCOMPARE(prop.value(), 3);
+ // If we remove the stickiness
+ privBinding->setSticky(false);
+ // the binding goes away on the next write
+ prop = 42;
+ QVERIFY(!prop.hasBinding());
+}
+
void tst_QProperty::replaceBinding()
{
QProperty<int> first(100);
@@ -310,74 +441,6 @@ void tst_QProperty::replaceBinding()
QCOMPARE(second.value(), 100);
}
-void tst_QProperty::swap()
-{
- QProperty<int> firstDependency(1);
- QProperty<int> secondDependency(2);
-
- QProperty<int> first(Qt::makePropertyBinding(firstDependency));
- QProperty<int> second(Qt::makePropertyBinding(secondDependency));
-
- QCOMPARE(first.value(), 1);
- QCOMPARE(second.value(), 2);
-
- std::swap(first, second);
-
- QCOMPARE(first.value(), 2);
- QCOMPARE(second.value(), 1);
-
- secondDependency = 20;
- QCOMPARE(first.value(), 20);
- QCOMPARE(second.value(), 1);
-
- firstDependency = 100;
- QCOMPARE(first.value(), 20);
- QCOMPARE(second.value(), 100);
-}
-
-void tst_QProperty::moveNotifies()
-{
- QProperty<int> first(1);
- QProperty<int> second(2);
-
- QProperty<int> propertyInTheMiddle(Qt::makePropertyBinding(first));
-
- QProperty<int> finalProp1(Qt::makePropertyBinding(propertyInTheMiddle));
- QProperty<int> finalProp2(Qt::makePropertyBinding(propertyInTheMiddle));
-
- QCOMPARE(finalProp1.value(), 1);
- QCOMPARE(finalProp2.value(), 1);
-
- QCOMPARE(QPropertyBindingDataPointer::get(propertyInTheMiddle).observerCount(), 2);
-
- QProperty<int> other(Qt::makePropertyBinding(second));
- QCOMPARE(other.value(), 2);
-
- QProperty<int> otherDep(Qt::makePropertyBinding(other));
- QCOMPARE(otherDep.value(), 2);
- QCOMPARE(QPropertyBindingDataPointer::get(other).observerCount(), 1);
-
- propertyInTheMiddle = std::move(other);
-
- QCOMPARE(QPropertyBindingDataPointer::get(other).observerCount(), 0);
-
- QCOMPARE(finalProp1.value(), 2);
- QCOMPARE(finalProp2.value(), 2);
-}
-
-void tst_QProperty::moveCtor()
-{
- QProperty<int> first(1);
-
- QProperty<int> intermediate(Qt::makePropertyBinding(first));
- QCOMPARE(intermediate.value(), 1);
- QCOMPARE(QPropertyBindingDataPointer::get(first).observerCount(), 1);
-
- QProperty<int> targetProp(std::move(first));
-
- QCOMPARE(QPropertyBindingDataPointer::get(targetProp).observerCount(), 0);
-}
-
void tst_QProperty::changeHandler()
{
QProperty<int> testProperty(0);
@@ -393,7 +456,7 @@ void tst_QProperty::changeHandler()
}
testProperty = 3;
- QCOMPARE(recordedValues.count(), 2);
+ QCOMPARE(recordedValues.size(), 2);
QCOMPARE(recordedValues.at(0), 1);
QCOMPARE(recordedValues.at(1), 2);
}
@@ -436,7 +499,7 @@ void tst_QProperty::subscribe()
}
testProperty = 3;
- QCOMPARE(recordedValues.count(), 3);
+ QCOMPARE(recordedValues.size(), 3);
QCOMPARE(recordedValues.at(0), 42);
QCOMPARE(recordedValues.at(1), 1);
QCOMPARE(recordedValues.at(2), 2);
@@ -495,7 +558,7 @@ void tst_QProperty::dontTriggerDependenciesIfUnchangedValue()
void tst_QProperty::bindingSourceLocation()
{
#if defined(QT_PROPERTY_COLLECT_BINDING_LOCATION)
- auto bindingLine = std::experimental::source_location::current().line() + 1;
+ auto bindingLine = QT_SOURCE_LOCATION_NAMESPACE::source_location::current().line() + 1;
auto binding = Qt::makePropertyBinding([]() { return 42; });
QCOMPARE(QPropertyBindingPrivate::get(binding)->sourceLocation().line, bindingLine);
#else
@@ -514,27 +577,131 @@ void tst_QProperty::bindingError()
QCOMPARE(prop.binding().error().description(), QString("my error"));
}
+
+
+class BindingLoopTester : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int eagerProp READ eagerProp WRITE setEagerProp BINDABLE bindableEagerProp)
+ Q_PROPERTY(int eagerProp2 READ eagerProp2 WRITE setEagerProp2 BINDABLE bindableEagerProp2)
+ public:
+ BindingLoopTester(QProperty<int> *i, QObject *parent = nullptr) : QObject(parent) {
+ eagerData.setBinding(Qt::makePropertyBinding([&](){ return eagerData2.value() + i->value(); } ) );
+ eagerData2.setBinding(Qt::makePropertyBinding([&](){ return eagerData.value() + 1; } ) );
+ i->setValue(42);
+ }
+ BindingLoopTester() {}
+
+ int eagerProp() {return eagerData.value();}
+ void setEagerProp(int i) { eagerData.setValue(i); eagerData.notify(); }
+ QBindable<int> bindableEagerProp() {return QBindable<int>(&eagerData);}
+ Q_OBJECT_COMPAT_PROPERTY(BindingLoopTester, int, eagerData, &BindingLoopTester::setEagerProp)
+
+ int eagerProp2() {return eagerData2.value();}
+ void setEagerProp2(int i) { eagerData2.setValue(i); eagerData2.notify(); }
+ QBindable<int> bindableEagerProp2() {return QBindable<int>(&eagerData2);}
+ Q_OBJECT_COMPAT_PROPERTY(BindingLoopTester, int, eagerData2, &BindingLoopTester::setEagerProp2)
+};
+
void tst_QProperty::bindingLoop()
{
- QScopedPointer<QProperty<int>> firstProp;
+ QProperty<int> firstProp;
QProperty<int> secondProp([&]() -> int {
- return firstProp ? firstProp->value() : 0;
+ return firstProp.value();
});
QProperty<int> thirdProp([&]() -> int {
return secondProp.value();
});
- firstProp.reset(new QProperty<int>());
- firstProp->setBinding([&]() -> int {
- return secondProp.value();
+ firstProp.setBinding([&]() -> int {
+ return secondProp.value() + thirdProp.value();
});
- QCOMPARE(thirdProp.value(), 0);
- QCOMPARE(secondProp.binding().error().type(), QPropertyBindingError::BindingLoop);
+ thirdProp.setValue(10);
+ QCOMPARE(firstProp.binding().error().type(), QPropertyBindingError::BindingLoop);
+
+
+ {
+ QProperty<int> i;
+ BindingLoopTester tester(&i);
+ QCOMPARE(tester.bindableEagerProp().binding().error().type(), QPropertyBindingError::BindingLoop);
+ QCOMPARE(tester.bindableEagerProp2().binding().error().type(), QPropertyBindingError::BindingLoop);
+ }
+ {
+ BindingLoopTester tester;
+ auto handler = tester.bindableEagerProp().onValueChanged([&]() {
+ tester.bindableEagerProp().setBinding([](){return 42;});
+ });
+ tester.bindableEagerProp().setBinding([]() {return 42;});
+ QCOMPARE(tester.bindableEagerProp().binding().error().type(), QPropertyBindingError::BindingLoop);
+ QCOMPARE(tester.bindableEagerProp().binding().error().description(), "Binding set during binding evaluation!");
+ }
}
+class ReallocTester : public QObject
+{
+ /*
+ * This class and the realloc test rely on the fact that the internal property hashmap has an
+ * initial capacity of 8 and a load factor of 0.5. Thus, it is necessary to cause actions which
+ * allocate 5 different QPropertyBindingData
+ * */
+ Q_OBJECT
+ Q_PROPERTY(int prop1 READ prop1 WRITE setProp1 BINDABLE bindableProp1)
+ Q_PROPERTY(int prop2 READ prop2 WRITE setProp2 BINDABLE bindableProp2)
+ Q_PROPERTY(int prop3 READ prop3 WRITE setProp3 BINDABLE bindableProp3)
+ Q_PROPERTY(int prop4 READ prop4 WRITE setProp4 BINDABLE bindableProp4)
+ Q_PROPERTY(int prop5 READ prop5 WRITE setProp5 BINDABLE bindableProp5)
+public:
+ ReallocTester(QObject *parent = nullptr) : QObject(parent) {}
+
+
+#define GEN(N) \
+ int prop##N() {return propData##N.value();} \
+ void setProp##N(int i) { if (i == propData##N) return; propData##N.setValue(i); propData##N.notify(); } \
+ QBindable<int> bindableProp##N() {return QBindable<int>(&propData##N);} \
+ Q_OBJECT_COMPAT_PROPERTY(ReallocTester, int, propData##N, &ReallocTester::setProp##N)
+ GEN(1)
+ GEN(2)
+ GEN(3)
+ GEN(4)
+ GEN(5)
+#undef GEN
+};
+
+void tst_QProperty::realloc()
+{
+ {
+ // Triggering a reallocation does not crash
+ ReallocTester tester;
+ tester.bindableProp1().setBinding([&](){return tester.prop5();});
+ tester.bindableProp2().setBinding([&](){return tester.prop5();});
+ tester.bindableProp3().setBinding([&](){return tester.prop5();});
+ tester.bindableProp4().setBinding([&](){return tester.prop5();});
+ tester.bindableProp5().setBinding([&]() -> int{return 42;});
+ QCOMPARE(tester.prop1(), 42);
+ }
+ {
+ // After a reallocation, property observers still work
+ ReallocTester tester;
+ int modificationCount = 0;
+ QPropertyChangeHandler observer {[&](){ ++modificationCount; }};
+ tester.bindableProp1().observe(&observer);
+ tester.setProp1(12);
+ QCOMPARE(modificationCount, 1);
+ QCOMPARE(tester.prop1(), 12);
+
+ tester.bindableProp1().setBinding([&](){return tester.prop5();});
+ QCOMPARE(modificationCount, 2);
+ tester.bindableProp2().setBinding([&](){return tester.prop5();});
+ tester.bindableProp3().setBinding([&](){return tester.prop5();});
+ tester.bindableProp4().setBinding([&](){return tester.prop5();});
+ tester.bindableProp5().setBinding([&]() -> int{return 42;});
+ QCOMPARE(modificationCount, 3);
+ }
+};
+
void tst_QProperty::changePropertyFromWithinChangeHandler()
{
QProperty<int> property(100);
@@ -575,7 +742,8 @@ void tst_QProperty::changePropertyFromWithinChangeHandlerThroughDependency()
resetPropertyOnChange = true;
sourceProperty = 42;
- QCOMPARE(property.value(), 100);
+ QVERIFY(property.value() == 100 || property.value() == 42);
+ QVERIFY(property.binding().error().type() == QPropertyBindingError::BindingLoop);
// changing the property value inside the change handler won't result in the change
// handler being called again.
QCOMPARE(changeHandlerCallCount, 1);
@@ -596,6 +764,7 @@ void tst_QProperty::changePropertyFromWithinChangeHandler2()
property = 42;
QCOMPARE(property.value(), 43);
+ QVERIFY(!property.hasBinding()); // setting the value in the change handler removed the binding
}
void tst_QProperty::settingPropertyValueDoesRemoveBinding()
@@ -622,7 +791,7 @@ void tst_QProperty::genericPropertyBinding()
{
QUntypedPropertyBinding doubleBinding(QMetaType::fromType<double>(),
- [](const QMetaType &, void *) -> bool {
+ [](QMetaType , void *) -> bool {
Q_ASSERT(false);
return true;
}, QPropertyBindingSourceLocation());
@@ -630,7 +799,7 @@ void tst_QProperty::genericPropertyBinding()
}
QUntypedPropertyBinding intBinding(QMetaType::fromType<int>(),
- [](const QMetaType &metaType, void *dataPtr) -> bool {
+ [](QMetaType metaType, void *dataPtr) -> bool {
Q_ASSERT(metaType.id() == qMetaTypeId<int>());
int *intPtr = reinterpret_cast<int*>(dataPtr);
@@ -650,7 +819,7 @@ void tst_QProperty::genericPropertyBindingBool()
QVERIFY(!property.value());
QUntypedPropertyBinding boolBinding(QMetaType::fromType<bool>(),
- [](const QMetaType &, void *dataPtr) -> bool {
+ [](QMetaType, void *dataPtr) -> bool {
auto boolPtr = reinterpret_cast<bool *>(dataPtr);
*boolPtr = true;
return true;
@@ -706,52 +875,6 @@ void tst_QProperty::multipleObservers()
QCOMPARE(property.value(), 22);
}
-void tst_QProperty::propertyAlias()
-{
- QScopedPointer<QProperty<int>> property(new QProperty<int>);
- property->setValue(5);
- QPropertyAlias alias(property.get());
- QVERIFY(alias.isValid());
- QCOMPARE(alias.value(), 5);
-
- int value1 = 1;
- auto changeHandler = alias.onValueChanged([&]() { value1 = alias.value(); });
- QCOMPARE(value1, 1);
-
- int value2 = 2;
- auto subscribeHandler = alias.subscribe([&]() { value2 = alias.value(); });
- QCOMPARE(value2, 5);
-
- alias.setValue(6);
- QVERIFY(alias.isValid());
- QCOMPARE(alias.value(), 6);
- QCOMPARE(value1, 6);
- QCOMPARE(value2, 6);
-
- alias.setBinding([]() { return 12; });
- QCOMPARE(value1, 12);
- QCOMPARE(value2, 12);
- QCOMPARE(alias.value(), 12);
-
- alias.setValue(22);
- QCOMPARE(value1, 22);
- QCOMPARE(value2, 22);
- QCOMPARE(alias.value(), 22);
-
- property.reset();
-
- QVERIFY(!alias.isValid());
- QCOMPARE(alias.value(), int());
- QCOMPARE(value1, 22);
- QCOMPARE(value2, 22);
-
- // Does not crash
- alias.setValue(25);
- QCOMPARE(alias.value(), int());
- QCOMPARE(value1, 22);
- QCOMPARE(value2, 22);
-}
-
void tst_QProperty::arrowAndStarOperator()
{
QString str("Hello");
@@ -811,7 +934,7 @@ void tst_QProperty::notifiedProperty()
check();
instance.property.setValue(42);
- QCOMPARE(instance.recordedValues.count(), 1);
+ QCOMPARE(instance.recordedValues.size(), 1);
QCOMPARE(instance.recordedValues.at(0), 42);
instance.recordedValues.clear();
check();
@@ -841,7 +964,7 @@ void tst_QProperty::notifiedProperty()
subscribedCount = 0;
QCOMPARE(instance.property.value(), 100);
- QCOMPARE(instance.recordedValues.count(), 1);
+ QCOMPARE(instance.recordedValues.size(), 1);
QCOMPARE(instance.recordedValues.at(0), 100);
instance.recordedValues.clear();
check();
@@ -849,7 +972,7 @@ void tst_QProperty::notifiedProperty()
injectedValue = 200;
QCOMPARE(instance.property.value(), 200);
- QCOMPARE(instance.recordedValues.count(), 1);
+ QCOMPARE(instance.recordedValues.size(), 1);
QCOMPARE(instance.recordedValues.at(0), 200);
instance.recordedValues.clear();
check();
@@ -858,7 +981,7 @@ void tst_QProperty::notifiedProperty()
injectedValue = 400;
QCOMPARE(instance.property.value(), 400);
- QCOMPARE(instance.recordedValues.count(), 1);
+ QCOMPARE(instance.recordedValues.size(), 1);
QCOMPARE(instance.recordedValues.at(0), 400);
instance.recordedValues.clear();
check();
@@ -965,25 +1088,79 @@ void tst_QProperty::bindingValueReplacement()
// QCOMPARE(test.iconText.value(), 42);
}
+void tst_QProperty::quntypedBindableApi()
+{
+ QProperty<int> iprop;
+ QUntypedBindable bindable(&iprop);
+ QVERIFY(!bindable.hasBinding());
+ QVERIFY(bindable.binding().isNull());
+ bindable.setBinding(Qt::makePropertyBinding([]() -> int {return 42;}));
+ QVERIFY(bindable.hasBinding());
+ QVERIFY(!bindable.binding().isNull());
+ QUntypedPropertyBinding binding = bindable.takeBinding();
+ QVERIFY(!bindable.hasBinding());
+ bindable.setBinding(binding);
+ QCOMPARE(iprop.value(), 42);
+ QUntypedBindable propLess;
+ QVERIFY(propLess.takeBinding().isNull());
+
+ QUntypedBindable invalidBindable;
+#ifndef QT_NO_DEBUG
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "setBinding: Could not set binding via bindable interface. The QBindable is invalid.");
+#endif
+ invalidBindable.setBinding(Qt::makePropertyBinding(iprop));
+
+ QUntypedBindable readOnlyBindable(static_cast<const QProperty<int> *>(&iprop) );
+ QVERIFY(readOnlyBindable.isReadOnly());
+#ifndef QT_NO_DEBUG
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "setBinding: Could not set binding via bindable interface. The QBindable is read-only.");
+#endif
+ readOnlyBindable.setBinding(Qt::makePropertyBinding(iprop));
+
+ QProperty<float> fprop;
+#ifndef QT_NO_DEBUG
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "setBinding: Could not set binding as the property expects it to be of type int but got float instead.");
+#endif
+ bindable.setBinding(Qt::makePropertyBinding(fprop));
+}
+
+void tst_QProperty::readonlyConstQBindable()
+{
+ QProperty<int> i {42};
+ const QBindable<int> bindableI(const_cast<const QProperty<int> *>(&i));
+
+ // check that read-only operations work with a const QBindable
+ QVERIFY(bindableI.isReadOnly());
+ QVERIFY(!bindableI.hasBinding());
+ // we can still create a binding to a read only bindable through the interface
+ QProperty<int> j;
+ j.setBinding(bindableI.makeBinding());
+ QCOMPARE(j.value(), bindableI.value());
+ int counter = 0;
+ auto observer = bindableI.subscribe([&](){++counter;});
+ QCOMPARE(counter, 1);
+ auto observer2 = bindableI.onValueChanged([&](){++counter;});
+ i = 0;
+ QCOMPARE(counter, 3);
+}
+
class MyQObject : public QObject
{
Q_OBJECT
Q_PROPERTY(int foo READ foo WRITE setFoo BINDABLE bindableFoo NOTIFY fooChanged)
Q_PROPERTY(int bar READ bar WRITE setBar BINDABLE bindableBar NOTIFY barChanged)
- Q_PROPERTY(int read READ read NOTIFY readChanged)
+ Q_PROPERTY(int read READ read)
Q_PROPERTY(int computed READ computed STORED false)
Q_PROPERTY(int compat READ compat WRITE setCompat NOTIFY compatChanged)
signals:
- void fooChanged();
+ void fooChanged(int newFoo);
void barChanged();
- void readChanged();
void compatChanged();
public slots:
void fooHasChanged() { fooChangedCount++; }
void barHasChanged() { barChangedCount++; }
- void readHasChanged() { readChangedCount++; }
void compatHasChanged() { compatChangedCount++; }
public:
@@ -1002,11 +1179,13 @@ public:
++setCompatCalled;
if (i < 0)
i = 0;
- compatData = i;
+ compatData.setValue(i);
+ compatData.notify();
emit compatChanged();
}
QBindable<int> bindableFoo() { return QBindable<int>(&fooData); }
+ const QBindable<int> bindableFoo() const { return QBindable<int>(&fooData); }
QBindable<int> bindableBar() { return QBindable<int>(&barData); }
QBindable<int> bindableRead() { return QBindable<int>(&readData); }
QBindable<int> bindableComputed() { return QBindable<int>(&computedData); }
@@ -1015,23 +1194,114 @@ public:
public:
int fooChangedCount = 0;
int barChangedCount = 0;
- int readChangedCount = 0;
int compatChangedCount = 0;
int setCompatCalled = 0;
Q_OBJECT_BINDABLE_PROPERTY(MyQObject, int, fooData, &MyQObject::fooChanged);
Q_OBJECT_BINDABLE_PROPERTY(MyQObject, int, barData, &MyQObject::barChanged);
- Q_OBJECT_BINDABLE_PROPERTY(MyQObject, int, readData, &MyQObject::readChanged);
+ Q_OBJECT_BINDABLE_PROPERTY(MyQObject, int, readData);
Q_OBJECT_COMPUTED_PROPERTY(MyQObject, int, computedData, &MyQObject::computed);
Q_OBJECT_COMPAT_PROPERTY(MyQObject, int, compatData, &MyQObject::setCompat)
};
+
+void tst_QProperty::qobjectBindableManualNotify()
+{
+ // Given an object of type MyQObject,
+ MyQObject object;
+ // track its foo property's change count
+ auto bindable = object.bindableFoo();
+ int fooChangeCount = 0;
+ auto changeHandler = bindable.onValueChanged([&](){++fooChangeCount;});
+ // and how many changed signals it emits.
+ QSignalSpy fooChangedSpy(&object, &MyQObject::fooChanged);
+
+ // If we bypass the bindings system,
+ object.fooData.setValueBypassingBindings(42);
+ // there is no change.
+ QCOMPARE(fooChangeCount, 0);
+ QCOMPARE(fooChangedSpy.size(), 0);
+ // Once we notify manually
+ object.fooData.notify();
+ // observers are notified and the signal arrives.
+ QCOMPARE(fooChangeCount, 1);
+ QCOMPARE(fooChangedSpy.size(), 1);
+
+ // If we set a binding
+ int i = 1;
+ object.fooData.setBinding([&](){return i;});
+ // then the value changes
+ QCOMPARE(object.foo(), 1);
+ // and the change and signal count are incremented.
+ QCOMPARE(fooChangeCount, 2);
+ QCOMPARE(fooChangedSpy.size(), 2);
+ // Changing a non-property won't trigger any notification.
+ i = 2;
+ QCOMPARE(fooChangeCount, 2);
+ QCOMPARE(fooChangedSpy.size(), 2);
+ // Manually triggering the notification
+ object.fooData.notify();
+ // increments the change count
+ QCOMPARE(fooChangeCount, 3);
+ QCOMPARE(fooChangedSpy.size(), 3);
+ // but doesn't actually cause a binding reevaluation.
+ QCOMPARE(object.foo(), 1);
+}
+
+
+struct ReallocObject : QObject {
+ ReallocObject()
+ { v.setBinding([this] { return x.value() + y.value() + z.value(); }); }
+ Q_OBJECT_BINDABLE_PROPERTY(ReallocObject, int, v)
+ Q_OBJECT_BINDABLE_PROPERTY(ReallocObject, int, x)
+ Q_OBJECT_BINDABLE_PROPERTY(ReallocObject, int, y)
+ Q_OBJECT_BINDABLE_PROPERTY(ReallocObject, int, z)
+};
+
+void tst_QProperty::qobjectBindableReallocatedBindingStorage()
+{
+ ReallocObject object;
+ object.x = 1;
+ QCOMPARE(object.v.value(), 1);
+}
+
+void tst_QProperty::qobjectBindableSignalTakingNewValue()
+{
+ // Given an object of type MyQObject,
+ MyQObject object;
+ // and tracking the values emitted via its fooChanged signal,
+ int newValue = -1;
+ QObject::connect(&object, &MyQObject::fooChanged, [&](int i){ newValue = i; } );
+
+ // when we change the property's value via the bindable interface
+ object.bindableFoo().setValue(1);
+ // we obtain the newly set value.
+ QCOMPARE(newValue, 1);
+
+ // The same holds true when we set a binding
+ QProperty<int> i {2};
+ object.bindableFoo().setBinding(Qt::makePropertyBinding(i));
+ QCOMPARE(newValue, 2);
+ // and when the binding gets reevaluated to a new value
+ i = 3;
+ QCOMPARE(newValue, 3);
+}
+
void tst_QProperty::testNewStuff()
{
+ MyQObject testReadOnly;
+#ifndef QT_NO_DEBUG
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "setBinding: Could not set binding via bindable interface. The QBindable is read-only.");
+#endif
+ testReadOnly.bindableFoo().setBinding([](){return 42;});
+ auto bindable = const_cast<const MyQObject&>(testReadOnly).bindableFoo();
+ QVERIFY(bindable.hasBinding());
+ QVERIFY(bindable.isReadOnly());
+
MyQObject object;
+ QVERIFY(!object.bindableFoo().isReadOnly());
QObject::connect(&object, &MyQObject::fooChanged, &object, &MyQObject::fooHasChanged);
QObject::connect(&object, &MyQObject::barChanged, &object, &MyQObject::barHasChanged);
- QObject::connect(&object, &MyQObject::readChanged, &object, &MyQObject::readHasChanged);
QCOMPARE(object.fooChangedCount, 0);
object.setFoo(10);
@@ -1085,6 +1355,23 @@ void tst_QProperty::testNewStuff()
object.readData.setValue(111);
QCOMPARE(object.computed(), 111);
+ object.bindableComputed().setBinding(object.bindableBar().makeBinding());
+ QCOMPARE(object.computed(), 111);
+ object.bindableComputed().setValue(10);
+ QCOMPARE(object.computed(), 111);
+
+ QCOMPARE(object.bindableFoo().value(), 111);
+ object.bindableFoo().setValue(24);
+ QCOMPARE(object.foo(), 24);
+
+ auto isCurrentlyEvaluatingBinding = []() {
+ return QtPrivate::isAnyBindingEvaluating();
+ };
+ QVERIFY(!isCurrentlyEvaluatingBinding());
+ QProperty<bool> evaluationDetector {false};
+ evaluationDetector.setBinding(isCurrentlyEvaluatingBinding);
+ QVERIFY(evaluationDetector.value());
+ QVERIFY(!isCurrentlyEvaluatingBinding());
}
void tst_QProperty::qobjectObservers()
@@ -1092,7 +1379,9 @@ void tst_QProperty::qobjectObservers()
MyQObject object;
int onValueChangedCalled = 0;
{
- auto handler = object.bindableFoo().onValueChanged([&onValueChangedCalled]() { ++onValueChangedCalled;});
+ auto handler = object.bindableFoo().onValueChanged([&onValueChangedCalled]() {
+ ++onValueChangedCalled;
+ });
QCOMPARE(onValueChangedCalled, 0);
object.setFoo(10);
@@ -1117,7 +1406,7 @@ void tst_QProperty::compatBindings()
QCOMPARE(object.compatData, 0);
// setting data through the private interface should not call the changed signal or the public setter
- object.compatData = 10;
+ object.compatData.setValue(10);
QCOMPARE(object.compatChangedCount, 0);
QCOMPARE(object.setCompatCalled, 0);
// going through the public API should emit the signal
@@ -1211,42 +1500,1083 @@ void tst_QProperty::metaProperty()
QCOMPARE(object.fooData.value(), 1);
}
-void tst_QProperty::aliasOnMetaProperty()
+void tst_QProperty::modifyObserverListWhileIterating()
{
- MyQObject object;
- QPropertyAlias<int> alias(object.bindableFoo());
+ struct DestructingObserver : QPropertyObserver {
+ DestructingObserver() : QPropertyObserver([](QPropertyObserver *self, QUntypedPropertyData *) {
+ auto This = static_cast<DestructingObserver *>(self);
+ (*This)();
+ }), m_target(this){}
+ void operator()() {
+ (*counter)++;
+ std::destroy_at(m_target);
+ }
+ DestructingObserver *m_target;
+ int *counter = nullptr;
+ };
+ union ObserverOrUninit {
+ DestructingObserver observer = {};
+ char* memory;
+ ~ObserverOrUninit() {}
+ ObserverOrUninit() {}
+ };
+ {
+ // observer deletes itself while running the notification
+ // while explicitly calling the destructor is rather unusual
+ // it is completely plausible for this to happen because the object to which a
+ // propertyobserver belongs has been destroyed
+ ObserverOrUninit data;
+ int counter = 0;
+ data.observer.counter = &counter;
+ QProperty<int> prop;
+ QUntypedBindable bindableProp(&prop);
+ bindableProp.observe(&data.observer);
+ prop = 42; // should not crash
+ QCOMPARE(counter, 1);
+ }
+ {
+ // observer deletes the next observer in the list
+ ObserverOrUninit data1;
+ ObserverOrUninit data2;
+ QProperty<int> prop;
+ QUntypedBindable bindableProp(&prop);
+ bindableProp.observe(&data1.observer);
+ bindableProp.observe(&data2.observer);
+ int counter = 0;
+ data1.observer.m_target = &data2.observer;
+ data1.observer.counter = &counter;
+ data2.observer.m_target = &data1.observer;
+ data2.observer.counter = &counter;
+ prop = 42; // should not crash
+ QCOMPARE(counter, 1); // only one trigger should run as the other has been deleted
+ }
+}
- QVERIFY(alias.isValid());
- QCOMPARE(alias.value(), object.foo());
- QVERIFY(!alias.hasBinding());
+void tst_QProperty::noDoubleCapture()
+{
+ QProperty<long long> size;
+ size = 3;
+ QProperty<int> max;
+ max.setBinding([&size]() -> int {
+ // each loop run attempts to capture size
+ for (int i = 0; i < size; ++i) {}
+ return size.value();
+ });
+ auto bindingPriv = QPropertyBindingPrivate::get(max.binding());
+ QCOMPARE(bindingPriv->dependencyObserverCount, 1U);
+ size = 4; // should not crash
+ QCOMPARE(max.value(), 4);
+}
+
+class CompatPropertyTester : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int prop1 READ prop1 WRITE setProp1 BINDABLE bindableProp1)
+ Q_PROPERTY(int prop2 READ prop2 WRITE setProp2 NOTIFY prop2Changed BINDABLE bindableProp2)
+ Q_PROPERTY(int prop3 READ prop3 WRITE setProp3 NOTIFY prop3Changed BINDABLE bindableProp3)
+ Q_PROPERTY(int prop4 READ prop4 WRITE setProp4 NOTIFY prop4Changed BINDABLE bindableProp4)
+public:
+ CompatPropertyTester(QObject *parent = nullptr) : QObject(parent) { }
+
+ int prop1() {return prop1Data.value();}
+ void setProp1(int i) { if (i == prop1Data) return; prop1Data.setValue(i); prop1Data.notify(); }
+ QBindable<int> bindableProp1() {return QBindable<int>(&prop1Data);}
+
+ int prop2() { return prop2Data.value(); }
+ void setProp2(int i)
+ {
+ if (i == prop2Data)
+ return;
+ prop2Data.setValue(i);
+ prop2Data.notify();
+ }
+ QBindable<int> bindableProp2() { return QBindable<int>(&prop2Data); }
+
+ int prop3() { return prop3Data.value(); }
+ void setProp3(int i)
+ {
+ if (i == prop3Data)
+ return;
+ prop3Data.setValue(i);
+ prop3Data.notify();
+ }
+ QBindable<int> bindableProp3() { return QBindable<int>(&prop3Data); }
+
+ int prop4() const
+ {
+ auto val = prop4Data.value();
+ return val == 0 ? 42 : val;
+ }
+
+ void setProp4(int i)
+ {
+ if (i == prop4Data)
+ return;
+ prop4Data.setValue(i);
+ prop4Data.notify();
+ }
+ QBindable<int> bindableProp4() { return QBindable<int>(&prop4Data); }
+
+signals:
+ void prop2Changed(int value);
+ void prop3Changed();
+ void prop4Changed(int value);
+
+private:
+ Q_OBJECT_COMPAT_PROPERTY(CompatPropertyTester, int, prop1Data, &CompatPropertyTester::setProp1)
+ Q_OBJECT_COMPAT_PROPERTY(CompatPropertyTester, int, prop2Data, &CompatPropertyTester::setProp2,
+ &CompatPropertyTester::prop2Changed)
+ Q_OBJECT_COMPAT_PROPERTY_WITH_ARGS(CompatPropertyTester, int, prop3Data,
+ &CompatPropertyTester::setProp3,
+ &CompatPropertyTester::prop3Changed, 1)
+ Q_OBJECT_COMPAT_PROPERTY_WITH_ARGS(CompatPropertyTester, int, prop4Data,
+ &CompatPropertyTester::setProp4,
+ &CompatPropertyTester::prop4Changed,
+ &CompatPropertyTester::prop4, 0)
+};
+
+void tst_QProperty::compatPropertyNoDobuleNotification()
+{
+ CompatPropertyTester tester;
+ int counter = 0;
+ QProperty<int> iprop {1};
+ tester.bindableProp1().setBinding([&]() -> int {return iprop;});
+ auto observer = tester.bindableProp1().onValueChanged([&](){++counter;});
+ iprop.setValue(2);
+ QCOMPARE(counter, 1);
+}
+
+void tst_QProperty::compatPropertySignals()
+{
+ CompatPropertyTester tester;
+
+ // Compat property with signal. Signal has parameter.
+ QProperty<int> prop2Observer;
+ prop2Observer.setBinding(tester.bindableProp2().makeBinding());
+
+ QSignalSpy prop2Spy(&tester, &CompatPropertyTester::prop2Changed);
+
+ tester.setProp2(10);
+
+ QCOMPARE(prop2Observer.value(), 10);
+ QCOMPARE(prop2Spy.size(), 1);
+ QList<QVariant> arguments = prop2Spy.takeFirst();
+ QCOMPARE(arguments.size(), 1);
+ QCOMPARE(arguments.at(0).metaType().id(), QMetaType::Int);
+ QCOMPARE(arguments.at(0).toInt(), 10);
+
+ // Compat property with signal and default value. Signal has no parameter.
+ QProperty<int> prop3Observer;
+ prop3Observer.setBinding(tester.bindableProp3().makeBinding());
+ QCOMPARE(prop3Observer.value(), 1);
+
+ QSignalSpy prop3Spy(&tester, &CompatPropertyTester::prop3Changed);
+
+ tester.setProp3(5);
+
+ QCOMPARE(prop3Observer.value(), 5);
+ QCOMPARE(prop3Spy.size(), 1);
+
+ // Compat property with signal, default value, and custom setter. Signal has parameter.
+ QProperty<int> prop4Observer;
+ prop4Observer.setBinding(tester.bindableProp4().makeBinding());
+ QCOMPARE(prop4Observer.value(), 42);
+
+ QSignalSpy prop4Spy(&tester, &CompatPropertyTester::prop4Changed);
+
+ tester.setProp4(10);
+
+ QCOMPARE(prop4Observer.value(), 10);
+ QCOMPARE(prop4Spy.size(), 1);
+ arguments = prop4Spy.takeFirst();
+ QCOMPARE(arguments.size(), 1);
+ QCOMPARE(arguments.at(0).metaType().id(), QMetaType::Int);
+ QCOMPARE(arguments.at(0).toInt(), 10);
+
+ tester.setProp4(42);
+
+ QCOMPARE(prop4Observer.value(), 42);
+ QCOMPARE(prop4Spy.size(), 1);
+ arguments = prop4Spy.takeFirst();
+ QCOMPARE(arguments.size(), 1);
+ QCOMPARE(arguments.at(0).metaType().id(), QMetaType::Int);
+ QCOMPARE(arguments.at(0).toInt(), 42);
- object.setFoo(42);
+ tester.setProp4(0);
+
+ QCOMPARE(prop4Observer.value(), 42);
+ QCOMPARE(prop4Spy.size(), 1);
+ arguments = prop4Spy.takeFirst();
+ QCOMPARE(arguments.size(), 1);
+ QCOMPARE(arguments.at(0).metaType().id(), QMetaType::Int);
+ QCOMPARE(arguments.at(0).toInt(), 42);
+}
+
+class FakeDependencyCreator : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(int prop1 READ prop1 WRITE setProp1 NOTIFY prop1Changed BINDABLE bindableProp1)
+ Q_PROPERTY(int prop2 READ prop2 WRITE setProp2 NOTIFY prop2Changed BINDABLE bindableProp2)
+ Q_PROPERTY(int prop3 READ prop3 WRITE setProp3 NOTIFY prop3Changed BINDABLE bindableProp3)
+
+signals:
+ void prop1Changed();
+ void prop2Changed();
+ void prop3Changed();
+
+public:
+ void setProp1(int val) { prop1Data.setValue(val); prop1Data.notify();}
+ void setProp2(int val) { prop2Data.setValue(val); prop2Data.notify();}
+ void setProp3(int val) { prop3Data.setValue(val); prop3Data.notify();}
+
+ int prop1() { return prop1Data; }
+ int prop2() { return prop2Data; }
+ int prop3() { return prop3Data; }
+
+ QBindable<int> bindableProp1() { return QBindable<int>(&prop1Data); }
+ QBindable<int> bindableProp2() { return QBindable<int>(&prop2Data); }
+ QBindable<int> bindableProp3() { return QBindable<int>(&prop3Data); }
+
+private:
+ Q_OBJECT_COMPAT_PROPERTY(FakeDependencyCreator, int, prop1Data, &FakeDependencyCreator::setProp1, &FakeDependencyCreator::prop1Changed);
+ Q_OBJECT_COMPAT_PROPERTY(FakeDependencyCreator, int, prop2Data, &FakeDependencyCreator::setProp2, &FakeDependencyCreator::prop2Changed);
+ Q_OBJECT_COMPAT_PROPERTY(FakeDependencyCreator, int, prop3Data, &FakeDependencyCreator::setProp3, &FakeDependencyCreator::prop3Changed);
+};
+
+void tst_QProperty::noFakeDependencies()
+{
+ FakeDependencyCreator fdc;
+ int bindingFunctionCalled = 0;
+ fdc.bindableProp1().setBinding([&]() -> int {++bindingFunctionCalled; return fdc.prop2();});
+ fdc.setProp2(42);
+ QCOMPARE(fdc.prop1(), 42); // basic binding works
+
+ int slotCounter = 0;
+ QObject::connect(&fdc, &FakeDependencyCreator::prop1Changed, &fdc, [&](){ (void) fdc.prop3(); ++slotCounter;});
+ fdc.setProp2(13);
+ QCOMPARE(slotCounter, 1); // sanity check
+ int old = bindingFunctionCalled;
+ fdc.setProp3(100);
+ QCOMPARE(old, bindingFunctionCalled);
+}
+
+class PropertyAdaptorTester : public QObject
+{
+ Q_OBJECT
+
+ Q_PROPERTY(int foo READ foo WRITE setFoo NOTIFY fooChanged)
+ Q_PROPERTY(int foo1 READ foo WRITE setFoo)
+
+signals:
+ void dummySignal1();
+ void dummySignal2();
+ void dummySignal3();
+ void dummySignal4();
+ void dummySignal5();
+ void dummySignal6();
+ void dummySignal7();
+ void dummySignal8();
+ void fooChanged(int newFoo);
+
+public slots:
+ void fooHasChanged() { fooChangedCount++; }
+
+public:
+ int foo() const { return fooData; }
+ void setFoo(int i)
+ {
+ if (i != fooData) {
+ fooData = i;
+ fooChanged(fooData);
+ }
+ }
+
+public:
+ int fooData = 0;
+ int fooChangedCount = 0;
+};
+
+void tst_QProperty::propertyAdaptorBinding()
+{
+ QProperty<int> source { 5 };
+ QProperty<int> dest1 { 99 };
+ QProperty<int> dest2 { 98 };
+
+ // Check binding of non BINDABLE property
+ PropertyAdaptorTester object;
+ // set up a dummy connection (needed to verify that the QBindable avoids an out-of-bounds read)
+ QObject::connect(&object, &PropertyAdaptorTester::dummySignal1, [](){});
+ QBindable<int> binding(&object, "foo");
+ QObject::connect(&object, &PropertyAdaptorTester::fooChanged, &object,
+ &PropertyAdaptorTester::fooHasChanged);
+ binding.setBinding([&]() { return source + 1; });
+ QCOMPARE(object.foo(), 6);
+ QCOMPARE(object.fooChangedCount, 1);
+
+ struct MyBindable : QBindable<int> {
+ using QBindable<int>::QBindable;
+ QtPrivate::QPropertyAdaptorSlotObject* data() {
+ return static_cast<QtPrivate::QPropertyAdaptorSlotObject*>(QUntypedBindable::data);
+ }
+ } dataBinding(&object, "foo");
+ QPropertyBindingDataPointer data{&dataBinding.data()->bindingData()};
+
+ QCOMPARE(data.observerCount(), 0);
+ dest1.setBinding(binding.makeBinding());
+ QCOMPARE(data.observerCount(), 1);
+ dest2.setBinding([=]() { return binding.value() + 1; });
+ binding = {};
+ QCOMPARE(data.observerCount(), 2);
+
+ // Check addNotifer
+ {
+ int local_foo = 0;
+ auto notifier = QBindable<int>(&object, "foo").addNotifier([&]() { local_foo++; });
+ QCOMPARE(data.observerCount(), 3);
+ QCOMPARE(object.foo(), 6);
+ QCOMPARE(dest1.value(), 6);
+ QCOMPARE(dest2.value(), 7);
+ QCOMPARE(local_foo, 0);
+ QCOMPARE(object.fooChangedCount, 1);
+
+ source = 7;
+ QCOMPARE(object.foo(), 8);
+ QCOMPARE(dest1.value(), 8);
+ QCOMPARE(dest2.value(), 9);
+ QCOMPARE(local_foo, 1);
+ QCOMPARE(object.fooChangedCount, 2);
+ }
+
+ QCOMPARE(data.observerCount(), 2);
+
+ // Check a new QBindable object can override the existing binding
+ QBindable<int>(&object, "foo").setValue(10);
+ QCOMPARE(object.foo(), 10);
+ QCOMPARE(dest1.value(), 10);
+ QCOMPARE(dest2.value(), 11);
+ QCOMPARE(object.fooChangedCount, 3);
+ source.setValue(99);
+ QCOMPARE(object.foo(), 10);
+ QCOMPARE(dest1.value(), 10);
+ QCOMPARE(dest2.value(), 11);
+ QCOMPARE(object.fooChangedCount, 3);
+ object.setFoo(12);
+ QCOMPARE(object.foo(), 12);
+ QCOMPARE(dest1.value(), 12);
+ QCOMPARE(dest2.value(), 13);
+ QCOMPARE(object.fooChangedCount, 4);
+
+ // Check binding multiple notifiers
+ QProperty<int> source2 { 20 };
+ source.setValue(21);
+ binding = QBindable<int>(&object, "foo");
+ binding.setBinding([&]() { return source + source2; });
+ QCOMPARE(object.foo(), 41);
+ QCOMPARE(dest1.value(), 41);
+ QCOMPARE(object.fooChangedCount, 5);
+ source.setValue(22);
+ QCOMPARE(object.foo(), 42);
+ QCOMPARE(dest1.value(), 42);
+ QCOMPARE(object.fooChangedCount, 6);
+ source2.setValue(21);
+ QCOMPARE(object.foo(), 43);
+ QCOMPARE(dest1.value(), 43);
+ QCOMPARE(object.fooChangedCount, 7);
+
+ // Check update group
+ {
+ const QScopedPropertyUpdateGroup guard;
+ source.setValue(23);
+ source2.setValue(22);
+ QCOMPARE(object.foo(), 43);
+ QCOMPARE(dest1.value(), 43);
+ QCOMPARE(object.fooChangedCount, 7);
+ }
+ QCOMPARE(object.foo(), 45);
+ QCOMPARE(dest1.value(), 45);
+ QCOMPARE(object.fooChangedCount, 8);
+
+ PropertyAdaptorTester object2;
+ PropertyAdaptorTester object3;
+
+ // Check multiple observers
+ QBindable<int> binding2(&object2, "foo");
+ QBindable<int> binding3(&object3, "foo");
+ binding.setBinding([=]() { return binding2.value(); });
+ binding3.setBinding([=]() { return binding.value(); });
+ QCOMPARE(object.foo(), 0);
+ QCOMPARE(object2.foo(), 0);
+ QCOMPARE(object3.foo(), 0);
+ QCOMPARE(dest1.value(), 0);
+ object2.setFoo(1);
+ QCOMPARE(object.foo(), 1);
+ QCOMPARE(object2.foo(), 1);
+ QCOMPARE(object3.foo(), 1);
+ QCOMPARE(dest1.value(), 1);
+
+ // Check interoperation with BINDABLE properties
+ MyQObject bindableObject;
+ bindableObject.fooData.setBinding([]() { return 5; });
+ QVERIFY(bindableObject.fooData.hasBinding());
+ QVERIFY(!bindableObject.barData.hasBinding());
+ QVERIFY(QBindable<int>(&bindableObject, "foo").hasBinding());
+ QBindable<int> bindableBar(&bindableObject, "bar");
+ QVERIFY(!bindableBar.hasBinding());
+ bindableBar.setBinding([]() { return 6; });
+ QVERIFY(bindableBar.hasBinding());
+ QVERIFY(bindableObject.barData.hasBinding());
+
+ // Check bad arguments
+#ifndef QT_NO_DEBUG
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "QUntypedBindable: Property is not valid");
+#endif
+ QVERIFY(!QBindable<int>(&object, QMetaProperty{}).isValid());
+#ifndef QT_NO_DEBUG
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "QUntypedBindable: Property foo1 has no notify signal");
+#endif
+ QVERIFY(!QBindable<int>(&object, "foo1").isValid());
+#ifndef QT_NO_DEBUG
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "QUntypedBindable: Property foo of type int does not match requested type bool");
+#endif
+ QVERIFY(!QBindable<bool>(&object, "foo").isValid());
+#ifndef QT_NO_DEBUG
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg,
+ "QUntypedBindable: Property foo does not belong to this object");
+#endif
+ QObject qobj;
+ QVERIFY(!QBindable<int>(
+ &qobj,
+ object.metaObject()->property(object.metaObject()->indexOfProperty("foo")))
+ .isValid());
+#ifndef QT_NO_DEBUG
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "QUntypedBindable: No property named fizz");
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "QUntypedBindable: Property is not valid");
+#endif
+ QVERIFY(!QBindable<int>(&object, "fizz").isValid());
+}
+
+#if QT_CONFIG(thread)
+struct ThreadSafetyTester : public QObject
+{
+ Q_OBJECT
+
+public:
+ ThreadSafetyTester(QObject *parent = nullptr) : QObject(parent) {}
+
+ Q_INVOKABLE bool hasCorrectStatus() const
+ {
+ return qGetBindingStorage(this)->status({}) == QtPrivate::getBindingStatus({});
+ }
+
+ Q_INVOKABLE bool bindingTest()
+ {
+ QProperty<QString> name(u"inThread"_s);
+ bindableObjectName().setBinding([&]() -> QString { return name; });
+ name = u"inThreadChanged"_s;
+ const bool nameChangedCorrectly = objectName() == name;
+ bindableObjectName().takeBinding();
+ return nameChangedCorrectly;
+ }
+};
+
+
+void tst_QProperty::threadSafety()
+{
+ QThread workerThread;
+ auto cleanup = qScopeGuard([&](){
+ QMetaObject::invokeMethod(&workerThread, "quit");
+ workerThread.wait();
+ });
+ QScopedPointer<ThreadSafetyTester> scopedObj1(new ThreadSafetyTester);
+ auto obj1 = scopedObj1.data();
+ auto child1 = new ThreadSafetyTester(obj1);
+ obj1->moveToThread(&workerThread);
+ const auto mainThreadBindingStatus = QtPrivate::getBindingStatus({});
+ QCOMPARE(qGetBindingStorage(child1)->status({}), nullptr);
+ workerThread.start();
+
+ bool correctStatus = false;
+ bool ok = QMetaObject::invokeMethod(obj1, "hasCorrectStatus", Qt::BlockingQueuedConnection,
+ Q_RETURN_ARG(bool, correctStatus));
+ QVERIFY(ok);
+ QVERIFY(correctStatus);
+
+ bool bindingWorks = false;
+ ok = QMetaObject::invokeMethod(obj1, "bindingTest", Qt::BlockingQueuedConnection,
+ Q_RETURN_ARG(bool, bindingWorks));
+ QVERIFY(ok);
+ QVERIFY(bindingWorks);
+
+ correctStatus = false;
+ ok = QMetaObject::invokeMethod(child1, "hasCorrectStatus", Qt::BlockingQueuedConnection,
+ Q_RETURN_ARG(bool, correctStatus));
+ QVERIFY(ok);
+ QVERIFY(correctStatus);
+
+ QScopedPointer scopedObj2(new ThreadSafetyTester);
+ auto obj2 = scopedObj2.data();
+ QCOMPARE(qGetBindingStorage(obj2)->status({}), mainThreadBindingStatus);
+
+ obj2->setObjectName("moved");
+ QCOMPARE(obj2->objectName(), "moved");
+
+ obj2->moveToThread(&workerThread);
+ correctStatus = false;
+ ok = QMetaObject::invokeMethod(obj2, "hasCorrectStatus", Qt::BlockingQueuedConnection,
+ Q_RETURN_ARG(bool, correctStatus));
+
+ QVERIFY(ok);
+ QVERIFY(correctStatus);
+ // potentially unsafe, but should still work (no writes in owning thread)
+ QCOMPARE(obj2->objectName(), "moved");
+
+
+ QScopedPointer scopedObj3(new ThreadSafetyTester);
+ auto obj3 = scopedObj3.data();
+ obj3->setObjectName("moved");
+ QCOMPARE(obj3->objectName(), "moved");
+ obj3->moveToThread(nullptr);
+ QCOMPARE(obj2->objectName(), "moved");
+ obj3->setObjectName("moved again");
+ QCOMPARE(obj3->objectName(), "moved again");
+}
+
+class QPropertyUsingThread : public QThread
+{
+public:
+ QPropertyUsingThread(QObject **dest, QThread *destThread) : dest(dest), destThread(destThread) {}
+ void run() override
+ {
+ scopedObj1.reset(new ThreadSafetyTester());
+ scopedObj1->setObjectName("test");
+ QObject *child = new ThreadSafetyTester(scopedObj1.get());
+ child->setObjectName("child");
+ exec();
+ scopedObj1->moveToThread(destThread);
+ *dest = scopedObj1.release();
+ }
+ std::unique_ptr<ThreadSafetyTester> scopedObj1;
+ QObject **dest;
+ QThread *destThread;
+};
+
+void tst_QProperty::threadSafety2()
+{
+ std::unique_ptr<QObject> movedObj;
+ {
+ QObject *tmp = nullptr;
+ QPropertyUsingThread workerThread(&tmp, QThread::currentThread());
+ workerThread.start();
+ workerThread.quit();
+ workerThread.wait();
+ movedObj.reset(tmp);
+ }
+
+ QCOMPARE(movedObj->objectName(), "test");
+ QCOMPARE(movedObj->children().first()->objectName(), "child");
+}
+#endif // QT_CONFIG(thread)
+
+struct CustomType
+{
+ CustomType() = default;
+ CustomType(int val) : value(val) { }
+ CustomType(int val, int otherVal) : value(val), anotherValue(otherVal) { }
+ CustomType(const CustomType &) = default;
+ CustomType(CustomType &&) = default;
+ ~CustomType() = default;
+ CustomType &operator=(const CustomType &) = default;
+ CustomType &operator=(CustomType &&) = default;
+ bool operator==(const CustomType &other) const
+ {
+ return (value == other.value) && (anotherValue == other.anotherValue);
+ }
+
+ int value = 0;
+ int anotherValue = 0;
+};
+
+class PropertyWithInitializationTester : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int prop1 READ prop1 WRITE setProp1 NOTIFY prop1Changed BINDABLE bindableProp1)
+ Q_PROPERTY(CustomType prop2 READ prop2 WRITE setProp2 BINDABLE bindableProp2)
+ Q_PROPERTY(CustomType prop3 READ prop3 WRITE setProp3 BINDABLE bindableProp3)
+signals:
+ void prop1Changed();
+
+public:
+ PropertyWithInitializationTester(QObject *parent = nullptr) : QObject(parent) { }
+
+ int prop1() { return prop1Data.value(); }
+ void setProp1(int i) { prop1Data = i; }
+ QBindable<int> bindableProp1() { return QBindable<int>(&prop1Data); }
+
+ CustomType prop2() { return prop2Data.value(); }
+ void setProp2(CustomType val) { prop2Data = val; }
+ QBindable<CustomType> bindableProp2() { return QBindable<CustomType>(&prop2Data); }
+
+ CustomType prop3() { return prop3Data.value(); }
+ void setProp3(CustomType val) { prop3Data.setValue(val); }
+ QBindable<CustomType> bindableProp3() { return QBindable<CustomType>(&prop3Data); }
+
+ Q_OBJECT_BINDABLE_PROPERTY_WITH_ARGS(PropertyWithInitializationTester, int, prop1Data, 5,
+ &PropertyWithInitializationTester::prop1Changed)
+ Q_OBJECT_BINDABLE_PROPERTY_WITH_ARGS(PropertyWithInitializationTester, CustomType, prop2Data,
+ CustomType(5))
+ Q_OBJECT_COMPAT_PROPERTY_WITH_ARGS(PropertyWithInitializationTester, CustomType, prop3Data,
+ &PropertyWithInitializationTester::setProp3,
+ CustomType(10, 20))
+};
+
+void tst_QProperty::bindablePropertyWithInitialization()
+{
+ PropertyWithInitializationTester tester;
+
+ QCOMPARE(tester.prop1(), 5);
+ QCOMPARE(tester.prop2().value, 5);
+ QCOMPARE(tester.prop3().value, 10);
+ QCOMPARE(tester.prop3().anotherValue, 20);
+}
+
+void tst_QProperty::noDoubleNotification()
+{
+ /* dependency graph for this test
+ x --> y means y depends on x
+ a-->b-->d
+ \ ^
+ \->c--/
+ */
+ QProperty<int> a(0);
+ QProperty<int> b;
+ b.setBinding([&](){ return a.value(); });
+ QProperty<int> c;
+ c.setBinding([&](){ return a.value(); });
+ QProperty<int> d;
+ d.setBinding([&](){ return b.value() + c.value(); });
+ int nNotifications = 0;
+ int expected = 0;
+ auto connection = d.subscribe([&](){
+ ++nNotifications;
+ QCOMPARE(d.value(), expected);
+ });
+ QCOMPARE(nNotifications, 1);
+ expected = 2;
+ a = 1;
+ QCOMPARE(nNotifications, 2);
+ expected = 4;
+ a = 2;
+ QCOMPARE(nNotifications, 3);
+}
+
+void tst_QProperty::groupedNotifications()
+{
+ QProperty<int> a(0);
+ QProperty<int> b;
+ b.setBinding([&](){ return a.value(); });
+ QProperty<int> c;
+ c.setBinding([&](){ return a.value(); });
+ QProperty<int> d;
+ QProperty<int> e;
+ e.setBinding([&](){ return b.value() + c.value() + d.value(); });
+ int nNotifications = 0;
+ int expected = 0;
+ auto connection = e.subscribe([&](){
+ ++nNotifications;
+ QCOMPARE(e.value(), expected);
+ });
+ QCOMPARE(nNotifications, 1);
+
+ expected = 2;
+ {
+ const QScopedPropertyUpdateGroup guard;
+ a = 1;
+ QCOMPARE(b.value(), 0);
+ QCOMPARE(c.value(), 0);
+ QCOMPARE(d.value(), 0);
+ QCOMPARE(nNotifications, 1);
+ }
+ QCOMPARE(b.value(), 1);
+ QCOMPARE(c.value(), 1);
+ QCOMPARE(e.value(), 2);
+ QCOMPARE(nNotifications, 2);
+
+ expected = 7;
+ {
+ const QScopedPropertyUpdateGroup guard;
+ a = 2;
+ d = 3;
+ QCOMPARE(b.value(), 1);
+ QCOMPARE(c.value(), 1);
+ QCOMPARE(d.value(), 3);
+ QCOMPARE(nNotifications, 2);
+ }
+ QCOMPARE(b.value(), 2);
+ QCOMPARE(c.value(), 2);
+ QCOMPARE(e.value(), 7);
+ QCOMPARE(nNotifications, 3);
+
+
+}
+
+void tst_QProperty::groupedNotificationConsistency()
+{
+ QProperty<int> i(0);
+ QProperty<int> j(0);
+ bool areEqual = true;
+
+ auto observer = i.onValueChanged([&](){
+ areEqual = i == j;
+ });
+
+ i = 1;
+ j = 1;
+ QVERIFY(!areEqual); // value changed runs before j = 1
+
+ {
+ const QScopedPropertyUpdateGroup guard;
+ i = 2;
+ j = 2;
+ }
+ QVERIFY(areEqual); // value changed runs after everything has been evaluated
+}
+
+void tst_QProperty::bindingGroupMovingBindingData()
+{
+ auto tester = std::make_unique<ClassWithNotifiedProperty>();
+ auto testerPriv = QObjectPrivate::get(tester.get());
+
+ auto dummyNotifier = tester->property.addNotifier([](){});
+ auto bindingData = testerPriv->bindingStorage.bindingData(&tester->property);
+ QVERIFY(bindingData); // we have a notifier, so there should be binding data
+
+ Qt::beginPropertyUpdateGroup();
+ auto cleanup = qScopeGuard([](){ Qt::endPropertyUpdateGroup(); });
+ tester->property = 42;
+ QCOMPARE(testerPriv->bindingStorage.bindingData(&tester->property), bindingData);
+ auto proxyData = QPropertyBindingDataPointer::proxyData(bindingData);
+ // as we've modified the property, we now should have a proxy for the delayed notification
+ QVERIFY(proxyData);
+ // trigger binding data reallocation
+ std::array<QUntypedPropertyData, 10> propertyDataArray;
+ for (auto&& data: propertyDataArray)
+ testerPriv->bindingStorage.bindingData(&data, true);
+ // binding data has moved
+ QVERIFY(testerPriv->bindingStorage.bindingData(&tester->property) != bindingData);
+ bindingData = testerPriv->bindingStorage.bindingData(&tester->property);
+ // the proxy data has been updated
+ QCOMPARE(proxyData->originalBindingData, bindingData);
+
+ tester.reset();
+ // the property data is gone, proxyData should have been informed
+ QCOMPARE(proxyData->originalBindingData, nullptr);
+ QVERIFY(proxyData);
+}
+
+void tst_QProperty::bindingGroupBindingDeleted()
+{
+ auto deleter = std::make_unique<ClassWithNotifiedProperty>();
+ auto toBeDeleted = std::make_unique<ClassWithNotifiedProperty>();
+
+ bool calledHandler = false;
+ deleter->property.setBinding([&](){
+ int newValue = toBeDeleted->property;
+ if (newValue == 42)
+ toBeDeleted.reset();
+ return newValue;
+ });
+ auto handler = toBeDeleted->property.onValueChanged([&]() { calledHandler = true; } );
+ {
+ Qt::beginPropertyUpdateGroup();
+ auto cleanup = qScopeGuard([](){ Qt::endPropertyUpdateGroup(); });
+ QVERIFY(toBeDeleted);
+ toBeDeleted->property = 42;
+ // ASAN should not complain here
+ }
+ QVERIFY(!toBeDeleted);
+ // the change notification is sent, even if the binding is deleted during evaluation
+ QVERIFY(calledHandler);
+}
+
+void tst_QProperty::uninstalledBindingDoesNotEvaluate()
+{
+ QProperty<int> i;
+ QProperty<int> j;
+ int bindingEvaluationCounter = 0;
+ i.setBinding([&](){
+ bindingEvaluationCounter++;
+ return j.value();
+ });
+ QCOMPARE(bindingEvaluationCounter, 1);
+ // Sanity check: if we force a binding reevaluation,
+ j = 42;
+ // the binding function will be called again.
+ QCOMPARE(bindingEvaluationCounter, 2);
+ // If we keep referencing the binding
+ auto keptBinding = i.binding();
+ // but have it not installed on a property
+ i = 10;
+ QVERIFY(!i.hasBinding());
+ QVERIFY(!keptBinding.isNull());
+ // then changing a dependency
+ j = 12;
+ // does not lead to the binding being reevaluated.
+ QCOMPARE(bindingEvaluationCounter, 2);
+}
+
+void tst_QProperty::notify()
+{
+ QProperty<int> testProperty(0);
+ QList<int> recordedValues;
+ int value = 0;
+ QPropertyNotifier notifier;
+
+ {
+ QPropertyNotifier handler = testProperty.addNotifier([&]() {
+ recordedValues << testProperty;
+ });
+ notifier = testProperty.addNotifier([&]() {
+ value = testProperty;
+ });
+
+ testProperty = 1;
+ testProperty = 2;
+ }
+ QCOMPARE(value, 2);
+ testProperty = 3;
+ QCOMPARE(value, 3);
+ notifier = {};
+ testProperty = 4;
+ QCOMPARE(value, 3);
+
+ QCOMPARE(recordedValues.size(), 2);
+ QCOMPARE(recordedValues.at(0), 1);
+ QCOMPARE(recordedValues.at(1), 2);
+}
+
+void tst_QProperty::bindableInterfaceOfCompatPropertyUsesSetter()
+{
+ MyQObject obj;
+ QBindable<int> bindable = obj.bindableCompat();
+ QCOMPARE(obj.setCompatCalled, 0);
+ bindable.setValue(42);
+ QCOMPARE(obj.setCompatCalled, 1);
+}
+
+void tst_QProperty::selfBindingShouldNotCrash()
+{
+ QProperty<int> i;
+ i.setBinding([&](){ return i+1; });
+ QVERIFY(i.binding().error().hasError());
+}
+
+void tst_QProperty::qpropertyAlias()
+{
+#if QT_DEPRECATED_SINCE(6, 6)
+ QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ std::unique_ptr<QProperty<int>> i {new QProperty<int>};
+ QPropertyAlias<int> alias(i.get());
+ QVERIFY(alias.isValid());
+ alias.setValue(42);
+ QCOMPARE(i->value(), 42);
+ QProperty<int> j;
+ bool notifierCalled = false;
+ auto myNotifier = alias.addNotifier([&](){notifierCalled = true;});
+ i->setBinding([&]() -> int { return j; });
+ QVERIFY(notifierCalled);
+ j.setValue(42);
QCOMPARE(alias.value(), 42);
+ i.reset();
+ QVERIFY(!alias.isValid());
+ QT_WARNING_POP
+#endif
+}
- auto f = [&object]() -> int {
- return object.barData;
- };
- object.bindableFoo().setBinding(f);
- QVERIFY(alias.hasBinding());
- QCOMPARE(alias.value(), object.bar());
+void tst_QProperty::scheduleNotify()
+{
+ int notifications = 0;
+ QProperty<int> p;
+ QCOMPARE(p.value(), 0);
+ const auto handler = p.addNotifier([&](){ ++notifications; });
+ QCOMPARE(notifications, 0);
+ QPropertyBinding<int> b([]() { return 0; }, QPropertyBindingSourceLocation());
+ QPropertyBindingPrivate::get(b)->scheduleNotify();
+ QCOMPARE(notifications, 0);
+ p.setBinding(b);
+ QCOMPARE(notifications, 1);
+ QCOMPARE(p.value(), 0);
+}
- object.setBar(111);
- QCOMPARE(alias.value(), 111);
+void tst_QProperty::notifyAfterAllDepsGone()
+{
+ bool b = true;
+ QProperty<int> iprop;
+ QProperty<int> jprop(42);
+ iprop.setBinding([&](){
+ if (b)
+ return jprop.value();
+ return 13;
+ });
+ int changeCounter = 0;
+ auto keepAlive = iprop.onValueChanged([&](){ changeCounter++; });
+ QCOMPARE(iprop.value(), 42);
+ jprop = 44;
+ QCOMPARE(iprop.value(), 44);
+ QCOMPARE(changeCounter, 1);
+ b = false;
+ jprop = 43;
+ QCOMPARE(iprop.value(), 13);
+ QCOMPARE(changeCounter, 2);
+}
- int changedCount = 0;
- auto observer = alias.onValueChanged([&changedCount]() { ++changedCount; });
- QCOMPARE(changedCount, 0);
- object.setBar(666);
- QCOMPARE(changedCount, 1);
+class TestObject : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int signaled READ signaled WRITE setSignaled NOTIFY signaledChanged FINAL)
+ Q_PROPERTY(int bindable1 READ bindable1 WRITE setBindable1 BINDABLE bindable1Bindable NOTIFY bindable1Changed FINAL)
+ Q_PROPERTY(int bindable2 READ bindable2 WRITE setBindable2 BINDABLE bindable2Bindable NOTIFY bindable2Changed FINAL)
+
+public:
+ int signaled() const
+ {
+ return m_signaled;
+ }
+
+ void setSignaled(int newSignaled)
+ {
+ if (m_signaled == newSignaled)
+ return;
+ m_signaled = newSignaled;
+ emit signaledChanged();
+ }
+
+ int bindable1() const
+ {
+ return m_bindable1;
+ }
+
+ void setBindable1(int newBindable1)
+ {
+ if (m_bindable1 == newBindable1)
+ return;
+ m_bindable1 = newBindable1;
+ emit bindable1Changed();
+ }
+
+ QBindable<int> bindable1Bindable()
+ {
+ return QBindable<int>(&m_bindable1);
+ }
+
+ int bindable2() const
+ {
+ return m_bindable2;
+ }
+
+ void setBindable2(int newBindable2)
+ {
+ if (m_bindable2 == newBindable2)
+ return;
+ m_bindable2 = newBindable2;
+ emit bindable2Changed();
+ }
+
+ QBindable<int> bindable2Bindable()
+ {
+ return QBindable<int>(&m_bindable2);
+ }
- alias.setBinding([&object]() { return object.read(); });
- QCOMPARE(changedCount, 2);
- QCOMPARE(alias.value(), 0);
- object.readData = 100;
- QCOMPARE(changedCount, 3);
- QCOMPARE(alias.value(), 100);
+signals:
+ void signaledChanged();
+ void bindable1Changed();
+ void bindable2Changed();
+
+private:
+ int m_signaled = 0;
+ Q_OBJECT_COMPAT_PROPERTY(TestObject, int, m_bindable1, &TestObject::setBindable1, &TestObject::bindable1Changed);
+ Q_OBJECT_COMPAT_PROPERTY(TestObject, int, m_bindable2, &TestObject::setBindable2, &TestObject::bindable2Changed);
+};
+
+void tst_QProperty::propertyUpdateViaSignaledProperty()
+{
+ TestObject o;
+ QProperty<int> rootTrigger;
+ QProperty<int> signalTrigger;
+
+ o.bindable1Bindable().setBinding([&]() {
+ return rootTrigger.value();
+ });
+
+ QObject::connect(&o, &TestObject::bindable1Changed, &o, [&]() {
+ // Signaled changes only once, doesn't actually depend on bindable1.
+ // In reality, there could be some complicated calculation behind this that changes
+ // on certain checkpoints, but not on every iteration.
+ o.setSignaled(40);
+ });
+
+ o.bindable2Bindable().setBinding([&]() {
+ return signalTrigger.value() - o.bindable1();
+ });
+
+ QObject::connect(&o, &TestObject::signaledChanged, &o, [&]() {
+ signalTrigger.setValue(o.signaled());
+ });
+
+ rootTrigger.setValue(2);
+ QCOMPARE(o.bindable1(), 2);
+ QCOMPARE(o.bindable2(), 38);
+ rootTrigger.setValue(3);
+ QCOMPARE(o.bindable1(), 3);
+ QCOMPARE(o.bindable2(), 37);
+ rootTrigger.setValue(4);
+ QCOMPARE(o.bindable1(), 4);
+ QCOMPARE(o.bindable2(), 36);
+}
+
+void tst_QProperty::derefFromObserver()
+{
+ int triggered = 0;
+ QProperty<int> source(11);
+
+ DtorCounter::counter = 0;
+ DtorCounter dc;
+
+ QProperty<int> target([&triggered, &source, dc]() mutable {
+ dc.shouldIncrement = true;
+ return ++triggered + source.value();
+ });
+ QCOMPARE(triggered, 1);
+
+ {
+ auto propObserver = std::make_unique<QPropertyObserver>();
+ QPropertyObserverPointer propObserverPtr { propObserver.get() };
+ propObserverPtr.setBindingToNotify(QPropertyBindingPrivate::get(target.binding()));
+
+ QBindingObserverPtr bindingPtr(propObserver.get());
+
+ QCOMPARE(triggered, 1);
+ source = 25;
+ QCOMPARE(triggered, 2);
+ QCOMPARE(target, 27);
+
+ target.setBinding([]() { return 8; });
+ QCOMPARE(target, 8);
+
+ // The QBindingObserverPtr still holds on to the binding.
+ QCOMPARE(dc.counter, 0);
+ }
+
+ // The binding is actually gone now.
+ QCOMPARE(dc.counter, 1);
+
+ source = 26;
+ QCOMPARE(triggered, 2);
+ QCOMPARE(target, 8);
}
QTEST_MAIN(tst_QProperty);
+#undef QT_SOURCE_LOCATION_NAMESPACE
+
#include "tst_qproperty.moc"
diff --git a/tests/auto/corelib/kernel/qsharedmemory/.prev_CMakeLists.txt b/tests/auto/corelib/kernel/qsharedmemory/.prev_CMakeLists.txt
deleted file mode 100644
index 90a9c9e17c..0000000000
--- a/tests/auto/corelib/kernel/qsharedmemory/.prev_CMakeLists.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-# Generated from qsharedmemory.pro.
-
- #####################################################################
- ## tst_qsharedmemory Test:
- #####################################################################
-
- qt_add_test(tst_qsharedmemory
- SOURCES
- tst_qsharedmemory.cpp
- PUBLIC_LIBRARIES
- Qt::CorePrivate
- )
-
- ## Scopes:
- #####################################################################
-
- qt_extend_target(tst_qsharedmemory CONDITION LINUX
- PUBLIC_LIBRARIES
- rt
- )
-if(QT_FEATURE_sharedmemory)
- add_subdirectory(producerconsumer)
-endif()
diff --git a/tests/auto/corelib/kernel/qsharedmemory/CMakeLists.txt b/tests/auto/corelib/kernel/qsharedmemory/CMakeLists.txt
deleted file mode 100644
index 8fb89d9af9..0000000000
--- a/tests/auto/corelib/kernel/qsharedmemory/CMakeLists.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-# Generated from qsharedmemory.pro.
-
-if(QT_FEATURE_sharedmemory) # special case
- #####################################################################
- ## tst_qsharedmemory Test:
- #####################################################################
-
- qt_add_test(tst_qsharedmemory
- SOURCES
- tst_qsharedmemory.cpp
- PUBLIC_LIBRARIES
- Qt::CorePrivate
- )
-
- ## Scopes:
- #####################################################################
-
- qt_extend_target(tst_qsharedmemory CONDITION LINUX
- PUBLIC_LIBRARIES
- rt
- )
-# if(QT_FEATURE_sharedmemory) # special case
- add_subdirectory(producerconsumer)
-endif()
diff --git a/tests/auto/corelib/kernel/qsharedmemory/producerconsumer/CMakeLists.txt b/tests/auto/corelib/kernel/qsharedmemory/producerconsumer/CMakeLists.txt
deleted file mode 100644
index 31d7f0386e..0000000000
--- a/tests/auto/corelib/kernel/qsharedmemory/producerconsumer/CMakeLists.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-# Generated from producerconsumer.pro.
-
-#####################################################################
-## producerconsumer_helper Binary:
-#####################################################################
-
-qt_add_test_helper(producerconsumer_helper
- SOURCES
- main.cpp
- PUBLIC_LIBRARIES
- Qt::Test
-)
diff --git a/tests/auto/corelib/kernel/qsharedmemory/producerconsumer/main.cpp b/tests/auto/corelib/kernel/qsharedmemory/producerconsumer/main.cpp
deleted file mode 100644
index ffbad37d82..0000000000
--- a/tests/auto/corelib/kernel/qsharedmemory/producerconsumer/main.cpp
+++ /dev/null
@@ -1,198 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QSharedMemory>
-#include <QStringList>
-#include <QDebug>
-#include <QTest>
-#include <stdio.h>
-
-void set(QSharedMemory &sm, int pos, QChar value)
-{
- ((char*)sm.data())[pos] = value.toLatin1();
-}
-
-QChar get(QSharedMemory &sm, int i)
-{
- return QChar::fromLatin1(((char*)sm.data())[i]);
-}
-
-int readonly_segfault()
-{
- QSharedMemory sharedMemory;
- sharedMemory.setKey("readonly_segfault");
- sharedMemory.create(1024, QSharedMemory::ReadOnly);
- sharedMemory.lock();
- set(sharedMemory, 0, 'a');
- sharedMemory.unlock();
- return EXIT_SUCCESS;
-}
-
-int producer()
-{
- QSharedMemory producer;
- producer.setKey("market");
-
- int size = 1024;
- if (!producer.create(size)) {
- if (producer.error() == QSharedMemory::AlreadyExists) {
- if (!producer.attach()) {
- qWarning() << "Could not attach to" << producer.key();
- return EXIT_FAILURE;
- }
- } else {
- qWarning() << "Could not create" << producer.key();
- return EXIT_FAILURE;
- }
- }
- // tell parent we're ready
- //qDebug("producer created and attached");
- puts("");
- fflush(stdout);
-
- if (!producer.lock()) {
- qWarning() << "Could not lock" << producer.key();
- return EXIT_FAILURE;
- }
- set(producer, 0, 'Q');
- if (!producer.unlock()) {
- qWarning() << "Could not lock" << producer.key();
- return EXIT_FAILURE;
- }
-
- int i = 0;
- while (i < 5) {
- if (!producer.lock()) {
- qWarning() << "Could not lock" << producer.key();
- return EXIT_FAILURE;
- }
- if (get(producer, 0) == 'Q') {
- if (!producer.unlock()) {
- qWarning() << "Could not unlock" << producer.key();
- return EXIT_FAILURE;
- }
- QTest::qSleep(1);
- continue;
- }
- //qDebug() << "producer:" << i);
- ++i;
- set(producer, 0, 'Q');
- if (!producer.unlock()) {
- qWarning() << "Could not unlock" << producer.key();
- return EXIT_FAILURE;
- }
- QTest::qSleep(1);
- }
- if (!producer.lock()) {
- qWarning() << "Could not lock" << producer.key();
- return EXIT_FAILURE;
- }
- set(producer, 0, 'E');
- if (!producer.unlock()) {
- qWarning() << "Could not unlock" << producer.key();
- return EXIT_FAILURE;
- }
-
- //qDebug("producer done");
-
- // Sleep for a bit to let all consumers exit
- getchar();
- return EXIT_SUCCESS;
-}
-
-int consumer()
-{
- QSharedMemory consumer;
- consumer.setKey("market");
-
- //qDebug("consumer starting");
- int tries = 0;
- while (!consumer.attach()) {
- if (tries == 5000) {
- qWarning() << "consumer exiting, waiting too long";
- return EXIT_FAILURE;
- }
- ++tries;
- QTest::qSleep(1);
- }
- //qDebug("consumer attached");
-
-
- int i = 0;
- while (true) {
- if (!consumer.lock()) {
- qWarning() << "Could not lock" << consumer.key();
- return EXIT_FAILURE;
- }
- if (get(consumer, 0) == 'Q') {
- set(consumer, 0, ++i);
- //qDebug() << "consumer sets" << i;
- }
- if (get(consumer, 0) == 'E') {
- if (!consumer.unlock()) {
- qWarning() << "Could not unlock" << consumer.key();
- return EXIT_FAILURE;
- }
- break;
- }
- if (!consumer.unlock()) {
- qWarning() << "Could not unlock" << consumer.key();
- return EXIT_FAILURE;
- }
- QTest::qSleep(10);
- }
-
- //qDebug("consumer detaching");
- if (!consumer.detach()) {
- qWarning() << "Could not detach" << consumer.key();
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
-}
-
-int main(int argc, char *argv[])
-{
- QCoreApplication app(argc, argv);
-
- QStringList arguments = app.arguments();
- if (app.arguments().count() != 2) {
- qWarning("Please call the helper with the function to call as argument");
- return EXIT_FAILURE;
- }
- QString function = arguments.at(1);
- if (function == QLatin1String("readonly_segfault"))
- return readonly_segfault();
- else if (function == QLatin1String("producer"))
- return producer();
- else if (function == QLatin1String("consumer"))
- return consumer();
- else
- qWarning() << "Unknown function" << arguments.at(1);
-
- return EXIT_SUCCESS;
-}
diff --git a/tests/auto/corelib/kernel/qsharedmemory/producerconsumer/producerconsumer.pro b/tests/auto/corelib/kernel/qsharedmemory/producerconsumer/producerconsumer.pro
deleted file mode 100644
index a6156ed5b6..0000000000
--- a/tests/auto/corelib/kernel/qsharedmemory/producerconsumer/producerconsumer.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-QT = core testlib
-
-SOURCES += main.cpp
-
-load(qt_test_helper)
diff --git a/tests/auto/corelib/kernel/qsharedmemory/qsharedmemory.pro b/tests/auto/corelib/kernel/qsharedmemory/qsharedmemory.pro
deleted file mode 100644
index 91ac28fe0d..0000000000
--- a/tests/auto/corelib/kernel/qsharedmemory/qsharedmemory.pro
+++ /dev/null
@@ -1,6 +0,0 @@
-TEMPLATE = subdirs
-
-qtConfig(sharedmemory) {
- SUBDIRS = producerconsumer \
- test.pro
-}
diff --git a/tests/auto/corelib/kernel/qsharedmemory/test.pro b/tests/auto/corelib/kernel/qsharedmemory/test.pro
deleted file mode 100644
index 8b3badadb0..0000000000
--- a/tests/auto/corelib/kernel/qsharedmemory/test.pro
+++ /dev/null
@@ -1,8 +0,0 @@
-CONFIG += testcase
-
-QT = core-private testlib
-
-TARGET = tst_qsharedmemory
-SOURCES += tst_qsharedmemory.cpp
-
-linux: LIBS += -lrt
diff --git a/tests/auto/corelib/kernel/qsharedmemory/tst_qsharedmemory.cpp b/tests/auto/corelib/kernel/qsharedmemory/tst_qsharedmemory.cpp
deleted file mode 100644
index 31b9c9740a..0000000000
--- a/tests/auto/corelib/kernel/qsharedmemory/tst_qsharedmemory.cpp
+++ /dev/null
@@ -1,822 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QDebug>
-#include <QFile>
-#if QT_CONFIG(process)
-# include <QProcess>
-#endif
-#include <QSharedMemory>
-#include <QTest>
-#include <QThread>
-#include <QElapsedTimer>
-
-#define EXISTING_SHARE "existing"
-#define EXISTING_SIZE 1024
-
-Q_DECLARE_METATYPE(QSharedMemory::SharedMemoryError)
-Q_DECLARE_METATYPE(QSharedMemory::AccessMode)
-
-class tst_QSharedMemory : public QObject
-{
- Q_OBJECT
-
-public:
- tst_QSharedMemory();
- virtual ~tst_QSharedMemory();
-
-public Q_SLOTS:
- void init();
- void cleanup();
-
-
-private slots:
- // basics
- void constructor();
- void key_data();
- void key();
- void create_data();
- void create();
- void attach_data();
- void attach();
- void lock();
-
- // custom edge cases
-#ifndef Q_OS_HPUX
- void removeWhileAttached();
-#endif
- void emptyMemory();
-#if !defined(Q_OS_WIN)
- void readOnly();
-#endif
-
- // basics all together
-#ifndef Q_OS_HPUX
- void simpleProducerConsumer_data();
- void simpleProducerConsumer();
- void simpleDoubleProducerConsumer();
-#endif
-
- // with threads
- void simpleThreadedProducerConsumer_data();
- void simpleThreadedProducerConsumer();
-
- // with processes
- void simpleProcessProducerConsumer_data();
- void simpleProcessProducerConsumer();
-
- // extreme cases
- void useTooMuchMemory();
-#if !defined(Q_OS_HPUX)
- void attachTooMuch();
-#endif
-
- // unique keys
- void uniqueKey_data();
- void uniqueKey();
-
-protected:
- int remove(const QString &key);
-
- QString rememberKey(const QString &key)
- {
- if (key == EXISTING_SHARE)
- return key;
- if (!keys.contains(key)) {
- keys.append(key);
- remove(key);
- }
- return key;
- }
-
- QStringList keys;
- QList<QSharedMemory*> jail;
- QSharedMemory *existingSharedMemory;
-
-private:
- const QString m_helperBinary;
-};
-
-tst_QSharedMemory::tst_QSharedMemory()
- : existingSharedMemory(0)
- , m_helperBinary("producerconsumer_helper")
-{
-}
-
-tst_QSharedMemory::~tst_QSharedMemory()
-{
-}
-
-void tst_QSharedMemory::init()
-{
- existingSharedMemory = new QSharedMemory(EXISTING_SHARE);
- if (!existingSharedMemory->create(EXISTING_SIZE)) {
- QCOMPARE(existingSharedMemory->error(), QSharedMemory::AlreadyExists);
- }
-}
-
-void tst_QSharedMemory::cleanup()
-{
- delete existingSharedMemory;
- qDeleteAll(jail.begin(), jail.end());
- jail.clear();
-
- keys.append(EXISTING_SHARE);
- for (int i = 0; i < keys.count(); ++i) {
- QSharedMemory sm(keys.at(i));
- if (!sm.create(1024)) {
- //if (sm.error() != QSharedMemory::KeyError)
- // qWarning() << "test cleanup: remove failed:" << keys.at(i) << sm.error() << sm.errorString();
- sm.attach();
- sm.detach();
- remove(keys.at(i));
- }
- }
-}
-
-#ifndef Q_OS_WIN
-#include <private/qsharedmemory_p.h>
-#include <sys/types.h>
-#ifndef QT_POSIX_IPC
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#else
-#include <sys/mman.h>
-#endif // QT_POSIX_IPC
-#include <errno.h>
-#endif
-
-int tst_QSharedMemory::remove(const QString &key)
-{
-#ifdef Q_OS_WIN
- Q_UNUSED(key);
- return 0;
-#else
- // On unix the shared memory might exists from a previously failed test
- // or segfault, remove it it does
- if (key.isEmpty())
- return -1;
-
- // ftok requires that an actual file exists somewhere
- QString fileName = QSharedMemoryPrivate::makePlatformSafeKey(key);
- if (!QFile::exists(fileName)) {
- //qDebug() << "exits failed";
- return -2;
- }
-
-#ifndef QT_POSIX_IPC
- int unix_key = ftok(fileName.toLatin1().constData(), 'Q');
- if (-1 == unix_key) {
- qDebug() << "ftok failed";
- return -3;
- }
-
- int id = shmget(unix_key, 0, 0600);
- if (-1 == id) {
- qDebug() << "shmget failed" << strerror(errno);
- return -4;
- }
-
- struct shmid_ds shmid_ds;
- if (-1 == shmctl(id, IPC_RMID, &shmid_ds)) {
- qDebug() << "shmctl failed";
- return -5;
- }
-#else
- if (shm_unlink(QFile::encodeName(fileName).constData()) == -1) {
- qDebug() << "shm_unlink failed";
- return -5;
- }
-#endif // QT_POSIX_IPC
-
- return QFile::remove(fileName);
-#endif // Q_OS_WIN
-}
-
-/*!
- Tests the default values
- */
-void tst_QSharedMemory::constructor()
-{
- QSharedMemory sm;
- QCOMPARE(sm.key(), QString());
- QVERIFY(!sm.isAttached());
- QVERIFY(!sm.data());
- QCOMPARE(sm.size(), 0);
- QCOMPARE(sm.error(), QSharedMemory::NoError);
- QCOMPARE(sm.errorString(), QString());
-}
-
-void tst_QSharedMemory::key_data()
-{
- QTest::addColumn<QString>("constructorKey");
- QTest::addColumn<QString>("setKey");
- QTest::addColumn<QString>("setNativeKey");
-
- QTest::newRow("null, null, null") << QString() << QString() << QString();
- QTest::newRow("one, null, null") << QString("one") << QString() << QString();
- QTest::newRow("null, one, null") << QString() << QString("one") << QString();
- QTest::newRow("null, null, one") << QString() << QString() << QString("one");
- QTest::newRow("one, two, null") << QString("one") << QString("two") << QString();
- QTest::newRow("one, null, two") << QString("one") << QString() << QString("two");
- QTest::newRow("null, one, two") << QString() << QString("one") << QString("two");
- QTest::newRow("one, two, three") << QString("one") << QString("two") << QString("three");
- QTest::newRow("invalid") << QString("o/e") << QString("t/o") << QString("|x");
-}
-
-/*!
- Basic key testing
- */
-void tst_QSharedMemory::key()
-{
- QFETCH(QString, constructorKey);
- QFETCH(QString, setKey);
- QFETCH(QString, setNativeKey);
-
- QSharedMemory sm(constructorKey);
- QCOMPARE(sm.key(), constructorKey);
- QCOMPARE(sm.nativeKey().isEmpty(), constructorKey.isEmpty());
- sm.setKey(setKey);
- QCOMPARE(sm.key(), setKey);
- QCOMPARE(sm.nativeKey().isEmpty(), setKey.isEmpty());
- sm.setNativeKey(setNativeKey);
- QVERIFY(sm.key().isNull());
- QCOMPARE(sm.nativeKey(), setNativeKey);
- QCOMPARE(sm.isAttached(), false);
-
- QCOMPARE(sm.error(), QSharedMemory::NoError);
- QCOMPARE(sm.errorString(), QString());
- QVERIFY(!sm.data());
- QCOMPARE(sm.size(), 0);
-
- QCOMPARE(sm.detach(), false);
-}
-
-void tst_QSharedMemory::create_data()
-{
- QTest::addColumn<QString>("key");
- QTest::addColumn<int>("size");
- QTest::addColumn<bool>("canCreate");
- QTest::addColumn<QSharedMemory::SharedMemoryError>("error");
-
- QTest::newRow("null key") << QString() << 1024
- << false << QSharedMemory::KeyError;
- QTest::newRow("-1 size") << QString("negsize") << -1
- << false << QSharedMemory::InvalidSize;
- QTest::newRow("nor size") << QString("norsize") << 1024
- << true << QSharedMemory::NoError;
- QTest::newRow("already exists") << QString(EXISTING_SHARE) << EXISTING_SIZE
- << false << QSharedMemory::AlreadyExists;
-}
-
-/*!
- Basic create testing
- */
-void tst_QSharedMemory::create()
-{
- QFETCH(QString, key);
- QFETCH(int, size);
- QFETCH(bool, canCreate);
- QFETCH(QSharedMemory::SharedMemoryError, error);
-
- QSharedMemory sm(rememberKey(key));
- QCOMPARE(sm.create(size), canCreate);
- if (sm.error() != error)
- qDebug() << sm.errorString();
- QCOMPARE(sm.key(), key);
- if (canCreate) {
- QCOMPARE(sm.errorString(), QString());
- QVERIFY(sm.data() != 0);
- QVERIFY(sm.size() != 0);
- } else {
- QVERIFY(!sm.data());
- QVERIFY(sm.errorString() != QString());
- }
-}
-
-void tst_QSharedMemory::attach_data()
-{
- QTest::addColumn<QString>("key");
- QTest::addColumn<bool>("exists");
- QTest::addColumn<QSharedMemory::SharedMemoryError>("error");
-
- QTest::newRow("null key") << QString() << false << QSharedMemory::KeyError;
- QTest::newRow("doesn't exists") << QString("doesntexists") << false << QSharedMemory::NotFound;
-
- // HPUX doesn't allow for multiple attaches per process.
-#ifndef Q_OS_HPUX
- QTest::newRow("already exists") << QString(EXISTING_SHARE) << true << QSharedMemory::NoError;
-#endif
-}
-
-/*!
- Basic attach/detach testing
- */
-void tst_QSharedMemory::attach()
-{
- QFETCH(QString, key);
- QFETCH(bool, exists);
- QFETCH(QSharedMemory::SharedMemoryError, error);
-
- QSharedMemory sm(key);
- QCOMPARE(sm.attach(), exists);
- QCOMPARE(sm.isAttached(), exists);
- QCOMPARE(sm.error(), error);
- QCOMPARE(sm.key(), key);
- if (exists) {
- QVERIFY(sm.data() != 0);
- QVERIFY(sm.size() != 0);
- QCOMPARE(sm.errorString(), QString());
- QVERIFY(sm.detach());
- // Make sure detach doesn't screw up something and we can't re-attach.
- QVERIFY(sm.attach());
- QVERIFY(sm.data() != 0);
- QVERIFY(sm.size() != 0);
- QVERIFY(sm.detach());
- QCOMPARE(sm.size(), 0);
- QVERIFY(!sm.data());
- } else {
- QVERIFY(!sm.data());
- QCOMPARE(sm.size(), 0);
- QVERIFY(sm.errorString() != QString());
- QVERIFY(!sm.detach());
- }
-}
-
-void tst_QSharedMemory::lock()
-{
- QSharedMemory shm;
- QVERIFY(!shm.lock());
- QCOMPARE(shm.error(), QSharedMemory::LockError);
-
- shm.setKey(QLatin1String("qsharedmemory"));
-
- QVERIFY(!shm.lock());
- QCOMPARE(shm.error(), QSharedMemory::LockError);
-
- QVERIFY(shm.create(100));
- QVERIFY(shm.lock());
- QTest::ignoreMessage(QtWarningMsg, "QSharedMemory::lock: already locked");
- QVERIFY(shm.lock());
- // we didn't unlock(), so ignore the warning from auto-detach in destructor
- QTest::ignoreMessage(QtWarningMsg, "QSharedMemory::lock: already locked");
-}
-
-/*!
- Other shared memory are allowed to be attached after we remove,
- but new shared memory are not allowed to attach after a remove.
- */
-// HPUX doesn't allow for multiple attaches per process.
-#ifndef Q_OS_HPUX
-void tst_QSharedMemory::removeWhileAttached()
-{
- rememberKey("one");
-
- // attach 1
- QSharedMemory *smOne = new QSharedMemory(QLatin1String("one"));
- QVERIFY(smOne->create(1024));
- QVERIFY(smOne->isAttached());
-
- // attach 2
- QSharedMemory *smTwo = new QSharedMemory(QLatin1String("one"));
- QVERIFY(smTwo->attach());
- QVERIFY(smTwo->isAttached());
-
- // detach 1 and remove, remove one first to catch another error.
- delete smOne;
- delete smTwo;
-
- // three shouldn't be able to attach
- QSharedMemory smThree(QLatin1String("one"));
- QVERIFY(!smThree.attach());
- QCOMPARE(smThree.error(), QSharedMemory::NotFound);
-}
-#endif
-
-/*!
- The memory should be set to 0 after created.
- */
-void tst_QSharedMemory::emptyMemory()
-{
- QSharedMemory sm(rememberKey(QLatin1String("voidland")));
- int size = 1024;
- QVERIFY(sm.create(size, QSharedMemory::ReadOnly));
- char *get = (char*)sm.data();
- char null = 0;
- for (int i = 0; i < size; ++i)
- QCOMPARE(get[i], null);
-}
-
-/*!
- Verify that attach with ReadOnly is actually read only
- by writing to data and causing a segfault.
-*/
-// This test opens a crash dialog on Windows.
-#if !defined(Q_OS_WIN)
-void tst_QSharedMemory::readOnly()
-{
-#if !QT_CONFIG(process)
- QSKIP("No qprocess support", SkipAll);
-#elif defined(Q_OS_MACOS)
- QSKIP("QTBUG-59936: Times out on macOS", SkipAll);
-#else
- rememberKey("readonly_segfault");
- // ### on windows disable the popup somehow
- QProcess p;
- p.start(m_helperBinary, QStringList("readonly_segfault"));
- p.setProcessChannelMode(QProcess::ForwardedChannels);
- p.waitForFinished();
- QCOMPARE(p.error(), QProcess::Crashed);
-#endif
-}
-#endif
-
-/*!
- Keep making shared memory until the kernel stops us.
- */
-void tst_QSharedMemory::useTooMuchMemory()
-{
-#ifdef Q_OS_LINUX
- bool success = true;
- int count = 0;
- while (success) {
- QString key = QLatin1String("maxmemorytest_") + QString::number(count++);
- QSharedMemory *sm = new QSharedMemory(rememberKey(key));
- QVERIFY(sm);
- jail.append(sm);
- int size = 32768 * 1024;
- success = sm->create(size);
- if (!success && sm->error() == QSharedMemory::AlreadyExists) {
- // left over from a crash, clean it up
- sm->attach();
- sm->detach();
- success = sm->create(size);
- }
-
- if (!success) {
- QVERIFY(!sm->isAttached());
- QCOMPARE(sm->key(), key);
- QCOMPARE(sm->size(), 0);
- QVERIFY(!sm->data());
- if (sm->error() != QSharedMemory::OutOfResources)
- qDebug() << sm->error() << sm->errorString();
- // ### Linux won't return OutOfResources if there are not enough semaphores to use.
- QVERIFY(sm->error() == QSharedMemory::OutOfResources
- || sm->error() == QSharedMemory::LockError);
- QVERIFY(sm->errorString() != QString());
- QVERIFY(!sm->attach());
- QVERIFY(!sm->detach());
- } else {
- QVERIFY(sm->isAttached());
- }
- }
-#endif
-}
-
-/*!
- Create one shared memory (government) and see how many other shared memories (wars) we can
- attach before the system runs out of resources.
- */
-// HPUX doesn't allow for multiple attaches per process.
-#if !defined(Q_OS_HPUX)
-void tst_QSharedMemory::attachTooMuch()
-{
- QSKIP("disabled");
-
- QSharedMemory government(rememberKey("government"));
- QVERIFY(government.create(1024));
- while (true) {
- QSharedMemory *war = new QSharedMemory(government.key());
- QVERIFY(war);
- jail.append(war);
- if (!war->attach()) {
- QVERIFY(!war->isAttached());
- QCOMPARE(war->key(), government.key());
- QCOMPARE(war->size(), 0);
- QVERIFY(!war->data());
- QCOMPARE(war->error(), QSharedMemory::OutOfResources);
- QVERIFY(war->errorString() != QString());
- QVERIFY(!war->detach());
- break;
- } else {
- QVERIFY(war->isAttached());
- }
- }
-}
-#endif
-
-// HPUX doesn't allow for multiple attaches per process.
-#ifndef Q_OS_HPUX
-void tst_QSharedMemory::simpleProducerConsumer_data()
-{
- QTest::addColumn<QSharedMemory::AccessMode>("mode");
-
- QTest::newRow("readonly") << QSharedMemory::ReadOnly;
- QTest::newRow("readwrite") << QSharedMemory::ReadWrite;
-}
-
-/*!
- The basic consumer producer that rounds out the basic testing.
- If this fails then any muli-threading/process might fail (but be
- harder to debug)
-
- This doesn't require nor test any locking system.
- */
-void tst_QSharedMemory::simpleProducerConsumer()
-{
- QFETCH(QSharedMemory::AccessMode, mode);
-
- rememberKey(QLatin1String("market"));
- QSharedMemory producer(QLatin1String("market"));
- QSharedMemory consumer(QLatin1String("market"));
- int size = 512;
- QVERIFY(producer.create(size));
- QVERIFY(consumer.attach(mode));
-
- char *put = (char*)producer.data();
- char *get = (char*)consumer.data();
- // On Windows CE you always have ReadWrite access. Thus
- // ViewMapOfFile returns the same pointer
- QVERIFY(put != get);
- for (int i = 0; i < size; ++i) {
- put[i] = 'Q';
- QCOMPARE(get[i], 'Q');
- }
- QVERIFY(consumer.detach());
-}
-#endif
-
-// HPUX doesn't allow for multiple attaches per process.
-#ifndef Q_OS_HPUX
-void tst_QSharedMemory::simpleDoubleProducerConsumer()
-{
- rememberKey(QLatin1String("market"));
- QSharedMemory producer(QLatin1String("market"));
- int size = 512;
- QVERIFY(producer.create(size));
- QVERIFY(producer.detach());
- QVERIFY(producer.create(size));
-
- {
- QSharedMemory consumer(QLatin1String("market"));
- QVERIFY(consumer.attach());
- }
-}
-#endif
-
-class Consumer : public QThread
-{
-
-public:
- void run() override
- {
- QSharedMemory consumer(QLatin1String("market"));
- while (!consumer.attach()) {
- if (consumer.error() != QSharedMemory::NotFound)
- qDebug() << "consumer: failed to connect" << consumer.error() << consumer.errorString();
- QVERIFY(consumer.error() == QSharedMemory::NotFound || consumer.error() == QSharedMemory::KeyError);
- QTest::qWait(1);
- }
-
- char *memory = (char*)consumer.data();
-
- int i = 0;
- while (true) {
- if (!consumer.lock())
- break;
- if (memory[0] == 'Q')
- memory[0] = ++i;
- if (memory[0] == 'E') {
- memory[1]++;
- QVERIFY(consumer.unlock());
- break;
- }
- QVERIFY(consumer.unlock());
- QTest::qWait(1);
- }
-
- QVERIFY(consumer.detach());
- }
-};
-
-class Producer : public QThread
-{
-
-public:
- Producer() : producer(QLatin1String("market"))
- {
- int size = 1024;
- if (!producer.create(size)) {
- // left over from a crash...
- if (producer.error() == QSharedMemory::AlreadyExists) {
- producer.attach();
- producer.detach();
- QVERIFY(producer.create(size));
- }
- }
- }
-
- void run() override
- {
-
- char *memory = (char*)producer.data();
- memory[1] = '0';
- QElapsedTimer timer;
- timer.start();
- int i = 0;
- while (i < 5 && timer.elapsed() < 5000) {
- QVERIFY(producer.lock());
- if (memory[0] == 'Q') {
- QVERIFY(producer.unlock());
- QTest::qWait(1);
- continue;
- }
- ++i;
- memory[0] = 'Q';
- QVERIFY(producer.unlock());
- QTest::qWait(1);
- }
-
- // tell everyone to quit
- QVERIFY(producer.lock());
- memory[0] = 'E';
- QVERIFY(producer.unlock());
-
- }
-
- QSharedMemory producer;
-private:
-
-};
-
-void tst_QSharedMemory::simpleThreadedProducerConsumer_data()
-{
- QTest::addColumn<bool>("producerIsThread");
- QTest::addColumn<int>("threads");
- for (int i = 0; i < 5; ++i) {
- QTest::newRow("1 consumer, producer is thread") << true << 1;
- QTest::newRow("1 consumer, producer is this") << false << 1;
- QTest::newRow("5 consumers, producer is thread") << true << 5;
- QTest::newRow("5 consumers, producer is this") << false << 5;
- }
-}
-
-/*!
- The basic producer/consumer, but this time using threads.
- */
-void tst_QSharedMemory::simpleThreadedProducerConsumer()
-{
- QFETCH(bool, producerIsThread);
- QFETCH(int, threads);
- rememberKey(QLatin1String("market"));
-
-#if defined Q_OS_HPUX && defined __ia64
- QSKIP("This test locks up on gravlaks.troll.no");
-#endif
-
- Producer p;
- QVERIFY(p.producer.isAttached());
- if (producerIsThread)
- p.start();
-
- QList<Consumer*> consumers;
- for (int i = 0; i < threads; ++i) {
- consumers.append(new Consumer());
- consumers.last()->start();
- }
-
- if (!producerIsThread)
- p.run();
-
- p.wait(5000);
- while (!consumers.isEmpty()) {
- Consumer *c = consumers.first();
- QVERIFY(c->isFinished() || c->wait(5000));
- delete consumers.takeFirst();
- }
-}
-
-void tst_QSharedMemory::simpleProcessProducerConsumer_data()
-{
-#if QT_CONFIG(process)
- QTest::addColumn<int>("processes");
- int tries = 5;
- for (int i = 0; i < tries; ++i) {
- QTest::newRow("1 process") << 1;
- QTest::newRow("5 processes") << 5;
- }
-#endif
-}
-
-/*!
- Create external processes that produce and consume.
- */
-void tst_QSharedMemory::simpleProcessProducerConsumer()
-{
-#if !QT_CONFIG(process)
- QSKIP("No qprocess support", SkipAll);
-#else
- QFETCH(int, processes);
-
- QSKIP("This test is unstable: QTBUG-25655");
-
- rememberKey("market");
-
- QProcess producer;
- producer.start(m_helperBinary, QStringList("producer"));
- QVERIFY2(producer.waitForStarted(), "Could not start helper binary");
- QVERIFY2(producer.waitForReadyRead(), "Helper process failed to create shared memory segment: " +
- producer.readAllStandardError());
-
- QList<QProcess*> consumers;
- unsigned int failedProcesses = 0;
- const QStringList consumerArguments = QStringList("consumer");
- for (int i = 0; i < processes; ++i) {
- QProcess *p = new QProcess;
- p->setProcessChannelMode(QProcess::ForwardedChannels);
- p->start(m_helperBinary, consumerArguments);
- if (p->waitForStarted(2000))
- consumers.append(p);
- else
- ++failedProcesses;
- }
-
- bool consumerFailed = false;
-
- while (!consumers.isEmpty()) {
- QVERIFY(consumers.first()->waitForFinished(3000));
- if (consumers.first()->state() == QProcess::Running ||
- consumers.first()->exitStatus() != QProcess::NormalExit ||
- consumers.first()->exitCode() != 0) {
- consumerFailed = true;
- }
- delete consumers.takeFirst();
- }
- QCOMPARE(consumerFailed, false);
- QCOMPARE(failedProcesses, (unsigned int)(0));
-
- // tell the producer to exit now
- producer.write("", 1);
- producer.waitForBytesWritten();
- QVERIFY(producer.waitForFinished(5000));
-#endif
-}
-
-void tst_QSharedMemory::uniqueKey_data()
-{
- QTest::addColumn<QString>("key1");
- QTest::addColumn<QString>("key2");
-
- QTest::newRow("null == null") << QString() << QString();
- QTest::newRow("key == key") << QString("key") << QString("key");
- QTest::newRow("key1 == key1") << QString("key1") << QString("key1");
- QTest::newRow("key != key1") << QString("key") << QString("key1");
- QTest::newRow("ke1y != key1") << QString("ke1y") << QString("key1");
- QTest::newRow("key1 != key2") << QString("key1") << QString("key2");
- QTest::newRow("Noël -> Nol") << QString::fromUtf8("N\xc3\xabl") << QString("Nol");
-}
-
-void tst_QSharedMemory::uniqueKey()
-{
- QFETCH(QString, key1);
- QFETCH(QString, key2);
-
- QSharedMemory sm1(key1);
- QSharedMemory sm2(key2);
-
- bool setEqual = (key1 == key2);
- bool keyEqual = (sm1.key() == sm2.key());
- bool nativeEqual = (sm1.nativeKey() == sm2.nativeKey());
-
- QCOMPARE(keyEqual, setEqual);
- QCOMPARE(nativeEqual, setEqual);
-}
-
-QTEST_MAIN(tst_QSharedMemory)
-#include "tst_qsharedmemory.moc"
-
diff --git a/tests/auto/corelib/kernel/qsignalblocker/CMakeLists.txt b/tests/auto/corelib/kernel/qsignalblocker/CMakeLists.txt
index a7a6306bfc..0effacb018 100644
--- a/tests/auto/corelib/kernel/qsignalblocker/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qsignalblocker/CMakeLists.txt
@@ -1,10 +1,17 @@
-# Generated from qsignalblocker.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qsignalblocker Test:
#####################################################################
-qt_add_test(tst_qsignalblocker
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsignalblocker LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qsignalblocker
SOURCES
tst_qsignalblocker.cpp
)
diff --git a/tests/auto/corelib/kernel/qsignalblocker/qsignalblocker.pro b/tests/auto/corelib/kernel/qsignalblocker/qsignalblocker.pro
deleted file mode 100644
index 6e4913db5d..0000000000
--- a/tests/auto/corelib/kernel/qsignalblocker/qsignalblocker.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-CONFIG += testcase console
-TARGET = tst_qsignalblocker
-QT = core testlib
-SOURCES = tst_qsignalblocker.cpp
-
diff --git a/tests/auto/corelib/kernel/qsignalblocker/tst_qsignalblocker.cpp b/tests/auto/corelib/kernel/qsignalblocker/tst_qsignalblocker.cpp
index 39b03ade61..bd1f149a3f 100644
--- a/tests/auto/corelib/kernel/qsignalblocker/tst_qsignalblocker.cpp
+++ b/tests/auto/corelib/kernel/qsignalblocker/tst_qsignalblocker.cpp
@@ -1,32 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@woboq.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@woboq.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
#include "qobject.h"
@@ -36,6 +11,7 @@ class tst_QSignalBlocker : public QObject
private slots:
void signalBlocking();
void moveAssignment();
+ void dismiss();
};
void tst_QSignalBlocker::signalBlocking()
@@ -158,5 +134,15 @@ void tst_QSignalBlocker::moveAssignment()
QVERIFY(!o2.signalsBlocked());
}
+void tst_QSignalBlocker::dismiss()
+{
+ QObject obj;
+ {
+ QSignalBlocker blocker(obj);
+ blocker.dismiss();
+ }
+ QVERIFY(obj.signalsBlocked());
+}
+
QTEST_MAIN(tst_QSignalBlocker)
#include "tst_qsignalblocker.moc"
diff --git a/tests/auto/corelib/kernel/qsignalmapper/CMakeLists.txt b/tests/auto/corelib/kernel/qsignalmapper/CMakeLists.txt
index 9ce292c242..b5de408ea8 100644
--- a/tests/auto/corelib/kernel/qsignalmapper/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qsignalmapper/CMakeLists.txt
@@ -1,10 +1,17 @@
-# Generated from qsignalmapper.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qsignalmapper Test:
#####################################################################
-qt_add_test(tst_qsignalmapper
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsignalmapper LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qsignalmapper
SOURCES
tst_qsignalmapper.cpp
)
diff --git a/tests/auto/corelib/kernel/qsignalmapper/qsignalmapper.pro b/tests/auto/corelib/kernel/qsignalmapper/qsignalmapper.pro
deleted file mode 100644
index 418d6dce62..0000000000
--- a/tests/auto/corelib/kernel/qsignalmapper/qsignalmapper.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qsignalmapper
-QT = core testlib
-SOURCES = tst_qsignalmapper.cpp
diff --git a/tests/auto/corelib/kernel/qsignalmapper/tst_qsignalmapper.cpp b/tests/auto/corelib/kernel/qsignalmapper/tst_qsignalmapper.cpp
index 78b0b5dc55..de54cd5adc 100644
--- a/tests/auto/corelib/kernel/qsignalmapper/tst_qsignalmapper.cpp
+++ b/tests/auto/corelib/kernel/qsignalmapper/tst_qsignalmapper.cpp
@@ -1,32 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
#include <qsignalmapper.h>
diff --git a/tests/auto/corelib/kernel/qsocketnotifier/BLACKLIST b/tests/auto/corelib/kernel/qsocketnotifier/BLACKLIST
deleted file mode 100644
index f2e5e78592..0000000000
--- a/tests/auto/corelib/kernel/qsocketnotifier/BLACKLIST
+++ /dev/null
@@ -1,3 +0,0 @@
-[unexpectedDisconnection]
-windows-7sp1
-windows-10 msvc-2015
diff --git a/tests/auto/corelib/kernel/qsocketnotifier/CMakeLists.txt b/tests/auto/corelib/kernel/qsocketnotifier/CMakeLists.txt
index 2367a8a54e..2a802b5f4d 100644
--- a/tests/auto/corelib/kernel/qsocketnotifier/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qsocketnotifier/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qsocketnotifier.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsocketnotifier LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -8,24 +15,19 @@ endif()
## tst_qsocketnotifier Test:
#####################################################################
-qt_add_test(tst_qsocketnotifier
+qt_internal_add_test(tst_qsocketnotifier
SOURCES
tst_qsocketnotifier.cpp
- INCLUDE_DIRECTORIES
- ${QT_SOURCE_TREE}/src/network
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::Network
Qt::NetworkPrivate
)
-#### Keys ignored in scope 1:.:.:qsocketnotifier.pro:<TRUE>:
-# _REQUIREMENTS = "qtConfig(private_tests)"
-
## Scopes:
#####################################################################
-qt_extend_target(tst_qsocketnotifier CONDITION WIN32
- PUBLIC_LIBRARIES
+qt_internal_extend_target(tst_qsocketnotifier CONDITION WIN32
+ LIBRARIES
ws2_32
)
diff --git a/tests/auto/corelib/kernel/qsocketnotifier/qsocketnotifier.pro b/tests/auto/corelib/kernel/qsocketnotifier/qsocketnotifier.pro
deleted file mode 100644
index 04806de5f7..0000000000
--- a/tests/auto/corelib/kernel/qsocketnotifier/qsocketnotifier.pro
+++ /dev/null
@@ -1,8 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qsocketnotifier
-QT = core-private network-private testlib
-SOURCES = tst_qsocketnotifier.cpp
-
-requires(qtConfig(private_tests))
-
-include(../../../network/socket/platformsocketengine/platformsocketengine.pri)
diff --git a/tests/auto/corelib/kernel/qsocketnotifier/tst_qsocketnotifier.cpp b/tests/auto/corelib/kernel/qsocketnotifier/tst_qsocketnotifier.cpp
index 9ab540cdf2..17bba73dab 100644
--- a/tests/auto/corelib/kernel/qsocketnotifier/tst_qsocketnotifier.cpp
+++ b/tests/auto/corelib/kernel/qsocketnotifier/tst_qsocketnotifier.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtTest/QTest>
#include <QtTest/QSignalSpy>
@@ -49,11 +24,13 @@
# undef min
#endif // Q_CC_MSVC
+using namespace std::chrono_literals;
class tst_QSocketNotifier : public QObject
{
Q_OBJECT
private slots:
+ void constructing();
void unexpectedDisconnection();
void mixingWithTimers();
#ifdef Q_OS_UNIX
@@ -85,6 +62,51 @@ static QHostAddress makeNonAny(const QHostAddress &address,
return address;
}
+void tst_QSocketNotifier::constructing()
+{
+ const qintptr fd = 15;
+
+ // Test constructing with no descriptor assigned.
+ {
+ QSocketNotifier notifier(QSocketNotifier::Read);
+
+ QVERIFY(!notifier.isValid());
+ QCOMPARE(notifier.socket(), Q_INT64_C(-1));
+ QCOMPARE(notifier.type(), QSocketNotifier::Read);
+ QVERIFY(!notifier.isEnabled());
+
+ notifier.setEnabled(true);
+ QVERIFY(!notifier.isEnabled());
+
+ notifier.setSocket(fd);
+ QVERIFY(notifier.isValid());
+ QCOMPARE(notifier.socket(), fd);
+ QVERIFY(!notifier.isEnabled());
+ notifier.setEnabled(true);
+ QVERIFY(notifier.isEnabled());
+ }
+
+ // Test constructing with the notifications enabled by default.
+ {
+ QSocketNotifier notifier(fd, QSocketNotifier::Write);
+
+ QVERIFY(notifier.isValid());
+ QCOMPARE(notifier.socket(), fd);
+ QCOMPARE(notifier.type(), QSocketNotifier::Write);
+ QVERIFY(notifier.isEnabled());
+
+ notifier.setSocket(fd);
+ QVERIFY(!notifier.isEnabled());
+
+ notifier.setEnabled(true);
+ QVERIFY(notifier.isEnabled());
+ notifier.setSocket(-1);
+ QVERIFY(!notifier.isValid());
+ QCOMPARE(notifier.socket(), Q_INT64_C(-1));
+ QVERIFY(!notifier.isEnabled());
+ }
+}
+
class UnexpectedDisconnectTester : public QObject
{
Q_OBJECT
@@ -110,11 +132,11 @@ public slots:
++sequence;
if (sequence == 1) {
// read from both ends
- (void) readEnd1->read(data1, sizeof(data1));
- (void) readEnd2->read(data2, sizeof(data2));
+ QCOMPARE(readEnd1->read(data1, sizeof(data1)), 1);
+ QCOMPARE(readEnd2->read(data2, sizeof(data2)), 1);
emit finished();
} else if (sequence == 2) {
- // we should never get here
+ // check that we can't read now because we've read our byte
QCOMPARE(readEnd2->read(data2, sizeof(data2)), qint64(-2));
QVERIFY(readEnd2->isValid());
}
@@ -130,7 +152,7 @@ void tst_QSocketNotifier::unexpectedDisconnection()
Given two sockets and two QSocketNotifiers registered on each
their socket. If both sockets receive data, and the first slot
invoked by one of the socket notifiers empties both sockets, the
- other notifier will also emit activated(). This results in
+ other notifier will also emit activated(). This was causing an
unexpected disconnection in QAbstractSocket.
The use case is that somebody calls one of the
@@ -147,7 +169,7 @@ void tst_QSocketNotifier::unexpectedDisconnection()
readEnd1.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd1.waitForWrite());
QCOMPARE(readEnd1.state(), QAbstractSocket::ConnectedState);
- QVERIFY(server.waitForNewConnection());
+ QVERIFY(server.waitForNewConnection(5000));
QTcpSocket *writeEnd1 = server.nextPendingConnection();
QVERIFY(writeEnd1 != 0);
@@ -156,7 +178,7 @@ void tst_QSocketNotifier::unexpectedDisconnection()
readEnd2.connectToHost(server.serverAddress(), server.serverPort());
QVERIFY(readEnd2.waitForWrite());
QCOMPARE(readEnd2.state(), QAbstractSocket::ConnectedState);
- QVERIFY(server.waitForNewConnection());
+ QVERIFY(server.waitForNewConnection(5000));
QTcpSocket *writeEnd2 = server.nextPendingConnection();
QVERIFY(writeEnd2 != 0);
@@ -166,8 +188,9 @@ void tst_QSocketNotifier::unexpectedDisconnection()
writeEnd1->waitForBytesWritten();
writeEnd2->waitForBytesWritten();
- writeEnd1->flush();
- writeEnd2->flush();
+ // ensure both read ends are ready for reading, before the event loop
+ QVERIFY(readEnd1.waitForRead(5s));
+ QVERIFY(readEnd2.waitForRead(5s));
UnexpectedDisconnectTester tester(&readEnd1, &readEnd2);
@@ -288,8 +311,8 @@ void tst_QSocketNotifier::posixSockets()
passive->waitForBytesWritten(5000);
QTestEventLoop::instance().enterLoop(3);
- QCOMPARE(readSpy.count(), 1);
- QCOMPARE(errorSpy.count(), 0);
+ QCOMPARE(readSpy.size(), 1);
+ QCOMPARE(errorSpy.size(), 0);
char buffer[100];
int r = qt_safe_read(posixSocket, buffer, 100);
@@ -303,9 +326,9 @@ void tst_QSocketNotifier::posixSockets()
qt_safe_write(posixSocket, "goodbye", 8);
QTestEventLoop::instance().enterLoop(3);
- QCOMPARE(readSpy.count(), 1);
- QCOMPARE(writeSpy.count(), 1);
- QCOMPARE(errorSpy.count(), 0);
+ QCOMPARE(readSpy.size(), 1);
+ QCOMPARE(writeSpy.size(), 1);
+ QCOMPARE(errorSpy.size(), 0);
// Write notifier may have fired before the read notifier inside
// QTcpSocket, give QTcpSocket a chance to see the incoming data
@@ -353,7 +376,7 @@ void tst_QSocketNotifier::asyncMultipleDatagram()
&tst_QSocketNotifier::async_readDatagramSlot);
// activate socket notifiers
- QTestEventLoop::instance().enterLoopMSecs(100);
+ QTestEventLoop::instance().enterLoop(100ms);
m_asyncSender->writeDatagram("1", makeNonAny(m_asyncReceiver->localAddress()), port);
m_asyncSender->writeDatagram("2", makeNonAny(m_asyncReceiver->localAddress()), port);
@@ -366,7 +389,7 @@ void tst_QSocketNotifier::asyncMultipleDatagram()
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
- QCOMPARE(spy.count(), 2);
+ QCOMPARE(spy.size(), 2);
delete m_asyncSender;
delete m_asyncReceiver;
diff --git a/tests/auto/corelib/kernel/qsystemsemaphore/CMakeLists.txt b/tests/auto/corelib/kernel/qsystemsemaphore/CMakeLists.txt
deleted file mode 100644
index 0024c522e4..0000000000
--- a/tests/auto/corelib/kernel/qsystemsemaphore/CMakeLists.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-# Generated from qsystemsemaphore.pro.
-
-#####################################################################
-## tst_qsystemsemaphore Test:
-#####################################################################
-
-qt_add_test(tst_qsystemsemaphore
- SOURCES
- tst_qsystemsemaphore.cpp
-)
-
-## Scopes:
-#####################################################################
-add_subdirectory(acquirerelease)
diff --git a/tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/CMakeLists.txt b/tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/CMakeLists.txt
deleted file mode 100644
index 74f7bf3f61..0000000000
--- a/tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/CMakeLists.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-# Generated from acquirerelease.pro.
-
-#####################################################################
-## acquirerelease_helper Binary:
-#####################################################################
-
-qt_add_test_helper(acquirerelease_helper
- SOURCES
- main.cpp
- PUBLIC_LIBRARIES
- Qt::Test
-)
diff --git a/tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/acquirerelease.pro b/tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/acquirerelease.pro
deleted file mode 100644
index a6156ed5b6..0000000000
--- a/tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/acquirerelease.pro
+++ /dev/null
@@ -1,5 +0,0 @@
-QT = core testlib
-
-SOURCES += main.cpp
-
-load(qt_test_helper)
diff --git a/tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/main.cpp b/tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/main.cpp
deleted file mode 100644
index 7bfb6b16cc..0000000000
--- a/tests/auto/corelib/kernel/qsystemsemaphore/acquirerelease/main.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QCoreApplication>
-#include <QDebug>
-#include <QStringList>
-#include <QSystemSemaphore>
-
-int acquire(int count = 1)
-{
- QSystemSemaphore sem("store");
-
- for (int i = 0; i < count; ++i) {
- if (!sem.acquire()) {
- qWarning() << "Could not acquire" << sem.key();
- return EXIT_FAILURE;
- }
- }
- qDebug("done aquiring");
- return EXIT_SUCCESS;
-}
-
-int release()
-{
- QSystemSemaphore sem("store");
- if (!sem.release()) {
- qWarning() << "Could not release" << sem.key();
- return EXIT_FAILURE;
- }
- qDebug("done releasing");
- return EXIT_SUCCESS;
-}
-
-int acquirerelease()
-{
- QSystemSemaphore sem("store");
- if (!sem.acquire()) {
- qWarning() << "Could not acquire" << sem.key();
- return EXIT_FAILURE;
- }
- if (!sem.release()) {
- qWarning() << "Could not release" << sem.key();
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
-}
-
-int main(int argc, char *argv[])
-{
- QCoreApplication app(argc, argv);
-
- QStringList arguments = app.arguments();
- // binary name is not used here
- arguments.takeFirst();
- if (arguments.count() < 1) {
- qWarning("Please call the helper with the function to call as argument");
- return EXIT_FAILURE;
- }
- QString function = arguments.takeFirst();
- if (function == QLatin1String("acquire")) {
- int count = 1;
- bool ok = true;
- if (arguments.count())
- count = arguments.takeFirst().toInt(&ok);
- if (!ok)
- count = 1;
- return acquire(count);
- } else if (function == QLatin1String("release")) {
- return release();
- } else if (function == QLatin1String("acquirerelease")) {
- return acquirerelease();
- } else {
- qWarning() << "Unknown function" << function;
- }
- return EXIT_SUCCESS;
-}
diff --git a/tests/auto/corelib/kernel/qsystemsemaphore/qsystemsemaphore.pro b/tests/auto/corelib/kernel/qsystemsemaphore/qsystemsemaphore.pro
deleted file mode 100644
index 70526426aa..0000000000
--- a/tests/auto/corelib/kernel/qsystemsemaphore/qsystemsemaphore.pro
+++ /dev/null
@@ -1,3 +0,0 @@
-TEMPLATE = subdirs
-
-SUBDIRS = acquirerelease test.pro
diff --git a/tests/auto/corelib/kernel/qsystemsemaphore/test.pro b/tests/auto/corelib/kernel/qsystemsemaphore/test.pro
deleted file mode 100644
index 13bd1fa270..0000000000
--- a/tests/auto/corelib/kernel/qsystemsemaphore/test.pro
+++ /dev/null
@@ -1,7 +0,0 @@
-CONFIG += testcase
-QT = core testlib
-
-SOURCES += tst_qsystemsemaphore.cpp
-TARGET = tst_qsystemsemaphore
-
-win32: CONFIG += console
diff --git a/tests/auto/corelib/kernel/qsystemsemaphore/tst_qsystemsemaphore.cpp b/tests/auto/corelib/kernel/qsystemsemaphore/tst_qsystemsemaphore.cpp
deleted file mode 100644
index 496e214b8f..0000000000
--- a/tests/auto/corelib/kernel/qsystemsemaphore/tst_qsystemsemaphore.cpp
+++ /dev/null
@@ -1,292 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
-#include <QtCore/QList>
-#include <QtCore/QSystemSemaphore>
-#include <QtCore/QTemporaryDir>
-
-#define EXISTING_SHARE "existing"
-#define HELPERWAITTIME 10000
-
-class tst_QSystemSemaphore : public QObject
-{
- Q_OBJECT
-
-public:
- tst_QSystemSemaphore();
-
-public Q_SLOTS:
- void init();
- void cleanup();
-
-private slots:
- void key_data();
- void key();
-
- void basicacquire();
- void complexacquire();
- void release();
-
- void basicProcesses();
-
- void processes_data();
- void processes();
-
-#if !defined(Q_OS_WIN) && !defined(QT_POSIX_IPC)
- void undo();
-#endif
- void initialValue();
-
-private:
- QSystemSemaphore *existingLock;
-
- const QString m_helperBinary;
-};
-
-tst_QSystemSemaphore::tst_QSystemSemaphore()
- : m_helperBinary("acquirerelease_helper")
-{
-}
-
-void tst_QSystemSemaphore::init()
-{
- existingLock = new QSystemSemaphore(EXISTING_SHARE, 1, QSystemSemaphore::Create);
-}
-
-void tst_QSystemSemaphore::cleanup()
-{
- delete existingLock;
-}
-
-void tst_QSystemSemaphore::key_data()
-{
- QTest::addColumn<QString>("constructorKey");
- QTest::addColumn<QString>("setKey");
-
- QTest::newRow("null, null") << QString() << QString();
- QTest::newRow("null, one") << QString() << QString("one");
- QTest::newRow("one, two") << QString("one") << QString("two");
-}
-
-/*!
- Basic key testing
- */
-void tst_QSystemSemaphore::key()
-{
- QFETCH(QString, constructorKey);
- QFETCH(QString, setKey);
-
- QSystemSemaphore sem(constructorKey);
- QCOMPARE(sem.key(), constructorKey);
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QCOMPARE(sem.errorString(), QString());
-
- sem.setKey(setKey);
- QCOMPARE(sem.key(), setKey);
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QCOMPARE(sem.errorString(), QString());
-}
-
-void tst_QSystemSemaphore::basicacquire()
-{
- QSystemSemaphore sem("QSystemSemaphore_basicacquire", 1, QSystemSemaphore::Create);
- QVERIFY(sem.acquire());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.release());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QCOMPARE(sem.errorString(), QString());
-}
-
-void tst_QSystemSemaphore::complexacquire()
-{
- QSystemSemaphore sem("QSystemSemaphore_complexacquire", 2, QSystemSemaphore::Create);
- QVERIFY(sem.acquire());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.release());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.acquire());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.release());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.acquire());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.acquire());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.release());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.release());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QCOMPARE(sem.errorString(), QString());
-}
-
-void tst_QSystemSemaphore::release()
-{
- QSystemSemaphore sem("QSystemSemaphore_release", 0, QSystemSemaphore::Create);
- QVERIFY(sem.release());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.release());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.acquire());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.acquire());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.release());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QVERIFY(sem.release());
- QCOMPARE(sem.error(), QSystemSemaphore::NoError);
- QCOMPARE(sem.errorString(), QString());
-}
-
-void tst_QSystemSemaphore::basicProcesses()
-{
-#if !QT_CONFIG(process)
- QSKIP("No qprocess support", SkipAll);
-#else
- QSystemSemaphore sem("store", 0, QSystemSemaphore::Create);
-
- QProcess acquire;
- acquire.setProcessChannelMode(QProcess::ForwardedChannels);
-
- QProcess release;
- release.setProcessChannelMode(QProcess::ForwardedChannels);
-
- acquire.start(m_helperBinary, QStringList("acquire"));
- QVERIFY2(acquire.waitForStarted(), "Could not start helper binary");
- acquire.waitForFinished(HELPERWAITTIME);
- QCOMPARE(acquire.state(), QProcess::Running);
- acquire.kill();
- release.start(m_helperBinary, QStringList("release"));
- QVERIFY2(release.waitForStarted(), "Could not start helper binary");
- acquire.waitForFinished(HELPERWAITTIME);
- release.waitForFinished(HELPERWAITTIME);
- QCOMPARE(acquire.state(), QProcess::NotRunning);
-#endif
-}
-
-void tst_QSystemSemaphore::processes_data()
-{
- QTest::addColumn<int>("processes");
- for (int i = 0; i < 5; ++i) {
- QTest::newRow("1 process") << 1;
- QTest::newRow("3 process") << 3;
- QTest::newRow("10 process") << 10;
- }
-}
-
-void tst_QSystemSemaphore::processes()
-{
-#if !QT_CONFIG(process)
- QSKIP("No qprocess support", SkipAll);
-#else
- QSystemSemaphore sem("store", 1, QSystemSemaphore::Create);
-
- QFETCH(int, processes);
- QList<QString> scripts(processes, "acquirerelease");
-
- QList<QProcess*> consumers;
- for (int i = 0; i < scripts.count(); ++i) {
- QProcess *p = new QProcess;
- p->setProcessChannelMode(QProcess::ForwardedChannels);
- consumers.append(p);
- p->start(m_helperBinary, QStringList(scripts.at(i)));
- }
-
- while (!consumers.isEmpty()) {
- consumers.first()->waitForFinished();
- QCOMPARE(consumers.first()->exitStatus(), QProcess::NormalExit);
- QCOMPARE(consumers.first()->exitCode(), 0);
- delete consumers.takeFirst();
- }
-#endif
-}
-
-// This test only checks a system v unix behavior.
-#if !defined(Q_OS_WIN) && !defined(QT_POSIX_IPC)
-void tst_QSystemSemaphore::undo()
-{
-#if !QT_CONFIG(process)
- QSKIP("No qprocess support", SkipAll);
-#else
- QSystemSemaphore sem("store", 1, QSystemSemaphore::Create);
-
- QStringList acquireArguments = QStringList("acquire");
- QProcess acquire;
- acquire.setProcessChannelMode(QProcess::ForwardedChannels);
- acquire.start(m_helperBinary, acquireArguments);
- QVERIFY2(acquire.waitForStarted(), "Could not start helper binary");
- acquire.waitForFinished(HELPERWAITTIME);
- QVERIFY(acquire.state()== QProcess::NotRunning);
-
- // At process exit the kernel should auto undo
-
- acquire.start(m_helperBinary, acquireArguments);
- QVERIFY2(acquire.waitForStarted(), "Could not start helper binary");
- acquire.waitForFinished(HELPERWAITTIME);
- QVERIFY(acquire.state()== QProcess::NotRunning);
-#endif
-}
-#endif
-
-void tst_QSystemSemaphore::initialValue()
-{
-#if !QT_CONFIG(process)
- QSKIP("No qprocess support", SkipAll);
-#else
- QSystemSemaphore sem("store", 1, QSystemSemaphore::Create);
-
- QStringList acquireArguments = QStringList("acquire");
- QStringList releaseArguments = QStringList("release");
- QProcess acquire;
- acquire.setProcessChannelMode(QProcess::ForwardedChannels);
-
- QProcess release;
- release.setProcessChannelMode(QProcess::ForwardedChannels);
-
- acquire.start(m_helperBinary, acquireArguments);
- QVERIFY2(acquire.waitForStarted(), "Could not start helper binary");
- acquire.waitForFinished(HELPERWAITTIME);
- QVERIFY(acquire.state()== QProcess::NotRunning);
-
- acquire.start(m_helperBinary, acquireArguments << QLatin1String("2"));
- QVERIFY2(acquire.waitForStarted(), "Could not start helper binary");
- acquire.waitForFinished(HELPERWAITTIME);
- QVERIFY(acquire.state()== QProcess::Running);
- acquire.kill();
-
- release.start(m_helperBinary, releaseArguments);
- QVERIFY2(release.waitForStarted(), "Could not start helper binary");
- acquire.waitForFinished(HELPERWAITTIME);
- release.waitForFinished(HELPERWAITTIME);
- QVERIFY(acquire.state()== QProcess::NotRunning);
-#endif
-}
-
-QTEST_MAIN(tst_QSystemSemaphore)
-#include "tst_qsystemsemaphore.moc"
-
diff --git a/tests/auto/corelib/kernel/qtimer/BLACKLIST b/tests/auto/corelib/kernel/qtimer/BLACKLIST
deleted file mode 100644
index 977b3a673a..0000000000
--- a/tests/auto/corelib/kernel/qtimer/BLACKLIST
+++ /dev/null
@@ -1,2 +0,0 @@
-[zeroTimer]
-ubuntu-20.04
diff --git a/tests/auto/corelib/kernel/qtimer/CMakeLists.txt b/tests/auto/corelib/kernel/qtimer/CMakeLists.txt
index d6e41f6344..6bb3b15850 100644
--- a/tests/auto/corelib/kernel/qtimer/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qtimer/CMakeLists.txt
@@ -1,15 +1,34 @@
-# Generated from qtimer.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
-#####################################################################
-## tst_qtimer Test:
-#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qtimer LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
-qt_add_test(tst_qtimer
- SOURCES
- tst_qtimer.cpp
- PUBLIC_LIBRARIES
- Qt::CorePrivate
-)
+if (NOT QT_FEATURE_thread)
+ return()
+endif()
+
+function(addTimerTest test)
+ qt_internal_add_test(${test}
+ SOURCES
+ tst_qtimer.cpp
+ LIBRARIES
+ Qt::CorePrivate
+ Qt::TestPrivate
+ )
+endfunction()
+
+addTimerTest(tst_qtimer)
+
+if(QT_FEATURE_glib AND UNIX)
+ addTimerTest(tst_qtimer_no_glib)
+ qt_internal_extend_target(tst_qtimer_no_glib
+ DEFINES
+ DISABLE_GLIB
+ tst_QTimer=tst_QTimer_no_glib # Class name in the unittest
+ )
+endif()
-## Scopes:
-#####################################################################
diff --git a/tests/auto/corelib/kernel/qtimer/qtimer.pro b/tests/auto/corelib/kernel/qtimer/qtimer.pro
deleted file mode 100644
index 710dfea682..0000000000
--- a/tests/auto/corelib/kernel/qtimer/qtimer.pro
+++ /dev/null
@@ -1,7 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qtimer
-QT = core core-private testlib
-SOURCES = tst_qtimer.cpp
-
-# Force C++17 if available
-contains(QT_CONFIG, c++1z): CONFIG += c++1z
diff --git a/tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp b/tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp
index 1db210e0bd..40190ca465 100644
--- a/tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp
+++ b/tests/auto/corelib/kernel/qtimer/tst_qtimer.cpp
@@ -1,49 +1,46 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+/* WARNING: this source-code is reused by another test.
+
+ As Qt built with GUI support may use a different backend for its event loops
+ and other timer-related matters, it is important to test it in that form, as
+ well as in its GUI-less form. So this source file is reused by a build config
+ in the GUI module. Similarly, testing with and without glib is supported,
+ where relevant (see DISABLE_GLIB below).
+*/
#ifdef QT_GUI_LIB
+// When compiled as tests/auto/gui/kernel/qguitimer/'s source-code:
# include <QtGui/QGuiApplication>
#else
+// When compiled as tests/auto/corelib/kernel/qtimer/'s source-code:
# include <QtCore/QCoreApplication>
#endif
#include <QtCore/private/qglobal_p.h>
-#include <QtTest/QtTest>
+#include <QTest>
+#include <QSignalSpy>
+#include <QtTest/private/qpropertytesthelper_p.h>
#include <qtimer.h>
#include <qthread.h>
#include <qelapsedtimer.h>
+#include <qproperty.h>
#if defined Q_OS_UNIX
#include <unistd.h>
#endif
+#ifdef DISABLE_GLIB
+static bool glibDisabled = []() {
+ qputenv("QT_NO_GLIB", "1");
+ return true;
+}();
+#endif
+
+using namespace std::chrono_literals;
+
class tst_QTimer : public QObject
{
Q_OBJECT
@@ -55,6 +52,12 @@ private slots:
void zeroTimer();
void singleShotTimeout();
void timeout();
+ void singleShotNormalizes_data();
+ void singleShotNormalizes();
+ void sequentialTimers_data();
+ void sequentialTimers();
+ void singleShotSequentialTimers_data();
+ void singleShotSequentialTimers();
void remainingTime();
void remainingTimeInitial_data();
void remainingTimeInitial();
@@ -79,6 +82,7 @@ private slots:
void singleShotToFunctors();
void singleShot_chrono();
void singleShot_static();
+ void crossThreadSingleShotToFunctor_data();
void crossThreadSingleShotToFunctor();
void timerOrder();
void timerOrder_data();
@@ -88,33 +92,46 @@ private slots:
void dontBlockEvents();
void postedEventsShouldNotStarveTimers();
void callOnTimeout();
+
+ void bindToTimer();
+ void bindTimer();
+ void automatedBindingTests();
+
+ void negativeInterval();
+ void testTimerId();
};
void tst_QTimer::zeroTimer()
{
QTimer timer;
+ QVERIFY(!timer.isSingleShot());
timer.setInterval(0);
+ timer.setSingleShot(true);
+ QVERIFY(timer.isSingleShot());
QSignalSpy timeoutSpy(&timer, &QTimer::timeout);
timer.start();
- QCoreApplication::processEvents();
+ // Pass timeout to work round glib issue, see QTBUG-84291.
+ QCoreApplication::processEvents(QEventLoop::AllEvents, INT_MAX);
- QCOMPARE(timeoutSpy.count(), 1);
+ QCOMPARE(timeoutSpy.size(), 1);
}
void tst_QTimer::singleShotTimeout()
{
QTimer timer;
+ QVERIFY(!timer.isSingleShot());
timer.setSingleShot(true);
+ QVERIFY(timer.isSingleShot());
QSignalSpy timeoutSpy(&timer, &QTimer::timeout);
timer.start(100);
QVERIFY(timeoutSpy.wait(500));
- QCOMPARE(timeoutSpy.count(), 1);
+ QCOMPARE(timeoutSpy.size(), 1);
QTest::qWait(500);
- QCOMPARE(timeoutSpy.count(), 1);
+ QCOMPARE(timeoutSpy.size(), 1);
}
#define TIMEOUT_TIMEOUT 200
@@ -125,12 +142,147 @@ void tst_QTimer::timeout()
QSignalSpy timeoutSpy(&timer, &QTimer::timeout);
timer.start(100);
- QCOMPARE(timeoutSpy.count(), 0);
+ QCOMPARE(timeoutSpy.size(), 0);
+
+ QTRY_VERIFY_WITH_TIMEOUT(timeoutSpy.size() > 0, TIMEOUT_TIMEOUT);
+ int oldCount = timeoutSpy.size();
+
+ QTRY_VERIFY_WITH_TIMEOUT(timeoutSpy.size() > oldCount, TIMEOUT_TIMEOUT);
+}
+
+void tst_QTimer::singleShotNormalizes_data()
+{
+ QTest::addColumn<QByteArray>("slotName");
+
+ QTest::newRow("normalized") << QByteArray(SLOT(exitLoop()));
+
+ QTest::newRow("space-before") << QByteArray(SLOT( exitLoop()));
+ QTest::newRow("space-after") << QByteArray(SLOT(exitLoop ()));
+ QTest::newRow("space-around") << QByteArray(SLOT( exitLoop ()));
+ QTest::newRow("spaces-before") << QByteArray(SLOT( exitLoop()));
+ QTest::newRow("spaces-after") << QByteArray(SLOT(exitLoop ()));
+ QTest::newRow("spaces-around") << QByteArray(SLOT( exitLoop ()));
+
+ QTest::newRow("space-in-parens") << QByteArray(SLOT(exitLoop( )));
+ QTest::newRow("spaces-in-parens") << QByteArray(SLOT(exitLoop( )));
+ QTest::newRow("space-after-parens") << QByteArray(SLOT(exitLoop() ));
+ QTest::newRow("spaces-after-parens") << QByteArray(SLOT(exitLoop() ));
+}
+
+void tst_QTimer::singleShotNormalizes()
+{
+ static constexpr auto TestTimeout = 250ms;
+ QFETCH(QByteArray, slotName);
+ QEventLoop loop;
+
+ // control test: regular connection
+ {
+ QTimer timer;
+ QVERIFY(QObject::connect(&timer, SIGNAL(timeout()), &QTestEventLoop::instance(), slotName));
+ timer.setSingleShot(true);
+ timer.start(1);
+ QTestEventLoop::instance().enterLoop(TestTimeout);
+ QVERIFY(!QTestEventLoop::instance().timeout());
+ }
+
+ // non-zero time
+ QTimer::singleShot(1, &QTestEventLoop::instance(), slotName);
+ QTestEventLoop::instance().enterLoop(TestTimeout);
+ QVERIFY(!QTestEventLoop::instance().timeout());
+
+ QTimer::singleShot(1ms, &QTestEventLoop::instance(), slotName);
+ QTestEventLoop::instance().enterLoop(TestTimeout);
+ QVERIFY(!QTestEventLoop::instance().timeout());
+
+ // zero time
+ QTimer::singleShot(0, &QTestEventLoop::instance(), slotName);
+ QTestEventLoop::instance().enterLoop(TestTimeout);
+ QVERIFY(!QTestEventLoop::instance().timeout());
+
+ QTimer::singleShot(0ms, &QTestEventLoop::instance(), slotName);
+ QTestEventLoop::instance().enterLoop(TestTimeout);
+ QVERIFY(!QTestEventLoop::instance().timeout());
+}
+
+void tst_QTimer::sequentialTimers_data()
+{
+#ifdef Q_OS_WIN
+ QSKIP("The API used by QEventDispatcherWin32 doesn't respect the order");
+#endif
+ QTest::addColumn<QList<int>>("timeouts");
+ auto addRow = [](const QList<int> &l) {
+ QByteArray name;
+ int last = -1;
+ for (int i = 0; i < l.size(); ++i) {
+ Q_ASSERT_X(l[i] >= last, "tst_QTimer", "input list must be sorted");
+ name += QByteArray::number(l[i]) + ',';
+ }
+ name.chop(1);
+ QTest::addRow("%s", name.constData()) << l;
+ };
+ // PreciseTimers
+ addRow({0, 0, 0, 0, 0, 0});
+ addRow({0, 1, 2});
+ addRow({1, 1, 1, 2, 2, 2, 2});
+ addRow({1, 2, 3});
+ addRow({19, 19, 19});
+ // CoarseTimer for setInterval
+ addRow({20, 20, 20, 20, 20});
+ addRow({25, 25, 25, 25, 25, 25, 50});
+}
+
+void tst_QTimer::sequentialTimers()
+{
+ QFETCH(const QList<int>, timeouts);
+ QByteArray result, expected;
+ std::vector<std::unique_ptr<QTimer>> timers;
+ expected.resize(timeouts.size());
+ result.reserve(timeouts.size());
+ timers.reserve(timeouts.size());
+ for (int i = 0; i < timeouts.size(); ++i) {
+ auto timer = std::make_unique<QTimer>();
+ timer->setSingleShot(true);
+ timer->setInterval(timeouts[i]);
+
+ char c = 'A' + i;
+ expected[i] = c;
+ QObject::connect(timer.get(), &QTimer::timeout, this, [&result, c = c]() {
+ result.append(c);
+ });
+ timers.push_back(std::move(timer));
+ }
+
+ // start the timers
+ for (auto &timer : timers)
+ timer->start();
+
+ QTestEventLoop::instance().enterLoopMSecs(timeouts.last() * 2 + 10);
+
+ QCOMPARE(result, expected);
+}
+
+void tst_QTimer::singleShotSequentialTimers_data()
+{
+ sequentialTimers_data();
+}
- QTRY_VERIFY_WITH_TIMEOUT(timeoutSpy.count() > 0, TIMEOUT_TIMEOUT);
- int oldCount = timeoutSpy.count();
+void tst_QTimer::singleShotSequentialTimers()
+{
+ QFETCH(const QList<int>, timeouts);
+ QByteArray result, expected;
+ expected.resize(timeouts.size());
+ result.reserve(timeouts.size());
+ for (int i = 0; i < timeouts.size(); ++i) {
+ char c = 'A' + i;
+ expected[i] = c;
+ QTimer::singleShot(timeouts[i], this, [&result, c = c]() {
+ result.append(c);
+ });
+ }
+
+ QTestEventLoop::instance().enterLoopMSecs(timeouts.last() * 2 + 10);
- QTRY_VERIFY_WITH_TIMEOUT(timeoutSpy.count() > oldCount, TIMEOUT_TIMEOUT);
+ QCOMPARE(result, expected);
}
void tst_QTimer::remainingTime()
@@ -204,7 +356,9 @@ void tst_QTimer::remainingTimeInitial()
QFETCH(Qt::TimerType, timerType);
QTimer timer;
+ QCOMPARE(timer.timerType(), Qt::CoarseTimer);
timer.setTimerType(timerType);
+ QCOMPARE(timer.timerType(), timerType);
timer.start(startTimeMs);
const int rt = timer.remainingTime();
@@ -252,19 +406,14 @@ void tst_QTimer::remainingTimeDuringActivation()
namespace {
-#if __has_include(<chrono>)
template <typename T>
std::chrono::milliseconds to_ms(T t)
{ return std::chrono::duration_cast<std::chrono::milliseconds>(t); }
-#endif
} // unnamed namespace
void tst_QTimer::basic_chrono()
{
-#if !__has_include(<chrono>)
- QSKIP("This test requires C++11 <chrono> support");
-#else
// duplicates zeroTimer, singleShotTimeout, interval and remainingTime
using namespace std::chrono;
QTimer timer;
@@ -276,24 +425,24 @@ void tst_QTimer::basic_chrono()
QCoreApplication::processEvents();
- QCOMPARE(timeoutSpy.count(), 1);
+ QCOMPARE(timeoutSpy.size(), 1);
timeoutSpy.clear();
timer.start(milliseconds(100));
- QCOMPARE(timeoutSpy.count(), 0);
+ QCOMPARE(timeoutSpy.size(), 0);
QVERIFY(timeoutSpy.wait(TIMEOUT_TIMEOUT));
- QVERIFY(timeoutSpy.count() > 0);
- int oldCount = timeoutSpy.count();
+ QVERIFY(timeoutSpy.size() > 0);
+ int oldCount = timeoutSpy.size();
QVERIFY(timeoutSpy.wait(TIMEOUT_TIMEOUT));
- QVERIFY(timeoutSpy.count() > oldCount);
+ QVERIFY(timeoutSpy.size() > oldCount);
timeoutSpy.clear();
timer.start(to_ms(microseconds(200000)));
QCOMPARE(timer.intervalAsDuration().count(), milliseconds::rep(200));
QTest::qWait(50);
- QCOMPARE(timeoutSpy.count(), 0);
+ QCOMPARE(timeoutSpy.size(), 0);
milliseconds rt = timer.remainingTimeAsDuration();
QVERIFY2(rt.count() >= 50 && rt.count() <= 200, qPrintable(QString::number(rt.count())));
@@ -302,10 +451,9 @@ void tst_QTimer::basic_chrono()
timer.setSingleShot(true);
timer.start(milliseconds(100));
QVERIFY(timeoutSpy.wait(TIMEOUT_TIMEOUT));
- QCOMPARE(timeoutSpy.count(), 1);
+ QCOMPARE(timeoutSpy.size(), 1);
QTest::qWait(500);
- QCOMPARE(timeoutSpy.count(), 1);
-#endif
+ QCOMPARE(timeoutSpy.size(), 1);
}
void tst_QTimer::livelock_data()
@@ -530,6 +678,7 @@ void tst_QTimer::moveToThread()
#endif
QTimer ti1;
QTimer ti2;
+ ti1.setSingleShot(true);
ti1.start(MOVETOTHREAD_TIMEOUT);
ti2.start(MOVETOTHREAD_TIMEOUT);
QVERIFY((ti1.timerId() & 0xffffff) != (ti2.timerId() & 0xffffff));
@@ -668,12 +817,10 @@ void tst_QTimer::timerFiresOnlyOncePerProcessEvents()
class TimerIdPersistsAfterThreadExitThread : public QThread
{
public:
- QTimer *timer;
- int timerId, returnValue;
+ QTimer *timer = nullptr;
+ Qt::TimerId timerId = Qt::TimerId::Invalid;
+ int returnValue = -1;
- TimerIdPersistsAfterThreadExitThread()
- : QThread(), timer(0), timerId(-1), returnValue(-1)
- { }
~TimerIdPersistsAfterThreadExitThread()
{
delete timer;
@@ -685,11 +832,15 @@ public:
timer = new QTimer;
connect(timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
timer->start(100);
- timerId = timer->timerId();
+ timerId = timer->id();
returnValue = eventLoop.exec();
}
};
+namespace {
+int operator&(Qt::TimerId id, int i) { return qToUnderlying(id) & i; }
+}
+
void tst_QTimer::timerIdPersistsAfterThreadExit()
{
TimerIdPersistsAfterThreadExitThread thread;
@@ -715,6 +866,19 @@ void tst_QTimer::cancelLongTimer()
QVERIFY(!timer.isActive());
}
+void tst_QTimer::testTimerId()
+{
+ QTimer timer;
+ timer.start(100ms);
+ QVERIFY(timer.isActive());
+ QCOMPARE_GT(timer.timerId(), 0);
+ QCOMPARE_GT(timer.id(), Qt::TimerId::Invalid);
+ timer.stop();
+ QVERIFY(!timer.isActive());
+ QCOMPARE(timer.timerId(), -1);
+ QCOMPARE(timer.id(), Qt::TimerId::Invalid);
+}
+
class TimeoutCounter : public QObject
{
Q_OBJECT
@@ -889,7 +1053,7 @@ void tst_QTimer::singleShotToFunctors()
thread.wait();
struct MoveOnly : CountedStruct {
- Q_DISABLE_COPY(MoveOnly);
+ Q_DISABLE_COPY(MoveOnly)
MoveOnly(MoveOnly &&o) : CountedStruct(std::move(o)) {};
MoveOnly(int *c) : CountedStruct(c) {}
};
@@ -902,9 +1066,6 @@ void tst_QTimer::singleShotToFunctors()
void tst_QTimer::singleShot_chrono()
{
-#if !__has_include(<chrono>)
- QSKIP("This test requires C++11 <chrono> support");
-#else
// duplicates singleShotStaticFunctionZeroTimeout and singleShotToFunctors
using namespace std::chrono;
{
@@ -941,7 +1102,6 @@ void tst_QTimer::singleShot_chrono()
QTRY_COMPARE(count, 3);
_e.reset();
-#endif
}
class DontBlockEvents : public QObject
@@ -1023,30 +1183,57 @@ void tst_QTimer::postedEventsShouldNotStarveTimers()
timer.start();
SlotRepeater slotRepeater;
slotRepeater.repeatThisSlot();
- QTRY_VERIFY_WITH_TIMEOUT(timeoutSpy.count() > 5, 100);
+ QTRY_VERIFY_WITH_TIMEOUT(timeoutSpy.size() > 5, 100);
}
struct DummyFunctor {
- void operator()() {}
+ static QThread *callThread;
+ void operator()() {
+ callThread = QThread::currentThread();
+ callThread->quit();
+ }
};
+QThread *DummyFunctor::callThread = nullptr;
+
+void tst_QTimer::crossThreadSingleShotToFunctor_data()
+{
+ QTest::addColumn<int>("timeout");
+
+ QTest::addRow("zero-timer") << 0;
+ QTest::addRow("1ms") << 1;
+}
void tst_QTimer::crossThreadSingleShotToFunctor()
{
- // We're testing for crashes here, so the test simply running to
- // completion is considered a success
- QThread t;
- t.start();
+ QFETCH(int, timeout);
+ // We're also testing for crashes here, so the test simply running to
+ // completion is part of the success
+ DummyFunctor::callThread = nullptr;
- QObject* o = new QObject();
+ QThread t;
+ std::unique_ptr<QObject> o(new QObject());
o->moveToThread(&t);
- for (int i = 0; i < 10000; i++) {
- QTimer::singleShot(0, o, DummyFunctor());
- }
+ QTimer::singleShot(timeout, o.get(), DummyFunctor());
- t.quit();
+ // wait enough time for the timer to have timed out before the timer
+ // could be start in the receiver's thread.
+ QTest::qWait(10 + timeout * 10);
+ t.start();
t.wait();
- delete o;
+ QCOMPARE(DummyFunctor::callThread, &t);
+
+ // continue with a stress test - the calling thread is busy, the
+ // timer should still fire and no crashes.
+ DummyFunctor::callThread = nullptr;
+ t.start();
+ for (int i = 0; i < 10000; i++)
+ QTimer::singleShot(timeout, o.get(), DummyFunctor());
+
+ t.wait();
+ o.reset();
+
+ QCOMPARE(DummyFunctor::callThread, &t);
}
void tst_QTimer::callOnTimeout()
@@ -1066,7 +1253,7 @@ void tst_QTimer::callOnTimeout()
QTest::qWait(100);
QCOMPARE(count, 2);
- QCOMPARE(timeoutSpy.count(), 1);
+ QCOMPARE(timeoutSpy.size(), 1);
// Test that connection is bound to context lifetime
QVERIFY(connection);
@@ -1074,6 +1261,179 @@ void tst_QTimer::callOnTimeout()
QVERIFY(!connection);
}
+void tst_QTimer::bindToTimer()
+{
+ QTimer timer;
+
+ // singleShot property
+ QProperty<bool> singleShot;
+ singleShot.setBinding(timer.bindableSingleShot().makeBinding());
+ QCOMPARE(timer.isSingleShot(), singleShot);
+
+ timer.setSingleShot(true);
+ QVERIFY(singleShot);
+ timer.setSingleShot(false);
+ QVERIFY(!singleShot);
+
+ // interval property
+ QProperty<int> interval;
+ interval.setBinding([&](){ return timer.interval(); });
+ QCOMPARE(timer.interval(), interval);
+
+ timer.setInterval(10);
+ QCOMPARE(interval, 10);
+ timer.setInterval(100);
+ QCOMPARE(interval, 100);
+
+ // timerType property
+ QProperty<Qt::TimerType> timerType;
+ timerType.setBinding(timer.bindableTimerType().makeBinding());
+ QCOMPARE(timer.timerType(), timerType);
+
+ timer.setTimerType(Qt::PreciseTimer);
+ QCOMPARE(timerType, Qt::PreciseTimer);
+
+ timer.setTimerType(Qt::VeryCoarseTimer);
+ QCOMPARE(timerType, Qt::VeryCoarseTimer);
+
+ // active property
+ QProperty<bool> active;
+ active.setBinding([&](){ return timer.isActive(); });
+ QCOMPARE(active, timer.isActive());
+
+ timer.start(1000);
+ QVERIFY(active);
+
+ timer.stop();
+ QVERIFY(!active);
+
+ auto ignoreMsg = [] {
+ QTest::ignoreMessage(QtWarningMsg,
+ "QObject::startTimer: Timers cannot have negative intervals");
+ };
+
+ // also test that using negative interval updates the binding correctly
+ timer.start(100);
+ QVERIFY(active);
+ ignoreMsg();
+ timer.setInterval(-100);
+ QVERIFY(!active);
+ timer.start(100);
+ QVERIFY(active);
+ ignoreMsg();
+ timer.start(-100);
+ QVERIFY(!active);
+}
+
+void tst_QTimer::bindTimer()
+{
+ QTimer timer;
+
+ // singleShot property
+ QVERIFY(!timer.isSingleShot());
+
+ QProperty<bool> singleShot;
+ timer.bindableSingleShot().setBinding(Qt::makePropertyBinding(singleShot));
+
+ singleShot = true;
+ QVERIFY(timer.isSingleShot());
+ singleShot = false;
+ QVERIFY(!timer.isSingleShot());
+
+ // interval property
+ QCOMPARE(timer.interval(), 0);
+
+ QProperty<int> interval;
+ timer.bindableInterval().setBinding(Qt::makePropertyBinding(interval));
+
+ interval = 10;
+ QCOMPARE(timer.interval(), 10);
+ interval = 100;
+ QCOMPARE(timer.interval(), 100);
+ timer.setInterval(50);
+ QCOMPARE(timer.interval(), 50);
+ interval = 30;
+ QCOMPARE(timer.interval(), 50);
+
+ // timerType property
+ QCOMPARE(timer.timerType(), Qt::CoarseTimer);
+
+ QProperty<Qt::TimerType> timerType;
+ timer.bindableTimerType().setBinding(Qt::makePropertyBinding(timerType));
+
+ timerType = Qt::PreciseTimer;
+ QCOMPARE(timer.timerType(), Qt::PreciseTimer);
+ timerType = Qt::VeryCoarseTimer;
+ QCOMPARE(timer.timerType(), Qt::VeryCoarseTimer);
+}
+
+void tst_QTimer::automatedBindingTests()
+{
+ QTimer timer;
+
+ QVERIFY(!timer.isSingleShot());
+ QTestPrivate::testReadWritePropertyBasics(timer, true, false, "singleShot");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QTimer::singleShot");
+ return;
+ }
+
+ QCOMPARE_NE(timer.interval(), 10);
+ QTestPrivate::testReadWritePropertyBasics(timer, 10, 20, "interval");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QTimer::interval");
+ return;
+ }
+
+ QCOMPARE_NE(timer.timerType(), Qt::PreciseTimer);
+ QTestPrivate::testReadWritePropertyBasics(timer, Qt::PreciseTimer, Qt::CoarseTimer,
+ "timerType");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QTimer::timerType");
+ return;
+ }
+
+ timer.start(1000);
+ QVERIFY(timer.isActive());
+ QTestPrivate::testReadOnlyPropertyBasics(timer, true, false, "active",
+ [&timer]() { timer.stop(); });
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QTimer::active");
+ return;
+ }
+}
+
+void tst_QTimer::negativeInterval()
+{
+ auto ignoreMsg = [] {
+ QTest::ignoreMessage(QtWarningMsg,
+ "QObject::startTimer: Timers cannot have negative intervals");
+ };
+
+ QTimer timer;
+
+ // Starting with a negative interval does not change active state.
+ ignoreMsg();
+ timer.start(-100ms);
+ QVERIFY(!timer.isActive());
+
+ // Updating the interval to a negative value stops the timer and changes
+ // the active state.
+ timer.start(100ms);
+ QVERIFY(timer.isActive());
+ ignoreMsg();
+ timer.setInterval(-100);
+ QVERIFY(!timer.isActive());
+
+ // Starting with a negative interval when already started leads to stop
+ // and inactive state.
+ timer.start(100);
+ QVERIFY(timer.isActive());
+ ignoreMsg();
+ timer.start(-100ms);
+ QVERIFY(!timer.isActive());
+}
+
class OrderHelper : public QObject
{
Q_OBJECT
@@ -1147,14 +1507,10 @@ void tst_QTimer::timerOrder_data()
void tst_QTimer::timerOrderBackgroundThread()
{
-#if !QT_CONFIG(cxx11_future)
- QSKIP("This test requires QThread::create");
-#else
auto *thread = QThread::create([this]() { timerOrder(); });
thread->start();
QVERIFY(thread->wait());
delete thread;
-#endif
}
struct StaticSingleShotUser
diff --git a/tests/auto/corelib/kernel/qtranslator/CMakeLists.txt b/tests/auto/corelib/kernel/qtranslator/CMakeLists.txt
index e1cefa3325..92b6edb17c 100644
--- a/tests/auto/corelib/kernel/qtranslator/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qtranslator/CMakeLists.txt
@@ -1,32 +1,44 @@
-# Generated from qtranslator.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qtranslator Test:
#####################################################################
-qt_add_test(tst_qtranslator
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qtranslator LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+if (NOT QT_FEATURE_thread)
+ return()
+endif()
+
+qt_internal_add_test(tst_qtranslator
SOURCES
tst_qtranslator.cpp
)
# Resources:
set(qtranslator_resource_files
+ "dependencies_la.qm"
"hellotr_empty.qm"
"hellotr_la.qm"
+ "msgfmt_from_po.qm"
)
-qt_add_resource(tst_qtranslator "qtranslator"
+qt_internal_add_resource(tst_qtranslator "qtranslator"
PREFIX
"/tst_qtranslator"
FILES
${qtranslator_resource_files}
)
-
## Scopes:
#####################################################################
-if(ANDROID AND NOT ANDROID_EMBEDDED)
+if(ANDROID)
# Resources:
set(android_testdata_resource_files
"dependencies_la.qm"
@@ -35,13 +47,10 @@ if(ANDROID AND NOT ANDROID_EMBEDDED)
"msgfmt_from_po.qm"
)
- qt_add_resource(tst_qtranslator "android_testdata"
+ qt_internal_add_resource(tst_qtranslator "android_testdata"
PREFIX
"/android_testdata"
FILES
${android_testdata_resource_files}
)
endif()
-
-#### Keys ignored in scope 3:.:.:qtranslator.pro:else:
-# TESTDATA = "dependencies_la.qm" "hellotr_empty.qm" "hellotr_la.qm" "msgfmt_from_po.qm"
diff --git a/tests/auto/corelib/kernel/qtranslator/android_testdata.qrc b/tests/auto/corelib/kernel/qtranslator/android_testdata.qrc
deleted file mode 100644
index 39b85db664..0000000000
--- a/tests/auto/corelib/kernel/qtranslator/android_testdata.qrc
+++ /dev/null
@@ -1,8 +0,0 @@
-<RCC>
- <qresource prefix="/android_testdata">
- <file>hellotr_la.qm</file>
- <file>hellotr_empty.qm</file>
- <file>msgfmt_from_po.qm</file>
- <file>dependencies_la.qm</file>
- </qresource>
-</RCC>
diff --git a/tests/auto/corelib/kernel/qtranslator/qtranslator.pro b/tests/auto/corelib/kernel/qtranslator/qtranslator.pro
deleted file mode 100644
index a985f35a14..0000000000
--- a/tests/auto/corelib/kernel/qtranslator/qtranslator.pro
+++ /dev/null
@@ -1,9 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qtranslator
-QT = core testlib
-SOURCES = tst_qtranslator.cpp
-RESOURCES += qtranslator.qrc
-
-android:!android-embedded: RESOURCES += android_testdata.qrc
-else: TESTDATA += dependencies_la.qm hellotr_empty.qm hellotr_la.qm msgfmt_from_po.qm
-
diff --git a/tests/auto/corelib/kernel/qtranslator/qtranslator.qrc b/tests/auto/corelib/kernel/qtranslator/qtranslator.qrc
deleted file mode 100644
index cb82c6cc95..0000000000
--- a/tests/auto/corelib/kernel/qtranslator/qtranslator.qrc
+++ /dev/null
@@ -1,6 +0,0 @@
-<RCC>
- <qresource prefix="/tst_qtranslator">
- <file>hellotr_la.qm</file>
- <file>hellotr_empty.qm</file>
- </qresource>
-</RCC>
diff --git a/tests/auto/corelib/kernel/qtranslator/tst_qtranslator.cpp b/tests/auto/corelib/kernel/qtranslator/tst_qtranslator.cpp
index d34fb3e8dc..c76500ea11 100644
--- a/tests/auto/corelib/kernel/qtranslator/tst_qtranslator.cpp
+++ b/tests/auto/corelib/kernel/qtranslator/tst_qtranslator.cpp
@@ -1,34 +1,17 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
+#include <QWaitCondition>
+#include <QMutex>
+#include <QStandardPaths>
#include <qtranslator.h>
#include <qfile.h>
+#include <qtemporarydir.h>
+
+#ifdef Q_OS_ANDROID
+#include <QDirIterator>
+#endif
class tst_QTranslator : public QObject
{
@@ -40,9 +23,11 @@ protected:
bool eventFilter(QObject *obj, QEvent *event) override;
private slots:
void initTestCase();
+ void init();
void load_data();
void load();
+ void loadLocale();
void threadLoad();
void testLanguageChange();
void plural();
@@ -64,38 +49,14 @@ tst_QTranslator::tst_QTranslator()
void tst_QTranslator::initTestCase()
{
-#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED)
- QString sourceDir(":/android_testdata/");
- QDirIterator it(sourceDir, QDirIterator::Subdirectories);
- while (it.hasNext()) {
- it.next();
-
- QFileInfo sourceFileInfo = it.fileInfo();
- if (!sourceFileInfo.isDir()) {
- QFileInfo destinationFileInfo(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1Char('/') + sourceFileInfo.filePath().mid(sourceDir.length()));
-
- if (!destinationFileInfo.exists()) {
- QVERIFY(QDir().mkpath(destinationFileInfo.path()));
- QVERIFY(QFile::copy(sourceFileInfo.filePath(), destinationFileInfo.filePath()));
- }
- }
- }
-
- QDir::setCurrent(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));
-#endif
-
- // chdir into the directory containing our testdata,
- // to make the code simpler (load testdata via relative paths)
-#if 0
- // ### TODO: Use this for all platforms in 5.7
- dataDir = QEXTRACTTESTDATA(QStringLiteral("/"));
+ dataDir = QEXTRACTTESTDATA(QStringLiteral("/tst_qtranslator"));
QVERIFY2(!dataDir.isNull(), qPrintable("Could not extract test data"));
- QVERIFY2(QDir::setCurrent(dataDir->path()), qPrintable("Could not chdir to " + dataDir->path()));
-#else
- QString testdata_dir = QFileInfo(QFINDTESTDATA("hellotr_la.qm")).absolutePath();
- QVERIFY2(QDir::setCurrent(testdata_dir), qPrintable("Could not chdir to " + testdata_dir));
-#endif
+}
+void tst_QTranslator::init()
+{
+ QVERIFY2(QDir::setCurrent(dataDir->path()),
+ qPrintable("Could not chdir to " + dataDir->path()));
}
bool tst_QTranslator::eventFilter(QObject *, QEvent *event)
@@ -134,7 +95,7 @@ void tst_QTranslator::load()
{
QFile file(filepath);
- file.open(QFile::ReadOnly);
+ QVERIFY(file.open(QFile::ReadOnly));
QByteArray data = file.readAll();
QTranslator tor;
QVERIFY(tor.load((const uchar *)data.constData(), data.length()));
@@ -155,6 +116,73 @@ void tst_QTranslator::load()
}
}
+void tst_QTranslator::loadLocale()
+{
+ QLocale locale;
+ auto localeName = locale.uiLanguages(QLocale::TagSeparator::Underscore).value(0);
+ if (localeName.isEmpty())
+ QSKIP("This test requires at least one available UI language.");
+
+ QByteArray ba;
+ {
+ QFile file(":/tst_qtranslator/hellotr_la.qm");
+ QVERIFY2(file.open(QFile::ReadOnly), qPrintable(file.errorString()));
+ ba = file.readAll();
+ QVERIFY(!ba.isEmpty());
+ }
+
+ QTemporaryDir dir;
+ QVERIFY(dir.isValid());
+
+ auto path = dir.path();
+ QFile file(path + "/dummy");
+ QVERIFY2(file.open(QFile::WriteOnly), qPrintable(file.errorString()));
+ QCOMPARE(file.write(ba), ba.size());
+ file.close();
+
+ /*
+ Test the following order:
+
+ /tmp/tmpDir/foo-en_US.qm
+ /tmp/tmpDir/foo-en_US
+ /tmp/tmpDir/foo-en.qm
+ /tmp/tmpDir/foo-en
+ /tmp/tmpDir/foo.qm
+ /tmp/tmpDir/foo-
+ /tmp/tmpDir/foo
+ */
+
+ QStringList files;
+ while (true) {
+ files.append(path + "/foo-" + localeName + ".qm");
+ QVERIFY2(file.copy(files.last()), qPrintable(file.errorString()));
+
+ files.append(path + "/foo-" + localeName);
+ QVERIFY2(file.copy(files.last()), qPrintable(file.errorString()));
+
+ int rightmost = localeName.lastIndexOf(QLatin1Char('_'));
+ if (rightmost <= 0)
+ break;
+ localeName.truncate(rightmost);
+ }
+
+ files.append(path + "/foo.qm");
+ QVERIFY2(file.copy(files.last()), qPrintable(file.errorString()));
+
+ files.append(path + "/foo-");
+ QVERIFY2(file.copy(files.last()), qPrintable(file.errorString()));
+
+ files.append(path + "/foo");
+ QVERIFY2(file.rename(files.last()), qPrintable(file.errorString()));
+
+ QTranslator tor;
+ for (const auto &filePath : files) {
+ QVERIFY(tor.load(locale, "foo", "-", path, ".qm"));
+ QCOMPARE(tor.filePath(), filePath);
+ QVERIFY2(file.remove(filePath), qPrintable(file.errorString()));
+ }
+}
+
class TranslatorThread : public QThread
{
void run() override {
@@ -301,12 +329,21 @@ void tst_QTranslator::dependencies()
{
QTranslator tor( 0 );
QFile file("dependencies_la.qm");
- file.open(QFile::ReadOnly);
+ QVERIFY(file.open(QFile::ReadOnly));
QByteArray data = file.readAll();
QVERIFY(tor.load((const uchar *)data.constData(), data.length()));
QVERIFY(!tor.isEmpty());
QCOMPARE(tor.translate("QPushButton", "Hello world!"), QLatin1String("Hallo Welt!"));
}
+
+ {
+ // Test resolution of paths relative to main file
+ const QString absoluteFile = QFileInfo("dependencies_la").absoluteFilePath();
+ QDir::setCurrent(QDir::tempPath());
+ QTranslator tor;
+ QVERIFY(tor.load(absoluteFile));
+ QVERIFY(!tor.isEmpty());
+ }
}
struct TranslateThread : public QThread
@@ -346,9 +383,9 @@ void tst_QTranslator::translationInThreadWhileInstallingTranslator()
thread.runningCondition.wait(&thread.startupLock);
- QTranslator *tor = new QTranslator;
- QVERIFY(tor->load("hellotr_la"));
- QCoreApplication::installTranslator(tor);
+ QTranslator tor;
+ QVERIFY(tor.load("hellotr_la"));
+ QVERIFY(QCoreApplication::installTranslator(&tor));
++thread.terminate;
diff --git a/tests/auto/corelib/kernel/qvariant/.prev_CMakeLists.txt b/tests/auto/corelib/kernel/qvariant/.prev_CMakeLists.txt
deleted file mode 100644
index 9534e22368..0000000000
--- a/tests/auto/corelib/kernel/qvariant/.prev_CMakeLists.txt
+++ /dev/null
@@ -1,44 +0,0 @@
-# Generated from qvariant.pro.
-
-#####################################################################
-## tst_qvariant Test:
-#####################################################################
-
-qt_add_test(tst_qvariant
- SOURCES
- tst_qvariant.cpp
- DEFINES
- QT_DISABLE_DEPRECATED_BEFORE=0
- INCLUDE_DIRECTORIES
- ../../../other/qvariant_common
- PUBLIC_LIBRARIES
- Qt::CorePrivate
- Qt::Gui
-)
-
-# Resources:
-set(qvariant_resource_files
- "stream/qt4.9/"
- "stream/qt5.0/"
-)
-
-qt_add_resource(tst_qvariant "qvariant"
- PREFIX
- "/"
- FILES
- ${qvariant_resource_files}
-)
-
-
-## Scopes:
-#####################################################################
-
-qt_extend_target(tst_qvariant CONDITION MSVC
- COMPILE_OPTIONS
- /bigobj
-)
-
-qt_extend_target(tst_qvariant CONDITION NOT QT_FEATURE_doubleconversion AND NOT QT_FEATURE_system_doubleconversion
- DEFINES
- QT_NO_DOUBLECONVERSION
-)
diff --git a/tests/auto/corelib/kernel/qvariant/CMakeLists.txt b/tests/auto/corelib/kernel/qvariant/CMakeLists.txt
index 9534e22368..eae9c0d30e 100644
--- a/tests/auto/corelib/kernel/qvariant/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qvariant/CMakeLists.txt
@@ -1,20 +1,15 @@
-# Generated from qvariant.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qvariant Test:
#####################################################################
-qt_add_test(tst_qvariant
- SOURCES
- tst_qvariant.cpp
- DEFINES
- QT_DISABLE_DEPRECATED_BEFORE=0
- INCLUDE_DIRECTORIES
- ../../../other/qvariant_common
- PUBLIC_LIBRARIES
- Qt::CorePrivate
- Qt::Gui
-)
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qvariant LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
# Resources:
set(qvariant_resource_files
@@ -22,23 +17,28 @@ set(qvariant_resource_files
"stream/qt5.0/"
)
-qt_add_resource(tst_qvariant "qvariant"
- PREFIX
- "/"
- FILES
- ${qvariant_resource_files}
+qt_internal_add_test(tst_qvariant
+ SOURCES
+ tst_qvariant.cpp
+ INCLUDE_DIRECTORIES
+ ../../../other/qvariant_common
+ LIBRARIES
+ Qt::CorePrivate
+ Qt::Gui
+ Qt::TestPrivate
+ TESTDATA ${qvariant_resource_files}
+ BUILTIN_TESTDATA
)
-
## Scopes:
#####################################################################
-qt_extend_target(tst_qvariant CONDITION MSVC
+qt_internal_extend_target(tst_qvariant CONDITION MSVC
COMPILE_OPTIONS
/bigobj
)
-qt_extend_target(tst_qvariant CONDITION NOT QT_FEATURE_doubleconversion AND NOT QT_FEATURE_system_doubleconversion
+qt_internal_extend_target(tst_qvariant CONDITION NOT QT_FEATURE_doubleconversion AND NOT QT_FEATURE_system_doubleconversion
DEFINES
QT_NO_DOUBLECONVERSION
)
diff --git a/tests/auto/corelib/kernel/qvariant/qvariant.pro b/tests/auto/corelib/kernel/qvariant/qvariant.pro
deleted file mode 100644
index 21f39567fb..0000000000
--- a/tests/auto/corelib/kernel/qvariant/qvariant.pro
+++ /dev/null
@@ -1,18 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qvariant
-QT = core-private gui testlib
-INCLUDEPATH += $$PWD/../../../other/qvariant_common
-SOURCES = tst_qvariant.cpp
-RESOURCES += qvariant.qrc
-DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
-qtConfig(c++14): CONFIG += c++14
-qtConfig(c++1z): CONFIG += c++1z
-
-msvc {
- # Prevents "fatal error C1128: number of sections exceeded object file format limit".
- QMAKE_CXXFLAGS += /bigobj
-}
-
-!qtConfig(doubleconversion):!qtConfig(system-doubleconversion) {
- DEFINES += QT_NO_DOUBLECONVERSION
-}
diff --git a/tests/auto/corelib/kernel/qvariant/qvariant.qrc b/tests/auto/corelib/kernel/qvariant/qvariant.qrc
deleted file mode 100644
index e6f7bdac80..0000000000
--- a/tests/auto/corelib/kernel/qvariant/qvariant.qrc
+++ /dev/null
@@ -1,6 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource>
- <file>stream/qt4.9/</file>
- <file>stream/qt5.0/</file>
-</qresource>
-</RCC>
diff --git a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
index 0eefd95ac7..23d41cafb2 100644
--- a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
+++ b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
@@ -1,73 +1,149 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Olivier Goffart <ogoffart@woboq.com>
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2021 The Qt Company Ltd.
+// Copyright (C) 2016 Olivier Goffart <ogoffart@woboq.com>
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <qvariant.h>
-#include <QtCore/private/qvariant_p.h>
-#include <qbitarray.h>
-#include <qbytearraylist.h>
-#include <qdatetime.h>
-#include <qmap.h>
-#include <qiodevice.h>
-#include <qurl.h>
-#include <qlocale.h>
-#include <qdebug.h>
-#include <qjsondocument.h>
-#include <quuid.h>
-
-#include <limits.h>
+
+// don't assume <type_traits>
+template <typename T, typename U>
+constexpr inline bool my_is_same_v = false;
+template <typename T>
+constexpr inline bool my_is_same_v<T, T> = true;
+
+#define CHECK_IMPL(func, arg, Variant, cvref, R) \
+ static_assert(my_is_same_v<decltype( func < arg >(std::declval< Variant cvref >())), R cvref >)
+
+#define CHECK_GET_IF(Variant, cvref) \
+ CHECK_IMPL(get_if, int, Variant, cvref *, int)
+
+#define CHECK_GET(Variant, cvref) \
+ CHECK_IMPL(get, int, Variant, cvref, int)
+
+CHECK_GET_IF(QVariant, /* unadorned */);
+CHECK_GET_IF(QVariant, const);
+
+CHECK_GET(QVariant, &);
+CHECK_GET(QVariant, const &);
+CHECK_GET(QVariant, &&);
+CHECK_GET(QVariant, const &&);
+
+// check for a type derived from QVariant:
+
+struct MyVariant : QVariant
+{
+ using QVariant::QVariant;
+};
+
+CHECK_GET_IF(MyVariant, /* unadorned */);
+CHECK_GET_IF(MyVariant, const);
+
+CHECK_GET(MyVariant, &);
+CHECK_GET(MyVariant, const &);
+CHECK_GET(MyVariant, &&);
+CHECK_GET(MyVariant, const &&);
+
+#undef CHECK_GET_IF
+#undef CHECK_GET
+#undef CHECK_IMPL
+
+#include <QTest>
+
+// Please stick to alphabetic order.
+#include <QAssociativeIterable>
+#include <QBitArray>
+#include <QBuffer>
+#include <QByteArrayList>
+#include <QDateTime>
+#include <QDebug>
+#include <QDir>
+#include <QEasingCurve>
+#include <QMap>
+#include <QIODevice>
+#include <QHash>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLocale>
+#include <QQueue>
+#include <QRegularExpression>
+#include <QScopeGuard>
+#include <QSequentialIterable>
+#include <QSet>
+#include <QStack>
+#include <QTimeZone>
+#include <QtNumeric>
+#include <QUrl>
+#include <QUuid>
+
+#include <private/qcomparisontesthelper_p.h>
+#include <private/qlocale_p.h>
+#include <private/qmetatype_p.h>
+#include "tst_qvariant_common.h"
+
+#include <limits>
#include <float.h>
#include <cmath>
-#if __has_include(<variant>) && __cplusplus >= 201703L
#include <variant>
-#endif
-#include <QRegularExpression>
-#include <QDir>
-#include <QBuffer>
-#include "qnumeric.h"
+#include <unordered_map>
-#include <private/qlocale_p.h>
-#include "tst_qvariant_common.h"
+using namespace Qt::StringLiterals;
class CustomNonQObject;
+struct NonDefaultConstructible;
+
+template<typename T, typename = void>
+struct QVariantFromValueCompiles
+{
+ static inline constexpr bool value = false;
+};
+
+template<typename T>
+struct QVariantFromValueCompiles<T, std::void_t<decltype (QVariant::fromValue(std::declval<T>()))>>
+{
+ static inline constexpr bool value = true;
+};
+
+static_assert(QVariantFromValueCompiles<int>::value);
+static_assert(!QVariantFromValueCompiles<QObject>::value);
+
+enum EnumTest_Enum0 { EnumTest_Enum0_value = 42, EnumTest_Enum0_negValue = -8 };
+Q_DECLARE_METATYPE(EnumTest_Enum0)
+enum EnumTest_Enum1 : qint64 { EnumTest_Enum1_value = 42, EnumTest_Enum1_bigValue = (Q_INT64_C(1) << 33) + 50 };
+Q_DECLARE_METATYPE(EnumTest_Enum1)
+
+enum EnumTest_Enum3 : qint64 { EnumTest_Enum3_value = -47, EnumTest_Enum3_bigValue = (Q_INT64_C(1) << 56) + 5 };
+Q_DECLARE_METATYPE(EnumTest_Enum3)
+enum EnumTest_Enum4 : quint64 { EnumTest_Enum4_value = 47, EnumTest_Enum4_bigValue = (Q_INT64_C(1) << 52) + 45 };
+Q_DECLARE_METATYPE(EnumTest_Enum4)
+enum EnumTest_Enum5 : uint { EnumTest_Enum5_value = 47 };
+Q_DECLARE_METATYPE(EnumTest_Enum5)
+enum EnumTest_Enum6 : uchar { EnumTest_Enum6_value = 47 };
+Q_DECLARE_METATYPE(EnumTest_Enum6)
+enum class EnumTest_Enum7 { EnumTest_Enum7_value = 47, ensureSignedEnum7 = -1 };
+Q_DECLARE_METATYPE(EnumTest_Enum7)
+enum EnumTest_Enum8 : short { EnumTest_Enum8_value = 47 };
+Q_DECLARE_METATYPE(EnumTest_Enum8)
+
+template <typename T> int qToUnderlying(QFlags<T> f)
+{
+ return f.toInt();
+}
class tst_QVariant : public QObject
{
Q_OBJECT
+ static void runTestFunction()
+ {
+ QFETCH(QFunctionPointer, testFunction);
+ testFunction();
+ }
+
public:
- tst_QVariant(QObject *parent = 0)
+ tst_QVariant(QObject *parent = nullptr)
: QObject(parent), customNonQObjectPointer(0)
{
-
}
@@ -100,6 +176,13 @@ private slots:
void canConvert_data();
void canConvert();
+ void canConvertAndConvert_ReturnFalse_WhenConvertingBetweenPointerAndValue_data();
+ void canConvertAndConvert_ReturnFalse_WhenConvertingBetweenPointerAndValue();
+
+ void canConvertAndConvert_ReturnFalse_WhenConvertingQObjectBetweenPointerAndValue();
+
+ void convert();
+
void toSize_data();
void toSize();
@@ -168,6 +251,7 @@ private slots:
void qvariant_cast_QObject_derived();
void qvariant_cast_QObject_wrapper();
void qvariant_cast_QSharedPointerQObject();
+ void qvariant_cast_const();
void toLocale();
@@ -188,9 +272,11 @@ private slots:
void operator_eq_eq_data();
void operator_eq_eq();
+#if QT_DEPRECATED_SINCE(6, 0)
void typeName_data();
void typeName();
void typeToName();
+#endif
void streamInvalidVariant();
@@ -205,6 +291,9 @@ private slots:
void variantHash();
void convertToQUint8() const;
+ void compareCompiles() const;
+ void compareNumerics_data() const;
+ void compareNumerics() const;
void comparePointers() const;
void voidStar() const;
void dataStar() const;
@@ -218,6 +307,7 @@ private slots:
void loadBrokenUserType();
void invalidDate() const;
+ void compareCustomTypes_data() const;
void compareCustomTypes() const;
void timeToDateTime() const;
void copyingUserTypes() const;
@@ -227,6 +317,7 @@ private slots:
void convertByteArrayToBool() const;
void convertByteArrayToBool_data() const;
void convertIterables() const;
+ void convertConstNonConst() const;
void toIntFromQString() const;
void toIntFromDouble() const;
void setValue();
@@ -244,8 +335,10 @@ private slots:
void forwardDeclare();
void debugStream_data();
void debugStream();
+#if QT_DEPRECATED_SINCE(6, 0)
void debugStreamType_data();
void debugStreamType();
+#endif
void loadQt4Stream_data();
void loadQt4Stream();
@@ -261,11 +354,18 @@ private slots:
void implicitConstruction();
+ void iterateSequentialContainerElements_data();
+ void iterateSequentialContainerElements() { runTestFunction(); }
+ void iterateAssociativeContainerElements_data();
+ void iterateAssociativeContainerElements() { runTestFunction(); }
void iterateContainerElements();
- void pairElements();
+ void pairElements_data();
+ void pairElements() { runTestFunction(); }
- void enums();
- void metaEnums();
+ void enums_data();
+ void enums() { runTestFunction(); }
+ void metaEnums_data();
+ void metaEnums() { runTestFunction(); }
void nullConvert();
@@ -280,7 +380,41 @@ private slots:
void preferDirectConversionOverInterfaces();
void mutableView();
+ void canViewAndView_ReturnFalseAndDefault_WhenConvertingBetweenPointerAndValue();
+
+ void moveOperations();
+ void equalsWithoutMetaObject();
+
+ void constructFromIncompatibleMetaType_data();
+ void constructFromIncompatibleMetaType();
+ void constructFromQtLT65MetaType();
+ void copyNonDefaultConstructible();
+
+ void inplaceConstruct();
+ void emplace();
+
+ void getIf_int() { getIf_impl(42); }
+ void getIf_QString() { getIf_impl(u"string"_s); };
+ void getIf_NonDefaultConstructible();
+ void getIfSpecial();
+
+ void get_int() { get_impl(42); }
+ void get_QString() { get_impl(u"string"_s); }
+ void get_NonDefaultConstructible();
+
private:
+ using StdVariant = std::variant<std::monostate,
+ // list here all the types with which we instantiate getIf_impl:
+ int,
+ QString,
+ NonDefaultConstructible
+ >;
+ template <typename T>
+ void getIf_impl(T t) const;
+ template <typename T>
+ void get_impl(T t) const;
+ template<typename T>
+ void canViewAndView_ReturnFalseAndDefault_WhenConvertingBetweenPointerAndValue_impl(const QByteArray &typeName);
void dataStream_data(QDataStream::Version version);
void loadQVariantFromDataStream(QDataStream::Version version);
void saveQVariantFromDataStream(QDataStream::Version version);
@@ -306,22 +440,32 @@ void tst_QVariant::constructor()
QVariant varll2(varll);
QCOMPARE(varll2, varll);
- QVariant var3(QVariant::String);
+ QVariant var3 {QMetaType::fromType<QString>()};
QCOMPARE(var3.typeName(), "QString");
QVERIFY(var3.isNull());
QVERIFY(var3.isValid());
- QVariant var4(QVariant::Invalid);
- QCOMPARE(var4.type(), QVariant::Invalid);
+ QVariant var3a = QVariant::fromMetaType(QMetaType::fromType<QString>());
+ QCOMPARE(var3a.typeName(), "QString");
+ QVERIFY(var3a.isNull());
+ QVERIFY(var3a.isValid());
+
+ QVariant var4 {QMetaType()};
+ QCOMPARE(var4.typeId(), QMetaType::UnknownType);
QVERIFY(var4.isNull());
QVERIFY(!var4.isValid());
+ QVariant var4a = QVariant::fromMetaType(QMetaType());
+ QCOMPARE(var4a.typeId(), QMetaType::UnknownType);
+ QVERIFY(var4a.isNull());
+ QVERIFY(!var4a.isValid());
+
QVariant var5(QLatin1String("hallo"));
- QCOMPARE(var5.type(), QVariant::String);
+ QCOMPARE(var5.typeId(), QMetaType::QString);
QCOMPARE(var5.typeName(), "QString");
QVariant var6(qlonglong(0));
- QCOMPARE(var6.type(), QVariant::LongLong);
+ QCOMPARE(var6.typeId(), QMetaType::LongLong);
QCOMPARE(var6.typeName(), "qlonglong");
QVariant var7 = 5;
@@ -350,10 +494,18 @@ void tst_QVariant::constructor_invalid()
QFETCH(uint, typeId);
{
QTest::ignoreMessage(QtWarningMsg, QRegularExpression("^Trying to construct an instance of an invalid type"));
- QVariant variant(static_cast<QVariant::Type>(typeId));
+ QVariant variant {QMetaType(typeId)};
+ QVERIFY(!variant.isValid());
+ QVERIFY(variant.isNull());
+ QCOMPARE(variant.typeId(), int(QMetaType::UnknownType));
+ QCOMPARE(variant.userType(), int(QMetaType::UnknownType));
+ }
+ {
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression("^Trying to construct an instance of an invalid type"));
+ QVariant variant = QVariant::fromMetaType(QMetaType(typeId));
QVERIFY(!variant.isValid());
QVERIFY(variant.isNull());
- QCOMPARE(int(variant.type()), int(QMetaType::UnknownType));
+ QCOMPARE(variant.typeId(), int(QMetaType::UnknownType));
QCOMPARE(variant.userType(), int(QMetaType::UnknownType));
}
{
@@ -367,9 +519,9 @@ void tst_QVariant::constructor_invalid()
void tst_QVariant::copy_constructor()
{
- QVariant var7(QVariant::Int);
+ QVariant var7 {QMetaType::fromType<int>()};
QVariant var8(var7);
- QCOMPARE(var8.type(), QVariant::Int);
+ QCOMPARE(var8.typeId(), QMetaType::Int);
QVERIFY(var8.isNull());
}
@@ -380,14 +532,16 @@ void tst_QVariant::isNull()
QVariant var;
QVERIFY( var.isNull() );
- QString str1;
- QVariant var1( str1 );
- QVERIFY( !var1.isNull() );
+ QVariant empty = QString();
+ QVERIFY(empty.toString().isNull());
+ QVERIFY(!empty.isNull());
+ QVERIFY(empty.isValid());
+ QCOMPARE(empty.typeName(), "QString");
QVariant var3( QString( "blah" ) );
QVERIFY( !var3.isNull() );
- var3 = QVariant(QVariant::String);
+ var3 = QVariant(QMetaType::fromType<QString>());
QVERIFY( var3.isNull() );
QVariant var4( 0 );
@@ -400,12 +554,12 @@ void tst_QVariant::isNull()
QVERIFY( !var6.isNull() );
var6 = QVariant();
QVERIFY( var6.isNull() );
- var6.convert( QVariant::String );
+ var6.convert(QMetaType::fromType<QString>());
QVERIFY( var6.isNull() );
QVariant varLL( (qlonglong)0 );
QVERIFY( !varLL.isNull() );
- QVariant var8(QMetaType(QMetaType::Nullptr), nullptr);
+ QVariant var8(QMetaType::fromType<std::nullptr_t>(), nullptr);
QVERIFY(var8.isNull());
var8 = QVariant::fromValue<std::nullptr_t>(nullptr);
QVERIFY(var8.isNull());
@@ -414,12 +568,12 @@ void tst_QVariant::isNull()
var9 = QVariant::fromValue<QJsonValue>(QJsonValue(QJsonValue::Null));
QVERIFY(!var9.isNull());
- QVariant var10(QMetaType(QMetaType::VoidStar), nullptr);
+ QVariant var10(QMetaType::fromType<void*>(), nullptr);
QVERIFY(var10.isNull());
var10 = QVariant::fromValue<void*>(nullptr);
QVERIFY(var10.isNull());
- QVariant var11(QMetaType(QMetaType::QObjectStar), nullptr);
+ QVariant var11(QMetaType::fromType<QObject*>(), nullptr);
QVERIFY(var11.isNull());
var11 = QVariant::fromValue<QObject*>(nullptr);
QVERIFY(var11.isNull());
@@ -434,9 +588,9 @@ void tst_QVariant::swap()
{
QVariant v1 = 1, v2 = 2.0;
v1.swap(v2);
- QCOMPARE(v1.type(),QVariant::Double);
+ QCOMPARE(v1.typeId(), QMetaType::Double);
QCOMPARE(v1.toDouble(),2.0);
- QCOMPARE(v2.type(),QVariant::Int);
+ QCOMPARE(v2.typeId(), QMetaType::Int);
QCOMPARE(v2.toInt(),1);
}
@@ -461,7 +615,7 @@ void tst_QVariant::canConvert_data()
<< var << Y << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N;
var = QVariant(QByteArray());
QTest::newRow("ByteArray")
- << var << N << N << Y << N << Y << Y << N << N << N << Y << N << N << Y << N << N << N << Y << N << N << N << N << N << N << N << N << N << Y << N << N << Y << Y;
+ << var << N << N << Y << N << Y << Y << N << N << N << Y << N << N << Y << N << N << Y << Y << N << N << N << N << N << N << N << N << N << Y << N << N << Y << Y;
var = QVariant(QDate());
QTest::newRow("Date")
<< var << N << N << N << N << N << N << N << Y << Y << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << Y << N << N << N << N;
@@ -500,7 +654,7 @@ void tst_QVariant::canConvert_data()
<< var << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << Y << N << N << N << N << N << N;
var = QVariant(QString());
QTest::newRow("String")
- << var << N << N << Y << N << Y << Y << N << Y << Y << Y << Y << N << Y << N << Y << N << Y << N << N << N << N << N << N << N << N << N << Y << Y << Y << Y << Y;
+ << var << N << N << Y << N << Y << Y << N << Y << Y << Y << Y << N << Y << N << Y << Y << Y << N << N << N << N << N << N << N << N << N << Y << Y << Y << Y << Y;
var = QVariant(QStringList("entry"));
QTest::newRow("StringList")
<< var << N << N << N << N << N << N << N << N << N << N << N << N << N << N << N << Y << N << N << N << N << N << N << N << N << N << N << Y << Y << N << N << N;
@@ -510,9 +664,6 @@ void tst_QVariant::canConvert_data()
var = QVariant((uint)1);
QTest::newRow("UInt")
<< var << N << N << Y << N << Y << N << N << N << N << Y << N << N << Y << N << N << N << Y << N << N << N << N << N << N << N << N << N << Y << N << N << Y << Y;
- var = QVariant((int)1);
- QTest::newRow("Int")
- << var << N << N << Y << N << Y << N << N << N << N << Y << N << N << Y << N << Y << N << Y << N << N << N << N << N << N << N << N << N << Y << N << N << Y << Y;
var = QVariant((qulonglong)1);
QTest::newRow("ULongLong")
<< var << N << N << Y << N << Y << N << N << N << N << Y << N << N << Y << N << N << N << Y << N << N << N << N << N << N << N << N << N << Y << N << N << Y << Y;
@@ -546,13 +697,131 @@ void tst_QVariant::canConvert()
{
TST_QVARIANT_CANCONVERT_FETCH_DATA
+ // This test links against QtGui but not QtWidgets, so QSizePolicy isn't real for it.
+ QTest::ignoreMessage(QtWarningMsg, // QSizePolicy's id is 0x2000, a.k.a. 8192
+ "Trying to construct an instance of an invalid type, type id: 8192");
TST_QVARIANT_CANCONVERT_COMPARE_DATA
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
// Invalid type ids
+ QTest::ignoreMessage(QtWarningMsg,
+ "Trying to construct an instance of an invalid type, type id: -1");
QCOMPARE(val.canConvert(-1), false);
+ QTest::ignoreMessage(QtWarningMsg,
+ "Trying to construct an instance of an invalid type, type id: -23");
QCOMPARE(val.canConvert(-23), false);
+ QTest::ignoreMessage(QtWarningMsg,
+ "Trying to construct an instance of an invalid type, type id: -23876");
QCOMPARE(val.canConvert(-23876), false);
+ QTest::ignoreMessage(QtWarningMsg,
+ "Trying to construct an instance of an invalid type, type id: 23876");
QCOMPARE(val.canConvert(23876), false);
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
+}
+
+namespace {
+
+// Used for testing canConvert/convert of QObject derived types
+struct QObjectDerived : QObject
+{
+ Q_OBJECT
+};
+
+// Adds a test table row for checking value <-> pointer conversion
+// If type is a pointer, the target type is value type and vice versa.
+template<typename T>
+void addRowForPointerValueConversion()
+{
+ using ValueType = std::remove_pointer_t<T>;
+ if constexpr (!std::is_same_v<ValueType, std::nullptr_t>) {
+
+ static ValueType instance{}; // static since we may need a pointer to a valid object
+
+ QVariant variant;
+ if constexpr (std::is_pointer_v<T>)
+ variant = QVariant::fromValue(&instance);
+ else
+ variant = QVariant::fromValue(instance);
+
+ // Toggle pointer/value type
+ using TargetType = std::conditional_t<std::is_pointer_v<T>, ValueType, T *>;
+
+ const QMetaType fromType = QMetaType::fromType<T>();
+ const QMetaType toType = QMetaType::fromType<TargetType>();
+
+ QTest::addRow("%s->%s", fromType.name(), toType.name())
+ << variant << QMetaType::fromType<TargetType>();
+ }
+}
+
+} // namespace
+
+void tst_QVariant::canConvertAndConvert_ReturnFalse_WhenConvertingBetweenPointerAndValue_data()
+{
+ QTest::addColumn<QVariant>("variant");
+ QTest::addColumn<QMetaType>("targetType");
+
+#define ADD_ROW(typeName, typeNameId, realType) \
+ addRowForPointerValueConversion<realType>(); \
+ addRowForPointerValueConversion<realType *>();
+
+ // Add rows for static primitive types
+ QT_FOR_EACH_STATIC_PRIMITIVE_NON_VOID_TYPE(ADD_ROW)
+
+ // Add rows for static core types
+ QT_FOR_EACH_STATIC_CORE_CLASS(ADD_ROW)
+#undef ADD_ROW
+
+}
+
+void tst_QVariant::canConvertAndConvert_ReturnFalse_WhenConvertingBetweenPointerAndValue()
+{
+ QFETCH(QVariant, variant);
+ QFETCH(QMetaType, targetType);
+
+ QVERIFY(!variant.canConvert(targetType));
+
+ QVERIFY(!variant.convert(targetType));
+
+ // As per the documentation, when QVariant::convert fails, the
+ // QVariant is cleared and changed to the requested type.
+ QVERIFY(variant.isNull());
+ QCOMPARE(variant.metaType(), targetType);
+}
+
+void tst_QVariant::canConvertAndConvert_ReturnFalse_WhenConvertingQObjectBetweenPointerAndValue()
+{
+ // Types derived from QObject are non-copyable and require their own test.
+ // We only test pointer -> value conversion, because constructing a QVariant
+ // from a non-copyable object will just set the QVariant to null.
+
+ QObjectDerived object;
+ QVariant variant = QVariant::fromValue(&object);
+
+ constexpr QMetaType targetType = QMetaType::fromType<QObjectDerived>();
+ QVERIFY(!variant.canConvert(targetType));
+
+ QTest::ignoreMessage(
+ QtWarningMsg,
+ QRegularExpression(".*does not support destruction and copy construction"));
+
+ QVERIFY(!variant.convert(targetType));
+
+ // When the QVariant::convert fails, the QVariant is cleared, and since the target type is
+ // invalid for QVariant, the QVariant's type is also cleared to an unknown type.
+ QVERIFY(variant.isNull());
+ QCOMPARE(variant.metaType(), QMetaType());
+}
+
+void tst_QVariant::convert()
+{
+ // verify that after convert(), the variant's type has been changed
+ QVariant var = QVariant::fromValue(QString("A string"));
+ var.convert(QMetaType::fromType<int>());
+ QCOMPARE(var.metaType(), QMetaType::fromType<int>());
+ QCOMPARE(var.toInt(), 0);
}
void tst_QVariant::toInt_data()
@@ -598,12 +867,19 @@ void tst_QVariant::toInt_data()
QTest::newRow("undefined-QJsonValue") << QVariant(QJsonValue(QJsonValue::Undefined)) << 0 << false;
}
+#if QT_DEPRECATED_SINCE(6, 0)
+# define EXEC_DEPRECATED_CALL(x) QT_IGNORE_DEPRECATIONS(x)
+#else
+# define EXEC_DEPRECATED_CALL(x)
+#endif
+
void tst_QVariant::toInt()
{
QFETCH( QVariant, value );
QFETCH( int, result );
QFETCH( bool, valueOK );
- QVERIFY( value.isValid() == value.canConvert( QVariant::Int ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.isValid() == value.canConvert( QVariant::Int ) );)
+ QVERIFY( value.isValid() == value.canConvert(QMetaType::fromType<int>()) );
bool ok;
int i = value.toInt( &ok );
QCOMPARE( i, result );
@@ -652,7 +928,8 @@ void tst_QVariant::toUInt()
QFETCH( uint, result );
QFETCH( bool, valueOK );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::UInt ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::UInt ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<uint>()) );
bool ok;
uint i = value.toUInt( &ok );
@@ -676,7 +953,8 @@ void tst_QVariant::toSize()
QFETCH( QVariant, value );
QFETCH( QSize, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::Size ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::Size ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QSize>()) );
QSize i = value.toSize();
QCOMPARE( i, result );
@@ -697,7 +975,8 @@ void tst_QVariant::toSizeF()
QFETCH( QVariant, value );
QFETCH( QSizeF, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::SizeF ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::SizeF ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QSizeF>()) );
QSizeF i = value.toSizeF();
QCOMPARE( i, result );
@@ -718,7 +997,8 @@ void tst_QVariant::toLine()
QFETCH( QVariant, value );
QFETCH( QLine, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::Line ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::Line ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QLine>()) );
QLine i = value.toLine();
QCOMPARE( i, result );
@@ -739,7 +1019,8 @@ void tst_QVariant::toLineF()
QFETCH( QVariant, value );
QFETCH( QLineF, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::LineF ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::LineF ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QLineF>()) );
QLineF i = value.toLineF();
QCOMPARE( i, result );
@@ -761,7 +1042,8 @@ void tst_QVariant::toPoint()
QFETCH( QVariant, value );
QFETCH( QPoint, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::Point ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::Point ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QPoint>()) );
QPoint i = value.toPoint();
QCOMPARE( i, result );
}
@@ -782,7 +1064,8 @@ void tst_QVariant::toRect()
QFETCH( QVariant, value );
QFETCH( QRect, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::Rect ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::Rect ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QRect>()) );
QRect i = value.toRect();
QCOMPARE( i, result );
}
@@ -800,7 +1083,8 @@ void tst_QVariant::toChar()
QFETCH( QVariant, value );
QFETCH( QChar, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::Char ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::Char ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QChar>()) );
QChar i = value.toChar();
QCOMPARE( i, result );
@@ -838,7 +1122,8 @@ void tst_QVariant::toBool()
QFETCH( QVariant, value );
QFETCH( bool, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::Bool ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::Bool ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<bool>()) );
bool i = value.toBool();
QCOMPARE( i, result );
@@ -857,7 +1142,8 @@ void tst_QVariant::toPointF()
QFETCH( QVariant, value );
QFETCH( QPointF, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::PointF ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::PointF ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QPointF>()) );
QPointF d = value.toPointF();
QCOMPARE( d, result );
}
@@ -877,7 +1163,8 @@ void tst_QVariant::toRectF()
QFETCH( QVariant, value );
QFETCH( QRectF, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::RectF ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::RectF ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QRectF>()) );
QRectF d = value.toRectF();
QCOMPARE( d, result );
}
@@ -904,7 +1191,8 @@ void tst_QVariant::toDouble()
QFETCH( double, result );
QFETCH( bool, valueOK );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::Double ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::Double ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<double>()) );
bool ok;
double d = value.toDouble( &ok );
QCOMPARE( d, result );
@@ -933,7 +1221,8 @@ void tst_QVariant::toFloat()
QFETCH(float, result);
QFETCH(bool, valueOK);
QVERIFY(value.isValid());
- QVERIFY(value.canConvert(QMetaType::Float));
+ EXEC_DEPRECATED_CALL(QVERIFY(value.canConvert(QMetaType::Float));)
+ QVERIFY(value.canConvert(QMetaType::fromType<float>()));
bool ok;
float d = value.toFloat(&ok);
QCOMPARE(d, result);
@@ -984,7 +1273,8 @@ void tst_QVariant::toLongLong()
QFETCH( qlonglong, result );
QFETCH( bool, valueOK );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::LongLong ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::LongLong ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<qlonglong>()) );
bool ok;
qlonglong ll = value.toLongLong( &ok );
QCOMPARE( ll, result );
@@ -1039,7 +1329,8 @@ void tst_QVariant::toULongLong()
QFETCH( qulonglong, result );
QFETCH( bool, valueOK );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::ULongLong ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::ULongLong ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<qulonglong>()) );
bool ok;
qulonglong ll = value.toULongLong( &ok );
QCOMPARE( ll, result );
@@ -1079,12 +1370,13 @@ void tst_QVariant::toByteArray()
QFETCH( QVariant, value );
QFETCH( QByteArray, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::ByteArray ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::ByteArray ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QByteArray>()) );
QByteArray ba = value.toByteArray();
QCOMPARE( ba.isNull(), result.isNull() );
QCOMPARE( ba, result );
- QVERIFY( value.convert( QVariant::ByteArray ) );
+ QVERIFY( value.convert(QMetaType::fromType<QByteArray>()) );
QCOMPARE( value.toByteArray(), result );
}
@@ -1121,12 +1413,13 @@ void tst_QVariant::toString()
QFETCH( QVariant, value );
QFETCH( QString, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::String ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::String ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QString>()) );
QString str = value.toString();
QCOMPARE( str.isNull(), result.isNull() );
QCOMPARE( str, result );
- QVERIFY( value.convert( QVariant::String ) );
+ QVERIFY( value.convert(QMetaType::fromType<QString>()) );
QCOMPARE( value.toString(), result );
}
@@ -1145,7 +1438,8 @@ void tst_QVariant::toDate()
QFETCH( QVariant, value );
QFETCH( QDate, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::Date ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::Date ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QDate>()) );
QCOMPARE( value.toDate(), result );
}
@@ -1165,7 +1459,8 @@ void tst_QVariant::toTime()
QFETCH( QVariant, value );
QFETCH( QTime, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::Time ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::Time ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QTime>()) );
QCOMPARE( value.toTime(), result );
}
@@ -1178,8 +1473,9 @@ void tst_QVariant::toDateTime_data()
<< QDateTime( QDate( 2002, 10, 10 ), QTime( 12, 34, 56 ) );
QTest::newRow( "qdate" ) << QVariant( QDate( 2002, 10, 10 ) ) << QDateTime( QDate( 2002, 10, 10 ), QTime( 0, 0, 0 ) );
QTest::newRow( "qstring" ) << QVariant( QString( "2002-10-10T12:34:56" ) ) << QDateTime( QDate( 2002, 10, 10 ), QTime( 12, 34, 56 ) );
- QTest::newRow( "qstring-utc" ) << QVariant( QString( "2002-10-10T12:34:56Z" ) )
- << QDateTime( QDate( 2002, 10, 10 ), QTime( 12, 34, 56 ), Qt::UTC );
+ QTest::newRow("qstring-utc")
+ << QVariant(QString("2002-10-10T12:34:56Z"))
+ << QDateTime(QDate(2002, 10, 10), QTime(12, 34, 56), QTimeZone::UTC);
QTest::newRow( "qstring-with-ms" ) << QVariant( QString( "2002-10-10T12:34:56.789" ) )
<< QDateTime( QDate( 2002, 10, 10 ), QTime( 12, 34, 56, 789 ) );
}
@@ -1189,10 +1485,13 @@ void tst_QVariant::toDateTime()
QFETCH( QVariant, value );
QFETCH( QDateTime, result );
QVERIFY( value.isValid() );
- QVERIFY( value.canConvert( QVariant::DateTime ) );
+ EXEC_DEPRECATED_CALL(QVERIFY( value.canConvert( QVariant::DateTime ) );)
+ QVERIFY( value.canConvert(QMetaType::fromType<QDateTime>()) );
QCOMPARE( value.toDateTime(), result );
}
+#undef EXEC_DEPRECATED_CALL
+
void tst_QVariant::toLocale()
{
QVariant variant;
@@ -1248,16 +1547,16 @@ void tst_QVariant::writeToReadFromDataStream_data()
}
QTest::newRow( "invalid" ) << QVariant() << true;
- QTest::newRow( "bitarray_invalid" ) << QVariant(QVariant::BitArray) << true;
+ QTest::newRow( "bitarray_invalid" ) << QVariant(QMetaType::fromType<QBitArray>()) << true;
QTest::newRow( "bitarray_empty" ) << QVariant( QBitArray() ) << false;
QBitArray bitarray( 3 );
bitarray[0] = 0;
bitarray[1] = 1;
bitarray[2] = 0;
QTest::newRow( "bitarray_valid" ) << QVariant( bitarray ) << false;
- QTest::newRow( "bytearray_invalid" ) << QVariant(QVariant::ByteArray) << true;
+ QTest::newRow( "bytearray_invalid" ) << QVariant(QMetaType::fromType<QByteArray>()) << true;
QTest::newRow( "bytearray_empty" ) << QVariant( QByteArray() ) << false;
- QTest::newRow( "int_invalid") << QVariant(QVariant::Int) << true;
+ QTest::newRow( "int_invalid") << QVariant(QMetaType::fromType<int>()) << true;
QByteArray bytearray(5, ' ');
bytearray[0] = 'T';
bytearray[1] = 'e';
@@ -1265,10 +1564,10 @@ void tst_QVariant::writeToReadFromDataStream_data()
bytearray[3] = 't';
bytearray[4] = '\0';
QTest::newRow( "bytearray_valid" ) << QVariant( bytearray ) << false;
- QTest::newRow( "date_invalid" ) << QVariant(QVariant::Date) << true;
+ QTest::newRow( "date_invalid" ) << QVariant(QMetaType::fromType<QDate>()) << true;
QTest::newRow( "date_empty" ) << QVariant( QDate() ) << false;
QTest::newRow( "date_valid" ) << QVariant( QDate( 2002, 07, 06 ) ) << false;
- QTest::newRow( "datetime_invalid" ) << QVariant(QVariant::DateTime) << true;
+ QTest::newRow( "datetime_invalid" ) << QVariant(QMetaType::fromType<QDateTime>()) << true;
QTest::newRow( "datetime_empty" ) << QVariant( QDateTime() ) << false;
QTest::newRow( "datetime_valid" ) << QVariant( QDateTime( QDate( 2002, 07, 06 ), QTime( 14, 0, 0 ) ) ) << false;
QTest::newRow( "double_valid" ) << QVariant( 123.456 ) << false;
@@ -1280,22 +1579,22 @@ void tst_QVariant::writeToReadFromDataStream_data()
vMap.insert( "double", QVariant( 3.45 ) );
vMap.insert( "float", QVariant( 3.45f ) );
QTest::newRow( "map_valid" ) << QVariant( vMap ) << false;
- QTest::newRow( "point_invalid" ) << QVariant(QVariant::Point) << true;
+ QTest::newRow( "point_invalid" ) << QVariant(QMetaType::fromType<QPoint>()) << true;
QTest::newRow( "point_empty" ) << QVariant::fromValue( QPoint() ) << false;
QTest::newRow( "point_valid" ) << QVariant::fromValue( QPoint( 10, 10 ) ) << false;
- QTest::newRow( "rect_invalid" ) << QVariant(QVariant::Rect) << true;
+ QTest::newRow( "rect_invalid" ) << QVariant(QMetaType::fromType<QRect>()) << true;
QTest::newRow( "rect_empty" ) << QVariant( QRect() ) << false;
QTest::newRow( "rect_valid" ) << QVariant( QRect( 10, 10, 20, 20 ) ) << false;
- QTest::newRow( "size_invalid" ) << QVariant(QVariant::Size) << true;
+ QTest::newRow( "size_invalid" ) << QVariant(QMetaType::fromType<QSize>()) << true;
QTest::newRow( "size_empty" ) << QVariant( QSize( 0, 0 ) ) << false;
QTest::newRow( "size_valid" ) << QVariant( QSize( 10, 10 ) ) << false;
- QTest::newRow( "string_invalid" ) << QVariant(QVariant::String) << true;
+ QTest::newRow( "string_invalid" ) << QVariant(QMetaType::fromType<QString>()) << true;
QTest::newRow( "string_empty" ) << QVariant( QString() ) << false;
QTest::newRow( "string_valid" ) << QVariant( QString( "Test" ) ) << false;
QStringList stringlist;
stringlist << "One" << "Two" << "Three";
QTest::newRow( "stringlist_valid" ) << QVariant( stringlist ) << false;
- QTest::newRow( "time_invalid" ) << QVariant(QVariant::Time) << true;
+ QTest::newRow( "time_invalid" ) << QVariant(QMetaType::fromType<QTime>()) << true;
QTest::newRow( "time_empty" ) << QVariant( QTime() ) << false;
QTest::newRow( "time_valid" ) << QVariant( QTime( 14, 0, 0 ) ) << false;
QTest::newRow( "uint_valid" ) << QVariant( (uint)123 ) << false;
@@ -1305,27 +1604,27 @@ void tst_QVariant::writeToReadFromDataStream_data()
QTest::newRow( "regularexpression_empty" ) << QVariant(QRegularExpression()) << false;
// types known to QMetaType, but not part of QVariant::Type
- QTest::newRow("QMetaType::Long invalid") << QVariant(QMetaType(QMetaType::Long), nullptr) << true;
+ QTest::newRow("QMetaType::Long invalid") << QVariant(QMetaType::fromType<long>(), nullptr) << true;
long longInt = -1l;
- QTest::newRow("QMetaType::Long") << QVariant(QMetaType(QMetaType::Long), &longInt) << false;
- QTest::newRow("QMetaType::Short invalid") << QVariant(QMetaType(QMetaType::Short), nullptr) << true;
+ QTest::newRow("QMetaType::Long") << QVariant(QMetaType::fromType<long>(), &longInt) << false;
+ QTest::newRow("QMetaType::Short invalid") << QVariant(QMetaType::fromType<short>(), nullptr) << true;
short shortInt = 1;
- QTest::newRow("QMetaType::Short") << QVariant(QMetaType(QMetaType::Short), &shortInt) << false;
- QTest::newRow("QMetaType::Char invalid") << QVariant(QMetaType(QMetaType::Char), nullptr) << true;
+ QTest::newRow("QMetaType::Short") << QVariant(QMetaType::fromType<short>(), &shortInt) << false;
+ QTest::newRow("QMetaType::Char invalid") << QVariant(QMetaType::fromType<QChar>(), nullptr) << true;
char ch = 'c';
- QTest::newRow("QMetaType::Char") << QVariant(QMetaType(QMetaType::Char), &ch) << false;
- QTest::newRow("QMetaType::ULong invalid") << QVariant(QMetaType(QMetaType::ULong), nullptr) << true;
+ QTest::newRow("QMetaType::Char") << QVariant(QMetaType::fromType<char>(), &ch) << false;
+ QTest::newRow("QMetaType::ULong invalid") << QVariant(QMetaType::fromType<ulong>(), nullptr) << true;
ulong ulongInt = 1ul;
- QTest::newRow("QMetaType::ULong") << QVariant(QMetaType(QMetaType::ULong), &ulongInt) << false;
- QTest::newRow("QMetaType::UShort invalid") << QVariant(QMetaType(QMetaType::UShort), nullptr) << true;
+ QTest::newRow("QMetaType::ULong") << QVariant(QMetaType::fromType<ulong>(), &ulongInt) << false;
+ QTest::newRow("QMetaType::UShort invalid") << QVariant(QMetaType::fromType<ushort>(), nullptr) << true;
ushort ushortInt = 1u;
- QTest::newRow("QMetaType::UShort") << QVariant(QMetaType(QMetaType::UShort), &ushortInt) << false;
- QTest::newRow("QMetaType::UChar invalid") << QVariant(QMetaType(QMetaType::UChar), nullptr) << true;
+ QTest::newRow("QMetaType::UShort") << QVariant(QMetaType::fromType<ushort>(), &ushortInt) << false;
+ QTest::newRow("QMetaType::UChar invalid") << QVariant(QMetaType::fromType<uchar>(), nullptr) << true;
uchar uch = 0xf0;
- QTest::newRow("QMetaType::UChar") << QVariant(QMetaType(QMetaType::UChar), &uch) << false;
- QTest::newRow("QMetaType::Float invalid") << QVariant(QMetaType(QMetaType::Float), nullptr) << true;
+ QTest::newRow("QMetaType::UChar") << QVariant(QMetaType::fromType<uchar>(), &uch) << false;
+ QTest::newRow("QMetaType::Float invalid") << QVariant(QMetaType::fromType<float>(), nullptr) << true;
float f = 1.234f;
- QTest::newRow("QMetaType::Float") << QVariant(QMetaType(QMetaType::Float), &f) << false;
+ QTest::newRow("QMetaType::Float") << QVariant(QMetaType::fromType<float>(), &f) << false;
CustomStreamableClass custom = {123};
QTest::newRow("Custom type") << QVariant::fromValue(custom) << false;
}
@@ -1347,10 +1646,11 @@ void tst_QVariant::writeToReadFromDataStream()
// Since only a few won't match since the serial numbers are different
// I won't bother adding another bool in the data test.
const int writeType = writeVariant.userType();
- if (writeType == qMetaTypeId<CustomStreamableClass>())
- QCOMPARE(qvariant_cast<CustomStreamableClass>(readVariant), qvariant_cast<CustomStreamableClass>(writeVariant));
- else if ( writeType != QVariant::Invalid && writeType != QVariant::Bitmap && writeType != QVariant::Pixmap
- && writeType != QVariant::Image) {
+ if (writeType == qMetaTypeId<CustomStreamableClass>()) {
+ QCOMPARE(qvariant_cast<CustomStreamableClass>(readVariant),
+ qvariant_cast<CustomStreamableClass>(writeVariant));
+ } else if ( writeType != QMetaType::UnknownType && writeType != QMetaType::QBitmap
+ && writeType != QMetaType::QPixmap && writeType != QMetaType::QImage) {
switch (writeType) {
default:
QCOMPARE( readVariant, writeVariant );
@@ -1425,7 +1725,7 @@ void tst_QVariant::checkDataStream()
// constructed. However, it might be worth considering changing that behavior
// in the future.
// QCOMPARE(in.status(), QDataStream::ReadCorruptData);
- QCOMPARE(v.type(), QVariant::Invalid);
+ QCOMPARE(v.typeId(), QMetaType::UnknownType);
}
void tst_QVariant::operator_eq_eq_data()
@@ -1442,7 +1742,7 @@ void tst_QVariant::operator_eq_eq_data()
// Int
QTest::newRow( "int1int1" ) << i1 << i1 << true;
QTest::newRow( "int1int0" ) << i1 << i0 << false;
- QTest::newRow( "nullint" ) << i0 << QVariant(QVariant::Int) << true;
+ QTest::newRow( "nullint" ) << i0 << QVariant(QMetaType::fromType<int>()) << true;
// LongLong and ULongLong
QVariant ll1( (qlonglong)1 );
@@ -1460,6 +1760,10 @@ void tst_QVariant::operator_eq_eq_data()
QVariant mIntString(QByteArray("-42"));
QVariant mIntQString(QString("-42"));
+ QVariant mIntZero(0);
+ QVariant mIntStringZero(QByteArray("0"));
+ QVariant mIntQStringZero(QString("0"));
+
QVariant mUInt(42u);
QVariant mUIntString(QByteArray("42"));
QVariant mUIntQString(QString("42"));
@@ -1500,6 +1804,9 @@ void tst_QVariant::operator_eq_eq_data()
QVariant mBoolString(QByteArray("false"));
QVariant mBoolQString(QString("false"));
+ QVariant mTextString(QByteArray("foobar"));
+ QVariant mTextQString(QString("foobar"));
+
QTest::newRow( "double_int" ) << QVariant(42.0) << QVariant(42) << true;
QTest::newRow( "float_int" ) << QVariant(42.f) << QVariant(42) << true;
QTest::newRow( "mInt_mIntString" ) << mInt << mIntString << false;
@@ -1507,6 +1814,21 @@ void tst_QVariant::operator_eq_eq_data()
QTest::newRow( "mInt_mIntQString" ) << mInt << mIntQString << true;
QTest::newRow( "mIntQString_mInt" ) << mIntQString << mInt << true;
+ QTest::newRow( "mIntZero_mIntStringZero" ) << mIntZero << mIntStringZero << false;
+ QTest::newRow( "mIntStringZero_mIntZero" ) << mIntStringZero << mIntZero << false;
+ QTest::newRow( "mIntZero_mIntQStringZero" ) << mIntZero << mIntQStringZero << true;
+ QTest::newRow( "mIntQStringZero_mIntZero" ) << mIntQStringZero << mIntZero << true;
+
+ QTest::newRow( "mInt_mTextString" ) << mInt << mTextString << false;
+ QTest::newRow( "mTextString_mInt" ) << mTextString << mInt << false;
+ QTest::newRow( "mInt_mTextQString" ) << mInt << mTextQString << false;
+ QTest::newRow( "mTextQString_mInt" ) << mTextQString << mInt << false;
+
+ QTest::newRow( "mIntZero_mTextString" ) << mIntZero << mTextString << false;
+ QTest::newRow( "mTextString_mIntZero" ) << mTextString << mIntZero << false;
+ QTest::newRow( "mIntZero_mTextQString" ) << mIntZero << mTextQString << false;
+ QTest::newRow( "mTextQString_mIntZero" ) << mTextQString << mIntZero << false;
+
QTest::newRow( "mUInt_mUIntString" ) << mUInt << mUIntString << false;
QTest::newRow( "mUIntString_mUInt" ) << mUIntString << mUInt << false;
QTest::newRow( "mUInt_mUIntQString" ) << mUInt << mUIntQString << true;
@@ -1517,6 +1839,11 @@ void tst_QVariant::operator_eq_eq_data()
QTest::newRow( "mDouble_mDoubleQString" ) << mDouble << mDoubleQString << true;
QTest::newRow( "mDoubleQString_mDouble" ) << mDoubleQString << mDouble << true;
+ QTest::newRow( "mDouble_mTextString" ) << mDouble << mTextString << false;
+ QTest::newRow( "mTextString_mDouble" ) << mTextString << mDouble << false;
+ QTest::newRow( "mDouble_mTextQString" ) << mDouble << mTextQString << false;
+ QTest::newRow( "mTextQString_mDouble" ) << mTextQString << mDouble << false;
+
QTest::newRow( "mFloat_mFloatString" ) << mFloat << mFloatString << false;
QTest::newRow( "mFloatString_mFloat" ) << mFloatString << mFloat << false;
QTest::newRow( "mFloat_mFloatQString" ) << mFloat << mFloatQString << true;
@@ -1683,9 +2010,11 @@ void tst_QVariant::operator_eq_eq()
QFETCH( QVariant, left );
QFETCH( QVariant, right );
QFETCH( bool, equal );
- QCOMPARE( left == right, equal );
+ QT_TEST_EQUALITY_OPS(left, right, equal);
}
+#if QT_DEPRECATED_SINCE(6, 0)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
void tst_QVariant::typeName_data()
{
QTest::addColumn<int>("type");
@@ -1758,17 +2087,23 @@ void tst_QVariant::typeToName()
// assumes that QVariant::Type contains consecutive values
int max = QVariant::LastGuiType;
- for ( int t = 1; t <= max; t++ ) {
+ for (int t = 1; t <= max; ++t) {
+ if (!QMetaType::isRegistered(t)) {
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression(
+ "^Trying to construct an instance of an invalid type"));
+ }
const char *n = QVariant::typeToName( (QVariant::Type)t );
if (n)
QCOMPARE( int(QVariant::nameToType( n )), t );
-
}
+
QCOMPARE(QVariant::typeToName(QVariant::Int), "int");
// not documented but we return 0 if the type is out of range
// by testing this we catch cases where QVariant is extended
// but type_map is not updated accordingly
- QCOMPARE( QVariant::typeToName( QVariant::Type(max+1) ), (char*)0 );
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression(
+ "^Trying to construct an instance of an invalid type"));
+ QCOMPARE(QVariant::typeToName(QVariant::Type(max + 1)), (const char *)nullptr);
// invalid type names
QVERIFY( QVariant::nameToType( 0 ) == QVariant::Invalid );
QVERIFY( QVariant::nameToType( "" ) == QVariant::Invalid );
@@ -1782,6 +2117,8 @@ void tst_QVariant::typeToName()
QCOMPARE(QVariant::nameToType("Q_LLONG"), QVariant::Invalid);
QCOMPARE(QVariant::nameToType("Q_ULLONG"), QVariant::Invalid);
}
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 0)
void tst_QVariant::streamInvalidVariant()
{
@@ -1792,7 +2129,7 @@ void tst_QVariant::streamInvalidVariant()
QVariant writeVariant;
QVariant readVariant;
- QVERIFY( writeVariant.type() == QVariant::Invalid );
+ QVERIFY( writeVariant.typeId() == QMetaType::UnknownType );
QByteArray data;
QDataStream writeStream( &data, QIODevice::WriteOnly );
@@ -1804,7 +2141,7 @@ void tst_QVariant::streamInvalidVariant()
QVERIFY( readX == writeX );
// Two invalid QVariant's aren't necessarily the same, so == will
// return false if one is invalid, so check the type() instead
- QVERIFY( readVariant.type() == QVariant::Invalid );
+ QVERIFY( readVariant.typeId() == QMetaType::UnknownType );
QVERIFY( readY == writeY );
}
@@ -1850,7 +2187,9 @@ void tst_QVariant::userType()
QVariant userVar;
userVar.setValue(data);
- QCOMPARE(userVar.type(), QVariant::UserType);
+ QVERIFY(QMetaType::fromName("MyType").isValid());
+ QCOMPARE(QMetaType::fromName("MyType"), QMetaType::fromType<MyType>());
+ QVERIFY(userVar.typeId() > QMetaType::User);
QCOMPARE(userVar.userType(), qMetaTypeId<MyType>());
QCOMPARE(userVar.typeName(), "MyType");
QVERIFY(!userVar.isNull());
@@ -1879,7 +2218,7 @@ void tst_QVariant::userType()
QVariant userVar;
userVar.setValue(&data);
- QCOMPARE(userVar.type(), QVariant::UserType);
+ QVERIFY(userVar.typeId() > QMetaType::User);
QCOMPARE(userVar.userType(), qMetaTypeId<MyType*>());
QCOMPARE(userVar.typeName(), "MyType*");
QVERIFY(!userVar.isNull());
@@ -1912,7 +2251,7 @@ void tst_QVariant::userType()
QCOMPARE(instanceCount, 3);
{
QVariant second = myCarrier;
- QCOMPARE(instanceCount, 4);
+ QCOMPARE(instanceCount, 3);
second.detach();
QCOMPARE(instanceCount, 4);
}
@@ -1973,7 +2312,15 @@ void tst_QVariant::podUserType()
pod.a = 10;
pod.b = 20;
+ // one of these two must register the type
+ // (QVariant::fromValue calls QMetaType::fromType)
QVariant pod_as_variant = QVariant::fromValue(pod);
+ QMetaType mt = QMetaType::fromType<MyTypePOD>();
+ QCOMPARE(pod_as_variant.metaType(), mt);
+ QCOMPARE(pod_as_variant.metaType().name(), mt.name());
+ QCOMPARE(QMetaType::fromName(mt.name()), mt);
+ QCOMPARE_NE(pod_as_variant.typeId(), 0);
+
MyTypePOD pod2 = qvariant_cast<MyTypePOD>(pod_as_variant);
QCOMPARE(pod.a, pod2.a);
@@ -1991,37 +2338,37 @@ void tst_QVariant::basicUserType()
QVariant v;
{
int i = 7;
- v = QVariant(QMetaType(QMetaType::Int), &i);
+ v = QVariant(QMetaType::fromType<int>(), &i);
}
- QCOMPARE(v.type(), QVariant::Int);
+ QCOMPARE(v.typeId(), QMetaType::Int);
QCOMPARE(v.toInt(), 7);
{
QString s("foo");
- v = QVariant(QMetaType(QMetaType::QString), &s);
+ v = QVariant(QMetaType::fromType<QString>(), &s);
}
- QCOMPARE(v.type(), QVariant::String);
+ QCOMPARE(v.typeId(), QMetaType::QString);
QCOMPARE(v.toString(), QString("foo"));
{
double d = 4.4;
- v = QVariant(QMetaType(QMetaType::Double), &d);
+ v = QVariant(QMetaType::fromType<double>(), &d);
}
- QCOMPARE(v.type(), QVariant::Double);
+ QCOMPARE(v.typeId(), QMetaType::Double);
QCOMPARE(v.toDouble(), 4.4);
{
float f = 4.5f;
- v = QVariant(QMetaType(QMetaType::Float), &f);
+ v = QVariant(QMetaType::fromType<float>(), &f);
}
QCOMPARE(v.userType(), int(QMetaType::Float));
QCOMPARE(v.toDouble(), 4.5);
{
QByteArray ba("bar");
- v = QVariant(QMetaType(QMetaType::QByteArray), &ba);
+ v = QVariant(QMetaType::fromType<QByteArray>(), &ba);
}
- QCOMPARE(v.type(), QVariant::ByteArray);
+ QCOMPARE(v.typeId(), QMetaType::QByteArray);
QCOMPARE(v.toByteArray(), QByteArray("bar"));
}
@@ -2186,7 +2533,7 @@ void tst_QVariant::saveLoadCustomTypes()
QVariant v = QVariant(tp, &i);
QCOMPARE(v.userType(), tp.id());
- QCOMPARE(v.type(), QVariant::UserType);
+ QVERIFY(v.typeId() > QMetaType::User);
{
QDataStream stream(&data, QIODevice::WriteOnly);
stream << v;
@@ -2199,7 +2546,7 @@ void tst_QVariant::saveLoadCustomTypes()
stream >> v;
}
- QCOMPARE(int(v.userType()), QMetaType::type("Blah"));
+ QCOMPARE(int(v.userType()), QMetaType::fromName("Blah").id());
int value = *(int*)v.constData();
QCOMPARE(value, 42);
}
@@ -2277,7 +2624,7 @@ void tst_QVariant::variantHash()
class CustomQObject : public QObject {
Q_OBJECT
public:
- CustomQObject(QObject *parent = 0) : QObject(parent) {}
+ CustomQObject(QObject *parent = nullptr) : QObject(parent) {}
};
Q_DECLARE_METATYPE(CustomQObject*)
@@ -2298,7 +2645,7 @@ void tst_QVariant::qvariant_cast_QObject_data()
QTest::addColumn<bool>("isNull");
QObject *obj = new QObject;
obj->setObjectName(QString::fromLatin1("Hello"));
- QTest::newRow("from QObject") << QVariant(QMetaType(QMetaType::QObjectStar), &obj) << true << false;
+ QTest::newRow("from QObject") << QVariant(QMetaType::fromType<QObject*>(), &obj) << true << false;
QTest::newRow("from QObject2") << QVariant::fromValue(obj) << true << false;
QTest::newRow("from String") << QVariant(QLatin1String("1, 2, 3")) << false << false;
QTest::newRow("from int") << QVariant((int) 123) << false << false;
@@ -2333,32 +2680,32 @@ void tst_QVariant::qvariant_cast_QObject()
if (!isNull)
QCOMPARE(o->objectName(), QString::fromLatin1("Hello"));
QVERIFY(data.canConvert<QObject*>());
- QVERIFY(data.canConvert(QMetaType::QObjectStar));
- QVERIFY(data.canConvert(::qMetaTypeId<QObject*>()));
- QCOMPARE(data.value<QObject*>() == 0, isNull);
- QVERIFY(data.convert(QMetaType::QObjectStar));
+ QVERIFY(data.canConvert(QMetaType::fromType<QObject*>()));
+ QVERIFY(data.canConvert(QMetaType(::qMetaTypeId<QObject*>())));
+ QCOMPARE(data.value<QObject*>() == nullptr, isNull);
+ QVERIFY(data.convert(QMetaType::fromType<QObject*>()));
QCOMPARE(data.userType(), int(QMetaType::QObjectStar));
} else {
QVERIFY(!data.canConvert<QObject*>());
- QVERIFY(!data.canConvert(QMetaType::QObjectStar));
- QVERIFY(!data.canConvert(::qMetaTypeId<QObject*>()));
+ QVERIFY(!data.canConvert(QMetaType::fromType<QObject*>()));
+ QVERIFY(!data.canConvert(QMetaType(::qMetaTypeId<QObject*>())));
QVERIFY(!data.value<QObject*>());
- QVERIFY(!data.convert(QMetaType::QObjectStar));
QVERIFY(data.userType() != QMetaType::QObjectStar);
+ QVERIFY(!data.convert(QMetaType::fromType<QObject*>()));
}
}
class CustomQObjectDerived : public CustomQObject {
Q_OBJECT
public:
- CustomQObjectDerived(QObject *parent = 0) : CustomQObject(parent) {}
+ CustomQObjectDerived(QObject *parent = nullptr) : CustomQObject(parent) {}
};
Q_DECLARE_METATYPE(CustomQObjectDerived*)
class CustomQObjectDerivedNoMetaType : public CustomQObject {
Q_OBJECT
public:
- CustomQObjectDerivedNoMetaType(QObject *parent = 0) : CustomQObject(parent) {}
+ CustomQObjectDerivedNoMetaType(QObject *parent = nullptr) : CustomQObject(parent) {}
};
void tst_QVariant::qvariant_cast_QObject_derived()
@@ -2385,7 +2732,7 @@ void tst_QVariant::qvariant_cast_QObject_derived()
QObject *object = new CustomQObjectDerivedNoMetaType(this);
QVariant data = QVariant::fromValue(object);
QVERIFY(data.canConvert<CustomQObjectDerivedNoMetaType*>());
- QVERIFY(data.convert(qMetaTypeId<CustomQObjectDerivedNoMetaType*>()));
+ QVERIFY(data.convert(QMetaType(qMetaTypeId<CustomQObjectDerivedNoMetaType*>())));
QCOMPARE(data.value<CustomQObjectDerivedNoMetaType*>(), object);
QCOMPARE(data.isNull(), false);
}
@@ -2393,7 +2740,7 @@ void tst_QVariant::qvariant_cast_QObject_derived()
struct QObjectWrapper
{
- explicit QObjectWrapper(QObject *o = 0) : obj(o) {}
+ explicit QObjectWrapper(QObject *o = nullptr) : obj(o) {}
QObject* getObject() const {
return obj;
@@ -2422,7 +2769,7 @@ class SmartPointer
T* pointer;
public:
typedef T element_type;
- explicit SmartPointer(T *t = 0)
+ explicit SmartPointer(T *t = nullptr)
: pointer(t)
{
}
@@ -2465,7 +2812,7 @@ void tst_QVariant::qvariant_cast_QObject_wrapper()
QObjectWrapper wrapper(object);
QVariant v = QVariant::fromValue(wrapper);
QCOMPARE(v.value<QObject*>(), object);
- v.convert(qMetaTypeId<QObject*>());
+ v.convert(QMetaType(qMetaTypeId<QObject*>()));
QCOMPARE(v.value<QObject*>(), object);
MyNS::SequentialContainer<int> sc;
@@ -2568,6 +2915,17 @@ void tst_QVariant::qvariant_cast_QSharedPointerQObject()
qRegisterMetaType<QSharedPointer<QObject> >();
}
+void tst_QVariant::qvariant_cast_const()
+{
+ int i = 42;
+ QVariant v = QVariant::fromValue(&i);
+ QVariant vConst = QVariant::fromValue(const_cast<const int*>(&i));
+ QCOMPARE(v.value<int *>(), &i);
+ QCOMPARE(v.value<const int *>(), &i);
+ QCOMPARE(vConst.value<int *>(), nullptr);
+ QCOMPARE(vConst.value<const int *>(), &i);
+}
+
void tst_QVariant::convertToQUint8() const
{
/* qint8. */
@@ -2625,18 +2983,289 @@ void tst_QVariant::convertToQUint8() const
}
}
-void tst_QVariant::comparePointers() const
+void tst_QVariant::compareCompiles() const
{
- class MyClass
- {
+ QTestPrivate::testEqualityOperatorsCompile<QVariant>();
+}
+
+void tst_QVariant::compareNumerics_data() const
+{
+ QTest::addColumn<QVariant>("v1");
+ QTest::addColumn<QVariant>("v2");
+ QTest::addColumn<QPartialOrdering>("result");
+
+ QTest::addRow("invalid-invalid")
+ << QVariant() << QVariant() << QPartialOrdering::Unordered;
+
+ static const auto asString = [](const QVariant &v) {
+ if (v.isNull())
+ return QStringLiteral("null");
+ if (v.metaType().flags() & QMetaType::IsEnumeration)
+ return v.metaType().flags() & QMetaType::IsUnsignedEnumeration ?
+ QString::number(v.toULongLong()) :
+ QString::number(v.toLongLong());
+ switch (v.typeId()) {
+ case QMetaType::Char16:
+ return QString::number(qvariant_cast<char16_t>(v));
+ case QMetaType::Char32:
+ return QString::number(qvariant_cast<char32_t>(v));
+ case QMetaType::Char:
+ case QMetaType::UChar:
+ return QString::number(v.toUInt());
+ case QMetaType::SChar:
+ return QString::number(v.toInt());
+ }
+ return v.toString();
};
- MyClass myClass;
+ auto addCompareToInvalid = [](auto value) {
+ QVariant v = QVariant::fromValue(value);
+ QTest::addRow("invalid-%s(%s)", v.typeName(), qPrintable(asString(v)))
+ << QVariant() << v << QPartialOrdering::Unordered;
+ QTest::addRow("%s(%s)-invalid", v.typeName(), qPrintable(asString(v)))
+ << v << QVariant() << QPartialOrdering::Unordered;
+ };
+ addCompareToInvalid(false);
+ addCompareToInvalid(true);
+ addCompareToInvalid(char(0));
+ addCompareToInvalid(qint8(0));
+ addCompareToInvalid(quint8(0));
+ addCompareToInvalid(short(0));
+ addCompareToInvalid(ushort(0));
+ addCompareToInvalid(int(0));
+ addCompareToInvalid(uint(0));
+ addCompareToInvalid(long(0));
+ addCompareToInvalid(ulong(0));
+ addCompareToInvalid(qint64(0));
+ addCompareToInvalid(quint64(0));
+ addCompareToInvalid(0.f);
+ addCompareToInvalid(0.0);
+ addCompareToInvalid(QCborSimpleType{});
+
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_CLANG("-Wsign-compare")
+QT_WARNING_DISABLE_GCC("-Wsign-compare")
+QT_WARNING_DISABLE_MSVC(4018) // '<': signed/unsigned mismatch
+ static const auto addComparePairWithResult = [](auto value1, auto value2, QPartialOrdering order) {
+ QVariant v1 = QVariant::fromValue(value1);
+ QVariant v2 = QVariant::fromValue(value2);
+ QTest::addRow("%s(%s)-%s(%s)", v1.typeName(), qPrintable(asString(v1)),
+ v2.typeName(), qPrintable(asString(v2)))
+ << v1 << v2 << order;
+ };
+
+ static const auto addComparePair = [](auto value1, auto value2) {
+ QPartialOrdering order = QPartialOrdering::Unordered;
+ if (value1 == value2)
+ order = QPartialOrdering::Equivalent;
+ else if (value1 < value2)
+ order = QPartialOrdering::Less;
+ else if (value1 > value2)
+ order = QPartialOrdering::Greater;
+ addComparePairWithResult(value1, value2, order);
+ };
+QT_WARNING_POP
+
+ // homogeneous first
+ static const auto addList = [](auto list) {
+ for (auto v1 : list)
+ for (auto v2 : list)
+ addComparePair(v1, v2);
+ };
+
+ auto addSingleType = [](auto zero) {
+ using T = decltype(zero);
+ T one = T(zero + 1);
+ T min = std::numeric_limits<T>::min();
+ T max = std::numeric_limits<T>::max();
+ T mid = max / 2 + 1;
+ if (min != zero)
+ addList(std::array{zero, one, min, mid, max});
+ else
+ addList(std::array{zero, one, mid, max});
+ };
+ addList(std::array{ false, true });
+ addList(std::array{ QCborSimpleType{}, QCborSimpleType::False, QCborSimpleType(0xff) });
+ addSingleType(char(0));
+ addSingleType(char16_t(0));
+ addSingleType(char32_t(0));
+ addSingleType(qint8(0));
+ addSingleType(quint8(0));
+ addSingleType(qint16(0));
+ addSingleType(quint16(0));
+ addSingleType(qint32(0));
+ addSingleType(quint32(0));
+ addSingleType(qint64(0));
+ addSingleType(quint64(0));
+ addSingleType(0.f);
+ addSingleType(0.0);
+ addList(std::array{ EnumTest_Enum0{}, EnumTest_Enum0_value, EnumTest_Enum0_negValue });
+ addList(std::array{ EnumTest_Enum1{}, EnumTest_Enum1_value, EnumTest_Enum1_bigValue });
+ addList(std::array{ EnumTest_Enum7{}, EnumTest_Enum7::EnumTest_Enum7_value, EnumTest_Enum7::ensureSignedEnum7 });
+ addList(std::array{ Qt::AlignRight|Qt::AlignHCenter, Qt::AlignCenter|Qt::AlignVCenter });
+
+ // heterogeneous
+ addComparePair(char(0), qint8(-127));
+ addComparePair(char(127), qint8(127));
+ addComparePair(char(127), quint8(127));
+ addComparePair(qint8(-1), quint8(255));
+ addComparePair(char16_t(256), qint8(-1));
+ addComparePair(char16_t(256), short(-1));
+ addComparePair(char16_t(256), int(-1));
+ addComparePair(char32_t(256), int(-1));
+ addComparePair(0U, -1);
+ addComparePair(~0U, -1);
+ addComparePair(Q_UINT64_C(0), -1);
+ addComparePair(~Q_UINT64_C(0), -1);
+ addComparePair(Q_UINT64_C(0), Q_INT64_C(-1));
+ addComparePair(~Q_UINT64_C(0), Q_INT64_C(-1));
+ addComparePair(INT_MAX, uint(INT_MAX));
+ addComparePair(INT_MAX, qint64(INT_MAX) + 1);
+ addComparePair(INT_MAX, UINT_MAX);
+ addComparePair(INT_MAX, qint64(UINT_MAX));
+ addComparePair(INT_MAX, qint64(UINT_MAX) + 1);
+ addComparePair(INT_MAX, quint64(UINT_MAX));
+ addComparePair(INT_MAX, quint64(UINT_MAX) + 1);
+ addComparePair(INT_MAX, LONG_MIN);
+ addComparePair(INT_MAX, LONG_MAX);
+ addComparePair(INT_MAX, LLONG_MIN);
+ addComparePair(INT_MAX, LLONG_MAX);
+ addComparePair(INT_MIN, uint(INT_MIN));
+ addComparePair(INT_MIN, uint(INT_MIN) + 1);
+ addComparePair(INT_MIN + 1, uint(INT_MIN));
+ addComparePair(INT_MIN + 1, uint(INT_MIN) + 1);
+ addComparePair(INT_MIN, qint64(INT_MIN) - 1);
+ addComparePair(INT_MIN + 1, qint64(INT_MIN) + 1);
+ addComparePair(INT_MIN + 1, qint64(INT_MIN) - 1);
+ addComparePair(INT_MIN, UINT_MAX);
+ addComparePair(INT_MIN, qint64(UINT_MAX));
+ addComparePair(INT_MIN, qint64(UINT_MAX) + 1);
+ addComparePair(INT_MIN, quint64(UINT_MAX));
+ addComparePair(INT_MIN, quint64(UINT_MAX) + 1);
+ addComparePair(UINT_MAX, qint64(UINT_MAX) + 1);
+ addComparePair(UINT_MAX, quint64(UINT_MAX) + 1);
+ addComparePair(UINT_MAX, qint64(INT_MIN) - 1);
+ addComparePair(UINT_MAX, quint64(INT_MIN) + 1);
+ addComparePair(LLONG_MAX, quint64(LLONG_MAX));
+ addComparePair(LLONG_MAX, quint64(LLONG_MAX) + 1);
+ addComparePair(LLONG_MIN, quint64(LLONG_MAX));
+ addComparePair(LLONG_MIN, quint64(LLONG_MAX) + 1);
+ addComparePair(LLONG_MIN, quint64(LLONG_MIN) + 1);
+ addComparePair(LLONG_MIN + 1, quint64(LLONG_MIN) + 1);
+ addComparePair(LLONG_MIN, LLONG_MAX - 1);
+ // addComparePair(LLONG_MIN, LLONG_MAX); // already added by addSingleType()
+
+ // floating point
+ addComparePair(0.f, 0);
+ addComparePair(0.f, 0U);
+ addComparePair(0.f, Q_INT64_C(0));
+ addComparePair(0.f, Q_UINT64_C(0));
+ addComparePair(0.f, 0.);
+ addComparePair(0.f, 1.);
+ addComparePair(float(1 << 24), 1 << 24);
+ addComparePair(float(1 << 24) - 1, (1 << 24) - 1);
+ addComparePair(-float(1 << 24), 1 << 24);
+ addComparePair(-float(1 << 24) + 1, -(1 << 24) + 1);
+ addComparePair(HUGE_VALF, qInf());
+ addComparePair(HUGE_VALF, -qInf());
+ addComparePair(qQNaN(), std::numeric_limits<float>::quiet_NaN());
+ if (sizeof(qreal) == sizeof(double)) {
+ addComparePair(std::numeric_limits<float>::min(), std::numeric_limits<double>::min());
+ addComparePair(std::numeric_limits<float>::min(), std::numeric_limits<double>::max());
+ addComparePair(std::numeric_limits<float>::max(), std::numeric_limits<double>::min());
+ addComparePair(std::numeric_limits<float>::max(), std::numeric_limits<double>::max());
+ addComparePair(double(Q_INT64_C(1) << 53), Q_INT64_C(1) << 53);
+ addComparePair(double(Q_INT64_C(1) << 53) - 1, (Q_INT64_C(1) << 53) - 1);
+ addComparePair(-double(Q_INT64_C(1) << 53), Q_INT64_C(1) << 53);
+ addComparePair(-double(Q_INT64_C(1) << 53) + 1, (Q_INT64_C(1) << 53) + 1);
+ }
+
+ // enums vs integers
+ addComparePair(EnumTest_Enum0_value, 0);
+ addComparePair(EnumTest_Enum0_value, 0U);
+ addComparePair(EnumTest_Enum0_value, 0LL);
+ addComparePair(EnumTest_Enum0_value, 0ULL);
+ addComparePair(EnumTest_Enum0_value, int(EnumTest_Enum0_value));
+ addComparePair(EnumTest_Enum0_value, qint64(EnumTest_Enum0_value));
+ addComparePair(EnumTest_Enum0_value, quint64(EnumTest_Enum0_value));
+ addComparePair(EnumTest_Enum0_negValue, int(EnumTest_Enum0_value));
+ addComparePair(EnumTest_Enum0_negValue, qint64(EnumTest_Enum0_value));
+ addComparePair(EnumTest_Enum0_negValue, quint64(EnumTest_Enum0_value));
+ addComparePair(EnumTest_Enum0_negValue, int(EnumTest_Enum0_negValue));
+ addComparePair(EnumTest_Enum0_negValue, qint64(EnumTest_Enum0_negValue));
+ addComparePair(EnumTest_Enum0_negValue, quint64(EnumTest_Enum0_negValue));
+
+ addComparePair(EnumTest_Enum1_value, 0);
+ addComparePair(EnumTest_Enum1_value, 0U);
+ addComparePair(EnumTest_Enum1_value, 0LL);
+ addComparePair(EnumTest_Enum1_value, 0ULL);
+ addComparePair(EnumTest_Enum1_value, int(EnumTest_Enum1_value));
+ addComparePair(EnumTest_Enum1_value, qint64(EnumTest_Enum1_value));
+ addComparePair(EnumTest_Enum1_value, quint64(EnumTest_Enum1_value));
+ addComparePair(EnumTest_Enum1_bigValue, int(EnumTest_Enum1_value));
+ addComparePair(EnumTest_Enum1_bigValue, qint64(EnumTest_Enum1_value));
+ addComparePair(EnumTest_Enum1_bigValue, quint64(EnumTest_Enum1_value));
+ addComparePair(EnumTest_Enum1_bigValue, int(EnumTest_Enum1_bigValue));
+ addComparePair(EnumTest_Enum1_bigValue, qint64(EnumTest_Enum1_bigValue));
+ addComparePair(EnumTest_Enum1_bigValue, quint64(EnumTest_Enum1_bigValue));
+
+ addComparePair(EnumTest_Enum3_value, 0);
+ addComparePair(EnumTest_Enum3_value, 0U);
+ addComparePair(EnumTest_Enum3_value, 0LL);
+ addComparePair(EnumTest_Enum3_value, 0ULL);
+ addComparePair(EnumTest_Enum3_value, int(EnumTest_Enum3_value));
+ addComparePair(EnumTest_Enum3_value, qint64(EnumTest_Enum3_value));
+ addComparePair(EnumTest_Enum3_value, quint64(EnumTest_Enum3_value));
+ addComparePair(EnumTest_Enum3_bigValue, int(EnumTest_Enum3_value));
+ addComparePair(EnumTest_Enum3_bigValue, qint64(EnumTest_Enum3_value));
+ addComparePair(EnumTest_Enum3_bigValue, quint64(EnumTest_Enum3_value));
+ addComparePair(EnumTest_Enum3_bigValue, int(EnumTest_Enum3_bigValue));
+ addComparePair(EnumTest_Enum3_bigValue, qint64(EnumTest_Enum3_bigValue));
+ addComparePair(EnumTest_Enum3_bigValue, quint64(EnumTest_Enum3_bigValue));
+
+ // enums of different types always compare as unordered
+ addComparePairWithResult(EnumTest_Enum0_value, EnumTest_Enum1_value, QPartialOrdering::Unordered);
+}
+
+void tst_QVariant::compareNumerics() const
+{
+ QFETCH(QVariant, v1);
+ QFETCH(QVariant, v2);
+ QFETCH(QPartialOrdering, result);
+ QCOMPARE(QVariant::compare(v1, v2), result);
+
+ QEXPECT_FAIL("invalid-invalid", "needs fixing", Abort);
+ QT_TEST_EQUALITY_OPS(v1, v2, is_eq(result));
+}
+
+void tst_QVariant::comparePointers() const
+{
+ class NonQObjectClass {};
+ const std::array<NonQObjectClass, 2> arr{ NonQObjectClass{}, NonQObjectClass{} };
+
+ const QVariant nonObjV1 = QVariant::fromValue<const void*>(&arr[0]);
+ const QVariant nonObjV2 = QVariant::fromValue<const void*>(&arr[1]);
+
+ Qt::partial_ordering expectedOrdering = Qt::partial_ordering::equivalent;
+ QCOMPARE(QVariant::compare(nonObjV1, nonObjV1), expectedOrdering);
+ QT_TEST_EQUALITY_OPS(nonObjV1, nonObjV1, is_eq(expectedOrdering));
+
+ expectedOrdering = Qt::partial_ordering::less;
+ QCOMPARE(QVariant::compare(nonObjV1, nonObjV2), expectedOrdering);
+ QT_TEST_EQUALITY_OPS(nonObjV1, nonObjV2, is_eq(expectedOrdering));
- QVariant v = QVariant::fromValue<void *>(&myClass);
- QVariant v2 = QVariant::fromValue<void *>(&myClass);
+ class QObjectClass : public QObject
+ {
+ public:
+ QObjectClass(QObject *parent = nullptr) : QObject(parent) {}
+ };
+ const QObjectClass c1;
+ const QObjectClass c2;
- QCOMPARE(v, v2);
+ const QVariant objV1 = QVariant::fromValue(&c1);
+ const QVariant objV2 = QVariant::fromValue(&c2);
+ QT_TEST_EQUALITY_OPS(objV1, objV1, true);
+ QT_TEST_EQUALITY_OPS(objV1, objV2, false);
}
struct Data {};
@@ -2656,7 +3285,7 @@ void tst_QVariant::voidStar() const
v2 = QVariant::fromValue(p2);
QCOMPARE(v1, v2);
- p2 = 0;
+ p2 = nullptr;
v2 = QVariant::fromValue(p2);
QVERIFY(v1 != v2);
}
@@ -2753,7 +3382,7 @@ void tst_QVariant::variantToDateTimeWithoutWarnings() const
{
QVariant v1(QLatin1String("xyz"));
- v1.convert(QVariant::DateTime);
+ v1.convert(QMetaType::fromType<QDateTime>());
QVariant v2(QLatin1String("xyz"));
QDateTime dt1(v2.toDateTime());
@@ -2767,7 +3396,7 @@ void tst_QVariant::invalidDateTime() const
{
QVariant variant(QString::fromLatin1("Invalid date time string"));
QVERIFY(!variant.toDateTime().isValid());
- QVERIFY(!variant.convert(QVariant::DateTime));
+ QVERIFY(!variant.convert(QMetaType::fromType<QDateTime>()));
}
struct MyClass
@@ -2808,22 +3437,22 @@ void tst_QVariant::invalidDate() const
{
QString foo("Hello");
QVariant variant(foo);
- QVERIFY(!variant.convert(QVariant::Date));
+ QVERIFY(!variant.convert(QMetaType::fromType<QDate>()));
variant = foo;
- QVERIFY(!variant.convert(QVariant::DateTime));
+ QVERIFY(!variant.convert(QMetaType::fromType<QDateTime>()));
variant = foo;
- QVERIFY(!variant.convert(QVariant::Time));
+ QVERIFY(!variant.convert(QMetaType::fromType<QTime>()));
variant = foo;
- QVERIFY(!variant.convert(QVariant::Int));
+ QVERIFY(!variant.convert(QMetaType::fromType<int>()));
variant = foo;
- QVERIFY(!variant.convert(QVariant::Double));
+ QVERIFY(!variant.convert(QMetaType::fromType<double>()));
variant = foo;
- QVERIFY(!variant.convert(QVariant::Type(QMetaType::Float)));
+ QVERIFY(!variant.convert(QMetaType::fromType<float>()));
}
struct WontCompare
@@ -2835,35 +3464,49 @@ Q_DECLARE_METATYPE(WontCompare);
struct WillCompare
{
int x;
+
+ friend bool operator==(const WillCompare &a, const WillCompare &b)
+ { return a.x == b.x; }
+ friend bool operator<(const WillCompare &a, const WillCompare &b)
+ { return a.x < b.x; }
};
-bool operator==(const WillCompare &a, const WillCompare &b) { return a.x == b.x; }
Q_DECLARE_METATYPE(WillCompare);
-void tst_QVariant::compareCustomTypes() const
+void tst_QVariant::compareCustomTypes_data() const
{
- {
- WontCompare f1{0};
- const QVariant variant1(QVariant::fromValue(f1));
+ QTest::addColumn<QVariant>("v1");
+ QTest::addColumn<QVariant>("v2");
+ QTest::addColumn<Qt::partial_ordering>("expectedOrdering");
- WontCompare f2{1};
- const QVariant variant2(QVariant::fromValue(f2));
+ QTest::newRow("same_uncomparable")
+ << QVariant::fromValue(WontCompare{0})
+ << QVariant::fromValue(WontCompare{0})
+ << Qt::partial_ordering::unordered;
- /* No comparison operator exists. */
- QVERIFY(variant1 != variant2);
- QVERIFY(variant1 != variant1);
- QVERIFY(variant2 != variant2);
- }
- {
- WillCompare f1{0};
- const QVariant variant1(QVariant::fromValue(f1));
+ QTest::newRow("same_comparable")
+ << QVariant::fromValue(WillCompare{0})
+ << QVariant::fromValue(WillCompare{0})
+ << Qt::partial_ordering::equivalent;
- WillCompare f2 {1};
- const QVariant variant2(QVariant::fromValue(f2));
+ QTest::newRow("different_comparable")
+ << QVariant::fromValue(WillCompare{1})
+ << QVariant::fromValue(WillCompare{0})
+ << Qt::partial_ordering::greater;
- QVERIFY(variant1 != variant2);
- QCOMPARE(variant1, variant1);
- QCOMPARE(variant2, variant2);
- }
+ QTest::newRow("qdatetime_vs_comparable")
+ << QVariant::fromValue(QDateTime::currentDateTimeUtc())
+ << QVariant::fromValue(WillCompare{0})
+ << Qt::partial_ordering::unordered;
+}
+
+void tst_QVariant::compareCustomTypes() const
+{
+ QFETCH(const QVariant, v1);
+ QFETCH(const QVariant, v2);
+ QFETCH(const Qt::partial_ordering, expectedOrdering);
+
+ QCOMPARE(QVariant::compare(v1, v2), expectedOrdering);
+ QT_TEST_EQUALITY_OPS(v1, v2, is_eq(expectedOrdering));
}
void tst_QVariant::timeToDateTime() const
{
@@ -3007,7 +3650,7 @@ void tst_QVariant::convertByteArrayToBool() const
QFETCH(QByteArray, output);
const QVariant variant(input);
- QCOMPARE(variant.type(), QVariant::Bool);
+ QCOMPARE(variant.typeId(), QMetaType::Bool);
QCOMPARE(variant.toBool(), input);
QVERIFY(variant.canConvert<bool>());
@@ -3033,60 +3676,88 @@ void tst_QVariant::convertIterables() const
{
QStringList list;
list.append("Hello");
- QCOMPARE(QVariant::fromValue(list).value<QVariantList>().count(), list.count());
+ QCOMPARE(QVariant::fromValue(list).value<QVariantList>().size(), list.size());
}
{
QByteArrayList list;
list.append("Hello");
- QCOMPARE(QVariant::fromValue(list).value<QVariantList>().count(), list.count());
+ QCOMPARE(QVariant::fromValue(list).value<QVariantList>().size(), list.size());
}
{
QVariantList list;
list.append("World");
- QCOMPARE(QVariant::fromValue(list).value<QVariantList>().count(), list.count());
+ QCOMPARE(QVariant::fromValue(list).value<QVariantList>().size(), list.size());
}
{
QMap<QString, int> map;
map.insert("3", 4);
- QCOMPARE(QVariant::fromValue(map).value<QVariantHash>().count(), map.count());
- QCOMPARE(QVariant::fromValue(map).value<QVariantMap>().count(), map.count());
+ QCOMPARE(QVariant::fromValue(map).value<QVariantHash>().size(), map.size());
+ QCOMPARE(QVariant::fromValue(map).value<QVariantMap>().size(), map.size());
map.insert("4", 5);
- QCOMPARE(QVariant::fromValue(map).value<QVariantHash>().count(), map.count());
- QCOMPARE(QVariant::fromValue(map).value<QVariantMap>().count(), map.count());
+ QCOMPARE(QVariant::fromValue(map).value<QVariantHash>().size(), map.size());
+ QCOMPARE(QVariant::fromValue(map).value<QVariantMap>().size(), map.size());
}
{
QVariantMap map;
map.insert("3", 4);
- QCOMPARE(QVariant::fromValue(map).value<QVariantHash>().count(), map.count());
- QCOMPARE(QVariant::fromValue(map).value<QVariantMap>().count(), map.count());
+ QCOMPARE(QVariant::fromValue(map).value<QVariantHash>().size(), map.size());
+ QCOMPARE(QVariant::fromValue(map).value<QVariantMap>().size(), map.size());
map.insert("4", 5);
- QCOMPARE(QVariant::fromValue(map).value<QVariantHash>().count(), map.count());
- QCOMPARE(QVariant::fromValue(map).value<QVariantMap>().count(), map.count());
+ QCOMPARE(QVariant::fromValue(map).value<QVariantHash>().size(), map.size());
+ QCOMPARE(QVariant::fromValue(map).value<QVariantMap>().size(), map.size());
}
{
QHash<QString, int> hash;
hash.insert("3", 4);
- QCOMPARE(QVariant::fromValue(hash).value<QVariantHash>().count(), hash.count());
- QCOMPARE(QVariant::fromValue(hash).value<QVariantMap>().count(), hash.count());
+ QCOMPARE(QVariant::fromValue(hash).value<QVariantHash>().size(), hash.size());
+ QCOMPARE(QVariant::fromValue(hash).value<QVariantMap>().size(), hash.size());
hash.insert("4", 5);
- QCOMPARE(QVariant::fromValue(hash).value<QVariantHash>().count(), hash.count());
- QCOMPARE(QVariant::fromValue(hash).value<QVariantMap>().count(), hash.count());
+ QCOMPARE(QVariant::fromValue(hash).value<QVariantHash>().size(), hash.size());
+ QCOMPARE(QVariant::fromValue(hash).value<QVariantMap>().size(), hash.size());
}
{
QVariantHash hash;
hash.insert("3", 4);
- QCOMPARE(QVariant::fromValue(hash).value<QVariantHash>().count(), hash.count());
- QCOMPARE(QVariant::fromValue(hash).value<QVariantMap>().count(), hash.count());
+ QCOMPARE(QVariant::fromValue(hash).value<QVariantHash>().size(), hash.size());
+ QCOMPARE(QVariant::fromValue(hash).value<QVariantMap>().size(), hash.size());
hash.insert("4", 5);
- QCOMPARE(QVariant::fromValue(hash).value<QVariantHash>().count(), hash.count());
- QCOMPARE(QVariant::fromValue(hash).value<QVariantMap>().count(), hash.count());
+ QCOMPARE(QVariant::fromValue(hash).value<QVariantHash>().size(), hash.size());
+ QCOMPARE(QVariant::fromValue(hash).value<QVariantMap>().size(), hash.size());
}
}
+struct Derived : QObject
+{
+ Q_OBJECT
+};
+
+void tst_QVariant::convertConstNonConst() const
+{
+ Derived *derived = new Derived;
+ QObject *obj = derived;
+ QObject const *unrelatedConstObj = new QObject;
+ auto cleanUp = qScopeGuard([&] {
+ delete unrelatedConstObj;
+ delete derived;
+ });
+ QObject const *constObj = obj;
+ Derived const *constDerived = derived;
+ QCOMPARE(QVariant::fromValue(constObj).value<QObject *>(), obj);
+ QCOMPARE(QVariant::fromValue(obj).value<QObject const *>(), constObj);
+
+ QCOMPARE(QVariant::fromValue(constDerived).value<QObject *>(), derived);
+ QCOMPARE(QVariant::fromValue(derived).value<QObject const *>(), derived);
+
+ QObject const *derivedAsConstObject = derived;
+ // up cast and remove const is possible, albeit dangerous
+ QCOMPARE(QVariant::fromValue(derivedAsConstObject).value<Derived *>(), derived);
+ QCOMPARE(QVariant::fromValue(unrelatedConstObj).value<Derived *>(), nullptr);
+}
+
/*!
We verify that:
1. Converting the string "9.9" to int fails. This is the behavior of
@@ -3147,13 +3818,13 @@ void tst_QVariant::fpStringRoundtrip() const
QFETCH(QVariant, number);
QVariant converted = number;
- QVERIFY(converted.convert(QVariant::String));
- QVERIFY(converted.convert(number.type()));
+ QVERIFY(converted.convert(QMetaType::fromType<QString>()));
+ QVERIFY(converted.convert(QMetaType(number.typeId())));
QCOMPARE(converted, number);
converted = number;
- QVERIFY(converted.convert(QVariant::ByteArray));
- QVERIFY(converted.convert(number.type()));
+ QVERIFY(converted.convert(QMetaType::fromType<QByteArray>()));
+ QVERIFY(converted.convert(QMetaType(number.typeId())));
QCOMPARE(converted, number);
}
@@ -3191,7 +3862,7 @@ void tst_QVariant::numericalConvert()
}
switch (v.userType())
{
- case QVariant::Double:
+ case QMetaType::Double:
QCOMPARE(v.toString() , QString::number(num, 'g', QLocale::FloatingPointShortest));
break;
case QMetaType::Float:
@@ -3256,10 +3927,8 @@ template<class T> void playWithVariant(const T &orig, bool isNull, const QString
QCOMPARE(v.toBool(), toBool);
QCOMPARE(qvariant_cast<T>(v), orig);
- if (qMetaTypeId<T>() != qMetaTypeId<QVariant>()) {
+ if (qMetaTypeId<T>() != qMetaTypeId<QVariant>())
QCOMPARE(v.userType(), qMetaTypeId<T>());
- QCOMPARE(QVariant::typeToName(QVariant::Type(v.userType())), QMetaType::typeName(qMetaTypeId<T>()));
- }
}
#define PLAY_WITH_VARIANT(Orig, IsNull, ToString, ToDouble, ToBool) \
@@ -3355,7 +4024,7 @@ struct MyShared : QSharedData {
};
QT_BEGIN_NAMESPACE
-Q_DECLARE_TYPEINFO(MyMovable, Q_MOVABLE_TYPE);
+Q_DECLARE_TYPEINFO(MyMovable, Q_RELOCATABLE_TYPE);
QT_END_NAMESPACE
Q_DECLARE_METATYPE(MyPrimitive)
@@ -3537,11 +4206,11 @@ void tst_QVariant::movabilityTest()
// prepare destination memory space to which variant will be moved
QVariant buffer[1];
- QCOMPARE(buffer[0].type(), QVariant::Invalid);
+ QCOMPARE(buffer[0].typeId(), QMetaType::UnknownType);
buffer[0].~QVariant();
- memcpy(buffer, &variant, sizeof(QVariant));
- QCOMPARE(buffer[0].type(), QVariant::UserType);
+ memcpy(static_cast<void *>(buffer), static_cast<void *>(&variant), sizeof(QVariant));
+ QVERIFY(buffer[0].typeId() > QMetaType::User);
QCOMPARE(buffer[0].userType(), qMetaTypeId<MyNotMovable>());
MyNotMovable tmp(buffer[0].value<MyNotMovable>());
@@ -3553,24 +4222,24 @@ void tst_QVariant::movabilityTest()
void tst_QVariant::variantInVariant()
{
QVariant var1 = 5;
- QCOMPARE(var1.type(), QVariant::Int);
+ QCOMPARE(var1.typeId(), QMetaType::Int);
QVariant var2 = var1;
QCOMPARE(var2, var1);
- QCOMPARE(var2.type(), QVariant::Int);
+ QCOMPARE(var2.typeId(), QMetaType::Int);
QVariant var3 = QVariant::fromValue(var1);
QCOMPARE(var3, var1);
- QCOMPARE(var3.type(), QVariant::Int);
+ QCOMPARE(var3.typeId(), QMetaType::Int);
QVariant var4 = qvariant_cast<QVariant>(var1);
QCOMPARE(var4, var1);
- QCOMPARE(var4.type(), QVariant::Int);
+ QCOMPARE(var4.typeId(), QMetaType::Int);
QVariant var5;
var5 = var1;
QCOMPARE(var5, var1);
- QCOMPARE(var5.type(), QVariant::Int);
+ QCOMPARE(var5.typeId(), QMetaType::Int);
QVariant var6;
var6.setValue(var1);
QCOMPARE(var6, var1);
- QCOMPARE(var6.type(), QVariant::Int);
+ QCOMPARE(var6.typeId(), QMetaType::Int);
QCOMPARE(QVariant::fromValue(var1), QVariant::fromValue(var2));
QCOMPARE(qvariant_cast<QVariant>(var3), QVariant::fromValue(var4));
@@ -3578,7 +4247,7 @@ void tst_QVariant::variantInVariant()
QString str("hello");
QVariant var8 = qvariant_cast<QVariant>(QVariant::fromValue(QVariant::fromValue(str)));
- QCOMPARE((int)var8.type(), (int)QVariant::String);
+ QCOMPARE(var8.typeId(), QMetaType::QString);
QCOMPARE(qvariant_cast<QString>(QVariant(qvariant_cast<QVariant>(var8))), str);
QVariant var9(QMetaType::fromType<QVariant>(), &var1);
@@ -3681,11 +4350,11 @@ void tst_QVariant::modelIndexConversion()
{
QVariant modelIndexVariant = QModelIndex();
QVERIFY(modelIndexVariant.canConvert<QPersistentModelIndex>());
- QVERIFY(modelIndexVariant.convert(QMetaType::QPersistentModelIndex));
- QCOMPARE(modelIndexVariant.type(), QVariant::PersistentModelIndex);
- QVERIFY(modelIndexVariant.canConvert(QMetaType::QModelIndex));
- QVERIFY(modelIndexVariant.convert(QMetaType::QModelIndex));
- QCOMPARE(modelIndexVariant.type(), QVariant::ModelIndex);
+ QVERIFY(modelIndexVariant.convert(QMetaType::fromType<QPersistentModelIndex>()));
+ QCOMPARE(modelIndexVariant.typeId(), QMetaType::QPersistentModelIndex);
+ QVERIFY(modelIndexVariant.canConvert(QMetaType::fromType<QModelIndex>()));
+ QVERIFY(modelIndexVariant.convert(QMetaType::fromType<QModelIndex>()));
+ QCOMPARE(modelIndexVariant.typeId(), QMetaType::QModelIndex);
}
class Forward;
@@ -3694,7 +4363,7 @@ Q_DECLARE_METATYPE(Forward*)
void tst_QVariant::forwardDeclare()
{
- Forward *f = 0;
+ Forward *f = nullptr;
QVariant v = QVariant::fromValue(f);
QCOMPARE(qvariant_cast<Forward*>(v), f);
}
@@ -3758,7 +4427,8 @@ void tst_QVariant::dataStream_data(QDataStream::Version version)
path = path.prepend(":/stream/").append("/");
QDir dir(path);
uint i = 0;
- foreach (const QFileInfo &fileInfo, dir.entryInfoList(QStringList() << "*.bin")) {
+ const auto entries = dir.entryInfoList(QStringList{u"*.bin"_s});
+ for (const QFileInfo &fileInfo : entries) {
QTest::newRow((path + fileInfo.fileName()).toLatin1()) << fileInfo.filePath();
i += 1;
}
@@ -3779,15 +4449,15 @@ void tst_QVariant::loadQVariantFromDataStream(QDataStream::Version version)
QVariant loadedVariant;
stream >> typeName >> loadedVariant;
- const int id = QMetaType::type(typeName.toLatin1());
+ const int id = QMetaType::fromName(typeName.toLatin1()).id();
if (id == QMetaType::Void) {
// Void type is not supported by QVariant
return;
}
- QVariant constructedVariant(static_cast<QVariant::Type>(id));
+ QVariant constructedVariant {QMetaType(id)};
QCOMPARE(constructedVariant.userType(), id);
- QCOMPARE(QMetaType::typeName(loadedVariant.userType()), typeName.toLatin1().constData());
+ QCOMPARE(QMetaType(loadedVariant.userType()).name(), typeName.toLatin1().constData());
QCOMPARE(loadedVariant.userType(), constructedVariant.userType());
}
@@ -3802,7 +4472,7 @@ void tst_QVariant::saveQVariantFromDataStream(QDataStream::Version version)
QString typeName;
dataFileStream >> typeName;
QByteArray data = file.readAll();
- const int id = QMetaType::type(typeName.toLatin1());
+ const int id = QMetaType::fromName(typeName.toLatin1()).id();
if (id == QMetaType::Void) {
// Void type is not supported by QVariant
return;
@@ -3813,7 +4483,7 @@ void tst_QVariant::saveQVariantFromDataStream(QDataStream::Version version)
QDataStream stream(&buffer);
stream.setVersion(version);
- QVariant constructedVariant(static_cast<QVariant::Type>(id));
+ QVariant constructedVariant {QMetaType(id)};
QCOMPARE(constructedVariant.userType(), id);
stream << constructedVariant;
@@ -3831,12 +4501,13 @@ void tst_QVariant::debugStream_data()
QTest::addColumn<QVariant>("variant");
QTest::addColumn<int>("typeId");
for (int id = 0; id < QMetaType::LastCoreType + 1; ++id) {
- const char *tagName = QMetaType::typeName(id);
- if (!tagName)
- continue;
- if (id != QMetaType::Void) {
- QTest::newRow(tagName) << QVariant(static_cast<QVariant::Type>(id)) << id;
+ if (id && !QMetaType::isRegistered(id)) {
+ QTest::ignoreMessage(QtWarningMsg, QRegularExpression(
+ "^Trying to construct an instance of an invalid type"));
}
+ const char *tagName = QMetaType(id).name();
+ if (tagName && id != QMetaType::Void)
+ QTest::newRow(tagName) << QVariant(QMetaType(id)) << id;
}
QTest::newRow("QBitArray(111)") << QVariant(QBitArray(3, true)) << qMetaTypeId<QBitArray>();
QTest::newRow("CustomStreamableClass") << QVariant(QMetaType::fromType<CustomStreamableClass>(), 0) << qMetaTypeId<CustomStreamableClass>();
@@ -3855,6 +4526,7 @@ void tst_QVariant::debugStream()
QVERIFY(msgHandler.testPassed());
}
+#if QT_DEPRECATED_SINCE(6, 0)
struct MessageHandlerType : public MessageHandler
{
MessageHandlerType(const int typeId)
@@ -3865,9 +4537,11 @@ struct MessageHandlerType : public MessageHandler
// Format itself is not important, but basic data as a type name should be included in the output
ok = msg.startsWith("QVariant::");
QVERIFY2(ok, (QString::fromLatin1("Message is not started correctly: '") + msg + '\'').toLatin1().constData());
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
ok &= (currentId == QMetaType::UnknownType
? msg.contains("Invalid")
: msg.contains(QMetaType::typeName(currentId)));
+QT_WARNING_POP
QVERIFY2(ok, (QString::fromLatin1("Message doesn't contain type name: '") + msg + '\'').toLatin1().constData());
}
};
@@ -3883,9 +4557,10 @@ void tst_QVariant::debugStreamType()
QFETCH(int, typeId);
MessageHandlerType msgHandler(typeId);
- qDebug() << QVariant::Type(typeId);
+ QT_IGNORE_DEPRECATIONS(qDebug() << QVariant::Type(typeId);)
QVERIFY(msgHandler.testPassed());
}
+#endif // QT_DEPRECATED_SINCE(6, 0)
void tst_QVariant::implicitConstruction()
{
@@ -4040,6 +4715,42 @@ struct ContainerAPI<Container, QByteArray>
}
};
+template<typename Container>
+struct ContainerAPI<Container, QChar>
+{
+ static void insert(Container &container, int value)
+ {
+ container.push_back(QChar::fromLatin1(char(value) + '0'));
+ }
+
+ static bool compare(const QVariant &variant, QChar value)
+ {
+ return variant.value<QChar>() == value;
+ }
+ static bool compare(QVariant variant, const QVariant &value)
+ {
+ return variant == value;
+ }
+};
+
+template<typename Container>
+struct ContainerAPI<Container, char>
+{
+ static void insert(Container &container, int value)
+ {
+ container.push_back(char(value) + '0');
+ }
+
+ static bool compare(const QVariant &variant, char value)
+ {
+ return variant.value<char>() == value;
+ }
+ static bool compare(QVariant variant, const QVariant &value)
+ {
+ return variant == value;
+ }
+};
+
#ifdef __has_include
# if __has_include(<forward_list>)
# define TEST_FORWARD_LIST
@@ -4127,11 +4838,6 @@ struct KeyGetter<std::map<T, U> >
};
-// We have no built-in defines to check the stdlib features.
-// #define TEST_UNORDERED_MAP
-
-#ifdef TEST_UNORDERED_MAP
-#include <unordered_map>
typedef std::unordered_map<int, bool> StdUnorderedMap_int_bool;
Q_DECLARE_ASSOCIATIVE_CONTAINER_METATYPE(std::unordered_map)
@@ -4150,7 +4856,6 @@ struct KeyGetter<std::unordered_map<T, U> >
return it->second;
}
};
-#endif
template<typename Iterator>
void sortIterable(QSequentialIterable *iterable)
@@ -4162,7 +4867,7 @@ void sortIterable(QSequentialIterable *iterable)
}
template<typename Container>
-void testSequentialIteration()
+static void testSequentialIteration()
{
int numSeen = 0;
Container sequence;
@@ -4187,16 +4892,6 @@ void testSequentialIteration()
QCOMPARE(numSeen, (int)std::distance(sequence.begin(), sequence.end()));
QCOMPARE(containerIter, containerEnd);
- containerIter = sequence.begin();
- numSeen = 0;
- Q_FOREACH (const QVariant &v, listIter) {
- QVERIFY(ContainerAPI<Container>::compare(v, *containerIter));
- QVERIFY(ContainerAPI<Container>::compare(v, varList.at(numSeen)));
- ++containerIter;
- ++numSeen;
- }
- QCOMPARE(numSeen, (int)std::distance(sequence.begin(), sequence.end()));
-
numSeen = 0;
containerIter = sequence.begin();
for (QVariant v : listIter) {
@@ -4211,7 +4906,7 @@ void testSequentialIteration()
int numSeen = 0;
auto varList = listVariant.value<QVariantList>();
auto varIter = varList.begin();
- for (const QVariant &v : qAsConst(listIter)) {
+ for (const QVariant &v : std::as_const(listIter)) {
QVERIFY(ContainerAPI<Container>::compare(v, *varIter));
++varIter;
++numSeen;
@@ -4259,43 +4954,156 @@ void testSequentialIteration()
QCOMPARE(listIter.at(4), third);
QCOMPARE(listIter.at(5), third);
- listIter.removeValue();
- compareLists();
- QCOMPARE(listIter.size(), 5);
- QCOMPARE(listIter.at(0), first);
- QCOMPARE(listIter.at(1), first);
- QCOMPARE(listIter.at(2), second);
- QCOMPARE(listIter.at(3), second);
- QCOMPARE(listIter.at(4), third);
+ if (listIter.metaContainer().canRemoveValue()) {
+ listIter.removeValue();
+ compareLists();
+ QCOMPARE(listIter.size(), 5);
+ QCOMPARE(listIter.at(0), first);
+ QCOMPARE(listIter.at(1), first);
+ QCOMPARE(listIter.at(2), second);
+ QCOMPARE(listIter.at(3), second);
+ QCOMPARE(listIter.at(4), third);
+ } else {
+ // QString and QByteArray have no pop_back or pop_front and it's unclear what other
+ // method we should use to remove an item.
+ QVERIFY((std::is_same_v<Container, QString> || std::is_same_v<Container, QByteArray>));
+ }
+
+ auto i = listIter.mutableBegin();
+ QVERIFY(i != listIter.mutableEnd());
+
+ *i = QStringLiteral("17");
+ if (listIter.metaContainer().valueMetaType() == QMetaType::fromType<int>())
+ QCOMPARE(listIter.at(0).toInt(), 17);
+ else if (listIter.metaContainer().valueMetaType() == QMetaType::fromType<bool>())
+ QCOMPARE(listIter.at(0).toBool(), false);
+
+ *i = QStringLiteral("true");
+ if (listIter.metaContainer().valueMetaType() == QMetaType::fromType<int>())
+ QCOMPARE(listIter.at(0).toInt(), 0);
+ else if (listIter.metaContainer().valueMetaType() == QMetaType::fromType<bool>())
+ QCOMPARE(listIter.at(0).toBool(), true);
}
-void tst_QVariant::iterateContainerElements()
+template<typename Container>
+static void testAssociativeIteration()
{
- testSequentialIteration<QQueue<int>>();
- testSequentialIteration<QQueue<QVariant>>();
- testSequentialIteration<QQueue<QString>>();
- testSequentialIteration<QList<int>>();
- testSequentialIteration<QList<QVariant>>();
- testSequentialIteration<QList<QString>>();
- testSequentialIteration<QList<QByteArray>>();
- testSequentialIteration<QStack<int>>();
- testSequentialIteration<QStack<QVariant>>();
- testSequentialIteration<QStack<QString>>();
- testSequentialIteration<std::vector<int>>();
- testSequentialIteration<std::vector<QVariant>>();
- testSequentialIteration<std::vector<QString>>();
- testSequentialIteration<std::list<int>>();
- testSequentialIteration<std::list<QVariant>>();
- testSequentialIteration<std::list<QString>>();
- testSequentialIteration<QStringList>();
- testSequentialIteration<QByteArrayList>();
+ using Key = typename Container::key_type;
+ using Mapped = typename Container::mapped_type;
+
+ int numSeen = 0;
+ Container mapping;
+ mapping[5] = true;
+ mapping[15] = false;
+
+ QVariant mappingVariant = QVariant::fromValue(mapping);
+ QVariantMap varMap = mappingVariant.value<QVariantMap>();
+ QVariantMap varHash = mappingVariant.value<QVariantMap>();
+ QAssociativeIterable mappingIter = mappingVariant.view<QAssociativeIterable>();
+
+ typename Container::const_iterator containerIter = mapping.begin();
+ const typename Container::const_iterator containerEnd = mapping.end();
+ for ( ;containerIter != containerEnd; ++containerIter, ++numSeen)
+ {
+ Mapped expected = KeyGetter<Container>::value(containerIter);
+ Key key = KeyGetter<Container>::get(containerIter);
+ Mapped actual = qvariant_cast<Mapped>(mappingIter.value(key));
+ QCOMPARE(qvariant_cast<Mapped>(varMap.value(QString::number(key))), expected);
+ QCOMPARE(qvariant_cast<Mapped>(varHash.value(QString::number(key))), expected);
+ QCOMPARE(actual, expected);
+ const QAssociativeIterable::const_iterator it = mappingIter.find(key);
+ QVERIFY(it != mappingIter.end());
+ QCOMPARE(it.value().value<Mapped>(), expected);
+ }
+ QCOMPARE(numSeen, (int)std::distance(mapping.begin(), mapping.end()));
+ QCOMPARE(containerIter, containerEnd);
+ QVERIFY(mappingIter.find(10) == mappingIter.end());
+
+ auto i = mappingIter.mutableFind(QStringLiteral("nonono"));
+ QCOMPARE(i, mappingIter.mutableEnd());
+ i = mappingIter.mutableFind(QStringLiteral("5"));
+ QVERIFY(i != mappingIter.mutableEnd());
+
+ *i = QStringLiteral("17");
+
+ if (mappingIter.metaContainer().mappedMetaType() == QMetaType::fromType<int>())
+ QCOMPARE(mappingIter.value(5).toInt(), 17);
+ else if (mappingIter.metaContainer().mappedMetaType() == QMetaType::fromType<bool>())
+ QCOMPARE(mappingIter.value(5).toBool(), true);
+
+ *i = QStringLiteral("true");
+ if (mappingIter.metaContainer().mappedMetaType() == QMetaType::fromType<int>())
+ QCOMPARE(mappingIter.value(5).toInt(), 0);
+ else if (mappingIter.metaContainer().mappedMetaType() == QMetaType::fromType<bool>())
+ QCOMPARE(mappingIter.value(5).toBool(), true);
+
+ QVERIFY(mappingIter.containsKey("5"));
+ mappingIter.removeKey(QStringLiteral("5"));
+ QCOMPARE(mappingIter.find(5), mappingIter.end());
+
+ mappingIter.setValue(5, 44);
+ if (mappingIter.metaContainer().mappedMetaType() == QMetaType::fromType<int>())
+ QCOMPARE(mappingIter.value(5).toInt(), 44);
+ else if (mappingIter.metaContainer().mappedMetaType() == QMetaType::fromType<bool>())
+ QCOMPARE(mappingIter.value(5).toBool(), true);
+
+ // Test that find() does not coerce
+ auto container = Container();
+ container[0] = true;
+
+ QVariant containerVariant = QVariant::fromValue(container);
+ QAssociativeIterable iter = containerVariant.value<QAssociativeIterable>();
+ auto f = iter.constFind(QStringLiteral("anything"));
+ QCOMPARE(f, iter.constEnd());
+}
+
+void tst_QVariant::iterateSequentialContainerElements_data()
+{
+ QTest::addColumn<QFunctionPointer>("testFunction");
+#define ADD(T) QTest::newRow(#T) << &testSequentialIteration<T>
+ ADD(QQueue<int>);
+ ADD(QQueue<QVariant>);
+ ADD(QQueue<QString>);
+ ADD(QList<int>);
+ ADD(QList<QVariant>);
+ ADD(QList<QString>);
+ ADD(QList<QByteArray>);
+ ADD(QStack<int>);
+ ADD(QStack<QVariant>);
+ ADD(QStack<QString>);
+ ADD(std::vector<int>);
+ ADD(std::vector<QVariant>);
+ ADD(std::vector<QString>);
+ ADD(std::list<int>);
+ ADD(std::list<QVariant>);
+ ADD(std::list<QString>);
+ ADD(QStringList);
+ ADD(QByteArrayList);
+ ADD(QString);
+ ADD(QByteArray);
#ifdef TEST_FORWARD_LIST
- testSequentialIteration<std::forward_list<int>>();
- testSequentialIteration<std::forward_list<QVariant>>();
- testSequentialIteration<std::forward_list<QString>>();
+ ADD(std::forward_list<int>);
+ ADD(std::forward_list<QVariant>);
+ ADD(std::forward_list<QString>);
#endif
+#undef ADD
+}
+void tst_QVariant::iterateAssociativeContainerElements_data()
+{
+ QTest::addColumn<QFunctionPointer>("testFunction");
+#define ADD(C, K, V) QTest::newRow(#C #K #V) << &testAssociativeIteration<C<K, V>>;
+ ADD(QHash, int, bool);
+ ADD(QHash, int, int);
+ ADD(QMap, int, bool);
+ ADD(std::map, int, bool);
+ ADD(std::unordered_map, int, bool);
+#undef ADD
+}
+
+void tst_QVariant::iterateContainerElements()
+{
{
QVariantList ints;
ints << 1 << 2 << 3;
@@ -4318,44 +5126,6 @@ void tst_QVariant::iterateContainerElements()
QCOMPARE(ints, intsCopy);
}
-#define TEST_ASSOCIATIVE_ITERATION(CONTAINER, KEY_TYPE, MAPPED_TYPE) \
- { \
- int numSeen = 0; \
- CONTAINER<KEY_TYPE, MAPPED_TYPE> mapping; \
- mapping[5] = true; \
- mapping[15] = false; \
- \
- QVariant mappingVariant = QVariant::fromValue(mapping); \
- QVariantMap varMap = mappingVariant.value<QVariantMap>(); \
- QVariantMap varHash = mappingVariant.value<QVariantMap>(); \
- QAssociativeIterable mappingIter = mappingVariant.value<QAssociativeIterable>(); \
- \
- CONTAINER<KEY_TYPE, MAPPED_TYPE>::const_iterator containerIter = mapping.begin(); \
- const CONTAINER<KEY_TYPE, MAPPED_TYPE>::const_iterator containerEnd = mapping.end(); \
- for ( ; containerIter != containerEnd; ++containerIter, ++numSeen) \
- { \
- MAPPED_TYPE expected = KeyGetter<CONTAINER<KEY_TYPE, MAPPED_TYPE> >::value(containerIter); \
- KEY_TYPE key = KeyGetter<CONTAINER<KEY_TYPE, MAPPED_TYPE> >::get(containerIter); \
- MAPPED_TYPE actual = mappingIter.value(key).value<MAPPED_TYPE >(); \
- QCOMPARE(varMap.value(QString::number(key)).value<MAPPED_TYPE>(), expected); \
- QCOMPARE(varHash.value(QString::number(key)).value<MAPPED_TYPE>(), expected); \
- QCOMPARE(actual, expected); \
- const QAssociativeIterable::const_iterator it = mappingIter.find(key); \
- QVERIFY(it != mappingIter.end()); \
- QCOMPARE(it.value().value<MAPPED_TYPE>(), expected); \
- } \
- QCOMPARE(numSeen, (int)std::distance(mapping.begin(), mapping.end())); \
- QCOMPARE(containerIter, containerEnd); \
- QVERIFY(mappingIter.find(10) == mappingIter.end()); \
- }
-
- TEST_ASSOCIATIVE_ITERATION(QHash, int, bool)
- TEST_ASSOCIATIVE_ITERATION(QMap, int, bool)
- TEST_ASSOCIATIVE_ITERATION(std::map, int, bool)
-#ifdef TEST_UNORDERED_MAP
- TEST_ASSOCIATIVE_ITERATION(std::unordered_map, int, bool)
-#endif
-
{
QMap<int, QString> mapping;
mapping.insert(1, "one");
@@ -4382,58 +5152,77 @@ void tst_QVariant::iterateContainerElements()
numsCopy << *(it++);
QCOMPARE(nums, numsCopy);
}
+
+ {
+ auto container = QVariantMap();
+
+ container["one"] = 1;
+
+ auto containerVariant = QVariant::fromValue(container);
+ auto iter = containerVariant.value<QAssociativeIterable>();
+ auto value = iter.value("one");
+ QCOMPARE(value, QVariant(1));
+
+ auto f = iter.constFind("one");
+ QCOMPARE(*f, QVariant(1));
+ }
}
-void tst_QVariant::pairElements()
+template <typename Pair> static void testVariantPairElements()
{
- typedef QPair<QVariant, QVariant> QVariantPair;
+ QFETCH(std::function<void(void *)>, makeValue);
+ Pair p;
+ makeValue(&p);
+ QVariant v = QVariant::fromValue(p);
-#define TEST_PAIR_ELEMENT_ACCESS(PAIR, T1, T2, VALUE1, VALUE2) \
- { \
- PAIR<T1, T2> p(VALUE1, VALUE2); \
- QVariant v = QVariant::fromValue(p); \
- \
- QVERIFY(v.canConvert<QVariantPair>()); \
- QVariantPair pi = v.value<QVariantPair>(); \
- QCOMPARE(pi.first, QVariant::fromValue(VALUE1)); \
- QCOMPARE(pi.second, QVariant::fromValue(VALUE2)); \
- }
-
- TEST_PAIR_ELEMENT_ACCESS(QPair, int, int, 4, 5)
- TEST_PAIR_ELEMENT_ACCESS(std::pair, int, int, 4, 5)
- TEST_PAIR_ELEMENT_ACCESS(QPair, QString, QString, QStringLiteral("one"), QStringLiteral("two"))
- TEST_PAIR_ELEMENT_ACCESS(std::pair, QString, QString, QStringLiteral("one"), QStringLiteral("two"))
- TEST_PAIR_ELEMENT_ACCESS(QPair, QVariant, QVariant, 4, 5)
- TEST_PAIR_ELEMENT_ACCESS(std::pair, QVariant, QVariant, 4, 5)
- TEST_PAIR_ELEMENT_ACCESS(QPair, QVariant, int, 41, 15)
- TEST_PAIR_ELEMENT_ACCESS(std::pair, QVariant, int, 34, 65)
- TEST_PAIR_ELEMENT_ACCESS(QPair, int, QVariant, 24, 25)
- TEST_PAIR_ELEMENT_ACCESS(std::pair, int, QVariant, 44, 15)
+ QVERIFY(v.canConvert<QVariantPair>());
+ QVariantPair pi = v.value<QVariantPair>();
+ QCOMPARE(pi.first, QVariant::fromValue(p.first));
+ QCOMPARE(pi.second, QVariant::fromValue(p.second));
}
-enum EnumTest_Enum0 { EnumTest_Enum0_value = 42, EnumTest_Enum0_negValue = -8 };
-Q_DECLARE_METATYPE(EnumTest_Enum0)
-enum EnumTest_Enum1 : qint64 { EnumTest_Enum1_value = 42, EnumTest_Enum1_bigValue = (Q_INT64_C(1) << 33) + 50 };
-Q_DECLARE_METATYPE(EnumTest_Enum1)
+void tst_QVariant::pairElements_data()
+{
+ QTest::addColumn<QFunctionPointer>("testFunction");
+ QTest::addColumn<std::function<void(void *)>>("makeValue");
-enum EnumTest_Enum3 : qint64 { EnumTest_Enum3_value = -47, EnumTest_Enum3_bigValue = (Q_INT64_C(1) << 56) + 5 };
-Q_DECLARE_METATYPE(EnumTest_Enum3)
-enum EnumTest_Enum4 : quint64 { EnumTest_Enum4_value = 47, EnumTest_Enum4_bigValue = (Q_INT64_C(1) << 52) + 45 };
-Q_DECLARE_METATYPE(EnumTest_Enum4)
-enum EnumTest_Enum5 : uint { EnumTest_Enum5_value = 47 };
-Q_DECLARE_METATYPE(EnumTest_Enum5)
-enum EnumTest_Enum6 : uchar { EnumTest_Enum6_value = 47 };
-Q_DECLARE_METATYPE(EnumTest_Enum6)
-enum class EnumTest_Enum7 { EnumTest_Enum7_value = 47, ensureSignedEnum7 = -1 };
-Q_DECLARE_METATYPE(EnumTest_Enum7)
-enum EnumTest_Enum8 : short { EnumTest_Enum8_value = 47 };
-Q_DECLARE_METATYPE(EnumTest_Enum8)
+ static auto makeString = [](auto &&value) -> QString {
+ using T = std::decay_t<decltype(value)>;
+ if constexpr (std::is_integral_v<T> || std::is_floating_point_v<T>) {
+ return QString::number(value);
+ } else if constexpr (std::is_same_v<T, QVariant>) {
+ return value.toString();
+ } else {
+ return value;
+ }
+ };
+ auto addRow = [](auto &&first, auto &&second) {
+ using Pair = std::pair<std::decay_t<decltype(first)>, std::decay_t<decltype(second)>>;
+ std::function<void(void *)> makeValue = [=](void *pair) {
+ *static_cast<Pair *>(pair) = Pair{first, second};
+ };
+
+ QTest::addRow("%s", qPrintable(makeString(first) + u',' + makeString(second)))
+ << &testVariantPairElements<Pair> << makeValue;
+ };
+
+ addRow(4, 5);
+ addRow(QStringLiteral("one"), QStringLiteral("two"));
+ addRow(QVariant(4), QVariant(5));
+ addRow(QVariant(41), 65);
+ addRow(41, QVariant(15));
+}
-template<typename Enum> void testVariant(Enum value, bool *ok)
+template <auto value> static void testVariantEnum()
{
- *ok = false;
- QVariant var = QVariant::fromValue(value);
+ using Enum = decltype(value);
+ auto canLosslesslyConvert = [=](auto zero) {
+ return sizeof(value) <= sizeof(zero) ||
+ value == Enum(decltype(zero)(qToUnderlying(value)));
+ };
+ bool losslessConvertToInt = canLosslesslyConvert(int{});
+ QVariant var = QVariant::fromValue(value);
QCOMPARE(var.userType(), qMetaTypeId<Enum>());
QVERIFY(var.canConvert<Enum>());
@@ -4444,7 +5233,6 @@ template<typename Enum> void testVariant(Enum value, bool *ok)
QVERIFY(var.canConvert<qint64>());
QVERIFY(var.canConvert<quint64>());
-
QCOMPARE(var.value<Enum>(), value);
QCOMPARE(var.value<int>(), static_cast<int>(value));
QCOMPARE(var.value<uint>(), static_cast<uint>(value));
@@ -4454,10 +5242,18 @@ template<typename Enum> void testVariant(Enum value, bool *ok)
QCOMPARE(var.value<quint64>(), static_cast<quint64>(value));
QVariant var2 = var;
- QVERIFY(var2.convert(QMetaType::Int));
+ QVERIFY(var2.convert(QMetaType::fromType<int>()));
QCOMPARE(var2.value<int>(), static_cast<int>(value));
- if ((static_cast<qint64>(value) <= INT_MAX) && (static_cast<qint64>(value) >= INT_MIN)) {
+ QVariant strVar = QString::number(qToUnderlying(value));
+ QVariant baVar = QByteArray::number(qToUnderlying(value));
+ QCOMPARE(strVar.value<Enum>(), value);
+ QCOMPARE(baVar.value<Enum>(), value);
+ QCOMPARE(var.value<QString>(), strVar);
+ QCOMPARE(var.value<QByteArray>(), baVar);
+
+ // unary + to silence gcc warning
+ if (losslessConvertToInt) {
int intValue = static_cast<int>(value);
QVariant intVar = intValue;
QVERIFY(intVar.canConvert<Enum>());
@@ -4467,71 +5263,126 @@ template<typename Enum> void testVariant(Enum value, bool *ok)
QVERIFY(QVariant(longValue).canConvert<Enum>());
QCOMPARE(QVariant(longValue).value<Enum>(), value);
- *ok = true;
-}
-
-void tst_QVariant::enums()
-{
- bool ok = false;
- testVariant(EnumTest_Enum0_value, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum0_negValue, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum1_value, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum1_bigValue, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum3::EnumTest_Enum3_value, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum3::EnumTest_Enum3_bigValue, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum4::EnumTest_Enum4_value, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum4::EnumTest_Enum4_bigValue, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum5::EnumTest_Enum5_value, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum6::EnumTest_Enum6_value, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum7::EnumTest_Enum7_value, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum8::EnumTest_Enum8_value, &ok);
- QVERIFY(ok);
- testVariant(EnumTest_Enum3::EnumTest_Enum3_value, &ok);
- QVERIFY(ok);
-}
-
-template<typename Enum> void testVariantMeta(Enum value, bool *ok, const char *string)
-{
- testVariant<Enum>(value, ok);
- QVERIFY(ok);
- *ok = false;
+ auto value2 = Enum(qToUnderlying(value) + 1);
+ var2 = QVariant::fromValue(value2);
+ QCOMPARE_EQ(var, var);
+ QCOMPARE_NE(var, var2);
+ QCOMPARE(QVariant::compare(var, var), QPartialOrdering::Equivalent);
+ QCOMPARE(QVariant::compare(var, var2), QPartialOrdering::Less);
+ QCOMPARE(QVariant::compare(var2, var), QPartialOrdering::Greater);
+
+ QCOMPARE_EQ(var, static_cast<qint64>(value));
+ QCOMPARE_EQ(var, static_cast<quint64>(value));
+ QCOMPARE_EQ(static_cast<qint64>(value), var);
+ QCOMPARE_EQ(static_cast<quint64>(value), var);
+ QCOMPARE_NE(var2, static_cast<qint64>(value));
+ QCOMPARE_NE(var2, static_cast<quint64>(value));
+ QCOMPARE_NE(static_cast<qint64>(value), var2);
+ QCOMPARE_NE(static_cast<quint64>(value), var2);
+
+ if (losslessConvertToInt) {
+ QCOMPARE_EQ(var, int(value));
+ QCOMPARE_EQ(int(value), var);
+ QCOMPARE_NE(var2, int(value));
+ QCOMPARE_NE(int(value), var2);
+ }
+ if (canLosslesslyConvert(uint{})) {
+ QCOMPARE_EQ(var, uint(value));
+ QCOMPARE_EQ(uint(value), var);
+ QCOMPARE_NE(var2, uint(value));
+ QCOMPARE_NE(uint(value), var2);
+ }
+ if (canLosslesslyConvert(short{})) {
+ QCOMPARE_EQ(var, short(value));
+ QCOMPARE_EQ(short(value), var);
+ QCOMPARE_NE(var2, short(value));
+ QCOMPARE_NE(short(value), var2);
+ }
+ if (canLosslesslyConvert(ushort{})) {
+ QCOMPARE_EQ(var, ushort(value));
+ QCOMPARE_EQ(ushort(value), var);
+ QCOMPARE_NE(var2, ushort(value));
+ QCOMPARE_NE(ushort(value), var2);
+ }
+ if (canLosslesslyConvert(char{})) {
+ QCOMPARE_EQ(var, char(value));
+ QCOMPARE_EQ(char(value), var);
+ QCOMPARE_NE(var2, char(value));
+ QCOMPARE_NE(char(value), var2);
+ }
+ if (canLosslesslyConvert(uchar{})) {
+ QCOMPARE_EQ(var, uchar(value));
+ QCOMPARE_EQ(uchar(value), var);
+ QCOMPARE_NE(var2, uchar(value));
+ QCOMPARE_NE(uchar(value), var2);
+ }
+ if (canLosslesslyConvert(qint8{})) {
+ QCOMPARE_EQ(var, qint8(value));
+ QCOMPARE_EQ(qint8(value), var);
+ QCOMPARE_NE(var2, qint8(value));
+ QCOMPARE_NE(qint8(value), var2);
+ }
+
+ // string compares too (of the values in decimal)
+ QCOMPARE_EQ(var, QString::number(qToUnderlying(value)));
+ QCOMPARE_EQ(QString::number(qToUnderlying(value)), var);
+ QCOMPARE_NE(var, QString::number(qToUnderlying(value2)));
+ QCOMPARE_NE(QString::number(qToUnderlying(value2)), var);
+}
+
+void tst_QVariant::enums_data()
+{
+ QTest::addColumn<QFunctionPointer>("testFunction");
+
+#define ADD(V) QTest::newRow(#V) << &testVariantEnum<V>
+ ADD(EnumTest_Enum0_value);
+ ADD(EnumTest_Enum0_negValue);
+ ADD(EnumTest_Enum1_value);
+ ADD(EnumTest_Enum1_bigValue);
+ ADD(EnumTest_Enum3::EnumTest_Enum3_value);
+ ADD(EnumTest_Enum3::EnumTest_Enum3_bigValue);
+ ADD(EnumTest_Enum4::EnumTest_Enum4_value);
+ ADD(EnumTest_Enum4::EnumTest_Enum4_bigValue);
+ ADD(EnumTest_Enum5::EnumTest_Enum5_value);
+ ADD(EnumTest_Enum6::EnumTest_Enum6_value);
+ ADD(EnumTest_Enum7::EnumTest_Enum7_value);
+ ADD(EnumTest_Enum8::EnumTest_Enum8_value);
+ ADD(EnumTest_Enum3::EnumTest_Enum3_value);
+#undef ADD
+}
+
+// ### C++20: this would be easier if QFlags were a structural type
+template <typename Enum, auto Value> static void testVariantMetaEnum()
+{
+ Enum value(Value);
+ QFETCH(QString, string);
QVariant var = QVariant::fromValue(value);
QVERIFY(var.canConvert<QString>());
QVERIFY(var.canConvert<QByteArray>());
- QCOMPARE(var.value<QString>(), QString::fromLatin1(string));
- QCOMPARE(var.value<QByteArray>(), QByteArray(string));
+ QCOMPARE(var.value<QString>(), string);
+ QCOMPARE(var.value<QByteArray>(), string.toLatin1());
- QVariant strVar = QString::fromLatin1(string);
+ QVariant strVar = string;
QVERIFY(strVar.canConvert<Enum>());
- if ((static_cast<qint64>(value) > INT_MAX) || (static_cast<qint64>(value) < INT_MIN)) {
+ // unary + to silence gcc warning
+ if ((+static_cast<qint64>(value) > INT_MAX) || (+static_cast<qint64>(value) < INT_MIN)) {
QEXPECT_FAIL("", "QMetaEnum api uses 'int' as return type QTBUG-27451", Abort);
- *ok = true;
}
QCOMPARE(strVar.value<Enum>(), value);
- strVar = QByteArray(string);
+ strVar = string.toLatin1();
QVERIFY(strVar.canConvert<Enum>());
QCOMPARE(strVar.value<Enum>(), value);
- *ok = true;
}
-void tst_QVariant::metaEnums()
+void tst_QVariant::metaEnums_data()
{
- bool ok = false;
+ QTest::addColumn<QFunctionPointer>("testFunction");
+ QTest::addColumn<QString>("string");
+
#define METAENUMS_TEST(Value) \
- testVariantMeta(Value, &ok, #Value); QVERIFY(ok)
+ QTest::newRow(#Value) << &testVariantMetaEnum<decltype(Value), Value> << #Value;
METAENUMS_TEST(MetaEnumTest_Enum0_value);
METAENUMS_TEST(MetaEnumTest_Enum1_value);
@@ -4544,17 +5395,26 @@ void tst_QVariant::metaEnums()
METAENUMS_TEST(MetaEnumTest_Enum5_value);
METAENUMS_TEST(MetaEnumTest_Enum6_value);
METAENUMS_TEST(MetaEnumTest_Enum8_value);
+ { using namespace Qt; METAENUMS_TEST(RichText); }
+#undef METAENUMS_TEST
+
+ QTest::newRow("AlignBottom")
+ << &testVariantMetaEnum<Qt::Alignment, Qt::AlignBottom> << "AlignBottom";
+
+ constexpr auto AlignHCenterBottom = Qt::AlignmentFlag((Qt::AlignHCenter | Qt::AlignBottom).toInt());
+ QTest::newRow("AlignHCenter|AlignBottom")
+ << &testVariantMetaEnum<Qt::Alignment, AlignHCenterBottom> << "AlignHCenter|AlignBottom";
}
void tst_QVariant::nullConvert()
{
// null variant with no initialized value
- QVariant nullVar(QVariant::String);
+ QVariant nullVar {QMetaType::fromType<QString>()};
QVERIFY(nullVar.isValid());
QVERIFY(nullVar.isNull());
// We can not convert a variant with no value
- QVERIFY(!nullVar.convert(QVariant::Url));
- QCOMPARE(nullVar.type(), QVariant::Url);
+ QVERIFY(!nullVar.convert(QMetaType::fromType<QUrl>()));
+ QCOMPARE(nullVar.typeId(), QMetaType::QUrl);
QVERIFY(nullVar.isNull());
}
@@ -4690,38 +5550,81 @@ void tst_QVariant::shouldDeleteVariantDataWorksForAssociative()
void tst_QVariant::fromStdVariant()
{
-#if __has_include(<variant>) && __cplusplus >= 201703L
+#define CHECK_EQUAL(lhs, rhs, type) do { \
+ QCOMPARE(lhs.typeId(), rhs.typeId()); \
+ if (lhs.isNull()) { \
+ QVERIFY(rhs.isNull()); \
+ } else { \
+ QVERIFY(!rhs.isNull()); \
+ QCOMPARE(get< type >(lhs), get< type >(rhs)); \
+ } \
+ } while (false)
+
{
typedef std::variant<int, bool> intorbool_t;
intorbool_t stdvar = 5;
QVariant qvar = QVariant::fromStdVariant(stdvar);
QVERIFY(!qvar.isNull());
- QCOMPARE(qvar.type(), QVariant::Int);
+ QCOMPARE(qvar.typeId(), QMetaType::Int);
QCOMPARE(qvar.value<int>(), std::get<int>(stdvar));
+ {
+ const auto qv2 = QVariant::fromStdVariant(std::move(stdvar));
+ CHECK_EQUAL(qv2, qvar, int);
+ }
+
stdvar = true;
qvar = QVariant::fromStdVariant(stdvar);
QVERIFY(!qvar.isNull());
- QCOMPARE(qvar.type(), QVariant::Bool);
+ QCOMPARE(qvar.typeId(), QMetaType::Bool);
QCOMPARE(qvar.value<bool>(), std::get<bool>(stdvar));
+ {
+ const auto qv2 = QVariant::fromStdVariant(std::move(stdvar));
+ CHECK_EQUAL(qv2, qvar, bool);
+ }
}
{
std::variant<std::monostate, int> stdvar;
QVariant qvar = QVariant::fromStdVariant(stdvar);
QVERIFY(!qvar.isValid());
+ {
+ const auto qv2 = QVariant::fromStdVariant(std::move(stdvar));
+ CHECK_EQUAL(qv2, qvar, int); // fake type, they're empty
+ }
stdvar = -4;
qvar = QVariant::fromStdVariant(stdvar);
QVERIFY(!qvar.isNull());
- QCOMPARE(qvar.type(), QVariant::Int);
+ QCOMPARE(qvar.typeId(), QMetaType::Int);
QCOMPARE(qvar.value<int>(), std::get<int>(stdvar));
+ {
+ const auto qv2 = QVariant::fromStdVariant(std::move(stdvar));
+ CHECK_EQUAL(qv2, qvar, int);
+ }
}
{
std::variant<int, bool, QChar> stdvar = QChar::fromLatin1(' ');
QVariant qvar = QVariant::fromStdVariant(stdvar);
QVERIFY(!qvar.isNull());
- QCOMPARE(qvar.type(), QVariant::Char);
+ QCOMPARE(qvar.typeId(), QMetaType::QChar);
QCOMPARE(qvar.value<QChar>(), std::get<QChar>(stdvar));
+ {
+ const auto qv2 = QVariant::fromStdVariant(std::move(stdvar));
+ CHECK_EQUAL(qv2, qvar, QChar);
+ }
}
-#endif
+ // rvalue fromStdVariant() actually moves:
+ {
+ const auto foo = u"foo"_s;
+ std::variant<QString, QByteArray> stdvar = foo;
+ QVariant qvar = QVariant::fromStdVariant(std::move(stdvar));
+ const auto ps = get_if<QString>(&stdvar);
+ QVERIFY(ps);
+ QVERIFY(ps->isNull()); // QString was moved from
+ QVERIFY(!qvar.isNull());
+ QCOMPARE(qvar.typeId(), QMetaType::QString);
+ QCOMPARE(get<QString>(qvar), foo);
+ }
+
+#undef CHECK_EQUAL
}
void tst_QVariant::qt4UuidDataStream()
@@ -4873,5 +5776,558 @@ void tst_QVariant::mutableView()
QCOMPARE(extracted.text, nullptr);
}
+template<typename T>
+void tst_QVariant::canViewAndView_ReturnFalseAndDefault_WhenConvertingBetweenPointerAndValue_impl(
+ const QByteArray &typeName)
+{
+ T instance{};
+
+ // Value -> Pointer
+ QVariant value = QVariant::fromValue(instance);
+ QVERIFY2(!value.canView<T *>(), typeName);
+ QCOMPARE(value.view<T *>(), nullptr); // Expect default constructed pointer
+
+ // Pointer -> Value
+ QVariant pointer = QVariant::fromValue(&instance);
+ QVERIFY2(!pointer.canView<T>(), typeName);
+ QCOMPARE(pointer.view<T>(), T{}); // Expect default constructed. Note: Weak test since instance
+ // is default constructed, but we detect data corruption
+}
+
+void tst_QVariant::canViewAndView_ReturnFalseAndDefault_WhenConvertingBetweenPointerAndValue()
+{
+#define ADD_TEST_IMPL(typeName, typeNameId, realType) \
+ canViewAndView_ReturnFalseAndDefault_WhenConvertingBetweenPointerAndValue_impl<realType>( \
+ #typeName);
+
+ // Add tests for static primitive types
+ QT_FOR_EACH_STATIC_PRIMITIVE_NON_VOID_TYPE(ADD_TEST_IMPL)
+
+ // Add tests for static core types
+ QT_FOR_EACH_STATIC_CORE_CLASS(ADD_TEST_IMPL)
+#undef ADD_TEST_IMPL
+}
+
+struct MoveTester
+{
+ bool wasMoved = false;
+ MoveTester() = default;
+ MoveTester(const MoveTester &) {}; // non-trivial on purpose
+ MoveTester(MoveTester &&other) { other.wasMoved = true; }
+ MoveTester& operator=(const MoveTester &) = default;
+ MoveTester& operator=(MoveTester &&other) {other.wasMoved = true; return *this;}
+};
+
+void tst_QVariant::moveOperations()
+{
+ {
+ QString str = "Hello";
+ auto v = QVariant::fromValue(str);
+ QVariant v2(std::move(v));
+ QCOMPARE(v2.toString(), str);
+
+ v = QVariant::fromValue(str);
+ v2 = std::move(v);
+ QCOMPARE(v2.toString(), str);
+ }
+
+ std::list<int> list;
+ auto v = QVariant::fromValue(list);
+ QVariant v2(std::move(v));
+ QVERIFY(v2.value<std::list<int>>() == list);
+
+ v = QVariant::fromValue(list);
+ v2 = std::move(v);
+ QVERIFY(v2.value<std::list<int>>() == list);
+
+ {
+ MoveTester tester;
+ QVariant::fromValue(tester);
+ QVERIFY(!tester.wasMoved);
+ QVariant::fromValue(std::move(tester));
+ QVERIFY(tester.wasMoved);
+ }
+ {
+ const MoveTester tester;
+ QVariant::fromValue(std::move(tester));
+ QVERIFY(!tester.wasMoved); // we don't want to move from const variables
+ }
+ {
+ QVariant var(std::in_place_type<MoveTester>);
+ const auto p = get_if<MoveTester>(&var);
+ QVERIFY(p);
+ auto &tester = *p;
+ QVERIFY(!tester.wasMoved);
+ [[maybe_unused]] auto copy = var.value<MoveTester>();
+ QVERIFY(!tester.wasMoved);
+ [[maybe_unused]] auto moved = std::move(var).value<MoveTester>();
+ QVERIFY(tester.wasMoved);
+ }
+}
+
+class NoMetaObject : public QObject {};
+void tst_QVariant::equalsWithoutMetaObject()
+{
+ using T = NoMetaObject*;
+ QtPrivate::QMetaTypeInterface d = {
+ /*.revision=*/ 0,
+ /*.alignment=*/ alignof(T),
+ /*.size=*/ sizeof(T),
+ /*.flags=*/ QtPrivate::QMetaTypeTypeFlags<T>::Flags,
+ /*.typeId=*/ 0,
+ /*.metaObject=*/ nullptr, // on purpose.
+ /*.name=*/ "NoMetaObject*",
+ /*.defaultCtr=*/ [](const QtPrivate::QMetaTypeInterface *, void *addr) {
+ new (addr) T();
+ },
+ /*.copyCtr=*/ [](const QtPrivate::QMetaTypeInterface *, void *addr, const void *other) {
+ new (addr) T(*reinterpret_cast<const T *>(other));
+ },
+ /*.moveCtr=*/ [](const QtPrivate::QMetaTypeInterface *, void *addr, void *other) {
+ new (addr) T(std::move(*reinterpret_cast<T *>(other)));
+ },
+ /*.dtor=*/ [](const QtPrivate::QMetaTypeInterface *, void *addr) {
+ reinterpret_cast<T *>(addr)->~T();
+ },
+ /*.equals*/ nullptr,
+ /*.lessThan*/ nullptr,
+ /*.debugStream=*/ nullptr,
+ /*.dataStreamOut=*/ nullptr,
+ /*.dataStreamIn=*/ nullptr,
+ /*.legacyRegisterOp=*/ nullptr
+ };
+
+ QMetaType noMetaObjectMetaType(&d);
+ QMetaType qobjectMetaType = QMetaType::fromType<tst_QVariant*>();
+
+ QVERIFY(noMetaObjectMetaType.flags() & QMetaType::PointerToQObject);
+ QVERIFY(qobjectMetaType.flags() & QMetaType::PointerToQObject);
+
+ QVariant noMetaObjectVariant(noMetaObjectMetaType, nullptr);
+ QVariant qobjectVariant(qobjectMetaType, nullptr);
+
+ // Shouldn't crash
+ QVERIFY(noMetaObjectVariant != qobjectVariant);
+ QVERIFY(qobjectVariant != noMetaObjectVariant);
+}
+
+struct NonDefaultConstructible
+{
+ NonDefaultConstructible(int i) :i(i) {}
+ int i;
+ friend bool operator==(NonDefaultConstructible l, NonDefaultConstructible r)
+ { return l.i == r.i; }
+};
+
+template <> char *QTest::toString<NonDefaultConstructible>(const NonDefaultConstructible &ndc)
+{
+ return qstrdup('{' + QByteArray::number(ndc.i) + '}');
+}
+
+struct Indestructible
+{
+ Indestructible() {}
+ Indestructible(const Indestructible &) {}
+ Indestructible &operator=(const Indestructible &) { return *this; }
+private:
+ ~Indestructible() {}
+};
+
+struct NotCopyable
+{
+ NotCopyable() = default;
+ NotCopyable(const NotCopyable&) = delete;
+ NotCopyable &operator=(const NotCopyable &) = delete;
+};
+
+void tst_QVariant::constructFromIncompatibleMetaType_data()
+{
+ QTest::addColumn<QMetaType>("type");
+ auto addRow = [](QMetaType meta) {
+ QTest::newRow(meta.name()) << meta;
+ };
+ addRow(QMetaType::fromType<void>());
+ addRow(QMetaType::fromType<NonDefaultConstructible>());
+ addRow(QMetaType::fromType<QObject>());
+ addRow(QMetaType::fromType<Indestructible>());
+ addRow(QMetaType::fromType<NotCopyable>());
+}
+
+void tst_QVariant::constructFromIncompatibleMetaType()
+{
+ QFETCH(QMetaType, type);
+ const auto anticipate = [type]() {
+ // In that case, we run into a different condition (size == 0), and do not warn
+ if (type == QMetaType::fromType<NonDefaultConstructible>()) {
+ QTest::ignoreMessage(QtWarningMsg,
+ "QVariant: Cannot create type 'NonDefaultConstructible' without a "
+ "default constructor");
+ } else if (type != QMetaType::fromType<void>()) {
+ QTest::ignoreMessage(
+ QtWarningMsg,
+ "QVariant: Provided metatype for '" + QByteArray(type.name()) +
+ "' does not support destruction and copy construction");
+ }
+ };
+ anticipate();
+ QVariant var(type, nullptr);
+ QVERIFY(!var.isValid());
+ QVERIFY(!var.metaType().isValid());
+
+ anticipate();
+ QVariant regular(1.0);
+ QVERIFY(!var.canView(type));
+ QVERIFY(!var.canConvert(type));
+ QVERIFY(!QVariant(regular).convert(type));
+}
+
+void tst_QVariant::constructFromQtLT65MetaType()
+{
+ auto qsizeIface = QtPrivate::qMetaTypeInterfaceForType<QSize>();
+
+ QtPrivate::QMetaTypeInterface qsize64Iface = {
+ /*revision*/0,
+ 8,
+ 8,
+ QMetaType::NeedsConstruction | QMetaType::NeedsDestruction,
+ 0,
+ qsizeIface->metaObjectFn,
+ "FakeQSize",
+ qsizeIface->defaultCtr,
+ qsizeIface->copyCtr,
+ qsizeIface->moveCtr,
+ /*dtor =*/ nullptr,
+ qsizeIface->equals,
+ qsizeIface->lessThan,
+ qsizeIface->debugStream,
+ qsizeIface->dataStreamOut,
+ qsizeIface->dataStreamIn,
+ /*legacyregop =*/ nullptr
+ };
+ QVariant var{ QMetaType(&qsize64Iface) };
+ QVERIFY(var.isValid());
+}
+
+void tst_QVariant::copyNonDefaultConstructible()
+{
+ NonDefaultConstructible ndc(42);
+ QVariant var = QVariant::fromValue(ndc);
+ QVERIFY(var.isDetached());
+ QCOMPARE(var.metaType(), QMetaType::fromType<NonDefaultConstructible>());
+ QVERIFY(var.constData() != &ndc);
+
+ // qvariant_cast<T> and QVariant::value<T> don't compile
+ QCOMPARE(get<NonDefaultConstructible>(std::as_const(var)), ndc);
+
+ QVariant var2 = var;
+ var2.detach(); // force another copy
+ QVERIFY(var2.isDetached());
+ QVERIFY(var2.constData() != var.constData());
+ QCOMPARE(get<NonDefaultConstructible>(std::as_const(var2)),
+ get<NonDefaultConstructible>(std::as_const(var)));
+ QCOMPARE(var2, var);
+}
+
+void tst_QVariant::inplaceConstruct()
+{
+ {
+ NonDefaultConstructible ndc(42);
+ QVariant var(std::in_place_type<NonDefaultConstructible>, 42);
+ QVERIFY(get_if<NonDefaultConstructible>(&var));
+ QCOMPARE(get<NonDefaultConstructible>(var), ndc);
+ }
+
+ {
+ std::vector<int> vec {1, 2, 3, 4};
+ QVariant var(std::in_place_type<std::vector<int>>, {1, 2, 3, 4});
+ QVERIFY(get_if<std::vector<int>>(&var));
+ QCOMPARE(get<std::vector<int>>(var), vec);
+ }
+}
+
+struct LargerThanInternalQVariantStorage {
+ char data[6 * sizeof(void *)];
+};
+
+struct alignas(256) LargerThanInternalQVariantStorageOveraligned {
+ char data[6 * sizeof(void *)];
+};
+
+struct alignas(128) SmallerAlignmentEvenLargerSize {
+ char data[17 * sizeof(void *)];
+};
+
+void tst_QVariant::emplace()
+{
+ {
+ // can emplace non default constructible + can emplace on null variant
+ NonDefaultConstructible ndc(42);
+ QVariant var;
+ var.emplace<NonDefaultConstructible>(42);
+ QVERIFY(get_if<NonDefaultConstructible>(&var));
+ QCOMPARE(get<NonDefaultConstructible>(var), ndc);
+ }
+ {
+ // can emplace using ctor taking initializer_list
+ QVariant var;
+ var.emplace<std::vector<int>>({0, 1, 2, 3, 4});
+ auto vecPtr = get_if<std::vector<int>>(&var);
+ QVERIFY(vecPtr);
+ QCOMPARE(vecPtr->size(), 5U);
+ for (int i = 0; i < 5; ++i)
+ QCOMPARE(vecPtr->at(size_t(i)), i);
+ }
+ // prequisites for the test
+ QCOMPARE_LE(sizeof(std::vector<int>), sizeof(std::string));
+ QCOMPARE(alignof(std::vector<int>), alignof(std::string));
+ {
+ // emplace can reuse storage
+ auto var = QVariant::fromValue(std::string{});
+ QVERIFY(var.data_ptr().is_shared);
+ auto data = var.constData();
+ std::vector<int> &vec = var.emplace<std::vector<int>>(3, 42);
+ /* alignment is the same, so the pointer is exactly the same;
+ no offset change */
+ auto expected = std::vector<int>{42, 42, 42};
+ QCOMPARE(get_if<std::vector<int>>(&var), &vec);
+ QCOMPARE(get<std::vector<int>>(var), expected);
+ QCOMPARE(var.constData(), data);
+ }
+ {
+ // emplace can't reuse storage if the variant is shared
+ auto var = QVariant::fromValue(std::string{});
+ [[maybe_unused]] QVariant causesSharing = var;
+ QVERIFY(var.data_ptr().is_shared);
+ auto data = var.constData();
+ var.emplace<std::vector<int>>(3, 42);
+ auto expected = std::vector<int>{42, 42, 42};
+ QVERIFY(get_if<std::vector<int>>(&var));
+ QCOMPARE(get<std::vector<int>>(var), expected);
+ QCOMPARE_NE(var.constData(), data);
+ }
+ {
+ // emplace puts element into the correct place - non-shared
+ QVERIFY(QVariant::Private::canUseInternalSpace(QMetaType::fromType<QString>().iface()));
+ QVariant var;
+ var.emplace<QString>(QChar('x'));
+ QVERIFY(!var.data_ptr().is_shared);
+ }
+ {
+ // emplace puts element into the correct place - shared
+ QVERIFY(!QVariant::Private::canUseInternalSpace(QMetaType::fromType<std::string>().iface()));
+ QVariant var;
+ var.emplace<std::string>(42, 'x');
+ QVERIFY(var.data_ptr().is_shared);
+ }
+ {
+ // emplace does not reuse the storage if alignment is too large
+ auto iface = QMetaType::fromType<LargerThanInternalQVariantStorage>().iface();
+ QVERIFY(!QVariant::Private::canUseInternalSpace(iface));
+ auto var = QVariant::fromValue(LargerThanInternalQVariantStorage{});
+ auto data = var.constData();
+ var.emplace<LargerThanInternalQVariantStorageOveraligned>();
+ QCOMPARE_NE(var.constData(), data);
+ }
+ {
+ // emplace does reuse the storage if new alignment and size are together small enough
+ auto iface = QMetaType::fromType<LargerThanInternalQVariantStorageOveraligned>().iface();
+ QVERIFY(!QVariant::Private::canUseInternalSpace(iface));
+ auto var = QVariant::fromValue(LargerThanInternalQVariantStorageOveraligned{});
+ auto data = var.constData();
+ var.emplace<SmallerAlignmentEvenLargerSize>();
+ // no exact match below - the alignment is after all different
+ QCOMPARE_LE(quintptr(var.constData()), quintptr(data));
+ QCOMPARE_LE(quintptr(var.constData()),
+ quintptr(data) + sizeof(LargerThanInternalQVariantStorageOveraligned));
+ }
+}
+
+void tst_QVariant::getIf_NonDefaultConstructible()
+{
+ getIf_impl(NonDefaultConstructible{42});
+}
+
+void tst_QVariant::getIfSpecial()
+{
+ QVariant v{QString{}}; // used to be a null QVariant in Qt 5
+ QCOMPARE_NE(get_if<QString>(&v), nullptr); // not anymore...
+}
+
+void tst_QVariant::get_NonDefaultConstructible()
+{
+ get_impl(NonDefaultConstructible{42});
+}
+
+template <typename T>
+T mutate(const T &t) { return t + t; }
+template <>
+NonDefaultConstructible mutate(const NonDefaultConstructible &t)
+{
+ return NonDefaultConstructible{t.i + t.i};
+}
+
+template <typename T>
+QVariant make_null_QVariant_of_type()
+{
+ return QVariant(QMetaType::fromType<T>());
+}
+
+template <typename T>
+void tst_QVariant::getIf_impl(T t) const
+{
+ QVariant v = QVariant::fromValue(t);
+
+ QVariant null;
+ QVERIFY(null.isNull());
+
+ [[maybe_unused]]
+ QVariant nulT;
+ if constexpr (std::is_default_constructible_v<T>) {
+ // typed null QVariants don't work with non-default-constuctable types
+ nulT = make_null_QVariant_of_type<T>();
+ QVERIFY(nulT.isNull());
+ }
+
+ QVariant date = QDate(2023, 3, 3);
+ static_assert(!std::is_same_v<T, QDate>);
+
+ // for behavioral comparison:
+ StdVariant stdn = {}, stdv = t;
+
+ // returns nullptr on type mismatch:
+ {
+ // const
+ QCOMPARE_EQ(get_if<T>(&std::as_const(stdn)), nullptr);
+ QCOMPARE_EQ(get_if<T>(&std::as_const(date)), nullptr);
+ // mutable
+ QCOMPARE_EQ(get_if<T>(&stdn), nullptr);
+ QCOMPARE_EQ(get_if<T>(&date), nullptr);
+ }
+
+ // returns nullptr on null variant (QVariant only):
+ {
+ QCOMPARE_EQ(get_if<T>(&std::as_const(null)), nullptr);
+ QCOMPARE_EQ(get_if<T>(&null), nullptr);
+ if constexpr (std::is_default_constructible_v<T>) {
+ // const access return nullptr
+ QCOMPARE_EQ(get_if<T>(&std::as_const(nulT)), nullptr);
+ // but mutable access makes typed null QVariants non-null (like data())
+ QCOMPARE_NE(get_if<T>(&nulT), nullptr);
+ QVERIFY(!nulT.isNull());
+ nulT = make_null_QVariant_of_type<T>(); // reset to null state
+ }
+ }
+
+ // const access:
+ {
+ auto ps = get_if<T>(&std::as_const(stdv));
+ static_assert(std::is_same_v<decltype(ps), const T*>);
+ QCOMPARE_NE(ps, nullptr);
+ QCOMPARE_EQ(*ps, t);
+
+ auto pv = get_if<T>(&std::as_const(v));
+ static_assert(std::is_same_v<decltype(ps), const T*>);
+ QCOMPARE_NE(pv, nullptr);
+ QCOMPARE_EQ(*pv, t);
+ }
+
+ // mutable access:
+ {
+ T t2 = mutate(t);
+
+ auto ps = get_if<T>(&stdv);
+ static_assert(std::is_same_v<decltype(ps), T*>);
+ QCOMPARE_NE(ps, nullptr);
+ QCOMPARE_EQ(*ps, t);
+ *ps = t2;
+ auto ps2 = get_if<T>(&stdv);
+ QCOMPARE_NE(ps2, nullptr);
+ QCOMPARE_EQ(*ps2, t2);
+
+ auto pv = get_if<T>(&v);
+ static_assert(std::is_same_v<decltype(pv), T*>);
+ QCOMPARE_NE(pv, nullptr);
+ QCOMPARE_EQ(*pv, t);
+ *pv = t2;
+ auto pv2 = get_if<T>(&v);
+ QCOMPARE_NE(pv2, nullptr);
+ QCOMPARE_EQ(*pv2, t2);
+
+ // typed null QVariants become non-null (data() behavior):
+ if constexpr (std::is_default_constructible_v<T>) {
+ QVERIFY(nulT.isNull());
+ auto pn = get_if<T>(&nulT);
+ QVERIFY(!nulT.isNull());
+ static_assert(std::is_same_v<decltype(pn), T*>);
+ QCOMPARE_NE(pn, nullptr);
+ QCOMPARE_EQ(*pn, T{});
+ *pn = t2;
+ auto pn2 = get_if<T>(&nulT);
+ QCOMPARE_NE(pn2, nullptr);
+ QCOMPARE_EQ(*pn2, t2);
+ }
+ }
+}
+
+template <typename T>
+void tst_QVariant::get_impl(T t) const
+{
+ QVariant v = QVariant::fromValue(t);
+
+ // for behavioral comparison:
+ StdVariant stdv = t;
+
+ #define FOR_EACH_CVREF(op) \
+ op(/*unadorned*/, &&) \
+ op(&, &) \
+ op(&&, &&) \
+ op(const, const &&) \
+ op(const &, const &) \
+ op(const &&, const &&) \
+ /* end */
+
+
+ #define CHECK_RETURN_TYPE_OF(Variant, cvref_in, cvref_out) \
+ static_assert(std::is_same_v< \
+ decltype(get<T>(std::declval<Variant cvref_in >())), \
+ T cvref_out \
+ >); \
+ /* end */
+ #define CHECK_RETURN_TYPE(cvref_in, cvref_out) \
+ CHECK_RETURN_TYPE_OF(StdVariant, cvref_in, cvref_out) \
+ CHECK_RETURN_TYPE_OF(QVariant, cvref_in, cvref_out) \
+ /* end */
+ FOR_EACH_CVREF(CHECK_RETURN_TYPE)
+ #undef CHECK_RETURN_TYPE
+
+ #undef FOR_EACH_CVREF
+
+ // const access:
+ {
+ auto &&rs = get<T>(std::as_const(stdv));
+ QCOMPARE_EQ(rs, t);
+
+ auto &&rv = get<T>(std::as_const(v));
+ QCOMPARE_EQ(rv, t);
+ }
+
+ // mutable access:
+ {
+ T t2 = mutate(t);
+
+ auto &&rs = get<T>(stdv);
+ QCOMPARE_EQ(rs, t);
+ rs = t2;
+ auto &&rs2 = get<T>(stdv);
+ QCOMPARE_EQ(rs2, t2);
+
+ auto &&rv = get<T>(v);
+ QCOMPARE_EQ(rv, t);
+ rv = t2;
+ auto &&rv2 = get<T>(v);
+ QCOMPARE_EQ(rv2, t2);
+ }
+}
+
QTEST_MAIN(tst_QVariant)
#include "tst_qvariant.moc"
diff --git a/tests/auto/corelib/kernel/qwineventnotifier/CMakeLists.txt b/tests/auto/corelib/kernel/qwineventnotifier/CMakeLists.txt
index 7974c3765b..81b2c9a58c 100644
--- a/tests/auto/corelib/kernel/qwineventnotifier/CMakeLists.txt
+++ b/tests/auto/corelib/kernel/qwineventnotifier/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qwineventnotifier.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qwineventnotifier Test:
#####################################################################
-qt_add_test(tst_qwineventnotifier
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qwineventnotifier LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qwineventnotifier
SOURCES
tst_qwineventnotifier.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
)
diff --git a/tests/auto/corelib/kernel/qwineventnotifier/qwineventnotifier.pro b/tests/auto/corelib/kernel/qwineventnotifier/qwineventnotifier.pro
deleted file mode 100644
index 20ec7572fb..0000000000
--- a/tests/auto/corelib/kernel/qwineventnotifier/qwineventnotifier.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-CONFIG += testcase
-TARGET = tst_qwineventnotifier
-QT = core-private testlib
-SOURCES = tst_qwineventnotifier.cpp
diff --git a/tests/auto/corelib/kernel/qwineventnotifier/tst_qwineventnotifier.cpp b/tests/auto/corelib/kernel/qwineventnotifier/tst_qwineventnotifier.cpp
index cd9268d736..bf08f85fb5 100644
--- a/tests/auto/corelib/kernel/qwineventnotifier/tst_qwineventnotifier.cpp
+++ b/tests/auto/corelib/kernel/qwineventnotifier/tst_qwineventnotifier.cpp
@@ -1,32 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtTest/QtTest>
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
+#include <QTestEventLoop>
+
#include <qlist.h>
#include <qtimer.h>
#include <qvarlengtharray.h>
diff --git a/tests/auto/corelib/kernel/qwinregistrykey/.gitignore b/tests/auto/corelib/kernel/qwinregistrykey/.gitignore
new file mode 100644
index 0000000000..3d888e2868
--- /dev/null
+++ b/tests/auto/corelib/kernel/qwinregistrykey/.gitignore
@@ -0,0 +1 @@
+tst_qwinregistrykey
diff --git a/tests/auto/corelib/kernel/qwinregistrykey/CMakeLists.txt b/tests/auto/corelib/kernel/qwinregistrykey/CMakeLists.txt
new file mode 100644
index 0000000000..aeda6f0033
--- /dev/null
+++ b/tests/auto/corelib/kernel/qwinregistrykey/CMakeLists.txt
@@ -0,0 +1,15 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qwinregistrykey LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qwinregistrykey
+ SOURCES
+ tst_qwinregistrykey.cpp
+ LIBRARIES
+ Qt::CorePrivate
+)
diff --git a/tests/auto/corelib/kernel/qwinregistrykey/tst_qwinregistrykey.cpp b/tests/auto/corelib/kernel/qwinregistrykey/tst_qwinregistrykey.cpp
new file mode 100644
index 0000000000..a5dca8a3d5
--- /dev/null
+++ b/tests/auto/corelib/kernel/qwinregistrykey/tst_qwinregistrykey.cpp
@@ -0,0 +1,242 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
+#include <QObject>
+#include <QPair>
+#include <QScopeGuard>
+#include <private/qwinregistry_p.h>
+#include <qt_windows.h>
+
+using namespace Qt::StringLiterals;
+
+static constexpr const wchar_t TEST_KEY[] = LR"(SOFTWARE\tst_qwinregistrykey)";
+
+static const QPair<QStringView, QString> TEST_STRING = qMakePair(u"string", u"string"_s);
+static const QPair<QStringView, QString> TEST_STRING_NULL = qMakePair(u"string_null", QString());
+static const QPair<QStringView, QStringList> TEST_STRINGLIST = qMakePair(u"stringlist", QStringList{ u"element1"_s, u"element2"_s, u"element3"_s });
+static const QPair<QStringView, QStringList> TEST_STRINGLIST_NULL = qMakePair(u"stringlist_null", QStringList());
+static const QPair<QStringView, quint32> TEST_DWORD = qMakePair(u"dword", 123);
+static const QPair<QStringView, quint64> TEST_QWORD = qMakePair(u"qword", 456);
+static const QPair<QStringView, QByteArray> TEST_BINARY = qMakePair(u"binary", "binary\0"_ba);
+static const QPair<QStringView, QVariant> TEST_NOT_EXIST = qMakePair(u"not_exist", QVariant());
+static const QPair<QStringView, QVariant> TEST_DEFAULT = qMakePair(u"", u"default"_s);
+
+[[nodiscard]] static inline bool write(const HKEY key, const QStringView name, const QVariant &value)
+{
+ DWORD type = REG_NONE;
+ QByteArray buf = {};
+
+ switch (value.typeId()) {
+ case QMetaType::QStringList: {
+ // If none of the elements contains '\0', we can use REG_MULTI_SZ, the
+ // native registry string list type. Otherwise we use REG_BINARY.
+ type = REG_MULTI_SZ;
+ const QStringList list = value.toStringList();
+ for (auto it = list.constBegin(); it != list.constEnd(); ++it) {
+ if ((*it).length() == 0 || it->contains(QChar::Null)) {
+ type = REG_BINARY;
+ break;
+ }
+ }
+
+ if (type == REG_BINARY) {
+ const QString str = value.toString();
+ buf = QByteArray(reinterpret_cast<const char *>(str.data()), str.length() * 2);
+ } else {
+ for (auto it = list.constBegin(); it != list.constEnd(); ++it) {
+ const QString &str = *it;
+ buf += QByteArray(reinterpret_cast<const char *>(str.utf16()), (str.length() + 1) * 2);
+ }
+ // According to Microsoft Docs, REG_MULTI_SZ requires double '\0'.
+ buf.append((char)0);
+ buf.append((char)0);
+ }
+ break;
+ }
+
+ case QMetaType::Int:
+ case QMetaType::UInt: {
+ type = REG_DWORD;
+ quint32 num = value.toUInt();
+ buf = QByteArray(reinterpret_cast<const char *>(&num), sizeof(quint32));
+ break;
+ }
+
+ case QMetaType::LongLong:
+ case QMetaType::ULongLong: {
+ type = REG_QWORD;
+ quint64 num = value.toULongLong();
+ buf = QByteArray(reinterpret_cast<const char *>(&num), sizeof(quint64));
+ break;
+ }
+
+ case QMetaType::QByteArray:
+ default: {
+ // If the string does not contain '\0', we can use REG_SZ, the native registry
+ // string type. Otherwise we use REG_BINARY.
+ const QString str = value.toString();
+ type = str.contains(QChar::Null) ? REG_BINARY : REG_SZ;
+ int length = str.length();
+ if (type == REG_SZ)
+ ++length;
+ buf = QByteArray(reinterpret_cast<const char *>(str.utf16()), sizeof(wchar_t) * length);
+ break;
+ }
+ }
+
+ const LONG ret = RegSetValueExW(key, reinterpret_cast<const wchar_t *>(name.utf16()),
+ 0, type, reinterpret_cast<LPBYTE>(buf.data()), buf.size());
+ return ret == ERROR_SUCCESS;
+}
+
+class tst_qwinregistrykey : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ void initTestCase();
+ void cleanupTestCase();
+ void qwinregistrykey();
+
+private:
+ bool m_available = false;
+};
+
+void tst_qwinregistrykey::initTestCase()
+{
+ HKEY key = nullptr;
+ const LONG ret = RegCreateKeyExW(HKEY_CURRENT_USER, TEST_KEY, 0, nullptr, 0,
+ KEY_READ | KEY_WRITE, nullptr, &key, nullptr);
+ if (ret != ERROR_SUCCESS)
+ return;
+ const auto cleanup = qScopeGuard([key](){ RegCloseKey(key); });
+ if (!write(key, TEST_STRING.first, TEST_STRING.second))
+ return;
+ if (!write(key, TEST_STRING_NULL.first, TEST_STRING_NULL.second))
+ return;
+ if (!write(key, TEST_STRINGLIST.first, TEST_STRINGLIST.second))
+ return;
+ if (!write(key, TEST_STRINGLIST_NULL.first, TEST_STRINGLIST_NULL.second))
+ return;
+ if (!write(key, TEST_DWORD.first, TEST_DWORD.second))
+ return;
+ if (!write(key, TEST_QWORD.first, TEST_QWORD.second))
+ return;
+ if (!write(key, TEST_BINARY.first, TEST_BINARY.second))
+ return;
+ if (!write(key, TEST_DEFAULT.first, TEST_DEFAULT.second))
+ return;
+ m_available = true;
+}
+
+void tst_qwinregistrykey::cleanupTestCase()
+{
+ HKEY key = nullptr;
+ const LONG ret = RegOpenKeyExW(HKEY_CURRENT_USER, TEST_KEY, 0, KEY_READ | KEY_WRITE, &key);
+ if (ret != ERROR_SUCCESS)
+ return;
+ #define C_STR(View) reinterpret_cast<const wchar_t *>(View.utf16())
+ RegDeleteValueW(key, C_STR(TEST_STRING.first));
+ RegDeleteValueW(key, C_STR(TEST_STRING_NULL.first));
+ RegDeleteValueW(key, C_STR(TEST_STRINGLIST.first));
+ RegDeleteValueW(key, C_STR(TEST_STRINGLIST_NULL.first));
+ RegDeleteValueW(key, C_STR(TEST_DWORD.first));
+ RegDeleteValueW(key, C_STR(TEST_QWORD.first));
+ RegDeleteValueW(key, C_STR(TEST_BINARY.first));
+ RegDeleteValueW(key, C_STR(TEST_DEFAULT.first));
+ #undef C_STR
+ RegDeleteKeyW(HKEY_CURRENT_USER, TEST_KEY);
+ RegCloseKey(key);
+}
+
+void tst_qwinregistrykey::qwinregistrykey()
+{
+ if (!m_available)
+ QSKIP("The test data is not ready.");
+
+ QWinRegistryKey registry(HKEY_CURRENT_USER, TEST_KEY);
+
+ QVERIFY(registry.isValid());
+
+ QVERIFY(registry.handle() != nullptr);
+
+ {
+ const auto value = registry.value<QString>(TEST_STRING.first);
+ QVERIFY(value.has_value());
+ QCOMPARE(value.value_or(QString()), TEST_STRING.second);
+ }
+
+ {
+ const auto value = registry.value<QString>(TEST_STRING_NULL.first);
+ QVERIFY(value.has_value());
+ QCOMPARE(value.value_or(QString()), TEST_STRING_NULL.second);
+
+ }
+
+ {
+ const auto value = registry.value<QStringList>(TEST_STRINGLIST.first);
+ QVERIFY(value.has_value());
+ QCOMPARE(value.value_or(QStringList()), TEST_STRINGLIST.second);
+ }
+
+ {
+ const auto value = registry.value<QStringList>(TEST_STRINGLIST_NULL.first);
+ QVERIFY(value.has_value());
+ QCOMPARE(value.value_or(QStringList()), TEST_STRINGLIST_NULL.second);
+ }
+
+ {
+ const auto value = registry.value<quint32>(TEST_DWORD.first);
+ QVERIFY(value.has_value());
+ QCOMPARE(value.value_or(0), TEST_DWORD.second);
+ }
+
+ {
+ const auto value = registry.value<quint64>(TEST_QWORD.first);
+ QVERIFY(value.has_value());
+ QCOMPARE(value.value_or(0), TEST_QWORD.second);
+ }
+
+ {
+ const auto value = registry.value<QByteArray>(TEST_BINARY.first);
+ QVERIFY(value.has_value());
+ QCOMPARE(value.value_or(QByteArray()), TEST_BINARY.second);
+ }
+
+ {
+ const auto value = registry.value<QVariant>(TEST_NOT_EXIST.first);
+ QVERIFY(!value.has_value());
+ QCOMPARE(value.value_or(QVariant()), QVariant());
+ }
+
+ {
+ const auto value = registry.value<QString>(TEST_DEFAULT.first);
+ QVERIFY(value.has_value());
+ QCOMPARE(value.value_or(QString()), TEST_DEFAULT.second);
+ }
+
+ {
+ const QString value = registry.stringValue(TEST_STRING.first);
+ QVERIFY(!value.isEmpty());
+ QCOMPARE(value, TEST_STRING.second);
+ }
+
+ QVERIFY(registry.stringValue(TEST_NOT_EXIST.first).isEmpty());
+
+ {
+ const auto value = registry.dwordValue(TEST_DWORD.first);
+ QVERIFY(value.second);
+ QCOMPARE(value.first, TEST_DWORD.second);
+ }
+
+ {
+ const auto value = registry.dwordValue(TEST_NOT_EXIST.first);
+ QVERIFY(!value.second);
+ QCOMPARE(value.first, DWORD(0));
+ }
+}
+
+QTEST_MAIN(tst_qwinregistrykey)
+
+#include "tst_qwinregistrykey.moc"